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/AST/APValue.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/Attr.h" 18 #include "clang/AST/AttrIterator.h" 19 #include "clang/AST/CharUnits.h" 20 #include "clang/AST/Decl.h" 21 #include "clang/AST/DeclBase.h" 22 #include "clang/AST/DeclCXX.h" 23 #include "clang/AST/DeclObjC.h" 24 #include "clang/AST/DeclarationName.h" 25 #include "clang/AST/EvaluatedExprVisitor.h" 26 #include "clang/AST/Expr.h" 27 #include "clang/AST/ExprCXX.h" 28 #include "clang/AST/ExprObjC.h" 29 #include "clang/AST/ExprOpenMP.h" 30 #include "clang/AST/NSAPI.h" 31 #include "clang/AST/OperationKinds.h" 32 #include "clang/AST/Stmt.h" 33 #include "clang/AST/TemplateBase.h" 34 #include "clang/AST/Type.h" 35 #include "clang/AST/TypeLoc.h" 36 #include "clang/AST/UnresolvedSet.h" 37 #include "clang/Analysis/Analyses/FormatString.h" 38 #include "clang/Basic/AddressSpaces.h" 39 #include "clang/Basic/CharInfo.h" 40 #include "clang/Basic/Diagnostic.h" 41 #include "clang/Basic/IdentifierTable.h" 42 #include "clang/Basic/LLVM.h" 43 #include "clang/Basic/LangOptions.h" 44 #include "clang/Basic/OpenCLOptions.h" 45 #include "clang/Basic/OperatorKinds.h" 46 #include "clang/Basic/PartialDiagnostic.h" 47 #include "clang/Basic/SourceLocation.h" 48 #include "clang/Basic/SourceManager.h" 49 #include "clang/Basic/Specifiers.h" 50 #include "clang/Basic/SyncScope.h" 51 #include "clang/Basic/TargetBuiltins.h" 52 #include "clang/Basic/TargetCXXABI.h" 53 #include "clang/Basic/TargetInfo.h" 54 #include "clang/Basic/TypeTraits.h" 55 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 56 #include "clang/Sema/Initialization.h" 57 #include "clang/Sema/Lookup.h" 58 #include "clang/Sema/Ownership.h" 59 #include "clang/Sema/Scope.h" 60 #include "clang/Sema/ScopeInfo.h" 61 #include "clang/Sema/Sema.h" 62 #include "clang/Sema/SemaInternal.h" 63 #include "llvm/ADT/APFloat.h" 64 #include "llvm/ADT/APInt.h" 65 #include "llvm/ADT/APSInt.h" 66 #include "llvm/ADT/ArrayRef.h" 67 #include "llvm/ADT/DenseMap.h" 68 #include "llvm/ADT/FoldingSet.h" 69 #include "llvm/ADT/None.h" 70 #include "llvm/ADT/Optional.h" 71 #include "llvm/ADT/STLExtras.h" 72 #include "llvm/ADT/SmallBitVector.h" 73 #include "llvm/ADT/SmallPtrSet.h" 74 #include "llvm/ADT/SmallString.h" 75 #include "llvm/ADT/SmallVector.h" 76 #include "llvm/ADT/StringRef.h" 77 #include "llvm/ADT/StringSwitch.h" 78 #include "llvm/ADT/Triple.h" 79 #include "llvm/Support/AtomicOrdering.h" 80 #include "llvm/Support/Casting.h" 81 #include "llvm/Support/Compiler.h" 82 #include "llvm/Support/ConvertUTF.h" 83 #include "llvm/Support/ErrorHandling.h" 84 #include "llvm/Support/Format.h" 85 #include "llvm/Support/Locale.h" 86 #include "llvm/Support/MathExtras.h" 87 #include "llvm/Support/raw_ostream.h" 88 #include <algorithm> 89 #include <cassert> 90 #include <cstddef> 91 #include <cstdint> 92 #include <functional> 93 #include <limits> 94 #include <string> 95 #include <tuple> 96 #include <utility> 97 98 using namespace clang; 99 using namespace sema; 100 101 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 102 unsigned ByteNo) const { 103 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts, 104 Context.getTargetInfo()); 105 } 106 107 /// Checks that a call expression's argument count is the desired number. 108 /// This is useful when doing custom type-checking. Returns true on error. 109 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { 110 unsigned argCount = call->getNumArgs(); 111 if (argCount == desiredArgCount) return false; 112 113 if (argCount < desiredArgCount) 114 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args) 115 << 0 /*function call*/ << desiredArgCount << argCount 116 << call->getSourceRange(); 117 118 // Highlight all the excess arguments. 119 SourceRange range(call->getArg(desiredArgCount)->getLocStart(), 120 call->getArg(argCount - 1)->getLocEnd()); 121 122 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) 123 << 0 /*function call*/ << desiredArgCount << argCount 124 << call->getArg(1)->getSourceRange(); 125 } 126 127 /// Check that the first argument to __builtin_annotation is an integer 128 /// and the second argument is a non-wide string literal. 129 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) { 130 if (checkArgCount(S, TheCall, 2)) 131 return true; 132 133 // First argument should be an integer. 134 Expr *ValArg = TheCall->getArg(0); 135 QualType Ty = ValArg->getType(); 136 if (!Ty->isIntegerType()) { 137 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg) 138 << ValArg->getSourceRange(); 139 return true; 140 } 141 142 // Second argument should be a constant string. 143 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts(); 144 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg); 145 if (!Literal || !Literal->isAscii()) { 146 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg) 147 << StrArg->getSourceRange(); 148 return true; 149 } 150 151 TheCall->setType(Ty); 152 return false; 153 } 154 155 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) { 156 // We need at least one argument. 157 if (TheCall->getNumArgs() < 1) { 158 S.Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 159 << 0 << 1 << TheCall->getNumArgs() 160 << TheCall->getCallee()->getSourceRange(); 161 return true; 162 } 163 164 // All arguments should be wide string literals. 165 for (Expr *Arg : TheCall->arguments()) { 166 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 167 if (!Literal || !Literal->isWide()) { 168 S.Diag(Arg->getLocStart(), diag::err_msvc_annotation_wide_str) 169 << Arg->getSourceRange(); 170 return true; 171 } 172 } 173 174 return false; 175 } 176 177 /// Check that the argument to __builtin_addressof is a glvalue, and set the 178 /// result type to the corresponding pointer type. 179 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) { 180 if (checkArgCount(S, TheCall, 1)) 181 return true; 182 183 ExprResult Arg(TheCall->getArg(0)); 184 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart()); 185 if (ResultType.isNull()) 186 return true; 187 188 TheCall->setArg(0, Arg.get()); 189 TheCall->setType(ResultType); 190 return false; 191 } 192 193 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) { 194 if (checkArgCount(S, TheCall, 3)) 195 return true; 196 197 // First two arguments should be integers. 198 for (unsigned I = 0; I < 2; ++I) { 199 Expr *Arg = TheCall->getArg(I); 200 QualType Ty = Arg->getType(); 201 if (!Ty->isIntegerType()) { 202 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int) 203 << Ty << Arg->getSourceRange(); 204 return true; 205 } 206 } 207 208 // Third argument should be a pointer to a non-const integer. 209 // IRGen correctly handles volatile, restrict, and address spaces, and 210 // the other qualifiers aren't possible. 211 { 212 Expr *Arg = TheCall->getArg(2); 213 QualType Ty = Arg->getType(); 214 const auto *PtrTy = Ty->getAs<PointerType>(); 215 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() && 216 !PtrTy->getPointeeType().isConstQualified())) { 217 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int) 218 << Ty << Arg->getSourceRange(); 219 return true; 220 } 221 } 222 223 return false; 224 } 225 226 static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl, 227 CallExpr *TheCall, unsigned SizeIdx, 228 unsigned DstSizeIdx) { 229 if (TheCall->getNumArgs() <= SizeIdx || 230 TheCall->getNumArgs() <= DstSizeIdx) 231 return; 232 233 const Expr *SizeArg = TheCall->getArg(SizeIdx); 234 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx); 235 236 llvm::APSInt Size, DstSize; 237 238 // find out if both sizes are known at compile time 239 if (!SizeArg->EvaluateAsInt(Size, S.Context) || 240 !DstSizeArg->EvaluateAsInt(DstSize, S.Context)) 241 return; 242 243 if (Size.ule(DstSize)) 244 return; 245 246 // confirmed overflow so generate the diagnostic. 247 IdentifierInfo *FnName = FDecl->getIdentifier(); 248 SourceLocation SL = TheCall->getLocStart(); 249 SourceRange SR = TheCall->getSourceRange(); 250 251 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName; 252 } 253 254 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { 255 if (checkArgCount(S, BuiltinCall, 2)) 256 return true; 257 258 SourceLocation BuiltinLoc = BuiltinCall->getLocStart(); 259 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); 260 Expr *Call = BuiltinCall->getArg(0); 261 Expr *Chain = BuiltinCall->getArg(1); 262 263 if (Call->getStmtClass() != Stmt::CallExprClass) { 264 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) 265 << Call->getSourceRange(); 266 return true; 267 } 268 269 auto CE = cast<CallExpr>(Call); 270 if (CE->getCallee()->getType()->isBlockPointerType()) { 271 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) 272 << Call->getSourceRange(); 273 return true; 274 } 275 276 const Decl *TargetDecl = CE->getCalleeDecl(); 277 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 278 if (FD->getBuiltinID()) { 279 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) 280 << Call->getSourceRange(); 281 return true; 282 } 283 284 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { 285 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) 286 << Call->getSourceRange(); 287 return true; 288 } 289 290 ExprResult ChainResult = S.UsualUnaryConversions(Chain); 291 if (ChainResult.isInvalid()) 292 return true; 293 if (!ChainResult.get()->getType()->isPointerType()) { 294 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) 295 << Chain->getSourceRange(); 296 return true; 297 } 298 299 QualType ReturnTy = CE->getCallReturnType(S.Context); 300 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; 301 QualType BuiltinTy = S.Context.getFunctionType( 302 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); 303 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); 304 305 Builtin = 306 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); 307 308 BuiltinCall->setType(CE->getType()); 309 BuiltinCall->setValueKind(CE->getValueKind()); 310 BuiltinCall->setObjectKind(CE->getObjectKind()); 311 BuiltinCall->setCallee(Builtin); 312 BuiltinCall->setArg(1, ChainResult.get()); 313 314 return false; 315 } 316 317 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 318 Scope::ScopeFlags NeededScopeFlags, 319 unsigned DiagID) { 320 // Scopes aren't available during instantiation. Fortunately, builtin 321 // functions cannot be template args so they cannot be formed through template 322 // instantiation. Therefore checking once during the parse is sufficient. 323 if (SemaRef.inTemplateInstantiation()) 324 return false; 325 326 Scope *S = SemaRef.getCurScope(); 327 while (S && !S->isSEHExceptScope()) 328 S = S->getParent(); 329 if (!S || !(S->getFlags() & NeededScopeFlags)) { 330 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 331 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 332 << DRE->getDecl()->getIdentifier(); 333 return true; 334 } 335 336 return false; 337 } 338 339 static inline bool isBlockPointer(Expr *Arg) { 340 return Arg->getType()->isBlockPointerType(); 341 } 342 343 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local 344 /// void*, which is a requirement of device side enqueue. 345 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { 346 const BlockPointerType *BPT = 347 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 348 ArrayRef<QualType> Params = 349 BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes(); 350 unsigned ArgCounter = 0; 351 bool IllegalParams = false; 352 // Iterate through the block parameters until either one is found that is not 353 // a local void*, or the block is valid. 354 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); 355 I != E; ++I, ++ArgCounter) { 356 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || 357 (*I)->getPointeeType().getQualifiers().getAddressSpace() != 358 LangAS::opencl_local) { 359 // Get the location of the error. If a block literal has been passed 360 // (BlockExpr) then we can point straight to the offending argument, 361 // else we just point to the variable reference. 362 SourceLocation ErrorLoc; 363 if (isa<BlockExpr>(BlockArg)) { 364 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); 365 ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart(); 366 } else if (isa<DeclRefExpr>(BlockArg)) { 367 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart(); 368 } 369 S.Diag(ErrorLoc, 370 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); 371 IllegalParams = true; 372 } 373 } 374 375 return IllegalParams; 376 } 377 378 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) { 379 if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) { 380 S.Diag(Call->getLocStart(), diag::err_opencl_requires_extension) 381 << 1 << Call->getDirectCallee() << "cl_khr_subgroups"; 382 return true; 383 } 384 return false; 385 } 386 387 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) { 388 if (checkArgCount(S, TheCall, 2)) 389 return true; 390 391 if (checkOpenCLSubgroupExt(S, TheCall)) 392 return true; 393 394 // First argument is an ndrange_t type. 395 Expr *NDRangeArg = TheCall->getArg(0); 396 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 397 S.Diag(NDRangeArg->getLocStart(), 398 diag::err_opencl_builtin_expected_type) 399 << TheCall->getDirectCallee() << "'ndrange_t'"; 400 return true; 401 } 402 403 Expr *BlockArg = TheCall->getArg(1); 404 if (!isBlockPointer(BlockArg)) { 405 S.Diag(BlockArg->getLocStart(), 406 diag::err_opencl_builtin_expected_type) 407 << TheCall->getDirectCallee() << "block"; 408 return true; 409 } 410 return checkOpenCLBlockArgs(S, BlockArg); 411 } 412 413 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the 414 /// get_kernel_work_group_size 415 /// and get_kernel_preferred_work_group_size_multiple builtin functions. 416 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { 417 if (checkArgCount(S, TheCall, 1)) 418 return true; 419 420 Expr *BlockArg = TheCall->getArg(0); 421 if (!isBlockPointer(BlockArg)) { 422 S.Diag(BlockArg->getLocStart(), 423 diag::err_opencl_builtin_expected_type) 424 << TheCall->getDirectCallee() << "block"; 425 return true; 426 } 427 return checkOpenCLBlockArgs(S, BlockArg); 428 } 429 430 /// Diagnose integer type and any valid implicit conversion to it. 431 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, 432 const QualType &IntType); 433 434 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 435 unsigned Start, unsigned End) { 436 bool IllegalParams = false; 437 for (unsigned I = Start; I <= End; ++I) 438 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), 439 S.Context.getSizeType()); 440 return IllegalParams; 441 } 442 443 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 444 /// 'local void*' parameter of passed block. 445 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 446 Expr *BlockArg, 447 unsigned NumNonVarArgs) { 448 const BlockPointerType *BPT = 449 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 450 unsigned NumBlockParams = 451 BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams(); 452 unsigned TotalNumArgs = TheCall->getNumArgs(); 453 454 // For each argument passed to the block, a corresponding uint needs to 455 // be passed to describe the size of the local memory. 456 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 457 S.Diag(TheCall->getLocStart(), 458 diag::err_opencl_enqueue_kernel_local_size_args); 459 return true; 460 } 461 462 // Check that the sizes of the local memory are specified by integers. 463 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 464 TotalNumArgs - 1); 465 } 466 467 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 468 /// overload formats specified in Table 6.13.17.1. 469 /// int enqueue_kernel(queue_t queue, 470 /// kernel_enqueue_flags_t flags, 471 /// const ndrange_t ndrange, 472 /// void (^block)(void)) 473 /// int enqueue_kernel(queue_t queue, 474 /// kernel_enqueue_flags_t flags, 475 /// const ndrange_t ndrange, 476 /// uint num_events_in_wait_list, 477 /// clk_event_t *event_wait_list, 478 /// clk_event_t *event_ret, 479 /// void (^block)(void)) 480 /// int enqueue_kernel(queue_t queue, 481 /// kernel_enqueue_flags_t flags, 482 /// const ndrange_t ndrange, 483 /// void (^block)(local void*, ...), 484 /// uint size0, ...) 485 /// int enqueue_kernel(queue_t queue, 486 /// kernel_enqueue_flags_t flags, 487 /// const ndrange_t ndrange, 488 /// uint num_events_in_wait_list, 489 /// clk_event_t *event_wait_list, 490 /// clk_event_t *event_ret, 491 /// void (^block)(local void*, ...), 492 /// uint size0, ...) 493 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 494 unsigned NumArgs = TheCall->getNumArgs(); 495 496 if (NumArgs < 4) { 497 S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args); 498 return true; 499 } 500 501 Expr *Arg0 = TheCall->getArg(0); 502 Expr *Arg1 = TheCall->getArg(1); 503 Expr *Arg2 = TheCall->getArg(2); 504 Expr *Arg3 = TheCall->getArg(3); 505 506 // First argument always needs to be a queue_t type. 507 if (!Arg0->getType()->isQueueT()) { 508 S.Diag(TheCall->getArg(0)->getLocStart(), 509 diag::err_opencl_builtin_expected_type) 510 << TheCall->getDirectCallee() << S.Context.OCLQueueTy; 511 return true; 512 } 513 514 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 515 if (!Arg1->getType()->isIntegerType()) { 516 S.Diag(TheCall->getArg(1)->getLocStart(), 517 diag::err_opencl_builtin_expected_type) 518 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)"; 519 return true; 520 } 521 522 // Third argument is always an ndrange_t type. 523 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 524 S.Diag(TheCall->getArg(2)->getLocStart(), 525 diag::err_opencl_builtin_expected_type) 526 << TheCall->getDirectCallee() << "'ndrange_t'"; 527 return true; 528 } 529 530 // With four arguments, there is only one form that the function could be 531 // called in: no events and no variable arguments. 532 if (NumArgs == 4) { 533 // check that the last argument is the right block type. 534 if (!isBlockPointer(Arg3)) { 535 S.Diag(Arg3->getLocStart(), diag::err_opencl_builtin_expected_type) 536 << TheCall->getDirectCallee() << "block"; 537 return true; 538 } 539 // we have a block type, check the prototype 540 const BlockPointerType *BPT = 541 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 542 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) { 543 S.Diag(Arg3->getLocStart(), 544 diag::err_opencl_enqueue_kernel_blocks_no_args); 545 return true; 546 } 547 return false; 548 } 549 // we can have block + varargs. 550 if (isBlockPointer(Arg3)) 551 return (checkOpenCLBlockArgs(S, Arg3) || 552 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 553 // last two cases with either exactly 7 args or 7 args and varargs. 554 if (NumArgs >= 7) { 555 // check common block argument. 556 Expr *Arg6 = TheCall->getArg(6); 557 if (!isBlockPointer(Arg6)) { 558 S.Diag(Arg6->getLocStart(), diag::err_opencl_builtin_expected_type) 559 << TheCall->getDirectCallee() << "block"; 560 return true; 561 } 562 if (checkOpenCLBlockArgs(S, Arg6)) 563 return true; 564 565 // Forth argument has to be any integer type. 566 if (!Arg3->getType()->isIntegerType()) { 567 S.Diag(TheCall->getArg(3)->getLocStart(), 568 diag::err_opencl_builtin_expected_type) 569 << TheCall->getDirectCallee() << "integer"; 570 return true; 571 } 572 // check remaining common arguments. 573 Expr *Arg4 = TheCall->getArg(4); 574 Expr *Arg5 = TheCall->getArg(5); 575 576 // Fifth argument is always passed as a pointer to clk_event_t. 577 if (!Arg4->isNullPointerConstant(S.Context, 578 Expr::NPC_ValueDependentIsNotNull) && 579 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 580 S.Diag(TheCall->getArg(4)->getLocStart(), 581 diag::err_opencl_builtin_expected_type) 582 << TheCall->getDirectCallee() 583 << S.Context.getPointerType(S.Context.OCLClkEventTy); 584 return true; 585 } 586 587 // Sixth argument is always passed as a pointer to clk_event_t. 588 if (!Arg5->isNullPointerConstant(S.Context, 589 Expr::NPC_ValueDependentIsNotNull) && 590 !(Arg5->getType()->isPointerType() && 591 Arg5->getType()->getPointeeType()->isClkEventT())) { 592 S.Diag(TheCall->getArg(5)->getLocStart(), 593 diag::err_opencl_builtin_expected_type) 594 << TheCall->getDirectCallee() 595 << S.Context.getPointerType(S.Context.OCLClkEventTy); 596 return true; 597 } 598 599 if (NumArgs == 7) 600 return false; 601 602 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 603 } 604 605 // None of the specific case has been detected, give generic error 606 S.Diag(TheCall->getLocStart(), 607 diag::err_opencl_enqueue_kernel_incorrect_args); 608 return true; 609 } 610 611 /// Returns OpenCL access qual. 612 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 613 return D->getAttr<OpenCLAccessAttr>(); 614 } 615 616 /// Returns true if pipe element type is different from the pointer. 617 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 618 const Expr *Arg0 = Call->getArg(0); 619 // First argument type should always be pipe. 620 if (!Arg0->getType()->isPipeType()) { 621 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg) 622 << Call->getDirectCallee() << Arg0->getSourceRange(); 623 return true; 624 } 625 OpenCLAccessAttr *AccessQual = 626 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 627 // Validates the access qualifier is compatible with the call. 628 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 629 // read_only and write_only, and assumed to be read_only if no qualifier is 630 // specified. 631 switch (Call->getDirectCallee()->getBuiltinID()) { 632 case Builtin::BIread_pipe: 633 case Builtin::BIreserve_read_pipe: 634 case Builtin::BIcommit_read_pipe: 635 case Builtin::BIwork_group_reserve_read_pipe: 636 case Builtin::BIsub_group_reserve_read_pipe: 637 case Builtin::BIwork_group_commit_read_pipe: 638 case Builtin::BIsub_group_commit_read_pipe: 639 if (!(!AccessQual || AccessQual->isReadOnly())) { 640 S.Diag(Arg0->getLocStart(), 641 diag::err_opencl_builtin_pipe_invalid_access_modifier) 642 << "read_only" << Arg0->getSourceRange(); 643 return true; 644 } 645 break; 646 case Builtin::BIwrite_pipe: 647 case Builtin::BIreserve_write_pipe: 648 case Builtin::BIcommit_write_pipe: 649 case Builtin::BIwork_group_reserve_write_pipe: 650 case Builtin::BIsub_group_reserve_write_pipe: 651 case Builtin::BIwork_group_commit_write_pipe: 652 case Builtin::BIsub_group_commit_write_pipe: 653 if (!(AccessQual && AccessQual->isWriteOnly())) { 654 S.Diag(Arg0->getLocStart(), 655 diag::err_opencl_builtin_pipe_invalid_access_modifier) 656 << "write_only" << Arg0->getSourceRange(); 657 return true; 658 } 659 break; 660 default: 661 break; 662 } 663 return false; 664 } 665 666 /// Returns true if pipe element type is different from the pointer. 667 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 668 const Expr *Arg0 = Call->getArg(0); 669 const Expr *ArgIdx = Call->getArg(Idx); 670 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 671 const QualType EltTy = PipeTy->getElementType(); 672 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 673 // The Idx argument should be a pointer and the type of the pointer and 674 // the type of pipe element should also be the same. 675 if (!ArgTy || 676 !S.Context.hasSameType( 677 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 678 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 679 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 680 << ArgIdx->getType() << ArgIdx->getSourceRange(); 681 return true; 682 } 683 return false; 684 } 685 686 // \brief Performs semantic analysis for the read/write_pipe call. 687 // \param S Reference to the semantic analyzer. 688 // \param Call A pointer to the builtin call. 689 // \return True if a semantic error has been found, false otherwise. 690 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 691 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 692 // functions have two forms. 693 switch (Call->getNumArgs()) { 694 case 2: 695 if (checkOpenCLPipeArg(S, Call)) 696 return true; 697 // The call with 2 arguments should be 698 // read/write_pipe(pipe T, T*). 699 // Check packet type T. 700 if (checkOpenCLPipePacketType(S, Call, 1)) 701 return true; 702 break; 703 704 case 4: { 705 if (checkOpenCLPipeArg(S, Call)) 706 return true; 707 // The call with 4 arguments should be 708 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 709 // Check reserve_id_t. 710 if (!Call->getArg(1)->getType()->isReserveIDT()) { 711 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 712 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 713 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 714 return true; 715 } 716 717 // Check the index. 718 const Expr *Arg2 = Call->getArg(2); 719 if (!Arg2->getType()->isIntegerType() && 720 !Arg2->getType()->isUnsignedIntegerType()) { 721 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 722 << Call->getDirectCallee() << S.Context.UnsignedIntTy 723 << Arg2->getType() << Arg2->getSourceRange(); 724 return true; 725 } 726 727 // Check packet type T. 728 if (checkOpenCLPipePacketType(S, Call, 3)) 729 return true; 730 } break; 731 default: 732 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num) 733 << Call->getDirectCallee() << Call->getSourceRange(); 734 return true; 735 } 736 737 return false; 738 } 739 740 // \brief Performs a semantic analysis on the {work_group_/sub_group_ 741 // /_}reserve_{read/write}_pipe 742 // \param S Reference to the semantic analyzer. 743 // \param Call The call to the builtin function to be analyzed. 744 // \return True if a semantic error was found, false otherwise. 745 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 746 if (checkArgCount(S, Call, 2)) 747 return true; 748 749 if (checkOpenCLPipeArg(S, Call)) 750 return true; 751 752 // Check the reserve size. 753 if (!Call->getArg(1)->getType()->isIntegerType() && 754 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 755 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 756 << Call->getDirectCallee() << S.Context.UnsignedIntTy 757 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 758 return true; 759 } 760 761 // Since return type of reserve_read/write_pipe built-in function is 762 // reserve_id_t, which is not defined in the builtin def file , we used int 763 // as return type and need to override the return type of these functions. 764 Call->setType(S.Context.OCLReserveIDTy); 765 766 return false; 767 } 768 769 // \brief Performs a semantic analysis on {work_group_/sub_group_ 770 // /_}commit_{read/write}_pipe 771 // \param S Reference to the semantic analyzer. 772 // \param Call The call to the builtin function to be analyzed. 773 // \return True if a semantic error was found, false otherwise. 774 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 775 if (checkArgCount(S, Call, 2)) 776 return true; 777 778 if (checkOpenCLPipeArg(S, Call)) 779 return true; 780 781 // Check reserve_id_t. 782 if (!Call->getArg(1)->getType()->isReserveIDT()) { 783 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 784 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 785 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 786 return true; 787 } 788 789 return false; 790 } 791 792 // \brief Performs a semantic analysis on the call to built-in Pipe 793 // Query Functions. 794 // \param S Reference to the semantic analyzer. 795 // \param Call The call to the builtin function to be analyzed. 796 // \return True if a semantic error was found, false otherwise. 797 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 798 if (checkArgCount(S, Call, 1)) 799 return true; 800 801 if (!Call->getArg(0)->getType()->isPipeType()) { 802 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg) 803 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 804 return true; 805 } 806 807 return false; 808 } 809 810 // \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions. 811 // \brief Performs semantic analysis for the to_global/local/private call. 812 // \param S Reference to the semantic analyzer. 813 // \param BuiltinID ID of the builtin function. 814 // \param Call A pointer to the builtin call. 815 // \return True if a semantic error has been found, false otherwise. 816 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 817 CallExpr *Call) { 818 if (Call->getNumArgs() != 1) { 819 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num) 820 << Call->getDirectCallee() << Call->getSourceRange(); 821 return true; 822 } 823 824 auto RT = Call->getArg(0)->getType(); 825 if (!RT->isPointerType() || RT->getPointeeType() 826 .getAddressSpace() == LangAS::opencl_constant) { 827 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg) 828 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 829 return true; 830 } 831 832 RT = RT->getPointeeType(); 833 auto Qual = RT.getQualifiers(); 834 switch (BuiltinID) { 835 case Builtin::BIto_global: 836 Qual.setAddressSpace(LangAS::opencl_global); 837 break; 838 case Builtin::BIto_local: 839 Qual.setAddressSpace(LangAS::opencl_local); 840 break; 841 case Builtin::BIto_private: 842 Qual.setAddressSpace(LangAS::opencl_private); 843 break; 844 default: 845 llvm_unreachable("Invalid builtin function"); 846 } 847 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 848 RT.getUnqualifiedType(), Qual))); 849 850 return false; 851 } 852 853 ExprResult 854 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 855 CallExpr *TheCall) { 856 ExprResult TheCallResult(TheCall); 857 858 // Find out if any arguments are required to be integer constant expressions. 859 unsigned ICEArguments = 0; 860 ASTContext::GetBuiltinTypeError Error; 861 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 862 if (Error != ASTContext::GE_None) 863 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 864 865 // If any arguments are required to be ICE's, check and diagnose. 866 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 867 // Skip arguments not required to be ICE's. 868 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 869 870 llvm::APSInt Result; 871 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 872 return true; 873 ICEArguments &= ~(1 << ArgNo); 874 } 875 876 switch (BuiltinID) { 877 case Builtin::BI__builtin___CFStringMakeConstantString: 878 assert(TheCall->getNumArgs() == 1 && 879 "Wrong # arguments to builtin CFStringMakeConstantString"); 880 if (CheckObjCString(TheCall->getArg(0))) 881 return ExprError(); 882 break; 883 case Builtin::BI__builtin_ms_va_start: 884 case Builtin::BI__builtin_stdarg_start: 885 case Builtin::BI__builtin_va_start: 886 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 887 return ExprError(); 888 break; 889 case Builtin::BI__va_start: { 890 switch (Context.getTargetInfo().getTriple().getArch()) { 891 case llvm::Triple::arm: 892 case llvm::Triple::thumb: 893 if (SemaBuiltinVAStartARMMicrosoft(TheCall)) 894 return ExprError(); 895 break; 896 default: 897 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 898 return ExprError(); 899 break; 900 } 901 break; 902 } 903 case Builtin::BI__builtin_isgreater: 904 case Builtin::BI__builtin_isgreaterequal: 905 case Builtin::BI__builtin_isless: 906 case Builtin::BI__builtin_islessequal: 907 case Builtin::BI__builtin_islessgreater: 908 case Builtin::BI__builtin_isunordered: 909 if (SemaBuiltinUnorderedCompare(TheCall)) 910 return ExprError(); 911 break; 912 case Builtin::BI__builtin_fpclassify: 913 if (SemaBuiltinFPClassification(TheCall, 6)) 914 return ExprError(); 915 break; 916 case Builtin::BI__builtin_isfinite: 917 case Builtin::BI__builtin_isinf: 918 case Builtin::BI__builtin_isinf_sign: 919 case Builtin::BI__builtin_isnan: 920 case Builtin::BI__builtin_isnormal: 921 if (SemaBuiltinFPClassification(TheCall, 1)) 922 return ExprError(); 923 break; 924 case Builtin::BI__builtin_shufflevector: 925 return SemaBuiltinShuffleVector(TheCall); 926 // TheCall will be freed by the smart pointer here, but that's fine, since 927 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 928 case Builtin::BI__builtin_prefetch: 929 if (SemaBuiltinPrefetch(TheCall)) 930 return ExprError(); 931 break; 932 case Builtin::BI__builtin_alloca_with_align: 933 if (SemaBuiltinAllocaWithAlign(TheCall)) 934 return ExprError(); 935 break; 936 case Builtin::BI__assume: 937 case Builtin::BI__builtin_assume: 938 if (SemaBuiltinAssume(TheCall)) 939 return ExprError(); 940 break; 941 case Builtin::BI__builtin_assume_aligned: 942 if (SemaBuiltinAssumeAligned(TheCall)) 943 return ExprError(); 944 break; 945 case Builtin::BI__builtin_object_size: 946 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 947 return ExprError(); 948 break; 949 case Builtin::BI__builtin_longjmp: 950 if (SemaBuiltinLongjmp(TheCall)) 951 return ExprError(); 952 break; 953 case Builtin::BI__builtin_setjmp: 954 if (SemaBuiltinSetjmp(TheCall)) 955 return ExprError(); 956 break; 957 case Builtin::BI_setjmp: 958 case Builtin::BI_setjmpex: 959 if (checkArgCount(*this, TheCall, 1)) 960 return true; 961 break; 962 case Builtin::BI__builtin_classify_type: 963 if (checkArgCount(*this, TheCall, 1)) return true; 964 TheCall->setType(Context.IntTy); 965 break; 966 case Builtin::BI__builtin_constant_p: 967 if (checkArgCount(*this, TheCall, 1)) return true; 968 TheCall->setType(Context.IntTy); 969 break; 970 case Builtin::BI__sync_fetch_and_add: 971 case Builtin::BI__sync_fetch_and_add_1: 972 case Builtin::BI__sync_fetch_and_add_2: 973 case Builtin::BI__sync_fetch_and_add_4: 974 case Builtin::BI__sync_fetch_and_add_8: 975 case Builtin::BI__sync_fetch_and_add_16: 976 case Builtin::BI__sync_fetch_and_sub: 977 case Builtin::BI__sync_fetch_and_sub_1: 978 case Builtin::BI__sync_fetch_and_sub_2: 979 case Builtin::BI__sync_fetch_and_sub_4: 980 case Builtin::BI__sync_fetch_and_sub_8: 981 case Builtin::BI__sync_fetch_and_sub_16: 982 case Builtin::BI__sync_fetch_and_or: 983 case Builtin::BI__sync_fetch_and_or_1: 984 case Builtin::BI__sync_fetch_and_or_2: 985 case Builtin::BI__sync_fetch_and_or_4: 986 case Builtin::BI__sync_fetch_and_or_8: 987 case Builtin::BI__sync_fetch_and_or_16: 988 case Builtin::BI__sync_fetch_and_and: 989 case Builtin::BI__sync_fetch_and_and_1: 990 case Builtin::BI__sync_fetch_and_and_2: 991 case Builtin::BI__sync_fetch_and_and_4: 992 case Builtin::BI__sync_fetch_and_and_8: 993 case Builtin::BI__sync_fetch_and_and_16: 994 case Builtin::BI__sync_fetch_and_xor: 995 case Builtin::BI__sync_fetch_and_xor_1: 996 case Builtin::BI__sync_fetch_and_xor_2: 997 case Builtin::BI__sync_fetch_and_xor_4: 998 case Builtin::BI__sync_fetch_and_xor_8: 999 case Builtin::BI__sync_fetch_and_xor_16: 1000 case Builtin::BI__sync_fetch_and_nand: 1001 case Builtin::BI__sync_fetch_and_nand_1: 1002 case Builtin::BI__sync_fetch_and_nand_2: 1003 case Builtin::BI__sync_fetch_and_nand_4: 1004 case Builtin::BI__sync_fetch_and_nand_8: 1005 case Builtin::BI__sync_fetch_and_nand_16: 1006 case Builtin::BI__sync_add_and_fetch: 1007 case Builtin::BI__sync_add_and_fetch_1: 1008 case Builtin::BI__sync_add_and_fetch_2: 1009 case Builtin::BI__sync_add_and_fetch_4: 1010 case Builtin::BI__sync_add_and_fetch_8: 1011 case Builtin::BI__sync_add_and_fetch_16: 1012 case Builtin::BI__sync_sub_and_fetch: 1013 case Builtin::BI__sync_sub_and_fetch_1: 1014 case Builtin::BI__sync_sub_and_fetch_2: 1015 case Builtin::BI__sync_sub_and_fetch_4: 1016 case Builtin::BI__sync_sub_and_fetch_8: 1017 case Builtin::BI__sync_sub_and_fetch_16: 1018 case Builtin::BI__sync_and_and_fetch: 1019 case Builtin::BI__sync_and_and_fetch_1: 1020 case Builtin::BI__sync_and_and_fetch_2: 1021 case Builtin::BI__sync_and_and_fetch_4: 1022 case Builtin::BI__sync_and_and_fetch_8: 1023 case Builtin::BI__sync_and_and_fetch_16: 1024 case Builtin::BI__sync_or_and_fetch: 1025 case Builtin::BI__sync_or_and_fetch_1: 1026 case Builtin::BI__sync_or_and_fetch_2: 1027 case Builtin::BI__sync_or_and_fetch_4: 1028 case Builtin::BI__sync_or_and_fetch_8: 1029 case Builtin::BI__sync_or_and_fetch_16: 1030 case Builtin::BI__sync_xor_and_fetch: 1031 case Builtin::BI__sync_xor_and_fetch_1: 1032 case Builtin::BI__sync_xor_and_fetch_2: 1033 case Builtin::BI__sync_xor_and_fetch_4: 1034 case Builtin::BI__sync_xor_and_fetch_8: 1035 case Builtin::BI__sync_xor_and_fetch_16: 1036 case Builtin::BI__sync_nand_and_fetch: 1037 case Builtin::BI__sync_nand_and_fetch_1: 1038 case Builtin::BI__sync_nand_and_fetch_2: 1039 case Builtin::BI__sync_nand_and_fetch_4: 1040 case Builtin::BI__sync_nand_and_fetch_8: 1041 case Builtin::BI__sync_nand_and_fetch_16: 1042 case Builtin::BI__sync_val_compare_and_swap: 1043 case Builtin::BI__sync_val_compare_and_swap_1: 1044 case Builtin::BI__sync_val_compare_and_swap_2: 1045 case Builtin::BI__sync_val_compare_and_swap_4: 1046 case Builtin::BI__sync_val_compare_and_swap_8: 1047 case Builtin::BI__sync_val_compare_and_swap_16: 1048 case Builtin::BI__sync_bool_compare_and_swap: 1049 case Builtin::BI__sync_bool_compare_and_swap_1: 1050 case Builtin::BI__sync_bool_compare_and_swap_2: 1051 case Builtin::BI__sync_bool_compare_and_swap_4: 1052 case Builtin::BI__sync_bool_compare_and_swap_8: 1053 case Builtin::BI__sync_bool_compare_and_swap_16: 1054 case Builtin::BI__sync_lock_test_and_set: 1055 case Builtin::BI__sync_lock_test_and_set_1: 1056 case Builtin::BI__sync_lock_test_and_set_2: 1057 case Builtin::BI__sync_lock_test_and_set_4: 1058 case Builtin::BI__sync_lock_test_and_set_8: 1059 case Builtin::BI__sync_lock_test_and_set_16: 1060 case Builtin::BI__sync_lock_release: 1061 case Builtin::BI__sync_lock_release_1: 1062 case Builtin::BI__sync_lock_release_2: 1063 case Builtin::BI__sync_lock_release_4: 1064 case Builtin::BI__sync_lock_release_8: 1065 case Builtin::BI__sync_lock_release_16: 1066 case Builtin::BI__sync_swap: 1067 case Builtin::BI__sync_swap_1: 1068 case Builtin::BI__sync_swap_2: 1069 case Builtin::BI__sync_swap_4: 1070 case Builtin::BI__sync_swap_8: 1071 case Builtin::BI__sync_swap_16: 1072 return SemaBuiltinAtomicOverloaded(TheCallResult); 1073 case Builtin::BI__builtin_nontemporal_load: 1074 case Builtin::BI__builtin_nontemporal_store: 1075 return SemaBuiltinNontemporalOverloaded(TheCallResult); 1076 #define BUILTIN(ID, TYPE, ATTRS) 1077 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 1078 case Builtin::BI##ID: \ 1079 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 1080 #include "clang/Basic/Builtins.def" 1081 case Builtin::BI__annotation: 1082 if (SemaBuiltinMSVCAnnotation(*this, TheCall)) 1083 return ExprError(); 1084 break; 1085 case Builtin::BI__builtin_annotation: 1086 if (SemaBuiltinAnnotation(*this, TheCall)) 1087 return ExprError(); 1088 break; 1089 case Builtin::BI__builtin_addressof: 1090 if (SemaBuiltinAddressof(*this, TheCall)) 1091 return ExprError(); 1092 break; 1093 case Builtin::BI__builtin_add_overflow: 1094 case Builtin::BI__builtin_sub_overflow: 1095 case Builtin::BI__builtin_mul_overflow: 1096 if (SemaBuiltinOverflow(*this, TheCall)) 1097 return ExprError(); 1098 break; 1099 case Builtin::BI__builtin_operator_new: 1100 case Builtin::BI__builtin_operator_delete: 1101 if (!getLangOpts().CPlusPlus) { 1102 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language) 1103 << (BuiltinID == Builtin::BI__builtin_operator_new 1104 ? "__builtin_operator_new" 1105 : "__builtin_operator_delete") 1106 << "C++"; 1107 return ExprError(); 1108 } 1109 // CodeGen assumes it can find the global new and delete to call, 1110 // so ensure that they are declared. 1111 DeclareGlobalNewDelete(); 1112 break; 1113 1114 // check secure string manipulation functions where overflows 1115 // are detectable at compile time 1116 case Builtin::BI__builtin___memcpy_chk: 1117 case Builtin::BI__builtin___memmove_chk: 1118 case Builtin::BI__builtin___memset_chk: 1119 case Builtin::BI__builtin___strlcat_chk: 1120 case Builtin::BI__builtin___strlcpy_chk: 1121 case Builtin::BI__builtin___strncat_chk: 1122 case Builtin::BI__builtin___strncpy_chk: 1123 case Builtin::BI__builtin___stpncpy_chk: 1124 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3); 1125 break; 1126 case Builtin::BI__builtin___memccpy_chk: 1127 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4); 1128 break; 1129 case Builtin::BI__builtin___snprintf_chk: 1130 case Builtin::BI__builtin___vsnprintf_chk: 1131 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3); 1132 break; 1133 case Builtin::BI__builtin_call_with_static_chain: 1134 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 1135 return ExprError(); 1136 break; 1137 case Builtin::BI__exception_code: 1138 case Builtin::BI_exception_code: 1139 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1140 diag::err_seh___except_block)) 1141 return ExprError(); 1142 break; 1143 case Builtin::BI__exception_info: 1144 case Builtin::BI_exception_info: 1145 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1146 diag::err_seh___except_filter)) 1147 return ExprError(); 1148 break; 1149 case Builtin::BI__GetExceptionInfo: 1150 if (checkArgCount(*this, TheCall, 1)) 1151 return ExprError(); 1152 1153 if (CheckCXXThrowOperand( 1154 TheCall->getLocStart(), 1155 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1156 TheCall)) 1157 return ExprError(); 1158 1159 TheCall->setType(Context.VoidPtrTy); 1160 break; 1161 // OpenCL v2.0, s6.13.16 - Pipe functions 1162 case Builtin::BIread_pipe: 1163 case Builtin::BIwrite_pipe: 1164 // Since those two functions are declared with var args, we need a semantic 1165 // check for the argument. 1166 if (SemaBuiltinRWPipe(*this, TheCall)) 1167 return ExprError(); 1168 TheCall->setType(Context.IntTy); 1169 break; 1170 case Builtin::BIreserve_read_pipe: 1171 case Builtin::BIreserve_write_pipe: 1172 case Builtin::BIwork_group_reserve_read_pipe: 1173 case Builtin::BIwork_group_reserve_write_pipe: 1174 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1175 return ExprError(); 1176 break; 1177 case Builtin::BIsub_group_reserve_read_pipe: 1178 case Builtin::BIsub_group_reserve_write_pipe: 1179 if (checkOpenCLSubgroupExt(*this, TheCall) || 1180 SemaBuiltinReserveRWPipe(*this, TheCall)) 1181 return ExprError(); 1182 break; 1183 case Builtin::BIcommit_read_pipe: 1184 case Builtin::BIcommit_write_pipe: 1185 case Builtin::BIwork_group_commit_read_pipe: 1186 case Builtin::BIwork_group_commit_write_pipe: 1187 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1188 return ExprError(); 1189 break; 1190 case Builtin::BIsub_group_commit_read_pipe: 1191 case Builtin::BIsub_group_commit_write_pipe: 1192 if (checkOpenCLSubgroupExt(*this, TheCall) || 1193 SemaBuiltinCommitRWPipe(*this, TheCall)) 1194 return ExprError(); 1195 break; 1196 case Builtin::BIget_pipe_num_packets: 1197 case Builtin::BIget_pipe_max_packets: 1198 if (SemaBuiltinPipePackets(*this, TheCall)) 1199 return ExprError(); 1200 TheCall->setType(Context.UnsignedIntTy); 1201 break; 1202 case Builtin::BIto_global: 1203 case Builtin::BIto_local: 1204 case Builtin::BIto_private: 1205 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1206 return ExprError(); 1207 break; 1208 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1209 case Builtin::BIenqueue_kernel: 1210 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1211 return ExprError(); 1212 break; 1213 case Builtin::BIget_kernel_work_group_size: 1214 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1215 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1216 return ExprError(); 1217 break; 1218 break; 1219 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 1220 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 1221 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) 1222 return ExprError(); 1223 break; 1224 case Builtin::BI__builtin_os_log_format: 1225 case Builtin::BI__builtin_os_log_format_buffer_size: 1226 if (SemaBuiltinOSLogFormat(TheCall)) 1227 return ExprError(); 1228 break; 1229 } 1230 1231 // Since the target specific builtins for each arch overlap, only check those 1232 // of the arch we are compiling for. 1233 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 1234 switch (Context.getTargetInfo().getTriple().getArch()) { 1235 case llvm::Triple::arm: 1236 case llvm::Triple::armeb: 1237 case llvm::Triple::thumb: 1238 case llvm::Triple::thumbeb: 1239 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall)) 1240 return ExprError(); 1241 break; 1242 case llvm::Triple::aarch64: 1243 case llvm::Triple::aarch64_be: 1244 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall)) 1245 return ExprError(); 1246 break; 1247 case llvm::Triple::mips: 1248 case llvm::Triple::mipsel: 1249 case llvm::Triple::mips64: 1250 case llvm::Triple::mips64el: 1251 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall)) 1252 return ExprError(); 1253 break; 1254 case llvm::Triple::systemz: 1255 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall)) 1256 return ExprError(); 1257 break; 1258 case llvm::Triple::x86: 1259 case llvm::Triple::x86_64: 1260 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall)) 1261 return ExprError(); 1262 break; 1263 case llvm::Triple::ppc: 1264 case llvm::Triple::ppc64: 1265 case llvm::Triple::ppc64le: 1266 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall)) 1267 return ExprError(); 1268 break; 1269 default: 1270 break; 1271 } 1272 } 1273 1274 return TheCallResult; 1275 } 1276 1277 // Get the valid immediate range for the specified NEON type code. 1278 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 1279 NeonTypeFlags Type(t); 1280 int IsQuad = ForceQuad ? true : Type.isQuad(); 1281 switch (Type.getEltType()) { 1282 case NeonTypeFlags::Int8: 1283 case NeonTypeFlags::Poly8: 1284 return shift ? 7 : (8 << IsQuad) - 1; 1285 case NeonTypeFlags::Int16: 1286 case NeonTypeFlags::Poly16: 1287 return shift ? 15 : (4 << IsQuad) - 1; 1288 case NeonTypeFlags::Int32: 1289 return shift ? 31 : (2 << IsQuad) - 1; 1290 case NeonTypeFlags::Int64: 1291 case NeonTypeFlags::Poly64: 1292 return shift ? 63 : (1 << IsQuad) - 1; 1293 case NeonTypeFlags::Poly128: 1294 return shift ? 127 : (1 << IsQuad) - 1; 1295 case NeonTypeFlags::Float16: 1296 assert(!shift && "cannot shift float types!"); 1297 return (4 << IsQuad) - 1; 1298 case NeonTypeFlags::Float32: 1299 assert(!shift && "cannot shift float types!"); 1300 return (2 << IsQuad) - 1; 1301 case NeonTypeFlags::Float64: 1302 assert(!shift && "cannot shift float types!"); 1303 return (1 << IsQuad) - 1; 1304 } 1305 llvm_unreachable("Invalid NeonTypeFlag!"); 1306 } 1307 1308 /// getNeonEltType - Return the QualType corresponding to the elements of 1309 /// the vector type specified by the NeonTypeFlags. This is used to check 1310 /// the pointer arguments for Neon load/store intrinsics. 1311 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 1312 bool IsPolyUnsigned, bool IsInt64Long) { 1313 switch (Flags.getEltType()) { 1314 case NeonTypeFlags::Int8: 1315 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 1316 case NeonTypeFlags::Int16: 1317 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 1318 case NeonTypeFlags::Int32: 1319 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 1320 case NeonTypeFlags::Int64: 1321 if (IsInt64Long) 1322 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 1323 else 1324 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 1325 : Context.LongLongTy; 1326 case NeonTypeFlags::Poly8: 1327 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 1328 case NeonTypeFlags::Poly16: 1329 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 1330 case NeonTypeFlags::Poly64: 1331 if (IsInt64Long) 1332 return Context.UnsignedLongTy; 1333 else 1334 return Context.UnsignedLongLongTy; 1335 case NeonTypeFlags::Poly128: 1336 break; 1337 case NeonTypeFlags::Float16: 1338 return Context.HalfTy; 1339 case NeonTypeFlags::Float32: 1340 return Context.FloatTy; 1341 case NeonTypeFlags::Float64: 1342 return Context.DoubleTy; 1343 } 1344 llvm_unreachable("Invalid NeonTypeFlag!"); 1345 } 1346 1347 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1348 llvm::APSInt Result; 1349 uint64_t mask = 0; 1350 unsigned TV = 0; 1351 int PtrArgNum = -1; 1352 bool HasConstPtr = false; 1353 switch (BuiltinID) { 1354 #define GET_NEON_OVERLOAD_CHECK 1355 #include "clang/Basic/arm_neon.inc" 1356 #include "clang/Basic/arm_fp16.inc" 1357 #undef GET_NEON_OVERLOAD_CHECK 1358 } 1359 1360 // For NEON intrinsics which are overloaded on vector element type, validate 1361 // the immediate which specifies which variant to emit. 1362 unsigned ImmArg = TheCall->getNumArgs()-1; 1363 if (mask) { 1364 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 1365 return true; 1366 1367 TV = Result.getLimitedValue(64); 1368 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 1369 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code) 1370 << TheCall->getArg(ImmArg)->getSourceRange(); 1371 } 1372 1373 if (PtrArgNum >= 0) { 1374 // Check that pointer arguments have the specified type. 1375 Expr *Arg = TheCall->getArg(PtrArgNum); 1376 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 1377 Arg = ICE->getSubExpr(); 1378 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 1379 QualType RHSTy = RHS.get()->getType(); 1380 1381 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 1382 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 1383 Arch == llvm::Triple::aarch64_be; 1384 bool IsInt64Long = 1385 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong; 1386 QualType EltTy = 1387 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 1388 if (HasConstPtr) 1389 EltTy = EltTy.withConst(); 1390 QualType LHSTy = Context.getPointerType(EltTy); 1391 AssignConvertType ConvTy; 1392 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 1393 if (RHS.isInvalid()) 1394 return true; 1395 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy, 1396 RHS.get(), AA_Assigning)) 1397 return true; 1398 } 1399 1400 // For NEON intrinsics which take an immediate value as part of the 1401 // instruction, range check them here. 1402 unsigned i = 0, l = 0, u = 0; 1403 switch (BuiltinID) { 1404 default: 1405 return false; 1406 #define GET_NEON_IMMEDIATE_CHECK 1407 #include "clang/Basic/arm_neon.inc" 1408 #include "clang/Basic/arm_fp16.inc" 1409 #undef GET_NEON_IMMEDIATE_CHECK 1410 } 1411 1412 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1413 } 1414 1415 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 1416 unsigned MaxWidth) { 1417 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 1418 BuiltinID == ARM::BI__builtin_arm_ldaex || 1419 BuiltinID == ARM::BI__builtin_arm_strex || 1420 BuiltinID == ARM::BI__builtin_arm_stlex || 1421 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1422 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1423 BuiltinID == AArch64::BI__builtin_arm_strex || 1424 BuiltinID == AArch64::BI__builtin_arm_stlex) && 1425 "unexpected ARM builtin"); 1426 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 1427 BuiltinID == ARM::BI__builtin_arm_ldaex || 1428 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1429 BuiltinID == AArch64::BI__builtin_arm_ldaex; 1430 1431 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 1432 1433 // Ensure that we have the proper number of arguments. 1434 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 1435 return true; 1436 1437 // Inspect the pointer argument of the atomic builtin. This should always be 1438 // a pointer type, whose element is an integral scalar or pointer type. 1439 // Because it is a pointer type, we don't have to worry about any implicit 1440 // casts here. 1441 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 1442 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 1443 if (PointerArgRes.isInvalid()) 1444 return true; 1445 PointerArg = PointerArgRes.get(); 1446 1447 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 1448 if (!pointerType) { 1449 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 1450 << PointerArg->getType() << PointerArg->getSourceRange(); 1451 return true; 1452 } 1453 1454 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 1455 // task is to insert the appropriate casts into the AST. First work out just 1456 // what the appropriate type is. 1457 QualType ValType = pointerType->getPointeeType(); 1458 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 1459 if (IsLdrex) 1460 AddrType.addConst(); 1461 1462 // Issue a warning if the cast is dodgy. 1463 CastKind CastNeeded = CK_NoOp; 1464 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 1465 CastNeeded = CK_BitCast; 1466 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers) 1467 << PointerArg->getType() 1468 << Context.getPointerType(AddrType) 1469 << AA_Passing << PointerArg->getSourceRange(); 1470 } 1471 1472 // Finally, do the cast and replace the argument with the corrected version. 1473 AddrType = Context.getPointerType(AddrType); 1474 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 1475 if (PointerArgRes.isInvalid()) 1476 return true; 1477 PointerArg = PointerArgRes.get(); 1478 1479 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 1480 1481 // In general, we allow ints, floats and pointers to be loaded and stored. 1482 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 1483 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 1484 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 1485 << PointerArg->getType() << PointerArg->getSourceRange(); 1486 return true; 1487 } 1488 1489 // But ARM doesn't have instructions to deal with 128-bit versions. 1490 if (Context.getTypeSize(ValType) > MaxWidth) { 1491 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 1492 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size) 1493 << PointerArg->getType() << PointerArg->getSourceRange(); 1494 return true; 1495 } 1496 1497 switch (ValType.getObjCLifetime()) { 1498 case Qualifiers::OCL_None: 1499 case Qualifiers::OCL_ExplicitNone: 1500 // okay 1501 break; 1502 1503 case Qualifiers::OCL_Weak: 1504 case Qualifiers::OCL_Strong: 1505 case Qualifiers::OCL_Autoreleasing: 1506 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 1507 << ValType << PointerArg->getSourceRange(); 1508 return true; 1509 } 1510 1511 if (IsLdrex) { 1512 TheCall->setType(ValType); 1513 return false; 1514 } 1515 1516 // Initialize the argument to be stored. 1517 ExprResult ValArg = TheCall->getArg(0); 1518 InitializedEntity Entity = InitializedEntity::InitializeParameter( 1519 Context, ValType, /*consume*/ false); 1520 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 1521 if (ValArg.isInvalid()) 1522 return true; 1523 TheCall->setArg(0, ValArg.get()); 1524 1525 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 1526 // but the custom checker bypasses all default analysis. 1527 TheCall->setType(Context.IntTy); 1528 return false; 1529 } 1530 1531 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1532 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 1533 BuiltinID == ARM::BI__builtin_arm_ldaex || 1534 BuiltinID == ARM::BI__builtin_arm_strex || 1535 BuiltinID == ARM::BI__builtin_arm_stlex) { 1536 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 1537 } 1538 1539 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 1540 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1541 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 1542 } 1543 1544 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 1545 BuiltinID == ARM::BI__builtin_arm_wsr64) 1546 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 1547 1548 if (BuiltinID == ARM::BI__builtin_arm_rsr || 1549 BuiltinID == ARM::BI__builtin_arm_rsrp || 1550 BuiltinID == ARM::BI__builtin_arm_wsr || 1551 BuiltinID == ARM::BI__builtin_arm_wsrp) 1552 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1553 1554 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1555 return true; 1556 1557 // For intrinsics which take an immediate value as part of the instruction, 1558 // range check them here. 1559 // FIXME: VFP Intrinsics should error if VFP not present. 1560 switch (BuiltinID) { 1561 default: return false; 1562 case ARM::BI__builtin_arm_ssat: 1563 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32); 1564 case ARM::BI__builtin_arm_usat: 1565 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31); 1566 case ARM::BI__builtin_arm_ssat16: 1567 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 1568 case ARM::BI__builtin_arm_usat16: 1569 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 1570 case ARM::BI__builtin_arm_vcvtr_f: 1571 case ARM::BI__builtin_arm_vcvtr_d: 1572 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 1573 case ARM::BI__builtin_arm_dmb: 1574 case ARM::BI__builtin_arm_dsb: 1575 case ARM::BI__builtin_arm_isb: 1576 case ARM::BI__builtin_arm_dbg: 1577 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15); 1578 } 1579 } 1580 1581 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, 1582 CallExpr *TheCall) { 1583 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 1584 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1585 BuiltinID == AArch64::BI__builtin_arm_strex || 1586 BuiltinID == AArch64::BI__builtin_arm_stlex) { 1587 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 1588 } 1589 1590 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 1591 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1592 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 1593 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 1594 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 1595 } 1596 1597 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 1598 BuiltinID == AArch64::BI__builtin_arm_wsr64) 1599 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1600 1601 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 1602 BuiltinID == AArch64::BI__builtin_arm_rsrp || 1603 BuiltinID == AArch64::BI__builtin_arm_wsr || 1604 BuiltinID == AArch64::BI__builtin_arm_wsrp) 1605 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1606 1607 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1608 return true; 1609 1610 // For intrinsics which take an immediate value as part of the instruction, 1611 // range check them here. 1612 unsigned i = 0, l = 0, u = 0; 1613 switch (BuiltinID) { 1614 default: return false; 1615 case AArch64::BI__builtin_arm_dmb: 1616 case AArch64::BI__builtin_arm_dsb: 1617 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 1618 } 1619 1620 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1621 } 1622 1623 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the 1624 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 1625 // ordering for DSP is unspecified. MSA is ordered by the data format used 1626 // by the underlying instruction i.e., df/m, df/n and then by size. 1627 // 1628 // FIXME: The size tests here should instead be tablegen'd along with the 1629 // definitions from include/clang/Basic/BuiltinsMips.def. 1630 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 1631 // be too. 1632 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1633 unsigned i = 0, l = 0, u = 0, m = 0; 1634 switch (BuiltinID) { 1635 default: return false; 1636 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 1637 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 1638 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 1639 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 1640 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 1641 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 1642 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 1643 // MSA instrinsics. Instructions (which the intrinsics maps to) which use the 1644 // df/m field. 1645 // These intrinsics take an unsigned 3 bit immediate. 1646 case Mips::BI__builtin_msa_bclri_b: 1647 case Mips::BI__builtin_msa_bnegi_b: 1648 case Mips::BI__builtin_msa_bseti_b: 1649 case Mips::BI__builtin_msa_sat_s_b: 1650 case Mips::BI__builtin_msa_sat_u_b: 1651 case Mips::BI__builtin_msa_slli_b: 1652 case Mips::BI__builtin_msa_srai_b: 1653 case Mips::BI__builtin_msa_srari_b: 1654 case Mips::BI__builtin_msa_srli_b: 1655 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 1656 case Mips::BI__builtin_msa_binsli_b: 1657 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 1658 // These intrinsics take an unsigned 4 bit immediate. 1659 case Mips::BI__builtin_msa_bclri_h: 1660 case Mips::BI__builtin_msa_bnegi_h: 1661 case Mips::BI__builtin_msa_bseti_h: 1662 case Mips::BI__builtin_msa_sat_s_h: 1663 case Mips::BI__builtin_msa_sat_u_h: 1664 case Mips::BI__builtin_msa_slli_h: 1665 case Mips::BI__builtin_msa_srai_h: 1666 case Mips::BI__builtin_msa_srari_h: 1667 case Mips::BI__builtin_msa_srli_h: 1668 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 1669 case Mips::BI__builtin_msa_binsli_h: 1670 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 1671 // These intrinsics take an unsigned 5 bit immedate. 1672 // The first block of intrinsics actually have an unsigned 5 bit field, 1673 // not a df/n field. 1674 case Mips::BI__builtin_msa_clei_u_b: 1675 case Mips::BI__builtin_msa_clei_u_h: 1676 case Mips::BI__builtin_msa_clei_u_w: 1677 case Mips::BI__builtin_msa_clei_u_d: 1678 case Mips::BI__builtin_msa_clti_u_b: 1679 case Mips::BI__builtin_msa_clti_u_h: 1680 case Mips::BI__builtin_msa_clti_u_w: 1681 case Mips::BI__builtin_msa_clti_u_d: 1682 case Mips::BI__builtin_msa_maxi_u_b: 1683 case Mips::BI__builtin_msa_maxi_u_h: 1684 case Mips::BI__builtin_msa_maxi_u_w: 1685 case Mips::BI__builtin_msa_maxi_u_d: 1686 case Mips::BI__builtin_msa_mini_u_b: 1687 case Mips::BI__builtin_msa_mini_u_h: 1688 case Mips::BI__builtin_msa_mini_u_w: 1689 case Mips::BI__builtin_msa_mini_u_d: 1690 case Mips::BI__builtin_msa_addvi_b: 1691 case Mips::BI__builtin_msa_addvi_h: 1692 case Mips::BI__builtin_msa_addvi_w: 1693 case Mips::BI__builtin_msa_addvi_d: 1694 case Mips::BI__builtin_msa_bclri_w: 1695 case Mips::BI__builtin_msa_bnegi_w: 1696 case Mips::BI__builtin_msa_bseti_w: 1697 case Mips::BI__builtin_msa_sat_s_w: 1698 case Mips::BI__builtin_msa_sat_u_w: 1699 case Mips::BI__builtin_msa_slli_w: 1700 case Mips::BI__builtin_msa_srai_w: 1701 case Mips::BI__builtin_msa_srari_w: 1702 case Mips::BI__builtin_msa_srli_w: 1703 case Mips::BI__builtin_msa_srlri_w: 1704 case Mips::BI__builtin_msa_subvi_b: 1705 case Mips::BI__builtin_msa_subvi_h: 1706 case Mips::BI__builtin_msa_subvi_w: 1707 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 1708 case Mips::BI__builtin_msa_binsli_w: 1709 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 1710 // These intrinsics take an unsigned 6 bit immediate. 1711 case Mips::BI__builtin_msa_bclri_d: 1712 case Mips::BI__builtin_msa_bnegi_d: 1713 case Mips::BI__builtin_msa_bseti_d: 1714 case Mips::BI__builtin_msa_sat_s_d: 1715 case Mips::BI__builtin_msa_sat_u_d: 1716 case Mips::BI__builtin_msa_slli_d: 1717 case Mips::BI__builtin_msa_srai_d: 1718 case Mips::BI__builtin_msa_srari_d: 1719 case Mips::BI__builtin_msa_srli_d: 1720 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 1721 case Mips::BI__builtin_msa_binsli_d: 1722 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 1723 // These intrinsics take a signed 5 bit immediate. 1724 case Mips::BI__builtin_msa_ceqi_b: 1725 case Mips::BI__builtin_msa_ceqi_h: 1726 case Mips::BI__builtin_msa_ceqi_w: 1727 case Mips::BI__builtin_msa_ceqi_d: 1728 case Mips::BI__builtin_msa_clti_s_b: 1729 case Mips::BI__builtin_msa_clti_s_h: 1730 case Mips::BI__builtin_msa_clti_s_w: 1731 case Mips::BI__builtin_msa_clti_s_d: 1732 case Mips::BI__builtin_msa_clei_s_b: 1733 case Mips::BI__builtin_msa_clei_s_h: 1734 case Mips::BI__builtin_msa_clei_s_w: 1735 case Mips::BI__builtin_msa_clei_s_d: 1736 case Mips::BI__builtin_msa_maxi_s_b: 1737 case Mips::BI__builtin_msa_maxi_s_h: 1738 case Mips::BI__builtin_msa_maxi_s_w: 1739 case Mips::BI__builtin_msa_maxi_s_d: 1740 case Mips::BI__builtin_msa_mini_s_b: 1741 case Mips::BI__builtin_msa_mini_s_h: 1742 case Mips::BI__builtin_msa_mini_s_w: 1743 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 1744 // These intrinsics take an unsigned 8 bit immediate. 1745 case Mips::BI__builtin_msa_andi_b: 1746 case Mips::BI__builtin_msa_nori_b: 1747 case Mips::BI__builtin_msa_ori_b: 1748 case Mips::BI__builtin_msa_shf_b: 1749 case Mips::BI__builtin_msa_shf_h: 1750 case Mips::BI__builtin_msa_shf_w: 1751 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 1752 case Mips::BI__builtin_msa_bseli_b: 1753 case Mips::BI__builtin_msa_bmnzi_b: 1754 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 1755 // df/n format 1756 // These intrinsics take an unsigned 4 bit immediate. 1757 case Mips::BI__builtin_msa_copy_s_b: 1758 case Mips::BI__builtin_msa_copy_u_b: 1759 case Mips::BI__builtin_msa_insve_b: 1760 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 1761 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 1762 // These intrinsics take an unsigned 3 bit immediate. 1763 case Mips::BI__builtin_msa_copy_s_h: 1764 case Mips::BI__builtin_msa_copy_u_h: 1765 case Mips::BI__builtin_msa_insve_h: 1766 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 1767 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 1768 // These intrinsics take an unsigned 2 bit immediate. 1769 case Mips::BI__builtin_msa_copy_s_w: 1770 case Mips::BI__builtin_msa_copy_u_w: 1771 case Mips::BI__builtin_msa_insve_w: 1772 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 1773 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 1774 // These intrinsics take an unsigned 1 bit immediate. 1775 case Mips::BI__builtin_msa_copy_s_d: 1776 case Mips::BI__builtin_msa_copy_u_d: 1777 case Mips::BI__builtin_msa_insve_d: 1778 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 1779 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 1780 // Memory offsets and immediate loads. 1781 // These intrinsics take a signed 10 bit immediate. 1782 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 1783 case Mips::BI__builtin_msa_ldi_h: 1784 case Mips::BI__builtin_msa_ldi_w: 1785 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 1786 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break; 1787 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break; 1788 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break; 1789 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break; 1790 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break; 1791 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break; 1792 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break; 1793 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break; 1794 } 1795 1796 if (!m) 1797 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 1798 1799 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 1800 SemaBuiltinConstantArgMultiple(TheCall, i, m); 1801 } 1802 1803 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1804 unsigned i = 0, l = 0, u = 0; 1805 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde || 1806 BuiltinID == PPC::BI__builtin_divdeu || 1807 BuiltinID == PPC::BI__builtin_bpermd; 1808 bool IsTarget64Bit = Context.getTargetInfo() 1809 .getTypeWidth(Context 1810 .getTargetInfo() 1811 .getIntPtrType()) == 64; 1812 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe || 1813 BuiltinID == PPC::BI__builtin_divweu || 1814 BuiltinID == PPC::BI__builtin_divde || 1815 BuiltinID == PPC::BI__builtin_divdeu; 1816 1817 if (Is64BitBltin && !IsTarget64Bit) 1818 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt) 1819 << TheCall->getSourceRange(); 1820 1821 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) || 1822 (BuiltinID == PPC::BI__builtin_bpermd && 1823 !Context.getTargetInfo().hasFeature("bpermd"))) 1824 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7) 1825 << TheCall->getSourceRange(); 1826 1827 switch (BuiltinID) { 1828 default: return false; 1829 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 1830 case PPC::BI__builtin_altivec_crypto_vshasigmad: 1831 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1832 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 1833 case PPC::BI__builtin_tbegin: 1834 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 1835 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 1836 case PPC::BI__builtin_tabortwc: 1837 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 1838 case PPC::BI__builtin_tabortwci: 1839 case PPC::BI__builtin_tabortdci: 1840 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 1841 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 1842 case PPC::BI__builtin_vsx_xxpermdi: 1843 case PPC::BI__builtin_vsx_xxsldwi: 1844 return SemaBuiltinVSX(TheCall); 1845 } 1846 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 1847 } 1848 1849 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 1850 CallExpr *TheCall) { 1851 if (BuiltinID == SystemZ::BI__builtin_tabort) { 1852 Expr *Arg = TheCall->getArg(0); 1853 llvm::APSInt AbortCode(32); 1854 if (Arg->isIntegerConstantExpr(AbortCode, Context) && 1855 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256) 1856 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code) 1857 << Arg->getSourceRange(); 1858 } 1859 1860 // For intrinsics which take an immediate value as part of the instruction, 1861 // range check them here. 1862 unsigned i = 0, l = 0, u = 0; 1863 switch (BuiltinID) { 1864 default: return false; 1865 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 1866 case SystemZ::BI__builtin_s390_verimb: 1867 case SystemZ::BI__builtin_s390_verimh: 1868 case SystemZ::BI__builtin_s390_verimf: 1869 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 1870 case SystemZ::BI__builtin_s390_vfaeb: 1871 case SystemZ::BI__builtin_s390_vfaeh: 1872 case SystemZ::BI__builtin_s390_vfaef: 1873 case SystemZ::BI__builtin_s390_vfaebs: 1874 case SystemZ::BI__builtin_s390_vfaehs: 1875 case SystemZ::BI__builtin_s390_vfaefs: 1876 case SystemZ::BI__builtin_s390_vfaezb: 1877 case SystemZ::BI__builtin_s390_vfaezh: 1878 case SystemZ::BI__builtin_s390_vfaezf: 1879 case SystemZ::BI__builtin_s390_vfaezbs: 1880 case SystemZ::BI__builtin_s390_vfaezhs: 1881 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 1882 case SystemZ::BI__builtin_s390_vfisb: 1883 case SystemZ::BI__builtin_s390_vfidb: 1884 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 1885 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 1886 case SystemZ::BI__builtin_s390_vftcisb: 1887 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 1888 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 1889 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 1890 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 1891 case SystemZ::BI__builtin_s390_vstrcb: 1892 case SystemZ::BI__builtin_s390_vstrch: 1893 case SystemZ::BI__builtin_s390_vstrcf: 1894 case SystemZ::BI__builtin_s390_vstrczb: 1895 case SystemZ::BI__builtin_s390_vstrczh: 1896 case SystemZ::BI__builtin_s390_vstrczf: 1897 case SystemZ::BI__builtin_s390_vstrcbs: 1898 case SystemZ::BI__builtin_s390_vstrchs: 1899 case SystemZ::BI__builtin_s390_vstrcfs: 1900 case SystemZ::BI__builtin_s390_vstrczbs: 1901 case SystemZ::BI__builtin_s390_vstrczhs: 1902 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 1903 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 1904 case SystemZ::BI__builtin_s390_vfminsb: 1905 case SystemZ::BI__builtin_s390_vfmaxsb: 1906 case SystemZ::BI__builtin_s390_vfmindb: 1907 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 1908 } 1909 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 1910 } 1911 1912 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 1913 /// This checks that the target supports __builtin_cpu_supports and 1914 /// that the string argument is constant and valid. 1915 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) { 1916 Expr *Arg = TheCall->getArg(0); 1917 1918 // Check if the argument is a string literal. 1919 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 1920 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal) 1921 << Arg->getSourceRange(); 1922 1923 // Check the contents of the string. 1924 StringRef Feature = 1925 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 1926 if (!S.Context.getTargetInfo().validateCpuSupports(Feature)) 1927 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports) 1928 << Arg->getSourceRange(); 1929 return false; 1930 } 1931 1932 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 1933 /// This checks that the target supports __builtin_cpu_is and 1934 /// that the string argument is constant and valid. 1935 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) { 1936 Expr *Arg = TheCall->getArg(0); 1937 1938 // Check if the argument is a string literal. 1939 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 1940 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal) 1941 << Arg->getSourceRange(); 1942 1943 // Check the contents of the string. 1944 StringRef Feature = 1945 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 1946 if (!S.Context.getTargetInfo().validateCpuIs(Feature)) 1947 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_is) 1948 << Arg->getSourceRange(); 1949 return false; 1950 } 1951 1952 // Check if the rounding mode is legal. 1953 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 1954 // Indicates if this instruction has rounding control or just SAE. 1955 bool HasRC = false; 1956 1957 unsigned ArgNum = 0; 1958 switch (BuiltinID) { 1959 default: 1960 return false; 1961 case X86::BI__builtin_ia32_vcvttsd2si32: 1962 case X86::BI__builtin_ia32_vcvttsd2si64: 1963 case X86::BI__builtin_ia32_vcvttsd2usi32: 1964 case X86::BI__builtin_ia32_vcvttsd2usi64: 1965 case X86::BI__builtin_ia32_vcvttss2si32: 1966 case X86::BI__builtin_ia32_vcvttss2si64: 1967 case X86::BI__builtin_ia32_vcvttss2usi32: 1968 case X86::BI__builtin_ia32_vcvttss2usi64: 1969 ArgNum = 1; 1970 break; 1971 case X86::BI__builtin_ia32_cvtps2pd512_mask: 1972 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 1973 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 1974 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 1975 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 1976 case X86::BI__builtin_ia32_cvttps2dq512_mask: 1977 case X86::BI__builtin_ia32_cvttps2qq512_mask: 1978 case X86::BI__builtin_ia32_cvttps2udq512_mask: 1979 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 1980 case X86::BI__builtin_ia32_exp2pd_mask: 1981 case X86::BI__builtin_ia32_exp2ps_mask: 1982 case X86::BI__builtin_ia32_getexppd512_mask: 1983 case X86::BI__builtin_ia32_getexpps512_mask: 1984 case X86::BI__builtin_ia32_rcp28pd_mask: 1985 case X86::BI__builtin_ia32_rcp28ps_mask: 1986 case X86::BI__builtin_ia32_rsqrt28pd_mask: 1987 case X86::BI__builtin_ia32_rsqrt28ps_mask: 1988 case X86::BI__builtin_ia32_vcomisd: 1989 case X86::BI__builtin_ia32_vcomiss: 1990 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 1991 ArgNum = 3; 1992 break; 1993 case X86::BI__builtin_ia32_cmppd512_mask: 1994 case X86::BI__builtin_ia32_cmpps512_mask: 1995 case X86::BI__builtin_ia32_cmpsd_mask: 1996 case X86::BI__builtin_ia32_cmpss_mask: 1997 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 1998 case X86::BI__builtin_ia32_getexpsd128_round_mask: 1999 case X86::BI__builtin_ia32_getexpss128_round_mask: 2000 case X86::BI__builtin_ia32_maxpd512_mask: 2001 case X86::BI__builtin_ia32_maxps512_mask: 2002 case X86::BI__builtin_ia32_maxsd_round_mask: 2003 case X86::BI__builtin_ia32_maxss_round_mask: 2004 case X86::BI__builtin_ia32_minpd512_mask: 2005 case X86::BI__builtin_ia32_minps512_mask: 2006 case X86::BI__builtin_ia32_minsd_round_mask: 2007 case X86::BI__builtin_ia32_minss_round_mask: 2008 case X86::BI__builtin_ia32_rcp28sd_round_mask: 2009 case X86::BI__builtin_ia32_rcp28ss_round_mask: 2010 case X86::BI__builtin_ia32_reducepd512_mask: 2011 case X86::BI__builtin_ia32_reduceps512_mask: 2012 case X86::BI__builtin_ia32_rndscalepd_mask: 2013 case X86::BI__builtin_ia32_rndscaleps_mask: 2014 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 2015 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 2016 ArgNum = 4; 2017 break; 2018 case X86::BI__builtin_ia32_fixupimmpd512_mask: 2019 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 2020 case X86::BI__builtin_ia32_fixupimmps512_mask: 2021 case X86::BI__builtin_ia32_fixupimmps512_maskz: 2022 case X86::BI__builtin_ia32_fixupimmsd_mask: 2023 case X86::BI__builtin_ia32_fixupimmsd_maskz: 2024 case X86::BI__builtin_ia32_fixupimmss_mask: 2025 case X86::BI__builtin_ia32_fixupimmss_maskz: 2026 case X86::BI__builtin_ia32_rangepd512_mask: 2027 case X86::BI__builtin_ia32_rangeps512_mask: 2028 case X86::BI__builtin_ia32_rangesd128_round_mask: 2029 case X86::BI__builtin_ia32_rangess128_round_mask: 2030 case X86::BI__builtin_ia32_reducesd_mask: 2031 case X86::BI__builtin_ia32_reducess_mask: 2032 case X86::BI__builtin_ia32_rndscalesd_round_mask: 2033 case X86::BI__builtin_ia32_rndscaless_round_mask: 2034 ArgNum = 5; 2035 break; 2036 case X86::BI__builtin_ia32_vcvtsd2si64: 2037 case X86::BI__builtin_ia32_vcvtsd2si32: 2038 case X86::BI__builtin_ia32_vcvtsd2usi32: 2039 case X86::BI__builtin_ia32_vcvtsd2usi64: 2040 case X86::BI__builtin_ia32_vcvtss2si32: 2041 case X86::BI__builtin_ia32_vcvtss2si64: 2042 case X86::BI__builtin_ia32_vcvtss2usi32: 2043 case X86::BI__builtin_ia32_vcvtss2usi64: 2044 ArgNum = 1; 2045 HasRC = true; 2046 break; 2047 case X86::BI__builtin_ia32_cvtsi2sd64: 2048 case X86::BI__builtin_ia32_cvtsi2ss32: 2049 case X86::BI__builtin_ia32_cvtsi2ss64: 2050 case X86::BI__builtin_ia32_cvtusi2sd64: 2051 case X86::BI__builtin_ia32_cvtusi2ss32: 2052 case X86::BI__builtin_ia32_cvtusi2ss64: 2053 ArgNum = 2; 2054 HasRC = true; 2055 break; 2056 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 2057 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 2058 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 2059 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 2060 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 2061 case X86::BI__builtin_ia32_cvtps2qq512_mask: 2062 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 2063 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 2064 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 2065 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 2066 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 2067 case X86::BI__builtin_ia32_sqrtpd512_mask: 2068 case X86::BI__builtin_ia32_sqrtps512_mask: 2069 ArgNum = 3; 2070 HasRC = true; 2071 break; 2072 case X86::BI__builtin_ia32_addpd512_mask: 2073 case X86::BI__builtin_ia32_addps512_mask: 2074 case X86::BI__builtin_ia32_divpd512_mask: 2075 case X86::BI__builtin_ia32_divps512_mask: 2076 case X86::BI__builtin_ia32_mulpd512_mask: 2077 case X86::BI__builtin_ia32_mulps512_mask: 2078 case X86::BI__builtin_ia32_subpd512_mask: 2079 case X86::BI__builtin_ia32_subps512_mask: 2080 case X86::BI__builtin_ia32_addss_round_mask: 2081 case X86::BI__builtin_ia32_addsd_round_mask: 2082 case X86::BI__builtin_ia32_divss_round_mask: 2083 case X86::BI__builtin_ia32_divsd_round_mask: 2084 case X86::BI__builtin_ia32_mulss_round_mask: 2085 case X86::BI__builtin_ia32_mulsd_round_mask: 2086 case X86::BI__builtin_ia32_subss_round_mask: 2087 case X86::BI__builtin_ia32_subsd_round_mask: 2088 case X86::BI__builtin_ia32_scalefpd512_mask: 2089 case X86::BI__builtin_ia32_scalefps512_mask: 2090 case X86::BI__builtin_ia32_scalefsd_round_mask: 2091 case X86::BI__builtin_ia32_scalefss_round_mask: 2092 case X86::BI__builtin_ia32_getmantpd512_mask: 2093 case X86::BI__builtin_ia32_getmantps512_mask: 2094 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 2095 case X86::BI__builtin_ia32_sqrtsd_round_mask: 2096 case X86::BI__builtin_ia32_sqrtss_round_mask: 2097 case X86::BI__builtin_ia32_vfmaddpd512_mask: 2098 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 2099 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 2100 case X86::BI__builtin_ia32_vfmaddps512_mask: 2101 case X86::BI__builtin_ia32_vfmaddps512_mask3: 2102 case X86::BI__builtin_ia32_vfmaddps512_maskz: 2103 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 2104 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 2105 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 2106 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 2107 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 2108 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 2109 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 2110 case X86::BI__builtin_ia32_vfmsubps512_mask3: 2111 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 2112 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 2113 case X86::BI__builtin_ia32_vfnmaddpd512_mask: 2114 case X86::BI__builtin_ia32_vfnmaddps512_mask: 2115 case X86::BI__builtin_ia32_vfnmsubpd512_mask: 2116 case X86::BI__builtin_ia32_vfnmsubpd512_mask3: 2117 case X86::BI__builtin_ia32_vfnmsubps512_mask: 2118 case X86::BI__builtin_ia32_vfnmsubps512_mask3: 2119 case X86::BI__builtin_ia32_vfmaddsd3_mask: 2120 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 2121 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 2122 case X86::BI__builtin_ia32_vfmaddss3_mask: 2123 case X86::BI__builtin_ia32_vfmaddss3_maskz: 2124 case X86::BI__builtin_ia32_vfmaddss3_mask3: 2125 ArgNum = 4; 2126 HasRC = true; 2127 break; 2128 case X86::BI__builtin_ia32_getmantsd_round_mask: 2129 case X86::BI__builtin_ia32_getmantss_round_mask: 2130 ArgNum = 5; 2131 HasRC = true; 2132 break; 2133 } 2134 2135 llvm::APSInt Result; 2136 2137 // We can't check the value of a dependent argument. 2138 Expr *Arg = TheCall->getArg(ArgNum); 2139 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2140 return false; 2141 2142 // Check constant-ness first. 2143 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 2144 return true; 2145 2146 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 2147 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 2148 // combined with ROUND_NO_EXC. 2149 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 2150 Result == 8/*ROUND_NO_EXC*/ || 2151 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 2152 return false; 2153 2154 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding) 2155 << Arg->getSourceRange(); 2156 } 2157 2158 // Check if the gather/scatter scale is legal. 2159 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 2160 CallExpr *TheCall) { 2161 unsigned ArgNum = 0; 2162 switch (BuiltinID) { 2163 default: 2164 return false; 2165 case X86::BI__builtin_ia32_gatherpfdpd: 2166 case X86::BI__builtin_ia32_gatherpfdps: 2167 case X86::BI__builtin_ia32_gatherpfqpd: 2168 case X86::BI__builtin_ia32_gatherpfqps: 2169 case X86::BI__builtin_ia32_scatterpfdpd: 2170 case X86::BI__builtin_ia32_scatterpfdps: 2171 case X86::BI__builtin_ia32_scatterpfqpd: 2172 case X86::BI__builtin_ia32_scatterpfqps: 2173 ArgNum = 3; 2174 break; 2175 case X86::BI__builtin_ia32_gatherd_pd: 2176 case X86::BI__builtin_ia32_gatherd_pd256: 2177 case X86::BI__builtin_ia32_gatherq_pd: 2178 case X86::BI__builtin_ia32_gatherq_pd256: 2179 case X86::BI__builtin_ia32_gatherd_ps: 2180 case X86::BI__builtin_ia32_gatherd_ps256: 2181 case X86::BI__builtin_ia32_gatherq_ps: 2182 case X86::BI__builtin_ia32_gatherq_ps256: 2183 case X86::BI__builtin_ia32_gatherd_q: 2184 case X86::BI__builtin_ia32_gatherd_q256: 2185 case X86::BI__builtin_ia32_gatherq_q: 2186 case X86::BI__builtin_ia32_gatherq_q256: 2187 case X86::BI__builtin_ia32_gatherd_d: 2188 case X86::BI__builtin_ia32_gatherd_d256: 2189 case X86::BI__builtin_ia32_gatherq_d: 2190 case X86::BI__builtin_ia32_gatherq_d256: 2191 case X86::BI__builtin_ia32_gather3div2df: 2192 case X86::BI__builtin_ia32_gather3div2di: 2193 case X86::BI__builtin_ia32_gather3div4df: 2194 case X86::BI__builtin_ia32_gather3div4di: 2195 case X86::BI__builtin_ia32_gather3div4sf: 2196 case X86::BI__builtin_ia32_gather3div4si: 2197 case X86::BI__builtin_ia32_gather3div8sf: 2198 case X86::BI__builtin_ia32_gather3div8si: 2199 case X86::BI__builtin_ia32_gather3siv2df: 2200 case X86::BI__builtin_ia32_gather3siv2di: 2201 case X86::BI__builtin_ia32_gather3siv4df: 2202 case X86::BI__builtin_ia32_gather3siv4di: 2203 case X86::BI__builtin_ia32_gather3siv4sf: 2204 case X86::BI__builtin_ia32_gather3siv4si: 2205 case X86::BI__builtin_ia32_gather3siv8sf: 2206 case X86::BI__builtin_ia32_gather3siv8si: 2207 case X86::BI__builtin_ia32_gathersiv8df: 2208 case X86::BI__builtin_ia32_gathersiv16sf: 2209 case X86::BI__builtin_ia32_gatherdiv8df: 2210 case X86::BI__builtin_ia32_gatherdiv16sf: 2211 case X86::BI__builtin_ia32_gathersiv8di: 2212 case X86::BI__builtin_ia32_gathersiv16si: 2213 case X86::BI__builtin_ia32_gatherdiv8di: 2214 case X86::BI__builtin_ia32_gatherdiv16si: 2215 case X86::BI__builtin_ia32_scatterdiv2df: 2216 case X86::BI__builtin_ia32_scatterdiv2di: 2217 case X86::BI__builtin_ia32_scatterdiv4df: 2218 case X86::BI__builtin_ia32_scatterdiv4di: 2219 case X86::BI__builtin_ia32_scatterdiv4sf: 2220 case X86::BI__builtin_ia32_scatterdiv4si: 2221 case X86::BI__builtin_ia32_scatterdiv8sf: 2222 case X86::BI__builtin_ia32_scatterdiv8si: 2223 case X86::BI__builtin_ia32_scattersiv2df: 2224 case X86::BI__builtin_ia32_scattersiv2di: 2225 case X86::BI__builtin_ia32_scattersiv4df: 2226 case X86::BI__builtin_ia32_scattersiv4di: 2227 case X86::BI__builtin_ia32_scattersiv4sf: 2228 case X86::BI__builtin_ia32_scattersiv4si: 2229 case X86::BI__builtin_ia32_scattersiv8sf: 2230 case X86::BI__builtin_ia32_scattersiv8si: 2231 case X86::BI__builtin_ia32_scattersiv8df: 2232 case X86::BI__builtin_ia32_scattersiv16sf: 2233 case X86::BI__builtin_ia32_scatterdiv8df: 2234 case X86::BI__builtin_ia32_scatterdiv16sf: 2235 case X86::BI__builtin_ia32_scattersiv8di: 2236 case X86::BI__builtin_ia32_scattersiv16si: 2237 case X86::BI__builtin_ia32_scatterdiv8di: 2238 case X86::BI__builtin_ia32_scatterdiv16si: 2239 ArgNum = 4; 2240 break; 2241 } 2242 2243 llvm::APSInt Result; 2244 2245 // We can't check the value of a dependent argument. 2246 Expr *Arg = TheCall->getArg(ArgNum); 2247 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2248 return false; 2249 2250 // Check constant-ness first. 2251 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 2252 return true; 2253 2254 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 2255 return false; 2256 2257 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale) 2258 << Arg->getSourceRange(); 2259 } 2260 2261 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2262 if (BuiltinID == X86::BI__builtin_cpu_supports) 2263 return SemaBuiltinCpuSupports(*this, TheCall); 2264 2265 if (BuiltinID == X86::BI__builtin_cpu_is) 2266 return SemaBuiltinCpuIs(*this, TheCall); 2267 2268 // If the intrinsic has rounding or SAE make sure its valid. 2269 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 2270 return true; 2271 2272 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 2273 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 2274 return true; 2275 2276 // For intrinsics which take an immediate value as part of the instruction, 2277 // range check them here. 2278 int i = 0, l = 0, u = 0; 2279 switch (BuiltinID) { 2280 default: 2281 return false; 2282 case X86::BI_mm_prefetch: 2283 i = 1; l = 0; u = 7; 2284 break; 2285 case X86::BI__builtin_ia32_sha1rnds4: 2286 case X86::BI__builtin_ia32_shuf_f32x4_256_mask: 2287 case X86::BI__builtin_ia32_shuf_f64x2_256_mask: 2288 case X86::BI__builtin_ia32_shuf_i32x4_256_mask: 2289 case X86::BI__builtin_ia32_shuf_i64x2_256_mask: 2290 i = 2; l = 0; u = 3; 2291 break; 2292 case X86::BI__builtin_ia32_vpermil2pd: 2293 case X86::BI__builtin_ia32_vpermil2pd256: 2294 case X86::BI__builtin_ia32_vpermil2ps: 2295 case X86::BI__builtin_ia32_vpermil2ps256: 2296 i = 3; l = 0; u = 3; 2297 break; 2298 case X86::BI__builtin_ia32_cmpb128_mask: 2299 case X86::BI__builtin_ia32_cmpw128_mask: 2300 case X86::BI__builtin_ia32_cmpd128_mask: 2301 case X86::BI__builtin_ia32_cmpq128_mask: 2302 case X86::BI__builtin_ia32_cmpb256_mask: 2303 case X86::BI__builtin_ia32_cmpw256_mask: 2304 case X86::BI__builtin_ia32_cmpd256_mask: 2305 case X86::BI__builtin_ia32_cmpq256_mask: 2306 case X86::BI__builtin_ia32_cmpb512_mask: 2307 case X86::BI__builtin_ia32_cmpw512_mask: 2308 case X86::BI__builtin_ia32_cmpd512_mask: 2309 case X86::BI__builtin_ia32_cmpq512_mask: 2310 case X86::BI__builtin_ia32_ucmpb128_mask: 2311 case X86::BI__builtin_ia32_ucmpw128_mask: 2312 case X86::BI__builtin_ia32_ucmpd128_mask: 2313 case X86::BI__builtin_ia32_ucmpq128_mask: 2314 case X86::BI__builtin_ia32_ucmpb256_mask: 2315 case X86::BI__builtin_ia32_ucmpw256_mask: 2316 case X86::BI__builtin_ia32_ucmpd256_mask: 2317 case X86::BI__builtin_ia32_ucmpq256_mask: 2318 case X86::BI__builtin_ia32_ucmpb512_mask: 2319 case X86::BI__builtin_ia32_ucmpw512_mask: 2320 case X86::BI__builtin_ia32_ucmpd512_mask: 2321 case X86::BI__builtin_ia32_ucmpq512_mask: 2322 case X86::BI__builtin_ia32_vpcomub: 2323 case X86::BI__builtin_ia32_vpcomuw: 2324 case X86::BI__builtin_ia32_vpcomud: 2325 case X86::BI__builtin_ia32_vpcomuq: 2326 case X86::BI__builtin_ia32_vpcomb: 2327 case X86::BI__builtin_ia32_vpcomw: 2328 case X86::BI__builtin_ia32_vpcomd: 2329 case X86::BI__builtin_ia32_vpcomq: 2330 i = 2; l = 0; u = 7; 2331 break; 2332 case X86::BI__builtin_ia32_roundps: 2333 case X86::BI__builtin_ia32_roundpd: 2334 case X86::BI__builtin_ia32_roundps256: 2335 case X86::BI__builtin_ia32_roundpd256: 2336 i = 1; l = 0; u = 15; 2337 break; 2338 case X86::BI__builtin_ia32_roundss: 2339 case X86::BI__builtin_ia32_roundsd: 2340 case X86::BI__builtin_ia32_rangepd128_mask: 2341 case X86::BI__builtin_ia32_rangepd256_mask: 2342 case X86::BI__builtin_ia32_rangepd512_mask: 2343 case X86::BI__builtin_ia32_rangeps128_mask: 2344 case X86::BI__builtin_ia32_rangeps256_mask: 2345 case X86::BI__builtin_ia32_rangeps512_mask: 2346 case X86::BI__builtin_ia32_getmantsd_round_mask: 2347 case X86::BI__builtin_ia32_getmantss_round_mask: 2348 i = 2; l = 0; u = 15; 2349 break; 2350 case X86::BI__builtin_ia32_cmpps: 2351 case X86::BI__builtin_ia32_cmpss: 2352 case X86::BI__builtin_ia32_cmppd: 2353 case X86::BI__builtin_ia32_cmpsd: 2354 case X86::BI__builtin_ia32_cmpps256: 2355 case X86::BI__builtin_ia32_cmppd256: 2356 case X86::BI__builtin_ia32_cmpps128_mask: 2357 case X86::BI__builtin_ia32_cmppd128_mask: 2358 case X86::BI__builtin_ia32_cmpps256_mask: 2359 case X86::BI__builtin_ia32_cmppd256_mask: 2360 case X86::BI__builtin_ia32_cmpps512_mask: 2361 case X86::BI__builtin_ia32_cmppd512_mask: 2362 case X86::BI__builtin_ia32_cmpsd_mask: 2363 case X86::BI__builtin_ia32_cmpss_mask: 2364 i = 2; l = 0; u = 31; 2365 break; 2366 case X86::BI__builtin_ia32_vcvtps2ph: 2367 case X86::BI__builtin_ia32_vcvtps2ph_mask: 2368 case X86::BI__builtin_ia32_vcvtps2ph256: 2369 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 2370 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 2371 case X86::BI__builtin_ia32_rndscaleps_128_mask: 2372 case X86::BI__builtin_ia32_rndscalepd_128_mask: 2373 case X86::BI__builtin_ia32_rndscaleps_256_mask: 2374 case X86::BI__builtin_ia32_rndscalepd_256_mask: 2375 case X86::BI__builtin_ia32_rndscaleps_mask: 2376 case X86::BI__builtin_ia32_rndscalepd_mask: 2377 case X86::BI__builtin_ia32_reducepd128_mask: 2378 case X86::BI__builtin_ia32_reducepd256_mask: 2379 case X86::BI__builtin_ia32_reducepd512_mask: 2380 case X86::BI__builtin_ia32_reduceps128_mask: 2381 case X86::BI__builtin_ia32_reduceps256_mask: 2382 case X86::BI__builtin_ia32_reduceps512_mask: 2383 case X86::BI__builtin_ia32_prold512_mask: 2384 case X86::BI__builtin_ia32_prolq512_mask: 2385 case X86::BI__builtin_ia32_prold128_mask: 2386 case X86::BI__builtin_ia32_prold256_mask: 2387 case X86::BI__builtin_ia32_prolq128_mask: 2388 case X86::BI__builtin_ia32_prolq256_mask: 2389 case X86::BI__builtin_ia32_prord128_mask: 2390 case X86::BI__builtin_ia32_prord256_mask: 2391 case X86::BI__builtin_ia32_prorq128_mask: 2392 case X86::BI__builtin_ia32_prorq256_mask: 2393 case X86::BI__builtin_ia32_fpclasspd128_mask: 2394 case X86::BI__builtin_ia32_fpclasspd256_mask: 2395 case X86::BI__builtin_ia32_fpclassps128_mask: 2396 case X86::BI__builtin_ia32_fpclassps256_mask: 2397 case X86::BI__builtin_ia32_fpclassps512_mask: 2398 case X86::BI__builtin_ia32_fpclasspd512_mask: 2399 case X86::BI__builtin_ia32_fpclasssd_mask: 2400 case X86::BI__builtin_ia32_fpclassss_mask: 2401 i = 1; l = 0; u = 255; 2402 break; 2403 case X86::BI__builtin_ia32_palignr128: 2404 case X86::BI__builtin_ia32_palignr256: 2405 case X86::BI__builtin_ia32_palignr512_mask: 2406 case X86::BI__builtin_ia32_vcomisd: 2407 case X86::BI__builtin_ia32_vcomiss: 2408 case X86::BI__builtin_ia32_shuf_f32x4_mask: 2409 case X86::BI__builtin_ia32_shuf_f64x2_mask: 2410 case X86::BI__builtin_ia32_shuf_i32x4_mask: 2411 case X86::BI__builtin_ia32_shuf_i64x2_mask: 2412 case X86::BI__builtin_ia32_dbpsadbw128_mask: 2413 case X86::BI__builtin_ia32_dbpsadbw256_mask: 2414 case X86::BI__builtin_ia32_dbpsadbw512_mask: 2415 case X86::BI__builtin_ia32_vpshldd128_mask: 2416 case X86::BI__builtin_ia32_vpshldd256_mask: 2417 case X86::BI__builtin_ia32_vpshldd512_mask: 2418 case X86::BI__builtin_ia32_vpshldq128_mask: 2419 case X86::BI__builtin_ia32_vpshldq256_mask: 2420 case X86::BI__builtin_ia32_vpshldq512_mask: 2421 case X86::BI__builtin_ia32_vpshldw128_mask: 2422 case X86::BI__builtin_ia32_vpshldw256_mask: 2423 case X86::BI__builtin_ia32_vpshldw512_mask: 2424 case X86::BI__builtin_ia32_vpshrdd128_mask: 2425 case X86::BI__builtin_ia32_vpshrdd256_mask: 2426 case X86::BI__builtin_ia32_vpshrdd512_mask: 2427 case X86::BI__builtin_ia32_vpshrdq128_mask: 2428 case X86::BI__builtin_ia32_vpshrdq256_mask: 2429 case X86::BI__builtin_ia32_vpshrdq512_mask: 2430 case X86::BI__builtin_ia32_vpshrdw128_mask: 2431 case X86::BI__builtin_ia32_vpshrdw256_mask: 2432 case X86::BI__builtin_ia32_vpshrdw512_mask: 2433 i = 2; l = 0; u = 255; 2434 break; 2435 case X86::BI__builtin_ia32_fixupimmpd512_mask: 2436 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 2437 case X86::BI__builtin_ia32_fixupimmps512_mask: 2438 case X86::BI__builtin_ia32_fixupimmps512_maskz: 2439 case X86::BI__builtin_ia32_fixupimmsd_mask: 2440 case X86::BI__builtin_ia32_fixupimmsd_maskz: 2441 case X86::BI__builtin_ia32_fixupimmss_mask: 2442 case X86::BI__builtin_ia32_fixupimmss_maskz: 2443 case X86::BI__builtin_ia32_fixupimmpd128_mask: 2444 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 2445 case X86::BI__builtin_ia32_fixupimmpd256_mask: 2446 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 2447 case X86::BI__builtin_ia32_fixupimmps128_mask: 2448 case X86::BI__builtin_ia32_fixupimmps128_maskz: 2449 case X86::BI__builtin_ia32_fixupimmps256_mask: 2450 case X86::BI__builtin_ia32_fixupimmps256_maskz: 2451 case X86::BI__builtin_ia32_pternlogd512_mask: 2452 case X86::BI__builtin_ia32_pternlogd512_maskz: 2453 case X86::BI__builtin_ia32_pternlogq512_mask: 2454 case X86::BI__builtin_ia32_pternlogq512_maskz: 2455 case X86::BI__builtin_ia32_pternlogd128_mask: 2456 case X86::BI__builtin_ia32_pternlogd128_maskz: 2457 case X86::BI__builtin_ia32_pternlogd256_mask: 2458 case X86::BI__builtin_ia32_pternlogd256_maskz: 2459 case X86::BI__builtin_ia32_pternlogq128_mask: 2460 case X86::BI__builtin_ia32_pternlogq128_maskz: 2461 case X86::BI__builtin_ia32_pternlogq256_mask: 2462 case X86::BI__builtin_ia32_pternlogq256_maskz: 2463 i = 3; l = 0; u = 255; 2464 break; 2465 case X86::BI__builtin_ia32_gatherpfdpd: 2466 case X86::BI__builtin_ia32_gatherpfdps: 2467 case X86::BI__builtin_ia32_gatherpfqpd: 2468 case X86::BI__builtin_ia32_gatherpfqps: 2469 case X86::BI__builtin_ia32_scatterpfdpd: 2470 case X86::BI__builtin_ia32_scatterpfdps: 2471 case X86::BI__builtin_ia32_scatterpfqpd: 2472 case X86::BI__builtin_ia32_scatterpfqps: 2473 i = 4; l = 2; u = 3; 2474 break; 2475 case X86::BI__builtin_ia32_rndscalesd_round_mask: 2476 case X86::BI__builtin_ia32_rndscaless_round_mask: 2477 i = 4; l = 0; u = 255; 2478 break; 2479 } 2480 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 2481 } 2482 2483 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 2484 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 2485 /// Returns true when the format fits the function and the FormatStringInfo has 2486 /// been populated. 2487 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 2488 FormatStringInfo *FSI) { 2489 FSI->HasVAListArg = Format->getFirstArg() == 0; 2490 FSI->FormatIdx = Format->getFormatIdx() - 1; 2491 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 2492 2493 // The way the format attribute works in GCC, the implicit this argument 2494 // of member functions is counted. However, it doesn't appear in our own 2495 // lists, so decrement format_idx in that case. 2496 if (IsCXXMember) { 2497 if(FSI->FormatIdx == 0) 2498 return false; 2499 --FSI->FormatIdx; 2500 if (FSI->FirstDataArg != 0) 2501 --FSI->FirstDataArg; 2502 } 2503 return true; 2504 } 2505 2506 /// Checks if a the given expression evaluates to null. 2507 /// 2508 /// \brief Returns true if the value evaluates to null. 2509 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 2510 // If the expression has non-null type, it doesn't evaluate to null. 2511 if (auto nullability 2512 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 2513 if (*nullability == NullabilityKind::NonNull) 2514 return false; 2515 } 2516 2517 // As a special case, transparent unions initialized with zero are 2518 // considered null for the purposes of the nonnull attribute. 2519 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 2520 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 2521 if (const CompoundLiteralExpr *CLE = 2522 dyn_cast<CompoundLiteralExpr>(Expr)) 2523 if (const InitListExpr *ILE = 2524 dyn_cast<InitListExpr>(CLE->getInitializer())) 2525 Expr = ILE->getInit(0); 2526 } 2527 2528 bool Result; 2529 return (!Expr->isValueDependent() && 2530 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 2531 !Result); 2532 } 2533 2534 static void CheckNonNullArgument(Sema &S, 2535 const Expr *ArgExpr, 2536 SourceLocation CallSiteLoc) { 2537 if (CheckNonNullExpr(S, ArgExpr)) 2538 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 2539 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange()); 2540 } 2541 2542 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 2543 FormatStringInfo FSI; 2544 if ((GetFormatStringType(Format) == FST_NSString) && 2545 getFormatStringInfo(Format, false, &FSI)) { 2546 Idx = FSI.FormatIdx; 2547 return true; 2548 } 2549 return false; 2550 } 2551 2552 /// \brief Diagnose use of %s directive in an NSString which is being passed 2553 /// as formatting string to formatting method. 2554 static void 2555 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 2556 const NamedDecl *FDecl, 2557 Expr **Args, 2558 unsigned NumArgs) { 2559 unsigned Idx = 0; 2560 bool Format = false; 2561 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 2562 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 2563 Idx = 2; 2564 Format = true; 2565 } 2566 else 2567 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 2568 if (S.GetFormatNSStringIdx(I, Idx)) { 2569 Format = true; 2570 break; 2571 } 2572 } 2573 if (!Format || NumArgs <= Idx) 2574 return; 2575 const Expr *FormatExpr = Args[Idx]; 2576 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 2577 FormatExpr = CSCE->getSubExpr(); 2578 const StringLiteral *FormatString; 2579 if (const ObjCStringLiteral *OSL = 2580 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 2581 FormatString = OSL->getString(); 2582 else 2583 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 2584 if (!FormatString) 2585 return; 2586 if (S.FormatStringHasSArg(FormatString)) { 2587 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 2588 << "%s" << 1 << 1; 2589 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 2590 << FDecl->getDeclName(); 2591 } 2592 } 2593 2594 /// Determine whether the given type has a non-null nullability annotation. 2595 static bool isNonNullType(ASTContext &ctx, QualType type) { 2596 if (auto nullability = type->getNullability(ctx)) 2597 return *nullability == NullabilityKind::NonNull; 2598 2599 return false; 2600 } 2601 2602 static void CheckNonNullArguments(Sema &S, 2603 const NamedDecl *FDecl, 2604 const FunctionProtoType *Proto, 2605 ArrayRef<const Expr *> Args, 2606 SourceLocation CallSiteLoc) { 2607 assert((FDecl || Proto) && "Need a function declaration or prototype"); 2608 2609 // Check the attributes attached to the method/function itself. 2610 llvm::SmallBitVector NonNullArgs; 2611 if (FDecl) { 2612 // Handle the nonnull attribute on the function/method declaration itself. 2613 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 2614 if (!NonNull->args_size()) { 2615 // Easy case: all pointer arguments are nonnull. 2616 for (const auto *Arg : Args) 2617 if (S.isValidPointerAttrType(Arg->getType())) 2618 CheckNonNullArgument(S, Arg, CallSiteLoc); 2619 return; 2620 } 2621 2622 for (unsigned Val : NonNull->args()) { 2623 if (Val >= Args.size()) 2624 continue; 2625 if (NonNullArgs.empty()) 2626 NonNullArgs.resize(Args.size()); 2627 NonNullArgs.set(Val); 2628 } 2629 } 2630 } 2631 2632 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 2633 // Handle the nonnull attribute on the parameters of the 2634 // function/method. 2635 ArrayRef<ParmVarDecl*> parms; 2636 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 2637 parms = FD->parameters(); 2638 else 2639 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 2640 2641 unsigned ParamIndex = 0; 2642 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 2643 I != E; ++I, ++ParamIndex) { 2644 const ParmVarDecl *PVD = *I; 2645 if (PVD->hasAttr<NonNullAttr>() || 2646 isNonNullType(S.Context, PVD->getType())) { 2647 if (NonNullArgs.empty()) 2648 NonNullArgs.resize(Args.size()); 2649 2650 NonNullArgs.set(ParamIndex); 2651 } 2652 } 2653 } else { 2654 // If we have a non-function, non-method declaration but no 2655 // function prototype, try to dig out the function prototype. 2656 if (!Proto) { 2657 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 2658 QualType type = VD->getType().getNonReferenceType(); 2659 if (auto pointerType = type->getAs<PointerType>()) 2660 type = pointerType->getPointeeType(); 2661 else if (auto blockType = type->getAs<BlockPointerType>()) 2662 type = blockType->getPointeeType(); 2663 // FIXME: data member pointers? 2664 2665 // Dig out the function prototype, if there is one. 2666 Proto = type->getAs<FunctionProtoType>(); 2667 } 2668 } 2669 2670 // Fill in non-null argument information from the nullability 2671 // information on the parameter types (if we have them). 2672 if (Proto) { 2673 unsigned Index = 0; 2674 for (auto paramType : Proto->getParamTypes()) { 2675 if (isNonNullType(S.Context, paramType)) { 2676 if (NonNullArgs.empty()) 2677 NonNullArgs.resize(Args.size()); 2678 2679 NonNullArgs.set(Index); 2680 } 2681 2682 ++Index; 2683 } 2684 } 2685 } 2686 2687 // Check for non-null arguments. 2688 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 2689 ArgIndex != ArgIndexEnd; ++ArgIndex) { 2690 if (NonNullArgs[ArgIndex]) 2691 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 2692 } 2693 } 2694 2695 /// Handles the checks for format strings, non-POD arguments to vararg 2696 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 2697 /// attributes. 2698 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 2699 const Expr *ThisArg, ArrayRef<const Expr *> Args, 2700 bool IsMemberFunction, SourceLocation Loc, 2701 SourceRange Range, VariadicCallType CallType) { 2702 // FIXME: We should check as much as we can in the template definition. 2703 if (CurContext->isDependentContext()) 2704 return; 2705 2706 // Printf and scanf checking. 2707 llvm::SmallBitVector CheckedVarArgs; 2708 if (FDecl) { 2709 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 2710 // Only create vector if there are format attributes. 2711 CheckedVarArgs.resize(Args.size()); 2712 2713 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 2714 CheckedVarArgs); 2715 } 2716 } 2717 2718 // Refuse POD arguments that weren't caught by the format string 2719 // checks above. 2720 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 2721 if (CallType != VariadicDoesNotApply && 2722 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 2723 unsigned NumParams = Proto ? Proto->getNumParams() 2724 : FDecl && isa<FunctionDecl>(FDecl) 2725 ? cast<FunctionDecl>(FDecl)->getNumParams() 2726 : FDecl && isa<ObjCMethodDecl>(FDecl) 2727 ? cast<ObjCMethodDecl>(FDecl)->param_size() 2728 : 0; 2729 2730 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 2731 // Args[ArgIdx] can be null in malformed code. 2732 if (const Expr *Arg = Args[ArgIdx]) { 2733 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 2734 checkVariadicArgument(Arg, CallType); 2735 } 2736 } 2737 } 2738 2739 if (FDecl || Proto) { 2740 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 2741 2742 // Type safety checking. 2743 if (FDecl) { 2744 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 2745 CheckArgumentWithTypeTag(I, Args, Loc); 2746 } 2747 } 2748 2749 if (FD) 2750 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 2751 } 2752 2753 /// CheckConstructorCall - Check a constructor call for correctness and safety 2754 /// properties not enforced by the C type system. 2755 void Sema::CheckConstructorCall(FunctionDecl *FDecl, 2756 ArrayRef<const Expr *> Args, 2757 const FunctionProtoType *Proto, 2758 SourceLocation Loc) { 2759 VariadicCallType CallType = 2760 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 2761 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 2762 Loc, SourceRange(), CallType); 2763 } 2764 2765 /// CheckFunctionCall - Check a direct function call for various correctness 2766 /// and safety properties not strictly enforced by the C type system. 2767 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 2768 const FunctionProtoType *Proto) { 2769 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 2770 isa<CXXMethodDecl>(FDecl); 2771 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 2772 IsMemberOperatorCall; 2773 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 2774 TheCall->getCallee()); 2775 Expr** Args = TheCall->getArgs(); 2776 unsigned NumArgs = TheCall->getNumArgs(); 2777 2778 Expr *ImplicitThis = nullptr; 2779 if (IsMemberOperatorCall) { 2780 // If this is a call to a member operator, hide the first argument 2781 // from checkCall. 2782 // FIXME: Our choice of AST representation here is less than ideal. 2783 ImplicitThis = Args[0]; 2784 ++Args; 2785 --NumArgs; 2786 } else if (IsMemberFunction) 2787 ImplicitThis = 2788 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 2789 2790 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 2791 IsMemberFunction, TheCall->getRParenLoc(), 2792 TheCall->getCallee()->getSourceRange(), CallType); 2793 2794 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 2795 // None of the checks below are needed for functions that don't have 2796 // simple names (e.g., C++ conversion functions). 2797 if (!FnInfo) 2798 return false; 2799 2800 CheckAbsoluteValueFunction(TheCall, FDecl); 2801 CheckMaxUnsignedZero(TheCall, FDecl); 2802 2803 if (getLangOpts().ObjC1) 2804 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 2805 2806 unsigned CMId = FDecl->getMemoryFunctionKind(); 2807 if (CMId == 0) 2808 return false; 2809 2810 // Handle memory setting and copying functions. 2811 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 2812 CheckStrlcpycatArguments(TheCall, FnInfo); 2813 else if (CMId == Builtin::BIstrncat) 2814 CheckStrncatArguments(TheCall, FnInfo); 2815 else 2816 CheckMemaccessArguments(TheCall, CMId, FnInfo); 2817 2818 return false; 2819 } 2820 2821 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 2822 ArrayRef<const Expr *> Args) { 2823 VariadicCallType CallType = 2824 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 2825 2826 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 2827 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 2828 CallType); 2829 2830 return false; 2831 } 2832 2833 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 2834 const FunctionProtoType *Proto) { 2835 QualType Ty; 2836 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 2837 Ty = V->getType().getNonReferenceType(); 2838 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 2839 Ty = F->getType().getNonReferenceType(); 2840 else 2841 return false; 2842 2843 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 2844 !Ty->isFunctionProtoType()) 2845 return false; 2846 2847 VariadicCallType CallType; 2848 if (!Proto || !Proto->isVariadic()) { 2849 CallType = VariadicDoesNotApply; 2850 } else if (Ty->isBlockPointerType()) { 2851 CallType = VariadicBlock; 2852 } else { // Ty->isFunctionPointerType() 2853 CallType = VariadicFunction; 2854 } 2855 2856 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 2857 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 2858 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 2859 TheCall->getCallee()->getSourceRange(), CallType); 2860 2861 return false; 2862 } 2863 2864 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 2865 /// such as function pointers returned from functions. 2866 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 2867 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 2868 TheCall->getCallee()); 2869 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 2870 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 2871 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 2872 TheCall->getCallee()->getSourceRange(), CallType); 2873 2874 return false; 2875 } 2876 2877 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 2878 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 2879 return false; 2880 2881 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 2882 switch (Op) { 2883 case AtomicExpr::AO__c11_atomic_init: 2884 case AtomicExpr::AO__opencl_atomic_init: 2885 llvm_unreachable("There is no ordering argument for an init"); 2886 2887 case AtomicExpr::AO__c11_atomic_load: 2888 case AtomicExpr::AO__opencl_atomic_load: 2889 case AtomicExpr::AO__atomic_load_n: 2890 case AtomicExpr::AO__atomic_load: 2891 return OrderingCABI != llvm::AtomicOrderingCABI::release && 2892 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 2893 2894 case AtomicExpr::AO__c11_atomic_store: 2895 case AtomicExpr::AO__opencl_atomic_store: 2896 case AtomicExpr::AO__atomic_store: 2897 case AtomicExpr::AO__atomic_store_n: 2898 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 2899 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 2900 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 2901 2902 default: 2903 return true; 2904 } 2905 } 2906 2907 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 2908 AtomicExpr::AtomicOp Op) { 2909 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 2910 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 2911 2912 // All the non-OpenCL operations take one of the following forms. 2913 // The OpenCL operations take the __c11 forms with one extra argument for 2914 // synchronization scope. 2915 enum { 2916 // C __c11_atomic_init(A *, C) 2917 Init, 2918 2919 // C __c11_atomic_load(A *, int) 2920 Load, 2921 2922 // void __atomic_load(A *, CP, int) 2923 LoadCopy, 2924 2925 // void __atomic_store(A *, CP, int) 2926 Copy, 2927 2928 // C __c11_atomic_add(A *, M, int) 2929 Arithmetic, 2930 2931 // C __atomic_exchange_n(A *, CP, int) 2932 Xchg, 2933 2934 // void __atomic_exchange(A *, C *, CP, int) 2935 GNUXchg, 2936 2937 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 2938 C11CmpXchg, 2939 2940 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 2941 GNUCmpXchg 2942 } Form = Init; 2943 2944 const unsigned NumForm = GNUCmpXchg + 1; 2945 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 2946 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 2947 // where: 2948 // C is an appropriate type, 2949 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 2950 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 2951 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 2952 // the int parameters are for orderings. 2953 2954 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 2955 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 2956 "need to update code for modified forms"); 2957 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 2958 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == 2959 AtomicExpr::AO__atomic_load, 2960 "need to update code for modified C11 atomics"); 2961 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 2962 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 2963 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 2964 Op <= AtomicExpr::AO__c11_atomic_fetch_xor) || 2965 IsOpenCL; 2966 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 2967 Op == AtomicExpr::AO__atomic_store_n || 2968 Op == AtomicExpr::AO__atomic_exchange_n || 2969 Op == AtomicExpr::AO__atomic_compare_exchange_n; 2970 bool IsAddSub = false; 2971 2972 switch (Op) { 2973 case AtomicExpr::AO__c11_atomic_init: 2974 case AtomicExpr::AO__opencl_atomic_init: 2975 Form = Init; 2976 break; 2977 2978 case AtomicExpr::AO__c11_atomic_load: 2979 case AtomicExpr::AO__opencl_atomic_load: 2980 case AtomicExpr::AO__atomic_load_n: 2981 Form = Load; 2982 break; 2983 2984 case AtomicExpr::AO__atomic_load: 2985 Form = LoadCopy; 2986 break; 2987 2988 case AtomicExpr::AO__c11_atomic_store: 2989 case AtomicExpr::AO__opencl_atomic_store: 2990 case AtomicExpr::AO__atomic_store: 2991 case AtomicExpr::AO__atomic_store_n: 2992 Form = Copy; 2993 break; 2994 2995 case AtomicExpr::AO__c11_atomic_fetch_add: 2996 case AtomicExpr::AO__c11_atomic_fetch_sub: 2997 case AtomicExpr::AO__opencl_atomic_fetch_add: 2998 case AtomicExpr::AO__opencl_atomic_fetch_sub: 2999 case AtomicExpr::AO__opencl_atomic_fetch_min: 3000 case AtomicExpr::AO__opencl_atomic_fetch_max: 3001 case AtomicExpr::AO__atomic_fetch_add: 3002 case AtomicExpr::AO__atomic_fetch_sub: 3003 case AtomicExpr::AO__atomic_add_fetch: 3004 case AtomicExpr::AO__atomic_sub_fetch: 3005 IsAddSub = true; 3006 LLVM_FALLTHROUGH; 3007 case AtomicExpr::AO__c11_atomic_fetch_and: 3008 case AtomicExpr::AO__c11_atomic_fetch_or: 3009 case AtomicExpr::AO__c11_atomic_fetch_xor: 3010 case AtomicExpr::AO__opencl_atomic_fetch_and: 3011 case AtomicExpr::AO__opencl_atomic_fetch_or: 3012 case AtomicExpr::AO__opencl_atomic_fetch_xor: 3013 case AtomicExpr::AO__atomic_fetch_and: 3014 case AtomicExpr::AO__atomic_fetch_or: 3015 case AtomicExpr::AO__atomic_fetch_xor: 3016 case AtomicExpr::AO__atomic_fetch_nand: 3017 case AtomicExpr::AO__atomic_and_fetch: 3018 case AtomicExpr::AO__atomic_or_fetch: 3019 case AtomicExpr::AO__atomic_xor_fetch: 3020 case AtomicExpr::AO__atomic_nand_fetch: 3021 Form = Arithmetic; 3022 break; 3023 3024 case AtomicExpr::AO__c11_atomic_exchange: 3025 case AtomicExpr::AO__opencl_atomic_exchange: 3026 case AtomicExpr::AO__atomic_exchange_n: 3027 Form = Xchg; 3028 break; 3029 3030 case AtomicExpr::AO__atomic_exchange: 3031 Form = GNUXchg; 3032 break; 3033 3034 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 3035 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 3036 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 3037 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 3038 Form = C11CmpXchg; 3039 break; 3040 3041 case AtomicExpr::AO__atomic_compare_exchange: 3042 case AtomicExpr::AO__atomic_compare_exchange_n: 3043 Form = GNUCmpXchg; 3044 break; 3045 } 3046 3047 unsigned AdjustedNumArgs = NumArgs[Form]; 3048 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 3049 ++AdjustedNumArgs; 3050 // Check we have the right number of arguments. 3051 if (TheCall->getNumArgs() < AdjustedNumArgs) { 3052 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 3053 << 0 << AdjustedNumArgs << TheCall->getNumArgs() 3054 << TheCall->getCallee()->getSourceRange(); 3055 return ExprError(); 3056 } else if (TheCall->getNumArgs() > AdjustedNumArgs) { 3057 Diag(TheCall->getArg(AdjustedNumArgs)->getLocStart(), 3058 diag::err_typecheck_call_too_many_args) 3059 << 0 << AdjustedNumArgs << TheCall->getNumArgs() 3060 << TheCall->getCallee()->getSourceRange(); 3061 return ExprError(); 3062 } 3063 3064 // Inspect the first argument of the atomic operation. 3065 Expr *Ptr = TheCall->getArg(0); 3066 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 3067 if (ConvertedPtr.isInvalid()) 3068 return ExprError(); 3069 3070 Ptr = ConvertedPtr.get(); 3071 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 3072 if (!pointerType) { 3073 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 3074 << Ptr->getType() << Ptr->getSourceRange(); 3075 return ExprError(); 3076 } 3077 3078 // For a __c11 builtin, this should be a pointer to an _Atomic type. 3079 QualType AtomTy = pointerType->getPointeeType(); // 'A' 3080 QualType ValType = AtomTy; // 'C' 3081 if (IsC11) { 3082 if (!AtomTy->isAtomicType()) { 3083 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic) 3084 << Ptr->getType() << Ptr->getSourceRange(); 3085 return ExprError(); 3086 } 3087 if (AtomTy.isConstQualified() || 3088 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 3089 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic) 3090 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 3091 << Ptr->getSourceRange(); 3092 return ExprError(); 3093 } 3094 ValType = AtomTy->getAs<AtomicType>()->getValueType(); 3095 } else if (Form != Load && Form != LoadCopy) { 3096 if (ValType.isConstQualified()) { 3097 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer) 3098 << Ptr->getType() << Ptr->getSourceRange(); 3099 return ExprError(); 3100 } 3101 } 3102 3103 // For an arithmetic operation, the implied arithmetic must be well-formed. 3104 if (Form == Arithmetic) { 3105 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 3106 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) { 3107 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 3108 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 3109 return ExprError(); 3110 } 3111 if (!IsAddSub && !ValType->isIntegerType()) { 3112 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int) 3113 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 3114 return ExprError(); 3115 } 3116 if (IsC11 && ValType->isPointerType() && 3117 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(), 3118 diag::err_incomplete_type)) { 3119 return ExprError(); 3120 } 3121 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 3122 // For __atomic_*_n operations, the value type must be a scalar integral or 3123 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 3124 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 3125 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 3126 return ExprError(); 3127 } 3128 3129 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 3130 !AtomTy->isScalarType()) { 3131 // For GNU atomics, require a trivially-copyable type. This is not part of 3132 // the GNU atomics specification, but we enforce it for sanity. 3133 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy) 3134 << Ptr->getType() << Ptr->getSourceRange(); 3135 return ExprError(); 3136 } 3137 3138 switch (ValType.getObjCLifetime()) { 3139 case Qualifiers::OCL_None: 3140 case Qualifiers::OCL_ExplicitNone: 3141 // okay 3142 break; 3143 3144 case Qualifiers::OCL_Weak: 3145 case Qualifiers::OCL_Strong: 3146 case Qualifiers::OCL_Autoreleasing: 3147 // FIXME: Can this happen? By this point, ValType should be known 3148 // to be trivially copyable. 3149 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 3150 << ValType << Ptr->getSourceRange(); 3151 return ExprError(); 3152 } 3153 3154 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the 3155 // volatile-ness of the pointee-type inject itself into the result or the 3156 // other operands. Similarly atomic_load can take a pointer to a const 'A'. 3157 ValType.removeLocalVolatile(); 3158 ValType.removeLocalConst(); 3159 QualType ResultType = ValType; 3160 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 3161 Form == Init) 3162 ResultType = Context.VoidTy; 3163 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 3164 ResultType = Context.BoolTy; 3165 3166 // The type of a parameter passed 'by value'. In the GNU atomics, such 3167 // arguments are actually passed as pointers. 3168 QualType ByValType = ValType; // 'CP' 3169 if (!IsC11 && !IsN) 3170 ByValType = Ptr->getType(); 3171 3172 // The first argument --- the pointer --- has a fixed type; we 3173 // deduce the types of the rest of the arguments accordingly. Walk 3174 // the remaining arguments, converting them to the deduced value type. 3175 for (unsigned i = 1; i != TheCall->getNumArgs(); ++i) { 3176 QualType Ty; 3177 if (i < NumVals[Form] + 1) { 3178 switch (i) { 3179 case 1: 3180 // The second argument is the non-atomic operand. For arithmetic, this 3181 // is always passed by value, and for a compare_exchange it is always 3182 // passed by address. For the rest, GNU uses by-address and C11 uses 3183 // by-value. 3184 assert(Form != Load); 3185 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 3186 Ty = ValType; 3187 else if (Form == Copy || Form == Xchg) 3188 Ty = ByValType; 3189 else if (Form == Arithmetic) 3190 Ty = Context.getPointerDiffType(); 3191 else { 3192 Expr *ValArg = TheCall->getArg(i); 3193 // Treat this argument as _Nonnull as we want to show a warning if 3194 // NULL is passed into it. 3195 CheckNonNullArgument(*this, ValArg, DRE->getLocStart()); 3196 LangAS AS = LangAS::Default; 3197 // Keep address space of non-atomic pointer type. 3198 if (const PointerType *PtrTy = 3199 ValArg->getType()->getAs<PointerType>()) { 3200 AS = PtrTy->getPointeeType().getAddressSpace(); 3201 } 3202 Ty = Context.getPointerType( 3203 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 3204 } 3205 break; 3206 case 2: 3207 // The third argument to compare_exchange / GNU exchange is a 3208 // (pointer to a) desired value. 3209 Ty = ByValType; 3210 break; 3211 case 3: 3212 // The fourth argument to GNU compare_exchange is a 'weak' flag. 3213 Ty = Context.BoolTy; 3214 break; 3215 } 3216 } else { 3217 // The order(s) and scope are always converted to int. 3218 Ty = Context.IntTy; 3219 } 3220 3221 InitializedEntity Entity = 3222 InitializedEntity::InitializeParameter(Context, Ty, false); 3223 ExprResult Arg = TheCall->getArg(i); 3224 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 3225 if (Arg.isInvalid()) 3226 return true; 3227 TheCall->setArg(i, Arg.get()); 3228 } 3229 3230 // Permute the arguments into a 'consistent' order. 3231 SmallVector<Expr*, 5> SubExprs; 3232 SubExprs.push_back(Ptr); 3233 switch (Form) { 3234 case Init: 3235 // Note, AtomicExpr::getVal1() has a special case for this atomic. 3236 SubExprs.push_back(TheCall->getArg(1)); // Val1 3237 break; 3238 case Load: 3239 SubExprs.push_back(TheCall->getArg(1)); // Order 3240 break; 3241 case LoadCopy: 3242 case Copy: 3243 case Arithmetic: 3244 case Xchg: 3245 SubExprs.push_back(TheCall->getArg(2)); // Order 3246 SubExprs.push_back(TheCall->getArg(1)); // Val1 3247 break; 3248 case GNUXchg: 3249 // Note, AtomicExpr::getVal2() has a special case for this atomic. 3250 SubExprs.push_back(TheCall->getArg(3)); // Order 3251 SubExprs.push_back(TheCall->getArg(1)); // Val1 3252 SubExprs.push_back(TheCall->getArg(2)); // Val2 3253 break; 3254 case C11CmpXchg: 3255 SubExprs.push_back(TheCall->getArg(3)); // Order 3256 SubExprs.push_back(TheCall->getArg(1)); // Val1 3257 SubExprs.push_back(TheCall->getArg(4)); // OrderFail 3258 SubExprs.push_back(TheCall->getArg(2)); // Val2 3259 break; 3260 case GNUCmpXchg: 3261 SubExprs.push_back(TheCall->getArg(4)); // Order 3262 SubExprs.push_back(TheCall->getArg(1)); // Val1 3263 SubExprs.push_back(TheCall->getArg(5)); // OrderFail 3264 SubExprs.push_back(TheCall->getArg(2)); // Val2 3265 SubExprs.push_back(TheCall->getArg(3)); // Weak 3266 break; 3267 } 3268 3269 if (SubExprs.size() >= 2 && Form != Init) { 3270 llvm::APSInt Result(32); 3271 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) && 3272 !isValidOrderingForOp(Result.getSExtValue(), Op)) 3273 Diag(SubExprs[1]->getLocStart(), 3274 diag::warn_atomic_op_has_invalid_memory_order) 3275 << SubExprs[1]->getSourceRange(); 3276 } 3277 3278 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 3279 auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1); 3280 llvm::APSInt Result(32); 3281 if (Scope->isIntegerConstantExpr(Result, Context) && 3282 !ScopeModel->isValid(Result.getZExtValue())) { 3283 Diag(Scope->getLocStart(), diag::err_atomic_op_has_invalid_synch_scope) 3284 << Scope->getSourceRange(); 3285 } 3286 SubExprs.push_back(Scope); 3287 } 3288 3289 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(), 3290 SubExprs, ResultType, Op, 3291 TheCall->getRParenLoc()); 3292 3293 if ((Op == AtomicExpr::AO__c11_atomic_load || 3294 Op == AtomicExpr::AO__c11_atomic_store || 3295 Op == AtomicExpr::AO__opencl_atomic_load || 3296 Op == AtomicExpr::AO__opencl_atomic_store ) && 3297 Context.AtomicUsesUnsupportedLibcall(AE)) 3298 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) 3299 << ((Op == AtomicExpr::AO__c11_atomic_load || 3300 Op == AtomicExpr::AO__opencl_atomic_load) 3301 ? 0 : 1); 3302 3303 return AE; 3304 } 3305 3306 /// checkBuiltinArgument - Given a call to a builtin function, perform 3307 /// normal type-checking on the given argument, updating the call in 3308 /// place. This is useful when a builtin function requires custom 3309 /// type-checking for some of its arguments but not necessarily all of 3310 /// them. 3311 /// 3312 /// Returns true on error. 3313 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 3314 FunctionDecl *Fn = E->getDirectCallee(); 3315 assert(Fn && "builtin call without direct callee!"); 3316 3317 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 3318 InitializedEntity Entity = 3319 InitializedEntity::InitializeParameter(S.Context, Param); 3320 3321 ExprResult Arg = E->getArg(0); 3322 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 3323 if (Arg.isInvalid()) 3324 return true; 3325 3326 E->setArg(ArgIndex, Arg.get()); 3327 return false; 3328 } 3329 3330 /// SemaBuiltinAtomicOverloaded - We have a call to a function like 3331 /// __sync_fetch_and_add, which is an overloaded function based on the pointer 3332 /// type of its first argument. The main ActOnCallExpr routines have already 3333 /// promoted the types of arguments because all of these calls are prototyped as 3334 /// void(...). 3335 /// 3336 /// This function goes through and does final semantic checking for these 3337 /// builtins, 3338 ExprResult 3339 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 3340 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 3341 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 3342 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 3343 3344 // Ensure that we have at least one argument to do type inference from. 3345 if (TheCall->getNumArgs() < 1) { 3346 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 3347 << 0 << 1 << TheCall->getNumArgs() 3348 << TheCall->getCallee()->getSourceRange(); 3349 return ExprError(); 3350 } 3351 3352 // Inspect the first argument of the atomic builtin. This should always be 3353 // a pointer type, whose element is an integral scalar or pointer type. 3354 // Because it is a pointer type, we don't have to worry about any implicit 3355 // casts here. 3356 // FIXME: We don't allow floating point scalars as input. 3357 Expr *FirstArg = TheCall->getArg(0); 3358 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 3359 if (FirstArgResult.isInvalid()) 3360 return ExprError(); 3361 FirstArg = FirstArgResult.get(); 3362 TheCall->setArg(0, FirstArg); 3363 3364 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 3365 if (!pointerType) { 3366 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 3367 << FirstArg->getType() << FirstArg->getSourceRange(); 3368 return ExprError(); 3369 } 3370 3371 QualType ValType = pointerType->getPointeeType(); 3372 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 3373 !ValType->isBlockPointerType()) { 3374 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr) 3375 << FirstArg->getType() << FirstArg->getSourceRange(); 3376 return ExprError(); 3377 } 3378 3379 switch (ValType.getObjCLifetime()) { 3380 case Qualifiers::OCL_None: 3381 case Qualifiers::OCL_ExplicitNone: 3382 // okay 3383 break; 3384 3385 case Qualifiers::OCL_Weak: 3386 case Qualifiers::OCL_Strong: 3387 case Qualifiers::OCL_Autoreleasing: 3388 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 3389 << ValType << FirstArg->getSourceRange(); 3390 return ExprError(); 3391 } 3392 3393 // Strip any qualifiers off ValType. 3394 ValType = ValType.getUnqualifiedType(); 3395 3396 // The majority of builtins return a value, but a few have special return 3397 // types, so allow them to override appropriately below. 3398 QualType ResultType = ValType; 3399 3400 // We need to figure out which concrete builtin this maps onto. For example, 3401 // __sync_fetch_and_add with a 2 byte object turns into 3402 // __sync_fetch_and_add_2. 3403 #define BUILTIN_ROW(x) \ 3404 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 3405 Builtin::BI##x##_8, Builtin::BI##x##_16 } 3406 3407 static const unsigned BuiltinIndices[][5] = { 3408 BUILTIN_ROW(__sync_fetch_and_add), 3409 BUILTIN_ROW(__sync_fetch_and_sub), 3410 BUILTIN_ROW(__sync_fetch_and_or), 3411 BUILTIN_ROW(__sync_fetch_and_and), 3412 BUILTIN_ROW(__sync_fetch_and_xor), 3413 BUILTIN_ROW(__sync_fetch_and_nand), 3414 3415 BUILTIN_ROW(__sync_add_and_fetch), 3416 BUILTIN_ROW(__sync_sub_and_fetch), 3417 BUILTIN_ROW(__sync_and_and_fetch), 3418 BUILTIN_ROW(__sync_or_and_fetch), 3419 BUILTIN_ROW(__sync_xor_and_fetch), 3420 BUILTIN_ROW(__sync_nand_and_fetch), 3421 3422 BUILTIN_ROW(__sync_val_compare_and_swap), 3423 BUILTIN_ROW(__sync_bool_compare_and_swap), 3424 BUILTIN_ROW(__sync_lock_test_and_set), 3425 BUILTIN_ROW(__sync_lock_release), 3426 BUILTIN_ROW(__sync_swap) 3427 }; 3428 #undef BUILTIN_ROW 3429 3430 // Determine the index of the size. 3431 unsigned SizeIndex; 3432 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 3433 case 1: SizeIndex = 0; break; 3434 case 2: SizeIndex = 1; break; 3435 case 4: SizeIndex = 2; break; 3436 case 8: SizeIndex = 3; break; 3437 case 16: SizeIndex = 4; break; 3438 default: 3439 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size) 3440 << FirstArg->getType() << FirstArg->getSourceRange(); 3441 return ExprError(); 3442 } 3443 3444 // Each of these builtins has one pointer argument, followed by some number of 3445 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 3446 // that we ignore. Find out which row of BuiltinIndices to read from as well 3447 // as the number of fixed args. 3448 unsigned BuiltinID = FDecl->getBuiltinID(); 3449 unsigned BuiltinIndex, NumFixed = 1; 3450 bool WarnAboutSemanticsChange = false; 3451 switch (BuiltinID) { 3452 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 3453 case Builtin::BI__sync_fetch_and_add: 3454 case Builtin::BI__sync_fetch_and_add_1: 3455 case Builtin::BI__sync_fetch_and_add_2: 3456 case Builtin::BI__sync_fetch_and_add_4: 3457 case Builtin::BI__sync_fetch_and_add_8: 3458 case Builtin::BI__sync_fetch_and_add_16: 3459 BuiltinIndex = 0; 3460 break; 3461 3462 case Builtin::BI__sync_fetch_and_sub: 3463 case Builtin::BI__sync_fetch_and_sub_1: 3464 case Builtin::BI__sync_fetch_and_sub_2: 3465 case Builtin::BI__sync_fetch_and_sub_4: 3466 case Builtin::BI__sync_fetch_and_sub_8: 3467 case Builtin::BI__sync_fetch_and_sub_16: 3468 BuiltinIndex = 1; 3469 break; 3470 3471 case Builtin::BI__sync_fetch_and_or: 3472 case Builtin::BI__sync_fetch_and_or_1: 3473 case Builtin::BI__sync_fetch_and_or_2: 3474 case Builtin::BI__sync_fetch_and_or_4: 3475 case Builtin::BI__sync_fetch_and_or_8: 3476 case Builtin::BI__sync_fetch_and_or_16: 3477 BuiltinIndex = 2; 3478 break; 3479 3480 case Builtin::BI__sync_fetch_and_and: 3481 case Builtin::BI__sync_fetch_and_and_1: 3482 case Builtin::BI__sync_fetch_and_and_2: 3483 case Builtin::BI__sync_fetch_and_and_4: 3484 case Builtin::BI__sync_fetch_and_and_8: 3485 case Builtin::BI__sync_fetch_and_and_16: 3486 BuiltinIndex = 3; 3487 break; 3488 3489 case Builtin::BI__sync_fetch_and_xor: 3490 case Builtin::BI__sync_fetch_and_xor_1: 3491 case Builtin::BI__sync_fetch_and_xor_2: 3492 case Builtin::BI__sync_fetch_and_xor_4: 3493 case Builtin::BI__sync_fetch_and_xor_8: 3494 case Builtin::BI__sync_fetch_and_xor_16: 3495 BuiltinIndex = 4; 3496 break; 3497 3498 case Builtin::BI__sync_fetch_and_nand: 3499 case Builtin::BI__sync_fetch_and_nand_1: 3500 case Builtin::BI__sync_fetch_and_nand_2: 3501 case Builtin::BI__sync_fetch_and_nand_4: 3502 case Builtin::BI__sync_fetch_and_nand_8: 3503 case Builtin::BI__sync_fetch_and_nand_16: 3504 BuiltinIndex = 5; 3505 WarnAboutSemanticsChange = true; 3506 break; 3507 3508 case Builtin::BI__sync_add_and_fetch: 3509 case Builtin::BI__sync_add_and_fetch_1: 3510 case Builtin::BI__sync_add_and_fetch_2: 3511 case Builtin::BI__sync_add_and_fetch_4: 3512 case Builtin::BI__sync_add_and_fetch_8: 3513 case Builtin::BI__sync_add_and_fetch_16: 3514 BuiltinIndex = 6; 3515 break; 3516 3517 case Builtin::BI__sync_sub_and_fetch: 3518 case Builtin::BI__sync_sub_and_fetch_1: 3519 case Builtin::BI__sync_sub_and_fetch_2: 3520 case Builtin::BI__sync_sub_and_fetch_4: 3521 case Builtin::BI__sync_sub_and_fetch_8: 3522 case Builtin::BI__sync_sub_and_fetch_16: 3523 BuiltinIndex = 7; 3524 break; 3525 3526 case Builtin::BI__sync_and_and_fetch: 3527 case Builtin::BI__sync_and_and_fetch_1: 3528 case Builtin::BI__sync_and_and_fetch_2: 3529 case Builtin::BI__sync_and_and_fetch_4: 3530 case Builtin::BI__sync_and_and_fetch_8: 3531 case Builtin::BI__sync_and_and_fetch_16: 3532 BuiltinIndex = 8; 3533 break; 3534 3535 case Builtin::BI__sync_or_and_fetch: 3536 case Builtin::BI__sync_or_and_fetch_1: 3537 case Builtin::BI__sync_or_and_fetch_2: 3538 case Builtin::BI__sync_or_and_fetch_4: 3539 case Builtin::BI__sync_or_and_fetch_8: 3540 case Builtin::BI__sync_or_and_fetch_16: 3541 BuiltinIndex = 9; 3542 break; 3543 3544 case Builtin::BI__sync_xor_and_fetch: 3545 case Builtin::BI__sync_xor_and_fetch_1: 3546 case Builtin::BI__sync_xor_and_fetch_2: 3547 case Builtin::BI__sync_xor_and_fetch_4: 3548 case Builtin::BI__sync_xor_and_fetch_8: 3549 case Builtin::BI__sync_xor_and_fetch_16: 3550 BuiltinIndex = 10; 3551 break; 3552 3553 case Builtin::BI__sync_nand_and_fetch: 3554 case Builtin::BI__sync_nand_and_fetch_1: 3555 case Builtin::BI__sync_nand_and_fetch_2: 3556 case Builtin::BI__sync_nand_and_fetch_4: 3557 case Builtin::BI__sync_nand_and_fetch_8: 3558 case Builtin::BI__sync_nand_and_fetch_16: 3559 BuiltinIndex = 11; 3560 WarnAboutSemanticsChange = true; 3561 break; 3562 3563 case Builtin::BI__sync_val_compare_and_swap: 3564 case Builtin::BI__sync_val_compare_and_swap_1: 3565 case Builtin::BI__sync_val_compare_and_swap_2: 3566 case Builtin::BI__sync_val_compare_and_swap_4: 3567 case Builtin::BI__sync_val_compare_and_swap_8: 3568 case Builtin::BI__sync_val_compare_and_swap_16: 3569 BuiltinIndex = 12; 3570 NumFixed = 2; 3571 break; 3572 3573 case Builtin::BI__sync_bool_compare_and_swap: 3574 case Builtin::BI__sync_bool_compare_and_swap_1: 3575 case Builtin::BI__sync_bool_compare_and_swap_2: 3576 case Builtin::BI__sync_bool_compare_and_swap_4: 3577 case Builtin::BI__sync_bool_compare_and_swap_8: 3578 case Builtin::BI__sync_bool_compare_and_swap_16: 3579 BuiltinIndex = 13; 3580 NumFixed = 2; 3581 ResultType = Context.BoolTy; 3582 break; 3583 3584 case Builtin::BI__sync_lock_test_and_set: 3585 case Builtin::BI__sync_lock_test_and_set_1: 3586 case Builtin::BI__sync_lock_test_and_set_2: 3587 case Builtin::BI__sync_lock_test_and_set_4: 3588 case Builtin::BI__sync_lock_test_and_set_8: 3589 case Builtin::BI__sync_lock_test_and_set_16: 3590 BuiltinIndex = 14; 3591 break; 3592 3593 case Builtin::BI__sync_lock_release: 3594 case Builtin::BI__sync_lock_release_1: 3595 case Builtin::BI__sync_lock_release_2: 3596 case Builtin::BI__sync_lock_release_4: 3597 case Builtin::BI__sync_lock_release_8: 3598 case Builtin::BI__sync_lock_release_16: 3599 BuiltinIndex = 15; 3600 NumFixed = 0; 3601 ResultType = Context.VoidTy; 3602 break; 3603 3604 case Builtin::BI__sync_swap: 3605 case Builtin::BI__sync_swap_1: 3606 case Builtin::BI__sync_swap_2: 3607 case Builtin::BI__sync_swap_4: 3608 case Builtin::BI__sync_swap_8: 3609 case Builtin::BI__sync_swap_16: 3610 BuiltinIndex = 16; 3611 break; 3612 } 3613 3614 // Now that we know how many fixed arguments we expect, first check that we 3615 // have at least that many. 3616 if (TheCall->getNumArgs() < 1+NumFixed) { 3617 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 3618 << 0 << 1+NumFixed << TheCall->getNumArgs() 3619 << TheCall->getCallee()->getSourceRange(); 3620 return ExprError(); 3621 } 3622 3623 if (WarnAboutSemanticsChange) { 3624 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change) 3625 << TheCall->getCallee()->getSourceRange(); 3626 } 3627 3628 // Get the decl for the concrete builtin from this, we can tell what the 3629 // concrete integer type we should convert to is. 3630 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 3631 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 3632 FunctionDecl *NewBuiltinDecl; 3633 if (NewBuiltinID == BuiltinID) 3634 NewBuiltinDecl = FDecl; 3635 else { 3636 // Perform builtin lookup to avoid redeclaring it. 3637 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 3638 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName); 3639 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 3640 assert(Res.getFoundDecl()); 3641 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 3642 if (!NewBuiltinDecl) 3643 return ExprError(); 3644 } 3645 3646 // The first argument --- the pointer --- has a fixed type; we 3647 // deduce the types of the rest of the arguments accordingly. Walk 3648 // the remaining arguments, converting them to the deduced value type. 3649 for (unsigned i = 0; i != NumFixed; ++i) { 3650 ExprResult Arg = TheCall->getArg(i+1); 3651 3652 // GCC does an implicit conversion to the pointer or integer ValType. This 3653 // can fail in some cases (1i -> int**), check for this error case now. 3654 // Initialize the argument. 3655 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 3656 ValType, /*consume*/ false); 3657 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 3658 if (Arg.isInvalid()) 3659 return ExprError(); 3660 3661 // Okay, we have something that *can* be converted to the right type. Check 3662 // to see if there is a potentially weird extension going on here. This can 3663 // happen when you do an atomic operation on something like an char* and 3664 // pass in 42. The 42 gets converted to char. This is even more strange 3665 // for things like 45.123 -> char, etc. 3666 // FIXME: Do this check. 3667 TheCall->setArg(i+1, Arg.get()); 3668 } 3669 3670 ASTContext& Context = this->getASTContext(); 3671 3672 // Create a new DeclRefExpr to refer to the new decl. 3673 DeclRefExpr* NewDRE = DeclRefExpr::Create( 3674 Context, 3675 DRE->getQualifierLoc(), 3676 SourceLocation(), 3677 NewBuiltinDecl, 3678 /*enclosing*/ false, 3679 DRE->getLocation(), 3680 Context.BuiltinFnTy, 3681 DRE->getValueKind()); 3682 3683 // Set the callee in the CallExpr. 3684 // FIXME: This loses syntactic information. 3685 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 3686 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 3687 CK_BuiltinFnToFnPtr); 3688 TheCall->setCallee(PromotedCall.get()); 3689 3690 // Change the result type of the call to match the original value type. This 3691 // is arbitrary, but the codegen for these builtins ins design to handle it 3692 // gracefully. 3693 TheCall->setType(ResultType); 3694 3695 return TheCallResult; 3696 } 3697 3698 /// SemaBuiltinNontemporalOverloaded - We have a call to 3699 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 3700 /// overloaded function based on the pointer type of its last argument. 3701 /// 3702 /// This function goes through and does final semantic checking for these 3703 /// builtins. 3704 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 3705 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 3706 DeclRefExpr *DRE = 3707 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 3708 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 3709 unsigned BuiltinID = FDecl->getBuiltinID(); 3710 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 3711 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 3712 "Unexpected nontemporal load/store builtin!"); 3713 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 3714 unsigned numArgs = isStore ? 2 : 1; 3715 3716 // Ensure that we have the proper number of arguments. 3717 if (checkArgCount(*this, TheCall, numArgs)) 3718 return ExprError(); 3719 3720 // Inspect the last argument of the nontemporal builtin. This should always 3721 // be a pointer type, from which we imply the type of the memory access. 3722 // Because it is a pointer type, we don't have to worry about any implicit 3723 // casts here. 3724 Expr *PointerArg = TheCall->getArg(numArgs - 1); 3725 ExprResult PointerArgResult = 3726 DefaultFunctionArrayLvalueConversion(PointerArg); 3727 3728 if (PointerArgResult.isInvalid()) 3729 return ExprError(); 3730 PointerArg = PointerArgResult.get(); 3731 TheCall->setArg(numArgs - 1, PointerArg); 3732 3733 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 3734 if (!pointerType) { 3735 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer) 3736 << PointerArg->getType() << PointerArg->getSourceRange(); 3737 return ExprError(); 3738 } 3739 3740 QualType ValType = pointerType->getPointeeType(); 3741 3742 // Strip any qualifiers off ValType. 3743 ValType = ValType.getUnqualifiedType(); 3744 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 3745 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 3746 !ValType->isVectorType()) { 3747 Diag(DRE->getLocStart(), 3748 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 3749 << PointerArg->getType() << PointerArg->getSourceRange(); 3750 return ExprError(); 3751 } 3752 3753 if (!isStore) { 3754 TheCall->setType(ValType); 3755 return TheCallResult; 3756 } 3757 3758 ExprResult ValArg = TheCall->getArg(0); 3759 InitializedEntity Entity = InitializedEntity::InitializeParameter( 3760 Context, ValType, /*consume*/ false); 3761 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 3762 if (ValArg.isInvalid()) 3763 return ExprError(); 3764 3765 TheCall->setArg(0, ValArg.get()); 3766 TheCall->setType(Context.VoidTy); 3767 return TheCallResult; 3768 } 3769 3770 /// CheckObjCString - Checks that the argument to the builtin 3771 /// CFString constructor is correct 3772 /// Note: It might also make sense to do the UTF-16 conversion here (would 3773 /// simplify the backend). 3774 bool Sema::CheckObjCString(Expr *Arg) { 3775 Arg = Arg->IgnoreParenCasts(); 3776 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 3777 3778 if (!Literal || !Literal->isAscii()) { 3779 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant) 3780 << Arg->getSourceRange(); 3781 return true; 3782 } 3783 3784 if (Literal->containsNonAsciiOrNull()) { 3785 StringRef String = Literal->getString(); 3786 unsigned NumBytes = String.size(); 3787 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 3788 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 3789 llvm::UTF16 *ToPtr = &ToBuf[0]; 3790 3791 llvm::ConversionResult Result = 3792 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 3793 ToPtr + NumBytes, llvm::strictConversion); 3794 // Check for conversion failure. 3795 if (Result != llvm::conversionOK) 3796 Diag(Arg->getLocStart(), 3797 diag::warn_cfstring_truncated) << Arg->getSourceRange(); 3798 } 3799 return false; 3800 } 3801 3802 /// CheckObjCString - Checks that the format string argument to the os_log() 3803 /// and os_trace() functions is correct, and converts it to const char *. 3804 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 3805 Arg = Arg->IgnoreParenCasts(); 3806 auto *Literal = dyn_cast<StringLiteral>(Arg); 3807 if (!Literal) { 3808 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 3809 Literal = ObjcLiteral->getString(); 3810 } 3811 } 3812 3813 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 3814 return ExprError( 3815 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant) 3816 << Arg->getSourceRange()); 3817 } 3818 3819 ExprResult Result(Literal); 3820 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 3821 InitializedEntity Entity = 3822 InitializedEntity::InitializeParameter(Context, ResultTy, false); 3823 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 3824 return Result; 3825 } 3826 3827 /// Check that the user is calling the appropriate va_start builtin for the 3828 /// target and calling convention. 3829 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 3830 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 3831 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 3832 bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64; 3833 bool IsWindows = TT.isOSWindows(); 3834 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 3835 if (IsX64 || IsAArch64) { 3836 CallingConv CC = CC_C; 3837 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 3838 CC = FD->getType()->getAs<FunctionType>()->getCallConv(); 3839 if (IsMSVAStart) { 3840 // Don't allow this in System V ABI functions. 3841 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 3842 return S.Diag(Fn->getLocStart(), 3843 diag::err_ms_va_start_used_in_sysv_function); 3844 } else { 3845 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 3846 // On x64 Windows, don't allow this in System V ABI functions. 3847 // (Yes, that means there's no corresponding way to support variadic 3848 // System V ABI functions on Windows.) 3849 if ((IsWindows && CC == CC_X86_64SysV) || 3850 (!IsWindows && CC == CC_Win64)) 3851 return S.Diag(Fn->getLocStart(), 3852 diag::err_va_start_used_in_wrong_abi_function) 3853 << !IsWindows; 3854 } 3855 return false; 3856 } 3857 3858 if (IsMSVAStart) 3859 return S.Diag(Fn->getLocStart(), diag::err_builtin_x64_aarch64_only); 3860 return false; 3861 } 3862 3863 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 3864 ParmVarDecl **LastParam = nullptr) { 3865 // Determine whether the current function, block, or obj-c method is variadic 3866 // and get its parameter list. 3867 bool IsVariadic = false; 3868 ArrayRef<ParmVarDecl *> Params; 3869 DeclContext *Caller = S.CurContext; 3870 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 3871 IsVariadic = Block->isVariadic(); 3872 Params = Block->parameters(); 3873 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 3874 IsVariadic = FD->isVariadic(); 3875 Params = FD->parameters(); 3876 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 3877 IsVariadic = MD->isVariadic(); 3878 // FIXME: This isn't correct for methods (results in bogus warning). 3879 Params = MD->parameters(); 3880 } else if (isa<CapturedDecl>(Caller)) { 3881 // We don't support va_start in a CapturedDecl. 3882 S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt); 3883 return true; 3884 } else { 3885 // This must be some other declcontext that parses exprs. 3886 S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function); 3887 return true; 3888 } 3889 3890 if (!IsVariadic) { 3891 S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function); 3892 return true; 3893 } 3894 3895 if (LastParam) 3896 *LastParam = Params.empty() ? nullptr : Params.back(); 3897 3898 return false; 3899 } 3900 3901 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 3902 /// for validity. Emit an error and return true on failure; return false 3903 /// on success. 3904 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 3905 Expr *Fn = TheCall->getCallee(); 3906 3907 if (checkVAStartABI(*this, BuiltinID, Fn)) 3908 return true; 3909 3910 if (TheCall->getNumArgs() > 2) { 3911 Diag(TheCall->getArg(2)->getLocStart(), 3912 diag::err_typecheck_call_too_many_args) 3913 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 3914 << Fn->getSourceRange() 3915 << SourceRange(TheCall->getArg(2)->getLocStart(), 3916 (*(TheCall->arg_end()-1))->getLocEnd()); 3917 return true; 3918 } 3919 3920 if (TheCall->getNumArgs() < 2) { 3921 return Diag(TheCall->getLocEnd(), 3922 diag::err_typecheck_call_too_few_args_at_least) 3923 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 3924 } 3925 3926 // Type-check the first argument normally. 3927 if (checkBuiltinArgument(*this, TheCall, 0)) 3928 return true; 3929 3930 // Check that the current function is variadic, and get its last parameter. 3931 ParmVarDecl *LastParam; 3932 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 3933 return true; 3934 3935 // Verify that the second argument to the builtin is the last argument of the 3936 // current function or method. 3937 bool SecondArgIsLastNamedArgument = false; 3938 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 3939 3940 // These are valid if SecondArgIsLastNamedArgument is false after the next 3941 // block. 3942 QualType Type; 3943 SourceLocation ParamLoc; 3944 bool IsCRegister = false; 3945 3946 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 3947 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 3948 SecondArgIsLastNamedArgument = PV == LastParam; 3949 3950 Type = PV->getType(); 3951 ParamLoc = PV->getLocation(); 3952 IsCRegister = 3953 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 3954 } 3955 } 3956 3957 if (!SecondArgIsLastNamedArgument) 3958 Diag(TheCall->getArg(1)->getLocStart(), 3959 diag::warn_second_arg_of_va_start_not_last_named_param); 3960 else if (IsCRegister || Type->isReferenceType() || 3961 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 3962 // Promotable integers are UB, but enumerations need a bit of 3963 // extra checking to see what their promotable type actually is. 3964 if (!Type->isPromotableIntegerType()) 3965 return false; 3966 if (!Type->isEnumeralType()) 3967 return true; 3968 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl(); 3969 return !(ED && 3970 Context.typesAreCompatible(ED->getPromotionType(), Type)); 3971 }()) { 3972 unsigned Reason = 0; 3973 if (Type->isReferenceType()) Reason = 1; 3974 else if (IsCRegister) Reason = 2; 3975 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason; 3976 Diag(ParamLoc, diag::note_parameter_type) << Type; 3977 } 3978 3979 TheCall->setType(Context.VoidTy); 3980 return false; 3981 } 3982 3983 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 3984 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 3985 // const char *named_addr); 3986 3987 Expr *Func = Call->getCallee(); 3988 3989 if (Call->getNumArgs() < 3) 3990 return Diag(Call->getLocEnd(), 3991 diag::err_typecheck_call_too_few_args_at_least) 3992 << 0 /*function call*/ << 3 << Call->getNumArgs(); 3993 3994 // Type-check the first argument normally. 3995 if (checkBuiltinArgument(*this, Call, 0)) 3996 return true; 3997 3998 // Check that the current function is variadic. 3999 if (checkVAStartIsInVariadicFunction(*this, Func)) 4000 return true; 4001 4002 // __va_start on Windows does not validate the parameter qualifiers 4003 4004 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 4005 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 4006 4007 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 4008 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 4009 4010 const QualType &ConstCharPtrTy = 4011 Context.getPointerType(Context.CharTy.withConst()); 4012 if (!Arg1Ty->isPointerType() || 4013 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy) 4014 Diag(Arg1->getLocStart(), diag::err_typecheck_convert_incompatible) 4015 << Arg1->getType() << ConstCharPtrTy 4016 << 1 /* different class */ 4017 << 0 /* qualifier difference */ 4018 << 3 /* parameter mismatch */ 4019 << 2 << Arg1->getType() << ConstCharPtrTy; 4020 4021 const QualType SizeTy = Context.getSizeType(); 4022 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 4023 Diag(Arg2->getLocStart(), diag::err_typecheck_convert_incompatible) 4024 << Arg2->getType() << SizeTy 4025 << 1 /* different class */ 4026 << 0 /* qualifier difference */ 4027 << 3 /* parameter mismatch */ 4028 << 3 << Arg2->getType() << SizeTy; 4029 4030 return false; 4031 } 4032 4033 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 4034 /// friends. This is declared to take (...), so we have to check everything. 4035 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 4036 if (TheCall->getNumArgs() < 2) 4037 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 4038 << 0 << 2 << TheCall->getNumArgs()/*function call*/; 4039 if (TheCall->getNumArgs() > 2) 4040 return Diag(TheCall->getArg(2)->getLocStart(), 4041 diag::err_typecheck_call_too_many_args) 4042 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 4043 << SourceRange(TheCall->getArg(2)->getLocStart(), 4044 (*(TheCall->arg_end()-1))->getLocEnd()); 4045 4046 ExprResult OrigArg0 = TheCall->getArg(0); 4047 ExprResult OrigArg1 = TheCall->getArg(1); 4048 4049 // Do standard promotions between the two arguments, returning their common 4050 // type. 4051 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false); 4052 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 4053 return true; 4054 4055 // Make sure any conversions are pushed back into the call; this is 4056 // type safe since unordered compare builtins are declared as "_Bool 4057 // foo(...)". 4058 TheCall->setArg(0, OrigArg0.get()); 4059 TheCall->setArg(1, OrigArg1.get()); 4060 4061 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 4062 return false; 4063 4064 // If the common type isn't a real floating type, then the arguments were 4065 // invalid for this operation. 4066 if (Res.isNull() || !Res->isRealFloatingType()) 4067 return Diag(OrigArg0.get()->getLocStart(), 4068 diag::err_typecheck_call_invalid_ordered_compare) 4069 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 4070 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd()); 4071 4072 return false; 4073 } 4074 4075 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 4076 /// __builtin_isnan and friends. This is declared to take (...), so we have 4077 /// to check everything. We expect the last argument to be a floating point 4078 /// value. 4079 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 4080 if (TheCall->getNumArgs() < NumArgs) 4081 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 4082 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/; 4083 if (TheCall->getNumArgs() > NumArgs) 4084 return Diag(TheCall->getArg(NumArgs)->getLocStart(), 4085 diag::err_typecheck_call_too_many_args) 4086 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 4087 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(), 4088 (*(TheCall->arg_end()-1))->getLocEnd()); 4089 4090 Expr *OrigArg = TheCall->getArg(NumArgs-1); 4091 4092 if (OrigArg->isTypeDependent()) 4093 return false; 4094 4095 // This operation requires a non-_Complex floating-point number. 4096 if (!OrigArg->getType()->isRealFloatingType()) 4097 return Diag(OrigArg->getLocStart(), 4098 diag::err_typecheck_call_invalid_unary_fp) 4099 << OrigArg->getType() << OrigArg->getSourceRange(); 4100 4101 // If this is an implicit conversion from float -> float or double, remove it. 4102 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) { 4103 // Only remove standard FloatCasts, leaving other casts inplace 4104 if (Cast->getCastKind() == CK_FloatingCast) { 4105 Expr *CastArg = Cast->getSubExpr(); 4106 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) { 4107 assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) || 4108 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) && 4109 "promotion from float to either float or double is the only expected cast here"); 4110 Cast->setSubExpr(nullptr); 4111 TheCall->setArg(NumArgs-1, CastArg); 4112 } 4113 } 4114 } 4115 4116 return false; 4117 } 4118 4119 // Customized Sema Checking for VSX builtins that have the following signature: 4120 // vector [...] builtinName(vector [...], vector [...], const int); 4121 // Which takes the same type of vectors (any legal vector type) for the first 4122 // two arguments and takes compile time constant for the third argument. 4123 // Example builtins are : 4124 // vector double vec_xxpermdi(vector double, vector double, int); 4125 // vector short vec_xxsldwi(vector short, vector short, int); 4126 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 4127 unsigned ExpectedNumArgs = 3; 4128 if (TheCall->getNumArgs() < ExpectedNumArgs) 4129 return Diag(TheCall->getLocEnd(), 4130 diag::err_typecheck_call_too_few_args_at_least) 4131 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 4132 << TheCall->getSourceRange(); 4133 4134 if (TheCall->getNumArgs() > ExpectedNumArgs) 4135 return Diag(TheCall->getLocEnd(), 4136 diag::err_typecheck_call_too_many_args_at_most) 4137 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 4138 << TheCall->getSourceRange(); 4139 4140 // Check the third argument is a compile time constant 4141 llvm::APSInt Value; 4142 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context)) 4143 return Diag(TheCall->getLocStart(), 4144 diag::err_vsx_builtin_nonconstant_argument) 4145 << 3 /* argument index */ << TheCall->getDirectCallee() 4146 << SourceRange(TheCall->getArg(2)->getLocStart(), 4147 TheCall->getArg(2)->getLocEnd()); 4148 4149 QualType Arg1Ty = TheCall->getArg(0)->getType(); 4150 QualType Arg2Ty = TheCall->getArg(1)->getType(); 4151 4152 // Check the type of argument 1 and argument 2 are vectors. 4153 SourceLocation BuiltinLoc = TheCall->getLocStart(); 4154 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 4155 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 4156 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 4157 << TheCall->getDirectCallee() 4158 << SourceRange(TheCall->getArg(0)->getLocStart(), 4159 TheCall->getArg(1)->getLocEnd()); 4160 } 4161 4162 // Check the first two arguments are the same type. 4163 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 4164 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 4165 << TheCall->getDirectCallee() 4166 << SourceRange(TheCall->getArg(0)->getLocStart(), 4167 TheCall->getArg(1)->getLocEnd()); 4168 } 4169 4170 // When default clang type checking is turned off and the customized type 4171 // checking is used, the returning type of the function must be explicitly 4172 // set. Otherwise it is _Bool by default. 4173 TheCall->setType(Arg1Ty); 4174 4175 return false; 4176 } 4177 4178 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 4179 // This is declared to take (...), so we have to check everything. 4180 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 4181 if (TheCall->getNumArgs() < 2) 4182 return ExprError(Diag(TheCall->getLocEnd(), 4183 diag::err_typecheck_call_too_few_args_at_least) 4184 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 4185 << TheCall->getSourceRange()); 4186 4187 // Determine which of the following types of shufflevector we're checking: 4188 // 1) unary, vector mask: (lhs, mask) 4189 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 4190 QualType resType = TheCall->getArg(0)->getType(); 4191 unsigned numElements = 0; 4192 4193 if (!TheCall->getArg(0)->isTypeDependent() && 4194 !TheCall->getArg(1)->isTypeDependent()) { 4195 QualType LHSType = TheCall->getArg(0)->getType(); 4196 QualType RHSType = TheCall->getArg(1)->getType(); 4197 4198 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 4199 return ExprError(Diag(TheCall->getLocStart(), 4200 diag::err_vec_builtin_non_vector) 4201 << TheCall->getDirectCallee() 4202 << SourceRange(TheCall->getArg(0)->getLocStart(), 4203 TheCall->getArg(1)->getLocEnd())); 4204 4205 numElements = LHSType->getAs<VectorType>()->getNumElements(); 4206 unsigned numResElements = TheCall->getNumArgs() - 2; 4207 4208 // Check to see if we have a call with 2 vector arguments, the unary shuffle 4209 // with mask. If so, verify that RHS is an integer vector type with the 4210 // same number of elts as lhs. 4211 if (TheCall->getNumArgs() == 2) { 4212 if (!RHSType->hasIntegerRepresentation() || 4213 RHSType->getAs<VectorType>()->getNumElements() != numElements) 4214 return ExprError(Diag(TheCall->getLocStart(), 4215 diag::err_vec_builtin_incompatible_vector) 4216 << TheCall->getDirectCallee() 4217 << SourceRange(TheCall->getArg(1)->getLocStart(), 4218 TheCall->getArg(1)->getLocEnd())); 4219 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 4220 return ExprError(Diag(TheCall->getLocStart(), 4221 diag::err_vec_builtin_incompatible_vector) 4222 << TheCall->getDirectCallee() 4223 << SourceRange(TheCall->getArg(0)->getLocStart(), 4224 TheCall->getArg(1)->getLocEnd())); 4225 } else if (numElements != numResElements) { 4226 QualType eltType = LHSType->getAs<VectorType>()->getElementType(); 4227 resType = Context.getVectorType(eltType, numResElements, 4228 VectorType::GenericVector); 4229 } 4230 } 4231 4232 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 4233 if (TheCall->getArg(i)->isTypeDependent() || 4234 TheCall->getArg(i)->isValueDependent()) 4235 continue; 4236 4237 llvm::APSInt Result(32); 4238 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 4239 return ExprError(Diag(TheCall->getLocStart(), 4240 diag::err_shufflevector_nonconstant_argument) 4241 << TheCall->getArg(i)->getSourceRange()); 4242 4243 // Allow -1 which will be translated to undef in the IR. 4244 if (Result.isSigned() && Result.isAllOnesValue()) 4245 continue; 4246 4247 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 4248 return ExprError(Diag(TheCall->getLocStart(), 4249 diag::err_shufflevector_argument_too_large) 4250 << TheCall->getArg(i)->getSourceRange()); 4251 } 4252 4253 SmallVector<Expr*, 32> exprs; 4254 4255 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 4256 exprs.push_back(TheCall->getArg(i)); 4257 TheCall->setArg(i, nullptr); 4258 } 4259 4260 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 4261 TheCall->getCallee()->getLocStart(), 4262 TheCall->getRParenLoc()); 4263 } 4264 4265 /// SemaConvertVectorExpr - Handle __builtin_convertvector 4266 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 4267 SourceLocation BuiltinLoc, 4268 SourceLocation RParenLoc) { 4269 ExprValueKind VK = VK_RValue; 4270 ExprObjectKind OK = OK_Ordinary; 4271 QualType DstTy = TInfo->getType(); 4272 QualType SrcTy = E->getType(); 4273 4274 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 4275 return ExprError(Diag(BuiltinLoc, 4276 diag::err_convertvector_non_vector) 4277 << E->getSourceRange()); 4278 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 4279 return ExprError(Diag(BuiltinLoc, 4280 diag::err_convertvector_non_vector_type)); 4281 4282 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 4283 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements(); 4284 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements(); 4285 if (SrcElts != DstElts) 4286 return ExprError(Diag(BuiltinLoc, 4287 diag::err_convertvector_incompatible_vector) 4288 << E->getSourceRange()); 4289 } 4290 4291 return new (Context) 4292 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 4293 } 4294 4295 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 4296 // This is declared to take (const void*, ...) and can take two 4297 // optional constant int args. 4298 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 4299 unsigned NumArgs = TheCall->getNumArgs(); 4300 4301 if (NumArgs > 3) 4302 return Diag(TheCall->getLocEnd(), 4303 diag::err_typecheck_call_too_many_args_at_most) 4304 << 0 /*function call*/ << 3 << NumArgs 4305 << TheCall->getSourceRange(); 4306 4307 // Argument 0 is checked for us and the remaining arguments must be 4308 // constant integers. 4309 for (unsigned i = 1; i != NumArgs; ++i) 4310 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 4311 return true; 4312 4313 return false; 4314 } 4315 4316 /// SemaBuiltinAssume - Handle __assume (MS Extension). 4317 // __assume does not evaluate its arguments, and should warn if its argument 4318 // has side effects. 4319 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 4320 Expr *Arg = TheCall->getArg(0); 4321 if (Arg->isInstantiationDependent()) return false; 4322 4323 if (Arg->HasSideEffects(Context)) 4324 Diag(Arg->getLocStart(), diag::warn_assume_side_effects) 4325 << Arg->getSourceRange() 4326 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 4327 4328 return false; 4329 } 4330 4331 /// Handle __builtin_alloca_with_align. This is declared 4332 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 4333 /// than 8. 4334 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 4335 // The alignment must be a constant integer. 4336 Expr *Arg = TheCall->getArg(1); 4337 4338 // We can't check the value of a dependent argument. 4339 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 4340 if (const auto *UE = 4341 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 4342 if (UE->getKind() == UETT_AlignOf) 4343 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof) 4344 << Arg->getSourceRange(); 4345 4346 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 4347 4348 if (!Result.isPowerOf2()) 4349 return Diag(TheCall->getLocStart(), 4350 diag::err_alignment_not_power_of_two) 4351 << Arg->getSourceRange(); 4352 4353 if (Result < Context.getCharWidth()) 4354 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small) 4355 << (unsigned)Context.getCharWidth() 4356 << Arg->getSourceRange(); 4357 4358 if (Result > std::numeric_limits<int32_t>::max()) 4359 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big) 4360 << std::numeric_limits<int32_t>::max() 4361 << Arg->getSourceRange(); 4362 } 4363 4364 return false; 4365 } 4366 4367 /// Handle __builtin_assume_aligned. This is declared 4368 /// as (const void*, size_t, ...) and can take one optional constant int arg. 4369 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 4370 unsigned NumArgs = TheCall->getNumArgs(); 4371 4372 if (NumArgs > 3) 4373 return Diag(TheCall->getLocEnd(), 4374 diag::err_typecheck_call_too_many_args_at_most) 4375 << 0 /*function call*/ << 3 << NumArgs 4376 << TheCall->getSourceRange(); 4377 4378 // The alignment must be a constant integer. 4379 Expr *Arg = TheCall->getArg(1); 4380 4381 // We can't check the value of a dependent argument. 4382 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 4383 llvm::APSInt Result; 4384 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 4385 return true; 4386 4387 if (!Result.isPowerOf2()) 4388 return Diag(TheCall->getLocStart(), 4389 diag::err_alignment_not_power_of_two) 4390 << Arg->getSourceRange(); 4391 } 4392 4393 if (NumArgs > 2) { 4394 ExprResult Arg(TheCall->getArg(2)); 4395 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 4396 Context.getSizeType(), false); 4397 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4398 if (Arg.isInvalid()) return true; 4399 TheCall->setArg(2, Arg.get()); 4400 } 4401 4402 return false; 4403 } 4404 4405 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 4406 unsigned BuiltinID = 4407 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 4408 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 4409 4410 unsigned NumArgs = TheCall->getNumArgs(); 4411 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 4412 if (NumArgs < NumRequiredArgs) { 4413 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 4414 << 0 /* function call */ << NumRequiredArgs << NumArgs 4415 << TheCall->getSourceRange(); 4416 } 4417 if (NumArgs >= NumRequiredArgs + 0x100) { 4418 return Diag(TheCall->getLocEnd(), 4419 diag::err_typecheck_call_too_many_args_at_most) 4420 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 4421 << TheCall->getSourceRange(); 4422 } 4423 unsigned i = 0; 4424 4425 // For formatting call, check buffer arg. 4426 if (!IsSizeCall) { 4427 ExprResult Arg(TheCall->getArg(i)); 4428 InitializedEntity Entity = InitializedEntity::InitializeParameter( 4429 Context, Context.VoidPtrTy, false); 4430 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4431 if (Arg.isInvalid()) 4432 return true; 4433 TheCall->setArg(i, Arg.get()); 4434 i++; 4435 } 4436 4437 // Check string literal arg. 4438 unsigned FormatIdx = i; 4439 { 4440 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 4441 if (Arg.isInvalid()) 4442 return true; 4443 TheCall->setArg(i, Arg.get()); 4444 i++; 4445 } 4446 4447 // Make sure variadic args are scalar. 4448 unsigned FirstDataArg = i; 4449 while (i < NumArgs) { 4450 ExprResult Arg = DefaultVariadicArgumentPromotion( 4451 TheCall->getArg(i), VariadicFunction, nullptr); 4452 if (Arg.isInvalid()) 4453 return true; 4454 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 4455 if (ArgSize.getQuantity() >= 0x100) { 4456 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big) 4457 << i << (int)ArgSize.getQuantity() << 0xff 4458 << TheCall->getSourceRange(); 4459 } 4460 TheCall->setArg(i, Arg.get()); 4461 i++; 4462 } 4463 4464 // Check formatting specifiers. NOTE: We're only doing this for the non-size 4465 // call to avoid duplicate diagnostics. 4466 if (!IsSizeCall) { 4467 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 4468 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 4469 bool Success = CheckFormatArguments( 4470 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 4471 VariadicFunction, TheCall->getLocStart(), SourceRange(), 4472 CheckedVarArgs); 4473 if (!Success) 4474 return true; 4475 } 4476 4477 if (IsSizeCall) { 4478 TheCall->setType(Context.getSizeType()); 4479 } else { 4480 TheCall->setType(Context.VoidPtrTy); 4481 } 4482 return false; 4483 } 4484 4485 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 4486 /// TheCall is a constant expression. 4487 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 4488 llvm::APSInt &Result) { 4489 Expr *Arg = TheCall->getArg(ArgNum); 4490 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4491 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 4492 4493 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 4494 4495 if (!Arg->isIntegerConstantExpr(Result, Context)) 4496 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type) 4497 << FDecl->getDeclName() << Arg->getSourceRange(); 4498 4499 return false; 4500 } 4501 4502 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 4503 /// TheCall is a constant expression in the range [Low, High]. 4504 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 4505 int Low, int High) { 4506 llvm::APSInt Result; 4507 4508 // We can't check the value of a dependent argument. 4509 Expr *Arg = TheCall->getArg(ArgNum); 4510 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4511 return false; 4512 4513 // Check constant-ness first. 4514 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4515 return true; 4516 4517 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) 4518 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 4519 << Low << High << Arg->getSourceRange(); 4520 4521 return false; 4522 } 4523 4524 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 4525 /// TheCall is a constant expression is a multiple of Num.. 4526 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 4527 unsigned Num) { 4528 llvm::APSInt Result; 4529 4530 // We can't check the value of a dependent argument. 4531 Expr *Arg = TheCall->getArg(ArgNum); 4532 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4533 return false; 4534 4535 // Check constant-ness first. 4536 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4537 return true; 4538 4539 if (Result.getSExtValue() % Num != 0) 4540 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple) 4541 << Num << Arg->getSourceRange(); 4542 4543 return false; 4544 } 4545 4546 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 4547 /// TheCall is an ARM/AArch64 special register string literal. 4548 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 4549 int ArgNum, unsigned ExpectedFieldNum, 4550 bool AllowName) { 4551 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 4552 BuiltinID == ARM::BI__builtin_arm_wsr64 || 4553 BuiltinID == ARM::BI__builtin_arm_rsr || 4554 BuiltinID == ARM::BI__builtin_arm_rsrp || 4555 BuiltinID == ARM::BI__builtin_arm_wsr || 4556 BuiltinID == ARM::BI__builtin_arm_wsrp; 4557 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 4558 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 4559 BuiltinID == AArch64::BI__builtin_arm_rsr || 4560 BuiltinID == AArch64::BI__builtin_arm_rsrp || 4561 BuiltinID == AArch64::BI__builtin_arm_wsr || 4562 BuiltinID == AArch64::BI__builtin_arm_wsrp; 4563 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 4564 4565 // We can't check the value of a dependent argument. 4566 Expr *Arg = TheCall->getArg(ArgNum); 4567 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4568 return false; 4569 4570 // Check if the argument is a string literal. 4571 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 4572 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal) 4573 << Arg->getSourceRange(); 4574 4575 // Check the type of special register given. 4576 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 4577 SmallVector<StringRef, 6> Fields; 4578 Reg.split(Fields, ":"); 4579 4580 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 4581 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg) 4582 << Arg->getSourceRange(); 4583 4584 // If the string is the name of a register then we cannot check that it is 4585 // valid here but if the string is of one the forms described in ACLE then we 4586 // can check that the supplied fields are integers and within the valid 4587 // ranges. 4588 if (Fields.size() > 1) { 4589 bool FiveFields = Fields.size() == 5; 4590 4591 bool ValidString = true; 4592 if (IsARMBuiltin) { 4593 ValidString &= Fields[0].startswith_lower("cp") || 4594 Fields[0].startswith_lower("p"); 4595 if (ValidString) 4596 Fields[0] = 4597 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 4598 4599 ValidString &= Fields[2].startswith_lower("c"); 4600 if (ValidString) 4601 Fields[2] = Fields[2].drop_front(1); 4602 4603 if (FiveFields) { 4604 ValidString &= Fields[3].startswith_lower("c"); 4605 if (ValidString) 4606 Fields[3] = Fields[3].drop_front(1); 4607 } 4608 } 4609 4610 SmallVector<int, 5> Ranges; 4611 if (FiveFields) 4612 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 4613 else 4614 Ranges.append({15, 7, 15}); 4615 4616 for (unsigned i=0; i<Fields.size(); ++i) { 4617 int IntField; 4618 ValidString &= !Fields[i].getAsInteger(10, IntField); 4619 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 4620 } 4621 4622 if (!ValidString) 4623 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg) 4624 << Arg->getSourceRange(); 4625 } else if (IsAArch64Builtin && Fields.size() == 1) { 4626 // If the register name is one of those that appear in the condition below 4627 // and the special register builtin being used is one of the write builtins, 4628 // then we require that the argument provided for writing to the register 4629 // is an integer constant expression. This is because it will be lowered to 4630 // an MSR (immediate) instruction, so we need to know the immediate at 4631 // compile time. 4632 if (TheCall->getNumArgs() != 2) 4633 return false; 4634 4635 std::string RegLower = Reg.lower(); 4636 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 4637 RegLower != "pan" && RegLower != "uao") 4638 return false; 4639 4640 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 4641 } 4642 4643 return false; 4644 } 4645 4646 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 4647 /// This checks that the target supports __builtin_longjmp and 4648 /// that val is a constant 1. 4649 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 4650 if (!Context.getTargetInfo().hasSjLjLowering()) 4651 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported) 4652 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd()); 4653 4654 Expr *Arg = TheCall->getArg(1); 4655 llvm::APSInt Result; 4656 4657 // TODO: This is less than ideal. Overload this to take a value. 4658 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 4659 return true; 4660 4661 if (Result != 1) 4662 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val) 4663 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 4664 4665 return false; 4666 } 4667 4668 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 4669 /// This checks that the target supports __builtin_setjmp. 4670 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 4671 if (!Context.getTargetInfo().hasSjLjLowering()) 4672 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported) 4673 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd()); 4674 return false; 4675 } 4676 4677 namespace { 4678 4679 class UncoveredArgHandler { 4680 enum { Unknown = -1, AllCovered = -2 }; 4681 4682 signed FirstUncoveredArg = Unknown; 4683 SmallVector<const Expr *, 4> DiagnosticExprs; 4684 4685 public: 4686 UncoveredArgHandler() = default; 4687 4688 bool hasUncoveredArg() const { 4689 return (FirstUncoveredArg >= 0); 4690 } 4691 4692 unsigned getUncoveredArg() const { 4693 assert(hasUncoveredArg() && "no uncovered argument"); 4694 return FirstUncoveredArg; 4695 } 4696 4697 void setAllCovered() { 4698 // A string has been found with all arguments covered, so clear out 4699 // the diagnostics. 4700 DiagnosticExprs.clear(); 4701 FirstUncoveredArg = AllCovered; 4702 } 4703 4704 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 4705 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 4706 4707 // Don't update if a previous string covers all arguments. 4708 if (FirstUncoveredArg == AllCovered) 4709 return; 4710 4711 // UncoveredArgHandler tracks the highest uncovered argument index 4712 // and with it all the strings that match this index. 4713 if (NewFirstUncoveredArg == FirstUncoveredArg) 4714 DiagnosticExprs.push_back(StrExpr); 4715 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 4716 DiagnosticExprs.clear(); 4717 DiagnosticExprs.push_back(StrExpr); 4718 FirstUncoveredArg = NewFirstUncoveredArg; 4719 } 4720 } 4721 4722 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 4723 }; 4724 4725 enum StringLiteralCheckType { 4726 SLCT_NotALiteral, 4727 SLCT_UncheckedLiteral, 4728 SLCT_CheckedLiteral 4729 }; 4730 4731 } // namespace 4732 4733 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 4734 BinaryOperatorKind BinOpKind, 4735 bool AddendIsRight) { 4736 unsigned BitWidth = Offset.getBitWidth(); 4737 unsigned AddendBitWidth = Addend.getBitWidth(); 4738 // There might be negative interim results. 4739 if (Addend.isUnsigned()) { 4740 Addend = Addend.zext(++AddendBitWidth); 4741 Addend.setIsSigned(true); 4742 } 4743 // Adjust the bit width of the APSInts. 4744 if (AddendBitWidth > BitWidth) { 4745 Offset = Offset.sext(AddendBitWidth); 4746 BitWidth = AddendBitWidth; 4747 } else if (BitWidth > AddendBitWidth) { 4748 Addend = Addend.sext(BitWidth); 4749 } 4750 4751 bool Ov = false; 4752 llvm::APSInt ResOffset = Offset; 4753 if (BinOpKind == BO_Add) 4754 ResOffset = Offset.sadd_ov(Addend, Ov); 4755 else { 4756 assert(AddendIsRight && BinOpKind == BO_Sub && 4757 "operator must be add or sub with addend on the right"); 4758 ResOffset = Offset.ssub_ov(Addend, Ov); 4759 } 4760 4761 // We add an offset to a pointer here so we should support an offset as big as 4762 // possible. 4763 if (Ov) { 4764 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 4765 "index (intermediate) result too big"); 4766 Offset = Offset.sext(2 * BitWidth); 4767 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 4768 return; 4769 } 4770 4771 Offset = ResOffset; 4772 } 4773 4774 namespace { 4775 4776 // This is a wrapper class around StringLiteral to support offsetted string 4777 // literals as format strings. It takes the offset into account when returning 4778 // the string and its length or the source locations to display notes correctly. 4779 class FormatStringLiteral { 4780 const StringLiteral *FExpr; 4781 int64_t Offset; 4782 4783 public: 4784 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 4785 : FExpr(fexpr), Offset(Offset) {} 4786 4787 StringRef getString() const { 4788 return FExpr->getString().drop_front(Offset); 4789 } 4790 4791 unsigned getByteLength() const { 4792 return FExpr->getByteLength() - getCharByteWidth() * Offset; 4793 } 4794 4795 unsigned getLength() const { return FExpr->getLength() - Offset; } 4796 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 4797 4798 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 4799 4800 QualType getType() const { return FExpr->getType(); } 4801 4802 bool isAscii() const { return FExpr->isAscii(); } 4803 bool isWide() const { return FExpr->isWide(); } 4804 bool isUTF8() const { return FExpr->isUTF8(); } 4805 bool isUTF16() const { return FExpr->isUTF16(); } 4806 bool isUTF32() const { return FExpr->isUTF32(); } 4807 bool isPascal() const { return FExpr->isPascal(); } 4808 4809 SourceLocation getLocationOfByte( 4810 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 4811 const TargetInfo &Target, unsigned *StartToken = nullptr, 4812 unsigned *StartTokenByteOffset = nullptr) const { 4813 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 4814 StartToken, StartTokenByteOffset); 4815 } 4816 4817 SourceLocation getLocStart() const LLVM_READONLY { 4818 return FExpr->getLocStart().getLocWithOffset(Offset); 4819 } 4820 4821 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); } 4822 }; 4823 4824 } // namespace 4825 4826 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 4827 const Expr *OrigFormatExpr, 4828 ArrayRef<const Expr *> Args, 4829 bool HasVAListArg, unsigned format_idx, 4830 unsigned firstDataArg, 4831 Sema::FormatStringType Type, 4832 bool inFunctionCall, 4833 Sema::VariadicCallType CallType, 4834 llvm::SmallBitVector &CheckedVarArgs, 4835 UncoveredArgHandler &UncoveredArg); 4836 4837 // Determine if an expression is a string literal or constant string. 4838 // If this function returns false on the arguments to a function expecting a 4839 // format string, we will usually need to emit a warning. 4840 // True string literals are then checked by CheckFormatString. 4841 static StringLiteralCheckType 4842 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 4843 bool HasVAListArg, unsigned format_idx, 4844 unsigned firstDataArg, Sema::FormatStringType Type, 4845 Sema::VariadicCallType CallType, bool InFunctionCall, 4846 llvm::SmallBitVector &CheckedVarArgs, 4847 UncoveredArgHandler &UncoveredArg, 4848 llvm::APSInt Offset) { 4849 tryAgain: 4850 assert(Offset.isSigned() && "invalid offset"); 4851 4852 if (E->isTypeDependent() || E->isValueDependent()) 4853 return SLCT_NotALiteral; 4854 4855 E = E->IgnoreParenCasts(); 4856 4857 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 4858 // Technically -Wformat-nonliteral does not warn about this case. 4859 // The behavior of printf and friends in this case is implementation 4860 // dependent. Ideally if the format string cannot be null then 4861 // it should have a 'nonnull' attribute in the function prototype. 4862 return SLCT_UncheckedLiteral; 4863 4864 switch (E->getStmtClass()) { 4865 case Stmt::BinaryConditionalOperatorClass: 4866 case Stmt::ConditionalOperatorClass: { 4867 // The expression is a literal if both sub-expressions were, and it was 4868 // completely checked only if both sub-expressions were checked. 4869 const AbstractConditionalOperator *C = 4870 cast<AbstractConditionalOperator>(E); 4871 4872 // Determine whether it is necessary to check both sub-expressions, for 4873 // example, because the condition expression is a constant that can be 4874 // evaluated at compile time. 4875 bool CheckLeft = true, CheckRight = true; 4876 4877 bool Cond; 4878 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) { 4879 if (Cond) 4880 CheckRight = false; 4881 else 4882 CheckLeft = false; 4883 } 4884 4885 // We need to maintain the offsets for the right and the left hand side 4886 // separately to check if every possible indexed expression is a valid 4887 // string literal. They might have different offsets for different string 4888 // literals in the end. 4889 StringLiteralCheckType Left; 4890 if (!CheckLeft) 4891 Left = SLCT_UncheckedLiteral; 4892 else { 4893 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 4894 HasVAListArg, format_idx, firstDataArg, 4895 Type, CallType, InFunctionCall, 4896 CheckedVarArgs, UncoveredArg, Offset); 4897 if (Left == SLCT_NotALiteral || !CheckRight) { 4898 return Left; 4899 } 4900 } 4901 4902 StringLiteralCheckType Right = 4903 checkFormatStringExpr(S, C->getFalseExpr(), Args, 4904 HasVAListArg, format_idx, firstDataArg, 4905 Type, CallType, InFunctionCall, CheckedVarArgs, 4906 UncoveredArg, Offset); 4907 4908 return (CheckLeft && Left < Right) ? Left : Right; 4909 } 4910 4911 case Stmt::ImplicitCastExprClass: 4912 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 4913 goto tryAgain; 4914 4915 case Stmt::OpaqueValueExprClass: 4916 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 4917 E = src; 4918 goto tryAgain; 4919 } 4920 return SLCT_NotALiteral; 4921 4922 case Stmt::PredefinedExprClass: 4923 // While __func__, etc., are technically not string literals, they 4924 // cannot contain format specifiers and thus are not a security 4925 // liability. 4926 return SLCT_UncheckedLiteral; 4927 4928 case Stmt::DeclRefExprClass: { 4929 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 4930 4931 // As an exception, do not flag errors for variables binding to 4932 // const string literals. 4933 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 4934 bool isConstant = false; 4935 QualType T = DR->getType(); 4936 4937 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 4938 isConstant = AT->getElementType().isConstant(S.Context); 4939 } else if (const PointerType *PT = T->getAs<PointerType>()) { 4940 isConstant = T.isConstant(S.Context) && 4941 PT->getPointeeType().isConstant(S.Context); 4942 } else if (T->isObjCObjectPointerType()) { 4943 // In ObjC, there is usually no "const ObjectPointer" type, 4944 // so don't check if the pointee type is constant. 4945 isConstant = T.isConstant(S.Context); 4946 } 4947 4948 if (isConstant) { 4949 if (const Expr *Init = VD->getAnyInitializer()) { 4950 // Look through initializers like const char c[] = { "foo" } 4951 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 4952 if (InitList->isStringLiteralInit()) 4953 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 4954 } 4955 return checkFormatStringExpr(S, Init, Args, 4956 HasVAListArg, format_idx, 4957 firstDataArg, Type, CallType, 4958 /*InFunctionCall*/ false, CheckedVarArgs, 4959 UncoveredArg, Offset); 4960 } 4961 } 4962 4963 // For vprintf* functions (i.e., HasVAListArg==true), we add a 4964 // special check to see if the format string is a function parameter 4965 // of the function calling the printf function. If the function 4966 // has an attribute indicating it is a printf-like function, then we 4967 // should suppress warnings concerning non-literals being used in a call 4968 // to a vprintf function. For example: 4969 // 4970 // void 4971 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 4972 // va_list ap; 4973 // va_start(ap, fmt); 4974 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 4975 // ... 4976 // } 4977 if (HasVAListArg) { 4978 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 4979 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 4980 int PVIndex = PV->getFunctionScopeIndex() + 1; 4981 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 4982 // adjust for implicit parameter 4983 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 4984 if (MD->isInstance()) 4985 ++PVIndex; 4986 // We also check if the formats are compatible. 4987 // We can't pass a 'scanf' string to a 'printf' function. 4988 if (PVIndex == PVFormat->getFormatIdx() && 4989 Type == S.GetFormatStringType(PVFormat)) 4990 return SLCT_UncheckedLiteral; 4991 } 4992 } 4993 } 4994 } 4995 } 4996 4997 return SLCT_NotALiteral; 4998 } 4999 5000 case Stmt::CallExprClass: 5001 case Stmt::CXXMemberCallExprClass: { 5002 const CallExpr *CE = cast<CallExpr>(E); 5003 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 5004 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) { 5005 unsigned ArgIndex = FA->getFormatIdx(); 5006 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 5007 if (MD->isInstance()) 5008 --ArgIndex; 5009 const Expr *Arg = CE->getArg(ArgIndex - 1); 5010 5011 return checkFormatStringExpr(S, Arg, Args, 5012 HasVAListArg, format_idx, firstDataArg, 5013 Type, CallType, InFunctionCall, 5014 CheckedVarArgs, UncoveredArg, Offset); 5015 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) { 5016 unsigned BuiltinID = FD->getBuiltinID(); 5017 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 5018 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 5019 const Expr *Arg = CE->getArg(0); 5020 return checkFormatStringExpr(S, Arg, Args, 5021 HasVAListArg, format_idx, 5022 firstDataArg, Type, CallType, 5023 InFunctionCall, CheckedVarArgs, 5024 UncoveredArg, Offset); 5025 } 5026 } 5027 } 5028 5029 return SLCT_NotALiteral; 5030 } 5031 case Stmt::ObjCMessageExprClass: { 5032 const auto *ME = cast<ObjCMessageExpr>(E); 5033 if (const auto *ND = ME->getMethodDecl()) { 5034 if (const auto *FA = ND->getAttr<FormatArgAttr>()) { 5035 unsigned ArgIndex = FA->getFormatIdx(); 5036 const Expr *Arg = ME->getArg(ArgIndex - 1); 5037 return checkFormatStringExpr( 5038 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 5039 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset); 5040 } 5041 } 5042 5043 return SLCT_NotALiteral; 5044 } 5045 case Stmt::ObjCStringLiteralClass: 5046 case Stmt::StringLiteralClass: { 5047 const StringLiteral *StrE = nullptr; 5048 5049 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 5050 StrE = ObjCFExpr->getString(); 5051 else 5052 StrE = cast<StringLiteral>(E); 5053 5054 if (StrE) { 5055 if (Offset.isNegative() || Offset > StrE->getLength()) { 5056 // TODO: It would be better to have an explicit warning for out of 5057 // bounds literals. 5058 return SLCT_NotALiteral; 5059 } 5060 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 5061 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 5062 firstDataArg, Type, InFunctionCall, CallType, 5063 CheckedVarArgs, UncoveredArg); 5064 return SLCT_CheckedLiteral; 5065 } 5066 5067 return SLCT_NotALiteral; 5068 } 5069 case Stmt::BinaryOperatorClass: { 5070 llvm::APSInt LResult; 5071 llvm::APSInt RResult; 5072 5073 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 5074 5075 // A string literal + an int offset is still a string literal. 5076 if (BinOp->isAdditiveOp()) { 5077 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context); 5078 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context); 5079 5080 if (LIsInt != RIsInt) { 5081 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 5082 5083 if (LIsInt) { 5084 if (BinOpKind == BO_Add) { 5085 sumOffsets(Offset, LResult, BinOpKind, RIsInt); 5086 E = BinOp->getRHS(); 5087 goto tryAgain; 5088 } 5089 } else { 5090 sumOffsets(Offset, RResult, BinOpKind, RIsInt); 5091 E = BinOp->getLHS(); 5092 goto tryAgain; 5093 } 5094 } 5095 } 5096 5097 return SLCT_NotALiteral; 5098 } 5099 case Stmt::UnaryOperatorClass: { 5100 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 5101 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 5102 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 5103 llvm::APSInt IndexResult; 5104 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) { 5105 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true); 5106 E = ASE->getBase(); 5107 goto tryAgain; 5108 } 5109 } 5110 5111 return SLCT_NotALiteral; 5112 } 5113 5114 default: 5115 return SLCT_NotALiteral; 5116 } 5117 } 5118 5119 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 5120 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 5121 .Case("scanf", FST_Scanf) 5122 .Cases("printf", "printf0", FST_Printf) 5123 .Cases("NSString", "CFString", FST_NSString) 5124 .Case("strftime", FST_Strftime) 5125 .Case("strfmon", FST_Strfmon) 5126 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 5127 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 5128 .Case("os_trace", FST_OSLog) 5129 .Case("os_log", FST_OSLog) 5130 .Default(FST_Unknown); 5131 } 5132 5133 /// CheckFormatArguments - Check calls to printf and scanf (and similar 5134 /// functions) for correct use of format strings. 5135 /// Returns true if a format string has been fully checked. 5136 bool Sema::CheckFormatArguments(const FormatAttr *Format, 5137 ArrayRef<const Expr *> Args, 5138 bool IsCXXMember, 5139 VariadicCallType CallType, 5140 SourceLocation Loc, SourceRange Range, 5141 llvm::SmallBitVector &CheckedVarArgs) { 5142 FormatStringInfo FSI; 5143 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 5144 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 5145 FSI.FirstDataArg, GetFormatStringType(Format), 5146 CallType, Loc, Range, CheckedVarArgs); 5147 return false; 5148 } 5149 5150 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 5151 bool HasVAListArg, unsigned format_idx, 5152 unsigned firstDataArg, FormatStringType Type, 5153 VariadicCallType CallType, 5154 SourceLocation Loc, SourceRange Range, 5155 llvm::SmallBitVector &CheckedVarArgs) { 5156 // CHECK: printf/scanf-like function is called with no format string. 5157 if (format_idx >= Args.size()) { 5158 Diag(Loc, diag::warn_missing_format_string) << Range; 5159 return false; 5160 } 5161 5162 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 5163 5164 // CHECK: format string is not a string literal. 5165 // 5166 // Dynamically generated format strings are difficult to 5167 // automatically vet at compile time. Requiring that format strings 5168 // are string literals: (1) permits the checking of format strings by 5169 // the compiler and thereby (2) can practically remove the source of 5170 // many format string exploits. 5171 5172 // Format string can be either ObjC string (e.g. @"%d") or 5173 // C string (e.g. "%d") 5174 // ObjC string uses the same format specifiers as C string, so we can use 5175 // the same format string checking logic for both ObjC and C strings. 5176 UncoveredArgHandler UncoveredArg; 5177 StringLiteralCheckType CT = 5178 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 5179 format_idx, firstDataArg, Type, CallType, 5180 /*IsFunctionCall*/ true, CheckedVarArgs, 5181 UncoveredArg, 5182 /*no string offset*/ llvm::APSInt(64, false) = 0); 5183 5184 // Generate a diagnostic where an uncovered argument is detected. 5185 if (UncoveredArg.hasUncoveredArg()) { 5186 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 5187 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 5188 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 5189 } 5190 5191 if (CT != SLCT_NotALiteral) 5192 // Literal format string found, check done! 5193 return CT == SLCT_CheckedLiteral; 5194 5195 // Strftime is particular as it always uses a single 'time' argument, 5196 // so it is safe to pass a non-literal string. 5197 if (Type == FST_Strftime) 5198 return false; 5199 5200 // Do not emit diag when the string param is a macro expansion and the 5201 // format is either NSString or CFString. This is a hack to prevent 5202 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 5203 // which are usually used in place of NS and CF string literals. 5204 SourceLocation FormatLoc = Args[format_idx]->getLocStart(); 5205 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 5206 return false; 5207 5208 // If there are no arguments specified, warn with -Wformat-security, otherwise 5209 // warn only with -Wformat-nonliteral. 5210 if (Args.size() == firstDataArg) { 5211 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 5212 << OrigFormatExpr->getSourceRange(); 5213 switch (Type) { 5214 default: 5215 break; 5216 case FST_Kprintf: 5217 case FST_FreeBSDKPrintf: 5218 case FST_Printf: 5219 Diag(FormatLoc, diag::note_format_security_fixit) 5220 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 5221 break; 5222 case FST_NSString: 5223 Diag(FormatLoc, diag::note_format_security_fixit) 5224 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 5225 break; 5226 } 5227 } else { 5228 Diag(FormatLoc, diag::warn_format_nonliteral) 5229 << OrigFormatExpr->getSourceRange(); 5230 } 5231 return false; 5232 } 5233 5234 namespace { 5235 5236 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 5237 protected: 5238 Sema &S; 5239 const FormatStringLiteral *FExpr; 5240 const Expr *OrigFormatExpr; 5241 const Sema::FormatStringType FSType; 5242 const unsigned FirstDataArg; 5243 const unsigned NumDataArgs; 5244 const char *Beg; // Start of format string. 5245 const bool HasVAListArg; 5246 ArrayRef<const Expr *> Args; 5247 unsigned FormatIdx; 5248 llvm::SmallBitVector CoveredArgs; 5249 bool usesPositionalArgs = false; 5250 bool atFirstArg = true; 5251 bool inFunctionCall; 5252 Sema::VariadicCallType CallType; 5253 llvm::SmallBitVector &CheckedVarArgs; 5254 UncoveredArgHandler &UncoveredArg; 5255 5256 public: 5257 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 5258 const Expr *origFormatExpr, 5259 const Sema::FormatStringType type, unsigned firstDataArg, 5260 unsigned numDataArgs, const char *beg, bool hasVAListArg, 5261 ArrayRef<const Expr *> Args, unsigned formatIdx, 5262 bool inFunctionCall, Sema::VariadicCallType callType, 5263 llvm::SmallBitVector &CheckedVarArgs, 5264 UncoveredArgHandler &UncoveredArg) 5265 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 5266 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 5267 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 5268 inFunctionCall(inFunctionCall), CallType(callType), 5269 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 5270 CoveredArgs.resize(numDataArgs); 5271 CoveredArgs.reset(); 5272 } 5273 5274 void DoneProcessing(); 5275 5276 void HandleIncompleteSpecifier(const char *startSpecifier, 5277 unsigned specifierLen) override; 5278 5279 void HandleInvalidLengthModifier( 5280 const analyze_format_string::FormatSpecifier &FS, 5281 const analyze_format_string::ConversionSpecifier &CS, 5282 const char *startSpecifier, unsigned specifierLen, 5283 unsigned DiagID); 5284 5285 void HandleNonStandardLengthModifier( 5286 const analyze_format_string::FormatSpecifier &FS, 5287 const char *startSpecifier, unsigned specifierLen); 5288 5289 void HandleNonStandardConversionSpecifier( 5290 const analyze_format_string::ConversionSpecifier &CS, 5291 const char *startSpecifier, unsigned specifierLen); 5292 5293 void HandlePosition(const char *startPos, unsigned posLen) override; 5294 5295 void HandleInvalidPosition(const char *startSpecifier, 5296 unsigned specifierLen, 5297 analyze_format_string::PositionContext p) override; 5298 5299 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 5300 5301 void HandleNullChar(const char *nullCharacter) override; 5302 5303 template <typename Range> 5304 static void 5305 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 5306 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 5307 bool IsStringLocation, Range StringRange, 5308 ArrayRef<FixItHint> Fixit = None); 5309 5310 protected: 5311 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 5312 const char *startSpec, 5313 unsigned specifierLen, 5314 const char *csStart, unsigned csLen); 5315 5316 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 5317 const char *startSpec, 5318 unsigned specifierLen); 5319 5320 SourceRange getFormatStringRange(); 5321 CharSourceRange getSpecifierRange(const char *startSpecifier, 5322 unsigned specifierLen); 5323 SourceLocation getLocationOfByte(const char *x); 5324 5325 const Expr *getDataArg(unsigned i) const; 5326 5327 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 5328 const analyze_format_string::ConversionSpecifier &CS, 5329 const char *startSpecifier, unsigned specifierLen, 5330 unsigned argIndex); 5331 5332 template <typename Range> 5333 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 5334 bool IsStringLocation, Range StringRange, 5335 ArrayRef<FixItHint> Fixit = None); 5336 }; 5337 5338 } // namespace 5339 5340 SourceRange CheckFormatHandler::getFormatStringRange() { 5341 return OrigFormatExpr->getSourceRange(); 5342 } 5343 5344 CharSourceRange CheckFormatHandler:: 5345 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 5346 SourceLocation Start = getLocationOfByte(startSpecifier); 5347 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 5348 5349 // Advance the end SourceLocation by one due to half-open ranges. 5350 End = End.getLocWithOffset(1); 5351 5352 return CharSourceRange::getCharRange(Start, End); 5353 } 5354 5355 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 5356 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 5357 S.getLangOpts(), S.Context.getTargetInfo()); 5358 } 5359 5360 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 5361 unsigned specifierLen){ 5362 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 5363 getLocationOfByte(startSpecifier), 5364 /*IsStringLocation*/true, 5365 getSpecifierRange(startSpecifier, specifierLen)); 5366 } 5367 5368 void CheckFormatHandler::HandleInvalidLengthModifier( 5369 const analyze_format_string::FormatSpecifier &FS, 5370 const analyze_format_string::ConversionSpecifier &CS, 5371 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 5372 using namespace analyze_format_string; 5373 5374 const LengthModifier &LM = FS.getLengthModifier(); 5375 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 5376 5377 // See if we know how to fix this length modifier. 5378 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 5379 if (FixedLM) { 5380 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 5381 getLocationOfByte(LM.getStart()), 5382 /*IsStringLocation*/true, 5383 getSpecifierRange(startSpecifier, specifierLen)); 5384 5385 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 5386 << FixedLM->toString() 5387 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 5388 5389 } else { 5390 FixItHint Hint; 5391 if (DiagID == diag::warn_format_nonsensical_length) 5392 Hint = FixItHint::CreateRemoval(LMRange); 5393 5394 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 5395 getLocationOfByte(LM.getStart()), 5396 /*IsStringLocation*/true, 5397 getSpecifierRange(startSpecifier, specifierLen), 5398 Hint); 5399 } 5400 } 5401 5402 void CheckFormatHandler::HandleNonStandardLengthModifier( 5403 const analyze_format_string::FormatSpecifier &FS, 5404 const char *startSpecifier, unsigned specifierLen) { 5405 using namespace analyze_format_string; 5406 5407 const LengthModifier &LM = FS.getLengthModifier(); 5408 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 5409 5410 // See if we know how to fix this length modifier. 5411 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 5412 if (FixedLM) { 5413 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5414 << LM.toString() << 0, 5415 getLocationOfByte(LM.getStart()), 5416 /*IsStringLocation*/true, 5417 getSpecifierRange(startSpecifier, specifierLen)); 5418 5419 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 5420 << FixedLM->toString() 5421 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 5422 5423 } else { 5424 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5425 << LM.toString() << 0, 5426 getLocationOfByte(LM.getStart()), 5427 /*IsStringLocation*/true, 5428 getSpecifierRange(startSpecifier, specifierLen)); 5429 } 5430 } 5431 5432 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 5433 const analyze_format_string::ConversionSpecifier &CS, 5434 const char *startSpecifier, unsigned specifierLen) { 5435 using namespace analyze_format_string; 5436 5437 // See if we know how to fix this conversion specifier. 5438 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 5439 if (FixedCS) { 5440 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5441 << CS.toString() << /*conversion specifier*/1, 5442 getLocationOfByte(CS.getStart()), 5443 /*IsStringLocation*/true, 5444 getSpecifierRange(startSpecifier, specifierLen)); 5445 5446 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 5447 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 5448 << FixedCS->toString() 5449 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 5450 } else { 5451 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5452 << CS.toString() << /*conversion specifier*/1, 5453 getLocationOfByte(CS.getStart()), 5454 /*IsStringLocation*/true, 5455 getSpecifierRange(startSpecifier, specifierLen)); 5456 } 5457 } 5458 5459 void CheckFormatHandler::HandlePosition(const char *startPos, 5460 unsigned posLen) { 5461 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 5462 getLocationOfByte(startPos), 5463 /*IsStringLocation*/true, 5464 getSpecifierRange(startPos, posLen)); 5465 } 5466 5467 void 5468 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 5469 analyze_format_string::PositionContext p) { 5470 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 5471 << (unsigned) p, 5472 getLocationOfByte(startPos), /*IsStringLocation*/true, 5473 getSpecifierRange(startPos, posLen)); 5474 } 5475 5476 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 5477 unsigned posLen) { 5478 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 5479 getLocationOfByte(startPos), 5480 /*IsStringLocation*/true, 5481 getSpecifierRange(startPos, posLen)); 5482 } 5483 5484 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 5485 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 5486 // The presence of a null character is likely an error. 5487 EmitFormatDiagnostic( 5488 S.PDiag(diag::warn_printf_format_string_contains_null_char), 5489 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 5490 getFormatStringRange()); 5491 } 5492 } 5493 5494 // Note that this may return NULL if there was an error parsing or building 5495 // one of the argument expressions. 5496 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 5497 return Args[FirstDataArg + i]; 5498 } 5499 5500 void CheckFormatHandler::DoneProcessing() { 5501 // Does the number of data arguments exceed the number of 5502 // format conversions in the format string? 5503 if (!HasVAListArg) { 5504 // Find any arguments that weren't covered. 5505 CoveredArgs.flip(); 5506 signed notCoveredArg = CoveredArgs.find_first(); 5507 if (notCoveredArg >= 0) { 5508 assert((unsigned)notCoveredArg < NumDataArgs); 5509 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 5510 } else { 5511 UncoveredArg.setAllCovered(); 5512 } 5513 } 5514 } 5515 5516 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 5517 const Expr *ArgExpr) { 5518 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 5519 "Invalid state"); 5520 5521 if (!ArgExpr) 5522 return; 5523 5524 SourceLocation Loc = ArgExpr->getLocStart(); 5525 5526 if (S.getSourceManager().isInSystemMacro(Loc)) 5527 return; 5528 5529 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 5530 for (auto E : DiagnosticExprs) 5531 PDiag << E->getSourceRange(); 5532 5533 CheckFormatHandler::EmitFormatDiagnostic( 5534 S, IsFunctionCall, DiagnosticExprs[0], 5535 PDiag, Loc, /*IsStringLocation*/false, 5536 DiagnosticExprs[0]->getSourceRange()); 5537 } 5538 5539 bool 5540 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 5541 SourceLocation Loc, 5542 const char *startSpec, 5543 unsigned specifierLen, 5544 const char *csStart, 5545 unsigned csLen) { 5546 bool keepGoing = true; 5547 if (argIndex < NumDataArgs) { 5548 // Consider the argument coverered, even though the specifier doesn't 5549 // make sense. 5550 CoveredArgs.set(argIndex); 5551 } 5552 else { 5553 // If argIndex exceeds the number of data arguments we 5554 // don't issue a warning because that is just a cascade of warnings (and 5555 // they may have intended '%%' anyway). We don't want to continue processing 5556 // the format string after this point, however, as we will like just get 5557 // gibberish when trying to match arguments. 5558 keepGoing = false; 5559 } 5560 5561 StringRef Specifier(csStart, csLen); 5562 5563 // If the specifier in non-printable, it could be the first byte of a UTF-8 5564 // sequence. In that case, print the UTF-8 code point. If not, print the byte 5565 // hex value. 5566 std::string CodePointStr; 5567 if (!llvm::sys::locale::isPrint(*csStart)) { 5568 llvm::UTF32 CodePoint; 5569 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 5570 const llvm::UTF8 *E = 5571 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 5572 llvm::ConversionResult Result = 5573 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 5574 5575 if (Result != llvm::conversionOK) { 5576 unsigned char FirstChar = *csStart; 5577 CodePoint = (llvm::UTF32)FirstChar; 5578 } 5579 5580 llvm::raw_string_ostream OS(CodePointStr); 5581 if (CodePoint < 256) 5582 OS << "\\x" << llvm::format("%02x", CodePoint); 5583 else if (CodePoint <= 0xFFFF) 5584 OS << "\\u" << llvm::format("%04x", CodePoint); 5585 else 5586 OS << "\\U" << llvm::format("%08x", CodePoint); 5587 OS.flush(); 5588 Specifier = CodePointStr; 5589 } 5590 5591 EmitFormatDiagnostic( 5592 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 5593 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 5594 5595 return keepGoing; 5596 } 5597 5598 void 5599 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 5600 const char *startSpec, 5601 unsigned specifierLen) { 5602 EmitFormatDiagnostic( 5603 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 5604 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 5605 } 5606 5607 bool 5608 CheckFormatHandler::CheckNumArgs( 5609 const analyze_format_string::FormatSpecifier &FS, 5610 const analyze_format_string::ConversionSpecifier &CS, 5611 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 5612 5613 if (argIndex >= NumDataArgs) { 5614 PartialDiagnostic PDiag = FS.usesPositionalArg() 5615 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 5616 << (argIndex+1) << NumDataArgs) 5617 : S.PDiag(diag::warn_printf_insufficient_data_args); 5618 EmitFormatDiagnostic( 5619 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 5620 getSpecifierRange(startSpecifier, specifierLen)); 5621 5622 // Since more arguments than conversion tokens are given, by extension 5623 // all arguments are covered, so mark this as so. 5624 UncoveredArg.setAllCovered(); 5625 return false; 5626 } 5627 return true; 5628 } 5629 5630 template<typename Range> 5631 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 5632 SourceLocation Loc, 5633 bool IsStringLocation, 5634 Range StringRange, 5635 ArrayRef<FixItHint> FixIt) { 5636 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 5637 Loc, IsStringLocation, StringRange, FixIt); 5638 } 5639 5640 /// \brief If the format string is not within the funcion call, emit a note 5641 /// so that the function call and string are in diagnostic messages. 5642 /// 5643 /// \param InFunctionCall if true, the format string is within the function 5644 /// call and only one diagnostic message will be produced. Otherwise, an 5645 /// extra note will be emitted pointing to location of the format string. 5646 /// 5647 /// \param ArgumentExpr the expression that is passed as the format string 5648 /// argument in the function call. Used for getting locations when two 5649 /// diagnostics are emitted. 5650 /// 5651 /// \param PDiag the callee should already have provided any strings for the 5652 /// diagnostic message. This function only adds locations and fixits 5653 /// to diagnostics. 5654 /// 5655 /// \param Loc primary location for diagnostic. If two diagnostics are 5656 /// required, one will be at Loc and a new SourceLocation will be created for 5657 /// the other one. 5658 /// 5659 /// \param IsStringLocation if true, Loc points to the format string should be 5660 /// used for the note. Otherwise, Loc points to the argument list and will 5661 /// be used with PDiag. 5662 /// 5663 /// \param StringRange some or all of the string to highlight. This is 5664 /// templated so it can accept either a CharSourceRange or a SourceRange. 5665 /// 5666 /// \param FixIt optional fix it hint for the format string. 5667 template <typename Range> 5668 void CheckFormatHandler::EmitFormatDiagnostic( 5669 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 5670 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 5671 Range StringRange, ArrayRef<FixItHint> FixIt) { 5672 if (InFunctionCall) { 5673 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 5674 D << StringRange; 5675 D << FixIt; 5676 } else { 5677 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 5678 << ArgumentExpr->getSourceRange(); 5679 5680 const Sema::SemaDiagnosticBuilder &Note = 5681 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 5682 diag::note_format_string_defined); 5683 5684 Note << StringRange; 5685 Note << FixIt; 5686 } 5687 } 5688 5689 //===--- CHECK: Printf format string checking ------------------------------===// 5690 5691 namespace { 5692 5693 class CheckPrintfHandler : public CheckFormatHandler { 5694 public: 5695 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 5696 const Expr *origFormatExpr, 5697 const Sema::FormatStringType type, unsigned firstDataArg, 5698 unsigned numDataArgs, bool isObjC, const char *beg, 5699 bool hasVAListArg, ArrayRef<const Expr *> Args, 5700 unsigned formatIdx, bool inFunctionCall, 5701 Sema::VariadicCallType CallType, 5702 llvm::SmallBitVector &CheckedVarArgs, 5703 UncoveredArgHandler &UncoveredArg) 5704 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 5705 numDataArgs, beg, hasVAListArg, Args, formatIdx, 5706 inFunctionCall, CallType, CheckedVarArgs, 5707 UncoveredArg) {} 5708 5709 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 5710 5711 /// Returns true if '%@' specifiers are allowed in the format string. 5712 bool allowsObjCArg() const { 5713 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 5714 FSType == Sema::FST_OSTrace; 5715 } 5716 5717 bool HandleInvalidPrintfConversionSpecifier( 5718 const analyze_printf::PrintfSpecifier &FS, 5719 const char *startSpecifier, 5720 unsigned specifierLen) override; 5721 5722 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 5723 const char *startSpecifier, 5724 unsigned specifierLen) override; 5725 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 5726 const char *StartSpecifier, 5727 unsigned SpecifierLen, 5728 const Expr *E); 5729 5730 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 5731 const char *startSpecifier, unsigned specifierLen); 5732 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 5733 const analyze_printf::OptionalAmount &Amt, 5734 unsigned type, 5735 const char *startSpecifier, unsigned specifierLen); 5736 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 5737 const analyze_printf::OptionalFlag &flag, 5738 const char *startSpecifier, unsigned specifierLen); 5739 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 5740 const analyze_printf::OptionalFlag &ignoredFlag, 5741 const analyze_printf::OptionalFlag &flag, 5742 const char *startSpecifier, unsigned specifierLen); 5743 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 5744 const Expr *E); 5745 5746 void HandleEmptyObjCModifierFlag(const char *startFlag, 5747 unsigned flagLen) override; 5748 5749 void HandleInvalidObjCModifierFlag(const char *startFlag, 5750 unsigned flagLen) override; 5751 5752 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 5753 const char *flagsEnd, 5754 const char *conversionPosition) 5755 override; 5756 }; 5757 5758 } // namespace 5759 5760 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 5761 const analyze_printf::PrintfSpecifier &FS, 5762 const char *startSpecifier, 5763 unsigned specifierLen) { 5764 const analyze_printf::PrintfConversionSpecifier &CS = 5765 FS.getConversionSpecifier(); 5766 5767 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 5768 getLocationOfByte(CS.getStart()), 5769 startSpecifier, specifierLen, 5770 CS.getStart(), CS.getLength()); 5771 } 5772 5773 bool CheckPrintfHandler::HandleAmount( 5774 const analyze_format_string::OptionalAmount &Amt, 5775 unsigned k, const char *startSpecifier, 5776 unsigned specifierLen) { 5777 if (Amt.hasDataArgument()) { 5778 if (!HasVAListArg) { 5779 unsigned argIndex = Amt.getArgIndex(); 5780 if (argIndex >= NumDataArgs) { 5781 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 5782 << k, 5783 getLocationOfByte(Amt.getStart()), 5784 /*IsStringLocation*/true, 5785 getSpecifierRange(startSpecifier, specifierLen)); 5786 // Don't do any more checking. We will just emit 5787 // spurious errors. 5788 return false; 5789 } 5790 5791 // Type check the data argument. It should be an 'int'. 5792 // Although not in conformance with C99, we also allow the argument to be 5793 // an 'unsigned int' as that is a reasonably safe case. GCC also 5794 // doesn't emit a warning for that case. 5795 CoveredArgs.set(argIndex); 5796 const Expr *Arg = getDataArg(argIndex); 5797 if (!Arg) 5798 return false; 5799 5800 QualType T = Arg->getType(); 5801 5802 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 5803 assert(AT.isValid()); 5804 5805 if (!AT.matchesType(S.Context, T)) { 5806 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 5807 << k << AT.getRepresentativeTypeName(S.Context) 5808 << T << Arg->getSourceRange(), 5809 getLocationOfByte(Amt.getStart()), 5810 /*IsStringLocation*/true, 5811 getSpecifierRange(startSpecifier, specifierLen)); 5812 // Don't do any more checking. We will just emit 5813 // spurious errors. 5814 return false; 5815 } 5816 } 5817 } 5818 return true; 5819 } 5820 5821 void CheckPrintfHandler::HandleInvalidAmount( 5822 const analyze_printf::PrintfSpecifier &FS, 5823 const analyze_printf::OptionalAmount &Amt, 5824 unsigned type, 5825 const char *startSpecifier, 5826 unsigned specifierLen) { 5827 const analyze_printf::PrintfConversionSpecifier &CS = 5828 FS.getConversionSpecifier(); 5829 5830 FixItHint fixit = 5831 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 5832 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 5833 Amt.getConstantLength())) 5834 : FixItHint(); 5835 5836 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 5837 << type << CS.toString(), 5838 getLocationOfByte(Amt.getStart()), 5839 /*IsStringLocation*/true, 5840 getSpecifierRange(startSpecifier, specifierLen), 5841 fixit); 5842 } 5843 5844 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 5845 const analyze_printf::OptionalFlag &flag, 5846 const char *startSpecifier, 5847 unsigned specifierLen) { 5848 // Warn about pointless flag with a fixit removal. 5849 const analyze_printf::PrintfConversionSpecifier &CS = 5850 FS.getConversionSpecifier(); 5851 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 5852 << flag.toString() << CS.toString(), 5853 getLocationOfByte(flag.getPosition()), 5854 /*IsStringLocation*/true, 5855 getSpecifierRange(startSpecifier, specifierLen), 5856 FixItHint::CreateRemoval( 5857 getSpecifierRange(flag.getPosition(), 1))); 5858 } 5859 5860 void CheckPrintfHandler::HandleIgnoredFlag( 5861 const analyze_printf::PrintfSpecifier &FS, 5862 const analyze_printf::OptionalFlag &ignoredFlag, 5863 const analyze_printf::OptionalFlag &flag, 5864 const char *startSpecifier, 5865 unsigned specifierLen) { 5866 // Warn about ignored flag with a fixit removal. 5867 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 5868 << ignoredFlag.toString() << flag.toString(), 5869 getLocationOfByte(ignoredFlag.getPosition()), 5870 /*IsStringLocation*/true, 5871 getSpecifierRange(startSpecifier, specifierLen), 5872 FixItHint::CreateRemoval( 5873 getSpecifierRange(ignoredFlag.getPosition(), 1))); 5874 } 5875 5876 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 5877 unsigned flagLen) { 5878 // Warn about an empty flag. 5879 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 5880 getLocationOfByte(startFlag), 5881 /*IsStringLocation*/true, 5882 getSpecifierRange(startFlag, flagLen)); 5883 } 5884 5885 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 5886 unsigned flagLen) { 5887 // Warn about an invalid flag. 5888 auto Range = getSpecifierRange(startFlag, flagLen); 5889 StringRef flag(startFlag, flagLen); 5890 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 5891 getLocationOfByte(startFlag), 5892 /*IsStringLocation*/true, 5893 Range, FixItHint::CreateRemoval(Range)); 5894 } 5895 5896 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 5897 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 5898 // Warn about using '[...]' without a '@' conversion. 5899 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 5900 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 5901 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 5902 getLocationOfByte(conversionPosition), 5903 /*IsStringLocation*/true, 5904 Range, FixItHint::CreateRemoval(Range)); 5905 } 5906 5907 // Determines if the specified is a C++ class or struct containing 5908 // a member with the specified name and kind (e.g. a CXXMethodDecl named 5909 // "c_str()"). 5910 template<typename MemberKind> 5911 static llvm::SmallPtrSet<MemberKind*, 1> 5912 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 5913 const RecordType *RT = Ty->getAs<RecordType>(); 5914 llvm::SmallPtrSet<MemberKind*, 1> Results; 5915 5916 if (!RT) 5917 return Results; 5918 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 5919 if (!RD || !RD->getDefinition()) 5920 return Results; 5921 5922 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 5923 Sema::LookupMemberName); 5924 R.suppressDiagnostics(); 5925 5926 // We just need to include all members of the right kind turned up by the 5927 // filter, at this point. 5928 if (S.LookupQualifiedName(R, RT->getDecl())) 5929 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 5930 NamedDecl *decl = (*I)->getUnderlyingDecl(); 5931 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 5932 Results.insert(FK); 5933 } 5934 return Results; 5935 } 5936 5937 /// Check if we could call '.c_str()' on an object. 5938 /// 5939 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 5940 /// allow the call, or if it would be ambiguous). 5941 bool Sema::hasCStrMethod(const Expr *E) { 5942 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 5943 5944 MethodSet Results = 5945 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 5946 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 5947 MI != ME; ++MI) 5948 if ((*MI)->getMinRequiredArguments() == 0) 5949 return true; 5950 return false; 5951 } 5952 5953 // Check if a (w)string was passed when a (w)char* was needed, and offer a 5954 // better diagnostic if so. AT is assumed to be valid. 5955 // Returns true when a c_str() conversion method is found. 5956 bool CheckPrintfHandler::checkForCStrMembers( 5957 const analyze_printf::ArgType &AT, const Expr *E) { 5958 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 5959 5960 MethodSet Results = 5961 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 5962 5963 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 5964 MI != ME; ++MI) { 5965 const CXXMethodDecl *Method = *MI; 5966 if (Method->getMinRequiredArguments() == 0 && 5967 AT.matchesType(S.Context, Method->getReturnType())) { 5968 // FIXME: Suggest parens if the expression needs them. 5969 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd()); 5970 S.Diag(E->getLocStart(), diag::note_printf_c_str) 5971 << "c_str()" 5972 << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 5973 return true; 5974 } 5975 } 5976 5977 return false; 5978 } 5979 5980 bool 5981 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 5982 &FS, 5983 const char *startSpecifier, 5984 unsigned specifierLen) { 5985 using namespace analyze_format_string; 5986 using namespace analyze_printf; 5987 5988 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 5989 5990 if (FS.consumesDataArgument()) { 5991 if (atFirstArg) { 5992 atFirstArg = false; 5993 usesPositionalArgs = FS.usesPositionalArg(); 5994 } 5995 else if (usesPositionalArgs != FS.usesPositionalArg()) { 5996 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 5997 startSpecifier, specifierLen); 5998 return false; 5999 } 6000 } 6001 6002 // First check if the field width, precision, and conversion specifier 6003 // have matching data arguments. 6004 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 6005 startSpecifier, specifierLen)) { 6006 return false; 6007 } 6008 6009 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 6010 startSpecifier, specifierLen)) { 6011 return false; 6012 } 6013 6014 if (!CS.consumesDataArgument()) { 6015 // FIXME: Technically specifying a precision or field width here 6016 // makes no sense. Worth issuing a warning at some point. 6017 return true; 6018 } 6019 6020 // Consume the argument. 6021 unsigned argIndex = FS.getArgIndex(); 6022 if (argIndex < NumDataArgs) { 6023 // The check to see if the argIndex is valid will come later. 6024 // We set the bit here because we may exit early from this 6025 // function if we encounter some other error. 6026 CoveredArgs.set(argIndex); 6027 } 6028 6029 // FreeBSD kernel extensions. 6030 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 6031 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 6032 // We need at least two arguments. 6033 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 6034 return false; 6035 6036 // Claim the second argument. 6037 CoveredArgs.set(argIndex + 1); 6038 6039 // Type check the first argument (int for %b, pointer for %D) 6040 const Expr *Ex = getDataArg(argIndex); 6041 const analyze_printf::ArgType &AT = 6042 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 6043 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 6044 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 6045 EmitFormatDiagnostic( 6046 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 6047 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 6048 << false << Ex->getSourceRange(), 6049 Ex->getLocStart(), /*IsStringLocation*/false, 6050 getSpecifierRange(startSpecifier, specifierLen)); 6051 6052 // Type check the second argument (char * for both %b and %D) 6053 Ex = getDataArg(argIndex + 1); 6054 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 6055 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 6056 EmitFormatDiagnostic( 6057 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 6058 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 6059 << false << Ex->getSourceRange(), 6060 Ex->getLocStart(), /*IsStringLocation*/false, 6061 getSpecifierRange(startSpecifier, specifierLen)); 6062 6063 return true; 6064 } 6065 6066 // Check for using an Objective-C specific conversion specifier 6067 // in a non-ObjC literal. 6068 if (!allowsObjCArg() && CS.isObjCArg()) { 6069 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 6070 specifierLen); 6071 } 6072 6073 // %P can only be used with os_log. 6074 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 6075 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 6076 specifierLen); 6077 } 6078 6079 // %n is not allowed with os_log. 6080 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 6081 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 6082 getLocationOfByte(CS.getStart()), 6083 /*IsStringLocation*/ false, 6084 getSpecifierRange(startSpecifier, specifierLen)); 6085 6086 return true; 6087 } 6088 6089 // Only scalars are allowed for os_trace. 6090 if (FSType == Sema::FST_OSTrace && 6091 (CS.getKind() == ConversionSpecifier::PArg || 6092 CS.getKind() == ConversionSpecifier::sArg || 6093 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 6094 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 6095 specifierLen); 6096 } 6097 6098 // Check for use of public/private annotation outside of os_log(). 6099 if (FSType != Sema::FST_OSLog) { 6100 if (FS.isPublic().isSet()) { 6101 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 6102 << "public", 6103 getLocationOfByte(FS.isPublic().getPosition()), 6104 /*IsStringLocation*/ false, 6105 getSpecifierRange(startSpecifier, specifierLen)); 6106 } 6107 if (FS.isPrivate().isSet()) { 6108 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 6109 << "private", 6110 getLocationOfByte(FS.isPrivate().getPosition()), 6111 /*IsStringLocation*/ false, 6112 getSpecifierRange(startSpecifier, specifierLen)); 6113 } 6114 } 6115 6116 // Check for invalid use of field width 6117 if (!FS.hasValidFieldWidth()) { 6118 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 6119 startSpecifier, specifierLen); 6120 } 6121 6122 // Check for invalid use of precision 6123 if (!FS.hasValidPrecision()) { 6124 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 6125 startSpecifier, specifierLen); 6126 } 6127 6128 // Precision is mandatory for %P specifier. 6129 if (CS.getKind() == ConversionSpecifier::PArg && 6130 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 6131 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 6132 getLocationOfByte(startSpecifier), 6133 /*IsStringLocation*/ false, 6134 getSpecifierRange(startSpecifier, specifierLen)); 6135 } 6136 6137 // Check each flag does not conflict with any other component. 6138 if (!FS.hasValidThousandsGroupingPrefix()) 6139 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 6140 if (!FS.hasValidLeadingZeros()) 6141 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 6142 if (!FS.hasValidPlusPrefix()) 6143 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 6144 if (!FS.hasValidSpacePrefix()) 6145 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 6146 if (!FS.hasValidAlternativeForm()) 6147 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 6148 if (!FS.hasValidLeftJustified()) 6149 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 6150 6151 // Check that flags are not ignored by another flag 6152 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 6153 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 6154 startSpecifier, specifierLen); 6155 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 6156 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 6157 startSpecifier, specifierLen); 6158 6159 // Check the length modifier is valid with the given conversion specifier. 6160 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 6161 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6162 diag::warn_format_nonsensical_length); 6163 else if (!FS.hasStandardLengthModifier()) 6164 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 6165 else if (!FS.hasStandardLengthConversionCombination()) 6166 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6167 diag::warn_format_non_standard_conversion_spec); 6168 6169 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 6170 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 6171 6172 // The remaining checks depend on the data arguments. 6173 if (HasVAListArg) 6174 return true; 6175 6176 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 6177 return false; 6178 6179 const Expr *Arg = getDataArg(argIndex); 6180 if (!Arg) 6181 return true; 6182 6183 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 6184 } 6185 6186 static bool requiresParensToAddCast(const Expr *E) { 6187 // FIXME: We should have a general way to reason about operator 6188 // precedence and whether parens are actually needed here. 6189 // Take care of a few common cases where they aren't. 6190 const Expr *Inside = E->IgnoreImpCasts(); 6191 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 6192 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 6193 6194 switch (Inside->getStmtClass()) { 6195 case Stmt::ArraySubscriptExprClass: 6196 case Stmt::CallExprClass: 6197 case Stmt::CharacterLiteralClass: 6198 case Stmt::CXXBoolLiteralExprClass: 6199 case Stmt::DeclRefExprClass: 6200 case Stmt::FloatingLiteralClass: 6201 case Stmt::IntegerLiteralClass: 6202 case Stmt::MemberExprClass: 6203 case Stmt::ObjCArrayLiteralClass: 6204 case Stmt::ObjCBoolLiteralExprClass: 6205 case Stmt::ObjCBoxedExprClass: 6206 case Stmt::ObjCDictionaryLiteralClass: 6207 case Stmt::ObjCEncodeExprClass: 6208 case Stmt::ObjCIvarRefExprClass: 6209 case Stmt::ObjCMessageExprClass: 6210 case Stmt::ObjCPropertyRefExprClass: 6211 case Stmt::ObjCStringLiteralClass: 6212 case Stmt::ObjCSubscriptRefExprClass: 6213 case Stmt::ParenExprClass: 6214 case Stmt::StringLiteralClass: 6215 case Stmt::UnaryOperatorClass: 6216 return false; 6217 default: 6218 return true; 6219 } 6220 } 6221 6222 static std::pair<QualType, StringRef> 6223 shouldNotPrintDirectly(const ASTContext &Context, 6224 QualType IntendedTy, 6225 const Expr *E) { 6226 // Use a 'while' to peel off layers of typedefs. 6227 QualType TyTy = IntendedTy; 6228 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 6229 StringRef Name = UserTy->getDecl()->getName(); 6230 QualType CastTy = llvm::StringSwitch<QualType>(Name) 6231 .Case("CFIndex", Context.getNSIntegerType()) 6232 .Case("NSInteger", Context.getNSIntegerType()) 6233 .Case("NSUInteger", Context.getNSUIntegerType()) 6234 .Case("SInt32", Context.IntTy) 6235 .Case("UInt32", Context.UnsignedIntTy) 6236 .Default(QualType()); 6237 6238 if (!CastTy.isNull()) 6239 return std::make_pair(CastTy, Name); 6240 6241 TyTy = UserTy->desugar(); 6242 } 6243 6244 // Strip parens if necessary. 6245 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 6246 return shouldNotPrintDirectly(Context, 6247 PE->getSubExpr()->getType(), 6248 PE->getSubExpr()); 6249 6250 // If this is a conditional expression, then its result type is constructed 6251 // via usual arithmetic conversions and thus there might be no necessary 6252 // typedef sugar there. Recurse to operands to check for NSInteger & 6253 // Co. usage condition. 6254 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 6255 QualType TrueTy, FalseTy; 6256 StringRef TrueName, FalseName; 6257 6258 std::tie(TrueTy, TrueName) = 6259 shouldNotPrintDirectly(Context, 6260 CO->getTrueExpr()->getType(), 6261 CO->getTrueExpr()); 6262 std::tie(FalseTy, FalseName) = 6263 shouldNotPrintDirectly(Context, 6264 CO->getFalseExpr()->getType(), 6265 CO->getFalseExpr()); 6266 6267 if (TrueTy == FalseTy) 6268 return std::make_pair(TrueTy, TrueName); 6269 else if (TrueTy.isNull()) 6270 return std::make_pair(FalseTy, FalseName); 6271 else if (FalseTy.isNull()) 6272 return std::make_pair(TrueTy, TrueName); 6273 } 6274 6275 return std::make_pair(QualType(), StringRef()); 6276 } 6277 6278 bool 6279 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 6280 const char *StartSpecifier, 6281 unsigned SpecifierLen, 6282 const Expr *E) { 6283 using namespace analyze_format_string; 6284 using namespace analyze_printf; 6285 6286 // Now type check the data expression that matches the 6287 // format specifier. 6288 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 6289 if (!AT.isValid()) 6290 return true; 6291 6292 QualType ExprTy = E->getType(); 6293 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 6294 ExprTy = TET->getUnderlyingExpr()->getType(); 6295 } 6296 6297 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy); 6298 6299 if (match == analyze_printf::ArgType::Match) { 6300 return true; 6301 } 6302 6303 // Look through argument promotions for our error message's reported type. 6304 // This includes the integral and floating promotions, but excludes array 6305 // and function pointer decay; seeing that an argument intended to be a 6306 // string has type 'char [6]' is probably more confusing than 'char *'. 6307 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 6308 if (ICE->getCastKind() == CK_IntegralCast || 6309 ICE->getCastKind() == CK_FloatingCast) { 6310 E = ICE->getSubExpr(); 6311 ExprTy = E->getType(); 6312 6313 // Check if we didn't match because of an implicit cast from a 'char' 6314 // or 'short' to an 'int'. This is done because printf is a varargs 6315 // function. 6316 if (ICE->getType() == S.Context.IntTy || 6317 ICE->getType() == S.Context.UnsignedIntTy) { 6318 // All further checking is done on the subexpression. 6319 if (AT.matchesType(S.Context, ExprTy)) 6320 return true; 6321 } 6322 } 6323 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 6324 // Special case for 'a', which has type 'int' in C. 6325 // Note, however, that we do /not/ want to treat multibyte constants like 6326 // 'MooV' as characters! This form is deprecated but still exists. 6327 if (ExprTy == S.Context.IntTy) 6328 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 6329 ExprTy = S.Context.CharTy; 6330 } 6331 6332 // Look through enums to their underlying type. 6333 bool IsEnum = false; 6334 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 6335 ExprTy = EnumTy->getDecl()->getIntegerType(); 6336 IsEnum = true; 6337 } 6338 6339 // %C in an Objective-C context prints a unichar, not a wchar_t. 6340 // If the argument is an integer of some kind, believe the %C and suggest 6341 // a cast instead of changing the conversion specifier. 6342 QualType IntendedTy = ExprTy; 6343 if (isObjCContext() && 6344 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 6345 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 6346 !ExprTy->isCharType()) { 6347 // 'unichar' is defined as a typedef of unsigned short, but we should 6348 // prefer using the typedef if it is visible. 6349 IntendedTy = S.Context.UnsignedShortTy; 6350 6351 // While we are here, check if the value is an IntegerLiteral that happens 6352 // to be within the valid range. 6353 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 6354 const llvm::APInt &V = IL->getValue(); 6355 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 6356 return true; 6357 } 6358 6359 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(), 6360 Sema::LookupOrdinaryName); 6361 if (S.LookupName(Result, S.getCurScope())) { 6362 NamedDecl *ND = Result.getFoundDecl(); 6363 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 6364 if (TD->getUnderlyingType() == IntendedTy) 6365 IntendedTy = S.Context.getTypedefType(TD); 6366 } 6367 } 6368 } 6369 6370 // Special-case some of Darwin's platform-independence types by suggesting 6371 // casts to primitive types that are known to be large enough. 6372 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 6373 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 6374 QualType CastTy; 6375 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 6376 if (!CastTy.isNull()) { 6377 IntendedTy = CastTy; 6378 ShouldNotPrintDirectly = true; 6379 } 6380 } 6381 6382 // We may be able to offer a FixItHint if it is a supported type. 6383 PrintfSpecifier fixedFS = FS; 6384 bool success = 6385 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 6386 6387 if (success) { 6388 // Get the fix string from the fixed format specifier 6389 SmallString<16> buf; 6390 llvm::raw_svector_ostream os(buf); 6391 fixedFS.toString(os); 6392 6393 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 6394 6395 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 6396 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 6397 if (match == analyze_format_string::ArgType::NoMatchPedantic) { 6398 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 6399 } 6400 // In this case, the specifier is wrong and should be changed to match 6401 // the argument. 6402 EmitFormatDiagnostic(S.PDiag(diag) 6403 << AT.getRepresentativeTypeName(S.Context) 6404 << IntendedTy << IsEnum << E->getSourceRange(), 6405 E->getLocStart(), 6406 /*IsStringLocation*/ false, SpecRange, 6407 FixItHint::CreateReplacement(SpecRange, os.str())); 6408 } else { 6409 // The canonical type for formatting this value is different from the 6410 // actual type of the expression. (This occurs, for example, with Darwin's 6411 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 6412 // should be printed as 'long' for 64-bit compatibility.) 6413 // Rather than emitting a normal format/argument mismatch, we want to 6414 // add a cast to the recommended type (and correct the format string 6415 // if necessary). 6416 SmallString<16> CastBuf; 6417 llvm::raw_svector_ostream CastFix(CastBuf); 6418 CastFix << "("; 6419 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 6420 CastFix << ")"; 6421 6422 SmallVector<FixItHint,4> Hints; 6423 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 6424 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 6425 6426 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 6427 // If there's already a cast present, just replace it. 6428 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 6429 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 6430 6431 } else if (!requiresParensToAddCast(E)) { 6432 // If the expression has high enough precedence, 6433 // just write the C-style cast. 6434 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(), 6435 CastFix.str())); 6436 } else { 6437 // Otherwise, add parens around the expression as well as the cast. 6438 CastFix << "("; 6439 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(), 6440 CastFix.str())); 6441 6442 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd()); 6443 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 6444 } 6445 6446 if (ShouldNotPrintDirectly) { 6447 // The expression has a type that should not be printed directly. 6448 // We extract the name from the typedef because we don't want to show 6449 // the underlying type in the diagnostic. 6450 StringRef Name; 6451 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 6452 Name = TypedefTy->getDecl()->getName(); 6453 else 6454 Name = CastTyName; 6455 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast) 6456 << Name << IntendedTy << IsEnum 6457 << E->getSourceRange(), 6458 E->getLocStart(), /*IsStringLocation=*/false, 6459 SpecRange, Hints); 6460 } else { 6461 // In this case, the expression could be printed using a different 6462 // specifier, but we've decided that the specifier is probably correct 6463 // and we should cast instead. Just use the normal warning message. 6464 EmitFormatDiagnostic( 6465 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 6466 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 6467 << E->getSourceRange(), 6468 E->getLocStart(), /*IsStringLocation*/false, 6469 SpecRange, Hints); 6470 } 6471 } 6472 } else { 6473 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 6474 SpecifierLen); 6475 // Since the warning for passing non-POD types to variadic functions 6476 // was deferred until now, we emit a warning for non-POD 6477 // arguments here. 6478 switch (S.isValidVarArgType(ExprTy)) { 6479 case Sema::VAK_Valid: 6480 case Sema::VAK_ValidInCXX11: { 6481 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 6482 if (match == analyze_printf::ArgType::NoMatchPedantic) { 6483 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 6484 } 6485 6486 EmitFormatDiagnostic( 6487 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 6488 << IsEnum << CSR << E->getSourceRange(), 6489 E->getLocStart(), /*IsStringLocation*/ false, CSR); 6490 break; 6491 } 6492 case Sema::VAK_Undefined: 6493 case Sema::VAK_MSVCUndefined: 6494 EmitFormatDiagnostic( 6495 S.PDiag(diag::warn_non_pod_vararg_with_format_string) 6496 << S.getLangOpts().CPlusPlus11 6497 << ExprTy 6498 << CallType 6499 << AT.getRepresentativeTypeName(S.Context) 6500 << CSR 6501 << E->getSourceRange(), 6502 E->getLocStart(), /*IsStringLocation*/false, CSR); 6503 checkForCStrMembers(AT, E); 6504 break; 6505 6506 case Sema::VAK_Invalid: 6507 if (ExprTy->isObjCObjectType()) 6508 EmitFormatDiagnostic( 6509 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 6510 << S.getLangOpts().CPlusPlus11 6511 << ExprTy 6512 << CallType 6513 << AT.getRepresentativeTypeName(S.Context) 6514 << CSR 6515 << E->getSourceRange(), 6516 E->getLocStart(), /*IsStringLocation*/false, CSR); 6517 else 6518 // FIXME: If this is an initializer list, suggest removing the braces 6519 // or inserting a cast to the target type. 6520 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format) 6521 << isa<InitListExpr>(E) << ExprTy << CallType 6522 << AT.getRepresentativeTypeName(S.Context) 6523 << E->getSourceRange(); 6524 break; 6525 } 6526 6527 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 6528 "format string specifier index out of range"); 6529 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 6530 } 6531 6532 return true; 6533 } 6534 6535 //===--- CHECK: Scanf format string checking ------------------------------===// 6536 6537 namespace { 6538 6539 class CheckScanfHandler : public CheckFormatHandler { 6540 public: 6541 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 6542 const Expr *origFormatExpr, Sema::FormatStringType type, 6543 unsigned firstDataArg, unsigned numDataArgs, 6544 const char *beg, bool hasVAListArg, 6545 ArrayRef<const Expr *> Args, unsigned formatIdx, 6546 bool inFunctionCall, Sema::VariadicCallType CallType, 6547 llvm::SmallBitVector &CheckedVarArgs, 6548 UncoveredArgHandler &UncoveredArg) 6549 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 6550 numDataArgs, beg, hasVAListArg, Args, formatIdx, 6551 inFunctionCall, CallType, CheckedVarArgs, 6552 UncoveredArg) {} 6553 6554 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 6555 const char *startSpecifier, 6556 unsigned specifierLen) override; 6557 6558 bool HandleInvalidScanfConversionSpecifier( 6559 const analyze_scanf::ScanfSpecifier &FS, 6560 const char *startSpecifier, 6561 unsigned specifierLen) override; 6562 6563 void HandleIncompleteScanList(const char *start, const char *end) override; 6564 }; 6565 6566 } // namespace 6567 6568 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 6569 const char *end) { 6570 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 6571 getLocationOfByte(end), /*IsStringLocation*/true, 6572 getSpecifierRange(start, end - start)); 6573 } 6574 6575 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 6576 const analyze_scanf::ScanfSpecifier &FS, 6577 const char *startSpecifier, 6578 unsigned specifierLen) { 6579 const analyze_scanf::ScanfConversionSpecifier &CS = 6580 FS.getConversionSpecifier(); 6581 6582 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 6583 getLocationOfByte(CS.getStart()), 6584 startSpecifier, specifierLen, 6585 CS.getStart(), CS.getLength()); 6586 } 6587 6588 bool CheckScanfHandler::HandleScanfSpecifier( 6589 const analyze_scanf::ScanfSpecifier &FS, 6590 const char *startSpecifier, 6591 unsigned specifierLen) { 6592 using namespace analyze_scanf; 6593 using namespace analyze_format_string; 6594 6595 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 6596 6597 // Handle case where '%' and '*' don't consume an argument. These shouldn't 6598 // be used to decide if we are using positional arguments consistently. 6599 if (FS.consumesDataArgument()) { 6600 if (atFirstArg) { 6601 atFirstArg = false; 6602 usesPositionalArgs = FS.usesPositionalArg(); 6603 } 6604 else if (usesPositionalArgs != FS.usesPositionalArg()) { 6605 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 6606 startSpecifier, specifierLen); 6607 return false; 6608 } 6609 } 6610 6611 // Check if the field with is non-zero. 6612 const OptionalAmount &Amt = FS.getFieldWidth(); 6613 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 6614 if (Amt.getConstantAmount() == 0) { 6615 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 6616 Amt.getConstantLength()); 6617 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 6618 getLocationOfByte(Amt.getStart()), 6619 /*IsStringLocation*/true, R, 6620 FixItHint::CreateRemoval(R)); 6621 } 6622 } 6623 6624 if (!FS.consumesDataArgument()) { 6625 // FIXME: Technically specifying a precision or field width here 6626 // makes no sense. Worth issuing a warning at some point. 6627 return true; 6628 } 6629 6630 // Consume the argument. 6631 unsigned argIndex = FS.getArgIndex(); 6632 if (argIndex < NumDataArgs) { 6633 // The check to see if the argIndex is valid will come later. 6634 // We set the bit here because we may exit early from this 6635 // function if we encounter some other error. 6636 CoveredArgs.set(argIndex); 6637 } 6638 6639 // Check the length modifier is valid with the given conversion specifier. 6640 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 6641 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6642 diag::warn_format_nonsensical_length); 6643 else if (!FS.hasStandardLengthModifier()) 6644 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 6645 else if (!FS.hasStandardLengthConversionCombination()) 6646 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6647 diag::warn_format_non_standard_conversion_spec); 6648 6649 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 6650 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 6651 6652 // The remaining checks depend on the data arguments. 6653 if (HasVAListArg) 6654 return true; 6655 6656 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 6657 return false; 6658 6659 // Check that the argument type matches the format specifier. 6660 const Expr *Ex = getDataArg(argIndex); 6661 if (!Ex) 6662 return true; 6663 6664 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 6665 6666 if (!AT.isValid()) { 6667 return true; 6668 } 6669 6670 analyze_format_string::ArgType::MatchKind match = 6671 AT.matchesType(S.Context, Ex->getType()); 6672 if (match == analyze_format_string::ArgType::Match) { 6673 return true; 6674 } 6675 6676 ScanfSpecifier fixedFS = FS; 6677 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 6678 S.getLangOpts(), S.Context); 6679 6680 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 6681 if (match == analyze_format_string::ArgType::NoMatchPedantic) { 6682 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 6683 } 6684 6685 if (success) { 6686 // Get the fix string from the fixed format specifier. 6687 SmallString<128> buf; 6688 llvm::raw_svector_ostream os(buf); 6689 fixedFS.toString(os); 6690 6691 EmitFormatDiagnostic( 6692 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) 6693 << Ex->getType() << false << Ex->getSourceRange(), 6694 Ex->getLocStart(), 6695 /*IsStringLocation*/ false, 6696 getSpecifierRange(startSpecifier, specifierLen), 6697 FixItHint::CreateReplacement( 6698 getSpecifierRange(startSpecifier, specifierLen), os.str())); 6699 } else { 6700 EmitFormatDiagnostic(S.PDiag(diag) 6701 << AT.getRepresentativeTypeName(S.Context) 6702 << Ex->getType() << false << Ex->getSourceRange(), 6703 Ex->getLocStart(), 6704 /*IsStringLocation*/ false, 6705 getSpecifierRange(startSpecifier, specifierLen)); 6706 } 6707 6708 return true; 6709 } 6710 6711 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 6712 const Expr *OrigFormatExpr, 6713 ArrayRef<const Expr *> Args, 6714 bool HasVAListArg, unsigned format_idx, 6715 unsigned firstDataArg, 6716 Sema::FormatStringType Type, 6717 bool inFunctionCall, 6718 Sema::VariadicCallType CallType, 6719 llvm::SmallBitVector &CheckedVarArgs, 6720 UncoveredArgHandler &UncoveredArg) { 6721 // CHECK: is the format string a wide literal? 6722 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 6723 CheckFormatHandler::EmitFormatDiagnostic( 6724 S, inFunctionCall, Args[format_idx], 6725 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(), 6726 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 6727 return; 6728 } 6729 6730 // Str - The format string. NOTE: this is NOT null-terminated! 6731 StringRef StrRef = FExpr->getString(); 6732 const char *Str = StrRef.data(); 6733 // Account for cases where the string literal is truncated in a declaration. 6734 const ConstantArrayType *T = 6735 S.Context.getAsConstantArrayType(FExpr->getType()); 6736 assert(T && "String literal not of constant array type!"); 6737 size_t TypeSize = T->getSize().getZExtValue(); 6738 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 6739 const unsigned numDataArgs = Args.size() - firstDataArg; 6740 6741 // Emit a warning if the string literal is truncated and does not contain an 6742 // embedded null character. 6743 if (TypeSize <= StrRef.size() && 6744 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 6745 CheckFormatHandler::EmitFormatDiagnostic( 6746 S, inFunctionCall, Args[format_idx], 6747 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 6748 FExpr->getLocStart(), 6749 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 6750 return; 6751 } 6752 6753 // CHECK: empty format string? 6754 if (StrLen == 0 && numDataArgs > 0) { 6755 CheckFormatHandler::EmitFormatDiagnostic( 6756 S, inFunctionCall, Args[format_idx], 6757 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(), 6758 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 6759 return; 6760 } 6761 6762 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 6763 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 6764 Type == Sema::FST_OSTrace) { 6765 CheckPrintfHandler H( 6766 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 6767 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 6768 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 6769 CheckedVarArgs, UncoveredArg); 6770 6771 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 6772 S.getLangOpts(), 6773 S.Context.getTargetInfo(), 6774 Type == Sema::FST_FreeBSDKPrintf)) 6775 H.DoneProcessing(); 6776 } else if (Type == Sema::FST_Scanf) { 6777 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 6778 numDataArgs, Str, HasVAListArg, Args, format_idx, 6779 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 6780 6781 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 6782 S.getLangOpts(), 6783 S.Context.getTargetInfo())) 6784 H.DoneProcessing(); 6785 } // TODO: handle other formats 6786 } 6787 6788 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 6789 // Str - The format string. NOTE: this is NOT null-terminated! 6790 StringRef StrRef = FExpr->getString(); 6791 const char *Str = StrRef.data(); 6792 // Account for cases where the string literal is truncated in a declaration. 6793 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 6794 assert(T && "String literal not of constant array type!"); 6795 size_t TypeSize = T->getSize().getZExtValue(); 6796 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 6797 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 6798 getLangOpts(), 6799 Context.getTargetInfo()); 6800 } 6801 6802 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 6803 6804 // Returns the related absolute value function that is larger, of 0 if one 6805 // does not exist. 6806 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 6807 switch (AbsFunction) { 6808 default: 6809 return 0; 6810 6811 case Builtin::BI__builtin_abs: 6812 return Builtin::BI__builtin_labs; 6813 case Builtin::BI__builtin_labs: 6814 return Builtin::BI__builtin_llabs; 6815 case Builtin::BI__builtin_llabs: 6816 return 0; 6817 6818 case Builtin::BI__builtin_fabsf: 6819 return Builtin::BI__builtin_fabs; 6820 case Builtin::BI__builtin_fabs: 6821 return Builtin::BI__builtin_fabsl; 6822 case Builtin::BI__builtin_fabsl: 6823 return 0; 6824 6825 case Builtin::BI__builtin_cabsf: 6826 return Builtin::BI__builtin_cabs; 6827 case Builtin::BI__builtin_cabs: 6828 return Builtin::BI__builtin_cabsl; 6829 case Builtin::BI__builtin_cabsl: 6830 return 0; 6831 6832 case Builtin::BIabs: 6833 return Builtin::BIlabs; 6834 case Builtin::BIlabs: 6835 return Builtin::BIllabs; 6836 case Builtin::BIllabs: 6837 return 0; 6838 6839 case Builtin::BIfabsf: 6840 return Builtin::BIfabs; 6841 case Builtin::BIfabs: 6842 return Builtin::BIfabsl; 6843 case Builtin::BIfabsl: 6844 return 0; 6845 6846 case Builtin::BIcabsf: 6847 return Builtin::BIcabs; 6848 case Builtin::BIcabs: 6849 return Builtin::BIcabsl; 6850 case Builtin::BIcabsl: 6851 return 0; 6852 } 6853 } 6854 6855 // Returns the argument type of the absolute value function. 6856 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 6857 unsigned AbsType) { 6858 if (AbsType == 0) 6859 return QualType(); 6860 6861 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 6862 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 6863 if (Error != ASTContext::GE_None) 6864 return QualType(); 6865 6866 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 6867 if (!FT) 6868 return QualType(); 6869 6870 if (FT->getNumParams() != 1) 6871 return QualType(); 6872 6873 return FT->getParamType(0); 6874 } 6875 6876 // Returns the best absolute value function, or zero, based on type and 6877 // current absolute value function. 6878 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 6879 unsigned AbsFunctionKind) { 6880 unsigned BestKind = 0; 6881 uint64_t ArgSize = Context.getTypeSize(ArgType); 6882 for (unsigned Kind = AbsFunctionKind; Kind != 0; 6883 Kind = getLargerAbsoluteValueFunction(Kind)) { 6884 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 6885 if (Context.getTypeSize(ParamType) >= ArgSize) { 6886 if (BestKind == 0) 6887 BestKind = Kind; 6888 else if (Context.hasSameType(ParamType, ArgType)) { 6889 BestKind = Kind; 6890 break; 6891 } 6892 } 6893 } 6894 return BestKind; 6895 } 6896 6897 enum AbsoluteValueKind { 6898 AVK_Integer, 6899 AVK_Floating, 6900 AVK_Complex 6901 }; 6902 6903 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 6904 if (T->isIntegralOrEnumerationType()) 6905 return AVK_Integer; 6906 if (T->isRealFloatingType()) 6907 return AVK_Floating; 6908 if (T->isAnyComplexType()) 6909 return AVK_Complex; 6910 6911 llvm_unreachable("Type not integer, floating, or complex"); 6912 } 6913 6914 // Changes the absolute value function to a different type. Preserves whether 6915 // the function is a builtin. 6916 static unsigned changeAbsFunction(unsigned AbsKind, 6917 AbsoluteValueKind ValueKind) { 6918 switch (ValueKind) { 6919 case AVK_Integer: 6920 switch (AbsKind) { 6921 default: 6922 return 0; 6923 case Builtin::BI__builtin_fabsf: 6924 case Builtin::BI__builtin_fabs: 6925 case Builtin::BI__builtin_fabsl: 6926 case Builtin::BI__builtin_cabsf: 6927 case Builtin::BI__builtin_cabs: 6928 case Builtin::BI__builtin_cabsl: 6929 return Builtin::BI__builtin_abs; 6930 case Builtin::BIfabsf: 6931 case Builtin::BIfabs: 6932 case Builtin::BIfabsl: 6933 case Builtin::BIcabsf: 6934 case Builtin::BIcabs: 6935 case Builtin::BIcabsl: 6936 return Builtin::BIabs; 6937 } 6938 case AVK_Floating: 6939 switch (AbsKind) { 6940 default: 6941 return 0; 6942 case Builtin::BI__builtin_abs: 6943 case Builtin::BI__builtin_labs: 6944 case Builtin::BI__builtin_llabs: 6945 case Builtin::BI__builtin_cabsf: 6946 case Builtin::BI__builtin_cabs: 6947 case Builtin::BI__builtin_cabsl: 6948 return Builtin::BI__builtin_fabsf; 6949 case Builtin::BIabs: 6950 case Builtin::BIlabs: 6951 case Builtin::BIllabs: 6952 case Builtin::BIcabsf: 6953 case Builtin::BIcabs: 6954 case Builtin::BIcabsl: 6955 return Builtin::BIfabsf; 6956 } 6957 case AVK_Complex: 6958 switch (AbsKind) { 6959 default: 6960 return 0; 6961 case Builtin::BI__builtin_abs: 6962 case Builtin::BI__builtin_labs: 6963 case Builtin::BI__builtin_llabs: 6964 case Builtin::BI__builtin_fabsf: 6965 case Builtin::BI__builtin_fabs: 6966 case Builtin::BI__builtin_fabsl: 6967 return Builtin::BI__builtin_cabsf; 6968 case Builtin::BIabs: 6969 case Builtin::BIlabs: 6970 case Builtin::BIllabs: 6971 case Builtin::BIfabsf: 6972 case Builtin::BIfabs: 6973 case Builtin::BIfabsl: 6974 return Builtin::BIcabsf; 6975 } 6976 } 6977 llvm_unreachable("Unable to convert function"); 6978 } 6979 6980 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 6981 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 6982 if (!FnInfo) 6983 return 0; 6984 6985 switch (FDecl->getBuiltinID()) { 6986 default: 6987 return 0; 6988 case Builtin::BI__builtin_abs: 6989 case Builtin::BI__builtin_fabs: 6990 case Builtin::BI__builtin_fabsf: 6991 case Builtin::BI__builtin_fabsl: 6992 case Builtin::BI__builtin_labs: 6993 case Builtin::BI__builtin_llabs: 6994 case Builtin::BI__builtin_cabs: 6995 case Builtin::BI__builtin_cabsf: 6996 case Builtin::BI__builtin_cabsl: 6997 case Builtin::BIabs: 6998 case Builtin::BIlabs: 6999 case Builtin::BIllabs: 7000 case Builtin::BIfabs: 7001 case Builtin::BIfabsf: 7002 case Builtin::BIfabsl: 7003 case Builtin::BIcabs: 7004 case Builtin::BIcabsf: 7005 case Builtin::BIcabsl: 7006 return FDecl->getBuiltinID(); 7007 } 7008 llvm_unreachable("Unknown Builtin type"); 7009 } 7010 7011 // If the replacement is valid, emit a note with replacement function. 7012 // Additionally, suggest including the proper header if not already included. 7013 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 7014 unsigned AbsKind, QualType ArgType) { 7015 bool EmitHeaderHint = true; 7016 const char *HeaderName = nullptr; 7017 const char *FunctionName = nullptr; 7018 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 7019 FunctionName = "std::abs"; 7020 if (ArgType->isIntegralOrEnumerationType()) { 7021 HeaderName = "cstdlib"; 7022 } else if (ArgType->isRealFloatingType()) { 7023 HeaderName = "cmath"; 7024 } else { 7025 llvm_unreachable("Invalid Type"); 7026 } 7027 7028 // Lookup all std::abs 7029 if (NamespaceDecl *Std = S.getStdNamespace()) { 7030 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 7031 R.suppressDiagnostics(); 7032 S.LookupQualifiedName(R, Std); 7033 7034 for (const auto *I : R) { 7035 const FunctionDecl *FDecl = nullptr; 7036 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 7037 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 7038 } else { 7039 FDecl = dyn_cast<FunctionDecl>(I); 7040 } 7041 if (!FDecl) 7042 continue; 7043 7044 // Found std::abs(), check that they are the right ones. 7045 if (FDecl->getNumParams() != 1) 7046 continue; 7047 7048 // Check that the parameter type can handle the argument. 7049 QualType ParamType = FDecl->getParamDecl(0)->getType(); 7050 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 7051 S.Context.getTypeSize(ArgType) <= 7052 S.Context.getTypeSize(ParamType)) { 7053 // Found a function, don't need the header hint. 7054 EmitHeaderHint = false; 7055 break; 7056 } 7057 } 7058 } 7059 } else { 7060 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 7061 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 7062 7063 if (HeaderName) { 7064 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 7065 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 7066 R.suppressDiagnostics(); 7067 S.LookupName(R, S.getCurScope()); 7068 7069 if (R.isSingleResult()) { 7070 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 7071 if (FD && FD->getBuiltinID() == AbsKind) { 7072 EmitHeaderHint = false; 7073 } else { 7074 return; 7075 } 7076 } else if (!R.empty()) { 7077 return; 7078 } 7079 } 7080 } 7081 7082 S.Diag(Loc, diag::note_replace_abs_function) 7083 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 7084 7085 if (!HeaderName) 7086 return; 7087 7088 if (!EmitHeaderHint) 7089 return; 7090 7091 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 7092 << FunctionName; 7093 } 7094 7095 template <std::size_t StrLen> 7096 static bool IsStdFunction(const FunctionDecl *FDecl, 7097 const char (&Str)[StrLen]) { 7098 if (!FDecl) 7099 return false; 7100 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 7101 return false; 7102 if (!FDecl->isInStdNamespace()) 7103 return false; 7104 7105 return true; 7106 } 7107 7108 // Warn when using the wrong abs() function. 7109 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 7110 const FunctionDecl *FDecl) { 7111 if (Call->getNumArgs() != 1) 7112 return; 7113 7114 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 7115 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 7116 if (AbsKind == 0 && !IsStdAbs) 7117 return; 7118 7119 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 7120 QualType ParamType = Call->getArg(0)->getType(); 7121 7122 // Unsigned types cannot be negative. Suggest removing the absolute value 7123 // function call. 7124 if (ArgType->isUnsignedIntegerType()) { 7125 const char *FunctionName = 7126 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 7127 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 7128 Diag(Call->getExprLoc(), diag::note_remove_abs) 7129 << FunctionName 7130 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 7131 return; 7132 } 7133 7134 // Taking the absolute value of a pointer is very suspicious, they probably 7135 // wanted to index into an array, dereference a pointer, call a function, etc. 7136 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 7137 unsigned DiagType = 0; 7138 if (ArgType->isFunctionType()) 7139 DiagType = 1; 7140 else if (ArgType->isArrayType()) 7141 DiagType = 2; 7142 7143 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 7144 return; 7145 } 7146 7147 // std::abs has overloads which prevent most of the absolute value problems 7148 // from occurring. 7149 if (IsStdAbs) 7150 return; 7151 7152 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 7153 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 7154 7155 // The argument and parameter are the same kind. Check if they are the right 7156 // size. 7157 if (ArgValueKind == ParamValueKind) { 7158 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 7159 return; 7160 7161 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 7162 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 7163 << FDecl << ArgType << ParamType; 7164 7165 if (NewAbsKind == 0) 7166 return; 7167 7168 emitReplacement(*this, Call->getExprLoc(), 7169 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 7170 return; 7171 } 7172 7173 // ArgValueKind != ParamValueKind 7174 // The wrong type of absolute value function was used. Attempt to find the 7175 // proper one. 7176 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 7177 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 7178 if (NewAbsKind == 0) 7179 return; 7180 7181 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 7182 << FDecl << ParamValueKind << ArgValueKind; 7183 7184 emitReplacement(*this, Call->getExprLoc(), 7185 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 7186 } 7187 7188 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 7189 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 7190 const FunctionDecl *FDecl) { 7191 if (!Call || !FDecl) return; 7192 7193 // Ignore template specializations and macros. 7194 if (inTemplateInstantiation()) return; 7195 if (Call->getExprLoc().isMacroID()) return; 7196 7197 // Only care about the one template argument, two function parameter std::max 7198 if (Call->getNumArgs() != 2) return; 7199 if (!IsStdFunction(FDecl, "max")) return; 7200 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 7201 if (!ArgList) return; 7202 if (ArgList->size() != 1) return; 7203 7204 // Check that template type argument is unsigned integer. 7205 const auto& TA = ArgList->get(0); 7206 if (TA.getKind() != TemplateArgument::Type) return; 7207 QualType ArgType = TA.getAsType(); 7208 if (!ArgType->isUnsignedIntegerType()) return; 7209 7210 // See if either argument is a literal zero. 7211 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 7212 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 7213 if (!MTE) return false; 7214 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr()); 7215 if (!Num) return false; 7216 if (Num->getValue() != 0) return false; 7217 return true; 7218 }; 7219 7220 const Expr *FirstArg = Call->getArg(0); 7221 const Expr *SecondArg = Call->getArg(1); 7222 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 7223 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 7224 7225 // Only warn when exactly one argument is zero. 7226 if (IsFirstArgZero == IsSecondArgZero) return; 7227 7228 SourceRange FirstRange = FirstArg->getSourceRange(); 7229 SourceRange SecondRange = SecondArg->getSourceRange(); 7230 7231 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 7232 7233 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 7234 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 7235 7236 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 7237 SourceRange RemovalRange; 7238 if (IsFirstArgZero) { 7239 RemovalRange = SourceRange(FirstRange.getBegin(), 7240 SecondRange.getBegin().getLocWithOffset(-1)); 7241 } else { 7242 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 7243 SecondRange.getEnd()); 7244 } 7245 7246 Diag(Call->getExprLoc(), diag::note_remove_max_call) 7247 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 7248 << FixItHint::CreateRemoval(RemovalRange); 7249 } 7250 7251 //===--- CHECK: Standard memory functions ---------------------------------===// 7252 7253 /// \brief Takes the expression passed to the size_t parameter of functions 7254 /// such as memcmp, strncat, etc and warns if it's a comparison. 7255 /// 7256 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 7257 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 7258 IdentifierInfo *FnName, 7259 SourceLocation FnLoc, 7260 SourceLocation RParenLoc) { 7261 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 7262 if (!Size) 7263 return false; 7264 7265 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 7266 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 7267 return false; 7268 7269 SourceRange SizeRange = Size->getSourceRange(); 7270 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 7271 << SizeRange << FnName; 7272 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 7273 << FnName << FixItHint::CreateInsertion( 7274 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")") 7275 << FixItHint::CreateRemoval(RParenLoc); 7276 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 7277 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 7278 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 7279 ")"); 7280 7281 return true; 7282 } 7283 7284 /// \brief Determine whether the given type is or contains a dynamic class type 7285 /// (e.g., whether it has a vtable). 7286 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 7287 bool &IsContained) { 7288 // Look through array types while ignoring qualifiers. 7289 const Type *Ty = T->getBaseElementTypeUnsafe(); 7290 IsContained = false; 7291 7292 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 7293 RD = RD ? RD->getDefinition() : nullptr; 7294 if (!RD || RD->isInvalidDecl()) 7295 return nullptr; 7296 7297 if (RD->isDynamicClass()) 7298 return RD; 7299 7300 // Check all the fields. If any bases were dynamic, the class is dynamic. 7301 // It's impossible for a class to transitively contain itself by value, so 7302 // infinite recursion is impossible. 7303 for (auto *FD : RD->fields()) { 7304 bool SubContained; 7305 if (const CXXRecordDecl *ContainedRD = 7306 getContainedDynamicClass(FD->getType(), SubContained)) { 7307 IsContained = true; 7308 return ContainedRD; 7309 } 7310 } 7311 7312 return nullptr; 7313 } 7314 7315 /// \brief If E is a sizeof expression, returns its argument expression, 7316 /// otherwise returns NULL. 7317 static const Expr *getSizeOfExprArg(const Expr *E) { 7318 if (const UnaryExprOrTypeTraitExpr *SizeOf = 7319 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 7320 if (SizeOf->getKind() == UETT_SizeOf && !SizeOf->isArgumentType()) 7321 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 7322 7323 return nullptr; 7324 } 7325 7326 /// \brief If E is a sizeof expression, returns its argument type. 7327 static QualType getSizeOfArgType(const Expr *E) { 7328 if (const UnaryExprOrTypeTraitExpr *SizeOf = 7329 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 7330 if (SizeOf->getKind() == UETT_SizeOf) 7331 return SizeOf->getTypeOfArgument(); 7332 7333 return QualType(); 7334 } 7335 7336 /// \brief Check for dangerous or invalid arguments to memset(). 7337 /// 7338 /// This issues warnings on known problematic, dangerous or unspecified 7339 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 7340 /// function calls. 7341 /// 7342 /// \param Call The call expression to diagnose. 7343 void Sema::CheckMemaccessArguments(const CallExpr *Call, 7344 unsigned BId, 7345 IdentifierInfo *FnName) { 7346 assert(BId != 0); 7347 7348 // It is possible to have a non-standard definition of memset. Validate 7349 // we have enough arguments, and if not, abort further checking. 7350 unsigned ExpectedNumArgs = 7351 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 7352 if (Call->getNumArgs() < ExpectedNumArgs) 7353 return; 7354 7355 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 7356 BId == Builtin::BIstrndup ? 1 : 2); 7357 unsigned LenArg = 7358 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 7359 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 7360 7361 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 7362 Call->getLocStart(), Call->getRParenLoc())) 7363 return; 7364 7365 // We have special checking when the length is a sizeof expression. 7366 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 7367 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 7368 llvm::FoldingSetNodeID SizeOfArgID; 7369 7370 // Although widely used, 'bzero' is not a standard function. Be more strict 7371 // with the argument types before allowing diagnostics and only allow the 7372 // form bzero(ptr, sizeof(...)). 7373 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 7374 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 7375 return; 7376 7377 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 7378 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 7379 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 7380 7381 QualType DestTy = Dest->getType(); 7382 QualType PointeeTy; 7383 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 7384 PointeeTy = DestPtrTy->getPointeeType(); 7385 7386 // Never warn about void type pointers. This can be used to suppress 7387 // false positives. 7388 if (PointeeTy->isVoidType()) 7389 continue; 7390 7391 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 7392 // actually comparing the expressions for equality. Because computing the 7393 // expression IDs can be expensive, we only do this if the diagnostic is 7394 // enabled. 7395 if (SizeOfArg && 7396 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 7397 SizeOfArg->getExprLoc())) { 7398 // We only compute IDs for expressions if the warning is enabled, and 7399 // cache the sizeof arg's ID. 7400 if (SizeOfArgID == llvm::FoldingSetNodeID()) 7401 SizeOfArg->Profile(SizeOfArgID, Context, true); 7402 llvm::FoldingSetNodeID DestID; 7403 Dest->Profile(DestID, Context, true); 7404 if (DestID == SizeOfArgID) { 7405 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 7406 // over sizeof(src) as well. 7407 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 7408 StringRef ReadableName = FnName->getName(); 7409 7410 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 7411 if (UnaryOp->getOpcode() == UO_AddrOf) 7412 ActionIdx = 1; // If its an address-of operator, just remove it. 7413 if (!PointeeTy->isIncompleteType() && 7414 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 7415 ActionIdx = 2; // If the pointee's size is sizeof(char), 7416 // suggest an explicit length. 7417 7418 // If the function is defined as a builtin macro, do not show macro 7419 // expansion. 7420 SourceLocation SL = SizeOfArg->getExprLoc(); 7421 SourceRange DSR = Dest->getSourceRange(); 7422 SourceRange SSR = SizeOfArg->getSourceRange(); 7423 SourceManager &SM = getSourceManager(); 7424 7425 if (SM.isMacroArgExpansion(SL)) { 7426 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 7427 SL = SM.getSpellingLoc(SL); 7428 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 7429 SM.getSpellingLoc(DSR.getEnd())); 7430 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 7431 SM.getSpellingLoc(SSR.getEnd())); 7432 } 7433 7434 DiagRuntimeBehavior(SL, SizeOfArg, 7435 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 7436 << ReadableName 7437 << PointeeTy 7438 << DestTy 7439 << DSR 7440 << SSR); 7441 DiagRuntimeBehavior(SL, SizeOfArg, 7442 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 7443 << ActionIdx 7444 << SSR); 7445 7446 break; 7447 } 7448 } 7449 7450 // Also check for cases where the sizeof argument is the exact same 7451 // type as the memory argument, and where it points to a user-defined 7452 // record type. 7453 if (SizeOfArgTy != QualType()) { 7454 if (PointeeTy->isRecordType() && 7455 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 7456 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 7457 PDiag(diag::warn_sizeof_pointer_type_memaccess) 7458 << FnName << SizeOfArgTy << ArgIdx 7459 << PointeeTy << Dest->getSourceRange() 7460 << LenExpr->getSourceRange()); 7461 break; 7462 } 7463 } 7464 } else if (DestTy->isArrayType()) { 7465 PointeeTy = DestTy; 7466 } 7467 7468 if (PointeeTy == QualType()) 7469 continue; 7470 7471 // Always complain about dynamic classes. 7472 bool IsContained; 7473 if (const CXXRecordDecl *ContainedRD = 7474 getContainedDynamicClass(PointeeTy, IsContained)) { 7475 7476 unsigned OperationType = 0; 7477 // "overwritten" if we're warning about the destination for any call 7478 // but memcmp; otherwise a verb appropriate to the call. 7479 if (ArgIdx != 0 || BId == Builtin::BImemcmp) { 7480 if (BId == Builtin::BImemcpy) 7481 OperationType = 1; 7482 else if(BId == Builtin::BImemmove) 7483 OperationType = 2; 7484 else if (BId == Builtin::BImemcmp) 7485 OperationType = 3; 7486 } 7487 7488 DiagRuntimeBehavior( 7489 Dest->getExprLoc(), Dest, 7490 PDiag(diag::warn_dyn_class_memaccess) 7491 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx) 7492 << FnName << IsContained << ContainedRD << OperationType 7493 << Call->getCallee()->getSourceRange()); 7494 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 7495 BId != Builtin::BImemset) 7496 DiagRuntimeBehavior( 7497 Dest->getExprLoc(), Dest, 7498 PDiag(diag::warn_arc_object_memaccess) 7499 << ArgIdx << FnName << PointeeTy 7500 << Call->getCallee()->getSourceRange()); 7501 else 7502 continue; 7503 7504 DiagRuntimeBehavior( 7505 Dest->getExprLoc(), Dest, 7506 PDiag(diag::note_bad_memaccess_silence) 7507 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 7508 break; 7509 } 7510 } 7511 7512 // A little helper routine: ignore addition and subtraction of integer literals. 7513 // This intentionally does not ignore all integer constant expressions because 7514 // we don't want to remove sizeof(). 7515 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 7516 Ex = Ex->IgnoreParenCasts(); 7517 7518 while (true) { 7519 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 7520 if (!BO || !BO->isAdditiveOp()) 7521 break; 7522 7523 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 7524 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 7525 7526 if (isa<IntegerLiteral>(RHS)) 7527 Ex = LHS; 7528 else if (isa<IntegerLiteral>(LHS)) 7529 Ex = RHS; 7530 else 7531 break; 7532 } 7533 7534 return Ex; 7535 } 7536 7537 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 7538 ASTContext &Context) { 7539 // Only handle constant-sized or VLAs, but not flexible members. 7540 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 7541 // Only issue the FIXIT for arrays of size > 1. 7542 if (CAT->getSize().getSExtValue() <= 1) 7543 return false; 7544 } else if (!Ty->isVariableArrayType()) { 7545 return false; 7546 } 7547 return true; 7548 } 7549 7550 // Warn if the user has made the 'size' argument to strlcpy or strlcat 7551 // be the size of the source, instead of the destination. 7552 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 7553 IdentifierInfo *FnName) { 7554 7555 // Don't crash if the user has the wrong number of arguments 7556 unsigned NumArgs = Call->getNumArgs(); 7557 if ((NumArgs != 3) && (NumArgs != 4)) 7558 return; 7559 7560 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 7561 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 7562 const Expr *CompareWithSrc = nullptr; 7563 7564 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 7565 Call->getLocStart(), Call->getRParenLoc())) 7566 return; 7567 7568 // Look for 'strlcpy(dst, x, sizeof(x))' 7569 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 7570 CompareWithSrc = Ex; 7571 else { 7572 // Look for 'strlcpy(dst, x, strlen(x))' 7573 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 7574 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 7575 SizeCall->getNumArgs() == 1) 7576 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 7577 } 7578 } 7579 7580 if (!CompareWithSrc) 7581 return; 7582 7583 // Determine if the argument to sizeof/strlen is equal to the source 7584 // argument. In principle there's all kinds of things you could do 7585 // here, for instance creating an == expression and evaluating it with 7586 // EvaluateAsBooleanCondition, but this uses a more direct technique: 7587 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 7588 if (!SrcArgDRE) 7589 return; 7590 7591 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 7592 if (!CompareWithSrcDRE || 7593 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 7594 return; 7595 7596 const Expr *OriginalSizeArg = Call->getArg(2); 7597 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size) 7598 << OriginalSizeArg->getSourceRange() << FnName; 7599 7600 // Output a FIXIT hint if the destination is an array (rather than a 7601 // pointer to an array). This could be enhanced to handle some 7602 // pointers if we know the actual size, like if DstArg is 'array+2' 7603 // we could say 'sizeof(array)-2'. 7604 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 7605 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 7606 return; 7607 7608 SmallString<128> sizeString; 7609 llvm::raw_svector_ostream OS(sizeString); 7610 OS << "sizeof("; 7611 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 7612 OS << ")"; 7613 7614 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size) 7615 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 7616 OS.str()); 7617 } 7618 7619 /// Check if two expressions refer to the same declaration. 7620 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 7621 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 7622 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 7623 return D1->getDecl() == D2->getDecl(); 7624 return false; 7625 } 7626 7627 static const Expr *getStrlenExprArg(const Expr *E) { 7628 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 7629 const FunctionDecl *FD = CE->getDirectCallee(); 7630 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 7631 return nullptr; 7632 return CE->getArg(0)->IgnoreParenCasts(); 7633 } 7634 return nullptr; 7635 } 7636 7637 // Warn on anti-patterns as the 'size' argument to strncat. 7638 // The correct size argument should look like following: 7639 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 7640 void Sema::CheckStrncatArguments(const CallExpr *CE, 7641 IdentifierInfo *FnName) { 7642 // Don't crash if the user has the wrong number of arguments. 7643 if (CE->getNumArgs() < 3) 7644 return; 7645 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 7646 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 7647 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 7648 7649 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(), 7650 CE->getRParenLoc())) 7651 return; 7652 7653 // Identify common expressions, which are wrongly used as the size argument 7654 // to strncat and may lead to buffer overflows. 7655 unsigned PatternType = 0; 7656 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 7657 // - sizeof(dst) 7658 if (referToTheSameDecl(SizeOfArg, DstArg)) 7659 PatternType = 1; 7660 // - sizeof(src) 7661 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 7662 PatternType = 2; 7663 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 7664 if (BE->getOpcode() == BO_Sub) { 7665 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 7666 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 7667 // - sizeof(dst) - strlen(dst) 7668 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 7669 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 7670 PatternType = 1; 7671 // - sizeof(src) - (anything) 7672 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 7673 PatternType = 2; 7674 } 7675 } 7676 7677 if (PatternType == 0) 7678 return; 7679 7680 // Generate the diagnostic. 7681 SourceLocation SL = LenArg->getLocStart(); 7682 SourceRange SR = LenArg->getSourceRange(); 7683 SourceManager &SM = getSourceManager(); 7684 7685 // If the function is defined as a builtin macro, do not show macro expansion. 7686 if (SM.isMacroArgExpansion(SL)) { 7687 SL = SM.getSpellingLoc(SL); 7688 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 7689 SM.getSpellingLoc(SR.getEnd())); 7690 } 7691 7692 // Check if the destination is an array (rather than a pointer to an array). 7693 QualType DstTy = DstArg->getType(); 7694 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 7695 Context); 7696 if (!isKnownSizeArray) { 7697 if (PatternType == 1) 7698 Diag(SL, diag::warn_strncat_wrong_size) << SR; 7699 else 7700 Diag(SL, diag::warn_strncat_src_size) << SR; 7701 return; 7702 } 7703 7704 if (PatternType == 1) 7705 Diag(SL, diag::warn_strncat_large_size) << SR; 7706 else 7707 Diag(SL, diag::warn_strncat_src_size) << SR; 7708 7709 SmallString<128> sizeString; 7710 llvm::raw_svector_ostream OS(sizeString); 7711 OS << "sizeof("; 7712 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 7713 OS << ") - "; 7714 OS << "strlen("; 7715 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 7716 OS << ") - 1"; 7717 7718 Diag(SL, diag::note_strncat_wrong_size) 7719 << FixItHint::CreateReplacement(SR, OS.str()); 7720 } 7721 7722 //===--- CHECK: Return Address of Stack Variable --------------------------===// 7723 7724 static const Expr *EvalVal(const Expr *E, 7725 SmallVectorImpl<const DeclRefExpr *> &refVars, 7726 const Decl *ParentDecl); 7727 static const Expr *EvalAddr(const Expr *E, 7728 SmallVectorImpl<const DeclRefExpr *> &refVars, 7729 const Decl *ParentDecl); 7730 7731 /// CheckReturnStackAddr - Check if a return statement returns the address 7732 /// of a stack variable. 7733 static void 7734 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType, 7735 SourceLocation ReturnLoc) { 7736 const Expr *stackE = nullptr; 7737 SmallVector<const DeclRefExpr *, 8> refVars; 7738 7739 // Perform checking for returned stack addresses, local blocks, 7740 // label addresses or references to temporaries. 7741 if (lhsType->isPointerType() || 7742 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) { 7743 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr); 7744 } else if (lhsType->isReferenceType()) { 7745 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr); 7746 } 7747 7748 if (!stackE) 7749 return; // Nothing suspicious was found. 7750 7751 // Parameters are initialized in the calling scope, so taking the address 7752 // of a parameter reference doesn't need a warning. 7753 for (auto *DRE : refVars) 7754 if (isa<ParmVarDecl>(DRE->getDecl())) 7755 return; 7756 7757 SourceLocation diagLoc; 7758 SourceRange diagRange; 7759 if (refVars.empty()) { 7760 diagLoc = stackE->getLocStart(); 7761 diagRange = stackE->getSourceRange(); 7762 } else { 7763 // We followed through a reference variable. 'stackE' contains the 7764 // problematic expression but we will warn at the return statement pointing 7765 // at the reference variable. We will later display the "trail" of 7766 // reference variables using notes. 7767 diagLoc = refVars[0]->getLocStart(); 7768 diagRange = refVars[0]->getSourceRange(); 7769 } 7770 7771 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { 7772 // address of local var 7773 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType() 7774 << DR->getDecl()->getDeclName() << diagRange; 7775 } else if (isa<BlockExpr>(stackE)) { // local block. 7776 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange; 7777 } else if (isa<AddrLabelExpr>(stackE)) { // address of label. 7778 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange; 7779 } else { // local temporary. 7780 // If there is an LValue->RValue conversion, then the value of the 7781 // reference type is used, not the reference. 7782 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) { 7783 if (ICE->getCastKind() == CK_LValueToRValue) { 7784 return; 7785 } 7786 } 7787 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref) 7788 << lhsType->isReferenceType() << diagRange; 7789 } 7790 7791 // Display the "trail" of reference variables that we followed until we 7792 // found the problematic expression using notes. 7793 for (unsigned i = 0, e = refVars.size(); i != e; ++i) { 7794 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl()); 7795 // If this var binds to another reference var, show the range of the next 7796 // var, otherwise the var binds to the problematic expression, in which case 7797 // show the range of the expression. 7798 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange() 7799 : stackE->getSourceRange(); 7800 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind) 7801 << VD->getDeclName() << range; 7802 } 7803 } 7804 7805 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that 7806 /// check if the expression in a return statement evaluates to an address 7807 /// to a location on the stack, a local block, an address of a label, or a 7808 /// reference to local temporary. The recursion is used to traverse the 7809 /// AST of the return expression, with recursion backtracking when we 7810 /// encounter a subexpression that (1) clearly does not lead to one of the 7811 /// above problematic expressions (2) is something we cannot determine leads to 7812 /// a problematic expression based on such local checking. 7813 /// 7814 /// Both EvalAddr and EvalVal follow through reference variables to evaluate 7815 /// the expression that they point to. Such variables are added to the 7816 /// 'refVars' vector so that we know what the reference variable "trail" was. 7817 /// 7818 /// EvalAddr processes expressions that are pointers that are used as 7819 /// references (and not L-values). EvalVal handles all other values. 7820 /// At the base case of the recursion is a check for the above problematic 7821 /// expressions. 7822 /// 7823 /// This implementation handles: 7824 /// 7825 /// * pointer-to-pointer casts 7826 /// * implicit conversions from array references to pointers 7827 /// * taking the address of fields 7828 /// * arbitrary interplay between "&" and "*" operators 7829 /// * pointer arithmetic from an address of a stack variable 7830 /// * taking the address of an array element where the array is on the stack 7831 static const Expr *EvalAddr(const Expr *E, 7832 SmallVectorImpl<const DeclRefExpr *> &refVars, 7833 const Decl *ParentDecl) { 7834 if (E->isTypeDependent()) 7835 return nullptr; 7836 7837 // We should only be called for evaluating pointer expressions. 7838 assert((E->getType()->isAnyPointerType() || 7839 E->getType()->isBlockPointerType() || 7840 E->getType()->isObjCQualifiedIdType()) && 7841 "EvalAddr only works on pointers"); 7842 7843 E = E->IgnoreParens(); 7844 7845 // Our "symbolic interpreter" is just a dispatch off the currently 7846 // viewed AST node. We then recursively traverse the AST by calling 7847 // EvalAddr and EvalVal appropriately. 7848 switch (E->getStmtClass()) { 7849 case Stmt::DeclRefExprClass: { 7850 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 7851 7852 // If we leave the immediate function, the lifetime isn't about to end. 7853 if (DR->refersToEnclosingVariableOrCapture()) 7854 return nullptr; 7855 7856 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) 7857 // If this is a reference variable, follow through to the expression that 7858 // it points to. 7859 if (V->hasLocalStorage() && 7860 V->getType()->isReferenceType() && V->hasInit()) { 7861 // Add the reference variable to the "trail". 7862 refVars.push_back(DR); 7863 return EvalAddr(V->getInit(), refVars, ParentDecl); 7864 } 7865 7866 return nullptr; 7867 } 7868 7869 case Stmt::UnaryOperatorClass: { 7870 // The only unary operator that make sense to handle here 7871 // is AddrOf. All others don't make sense as pointers. 7872 const UnaryOperator *U = cast<UnaryOperator>(E); 7873 7874 if (U->getOpcode() == UO_AddrOf) 7875 return EvalVal(U->getSubExpr(), refVars, ParentDecl); 7876 return nullptr; 7877 } 7878 7879 case Stmt::BinaryOperatorClass: { 7880 // Handle pointer arithmetic. All other binary operators are not valid 7881 // in this context. 7882 const BinaryOperator *B = cast<BinaryOperator>(E); 7883 BinaryOperatorKind op = B->getOpcode(); 7884 7885 if (op != BO_Add && op != BO_Sub) 7886 return nullptr; 7887 7888 const Expr *Base = B->getLHS(); 7889 7890 // Determine which argument is the real pointer base. It could be 7891 // the RHS argument instead of the LHS. 7892 if (!Base->getType()->isPointerType()) 7893 Base = B->getRHS(); 7894 7895 assert(Base->getType()->isPointerType()); 7896 return EvalAddr(Base, refVars, ParentDecl); 7897 } 7898 7899 // For conditional operators we need to see if either the LHS or RHS are 7900 // valid DeclRefExpr*s. If one of them is valid, we return it. 7901 case Stmt::ConditionalOperatorClass: { 7902 const ConditionalOperator *C = cast<ConditionalOperator>(E); 7903 7904 // Handle the GNU extension for missing LHS. 7905 // FIXME: That isn't a ConditionalOperator, so doesn't get here. 7906 if (const Expr *LHSExpr = C->getLHS()) { 7907 // In C++, we can have a throw-expression, which has 'void' type. 7908 if (!LHSExpr->getType()->isVoidType()) 7909 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl)) 7910 return LHS; 7911 } 7912 7913 // In C++, we can have a throw-expression, which has 'void' type. 7914 if (C->getRHS()->getType()->isVoidType()) 7915 return nullptr; 7916 7917 return EvalAddr(C->getRHS(), refVars, ParentDecl); 7918 } 7919 7920 case Stmt::BlockExprClass: 7921 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures()) 7922 return E; // local block. 7923 return nullptr; 7924 7925 case Stmt::AddrLabelExprClass: 7926 return E; // address of label. 7927 7928 case Stmt::ExprWithCleanupsClass: 7929 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars, 7930 ParentDecl); 7931 7932 // For casts, we need to handle conversions from arrays to 7933 // pointer values, and pointer-to-pointer conversions. 7934 case Stmt::ImplicitCastExprClass: 7935 case Stmt::CStyleCastExprClass: 7936 case Stmt::CXXFunctionalCastExprClass: 7937 case Stmt::ObjCBridgedCastExprClass: 7938 case Stmt::CXXStaticCastExprClass: 7939 case Stmt::CXXDynamicCastExprClass: 7940 case Stmt::CXXConstCastExprClass: 7941 case Stmt::CXXReinterpretCastExprClass: { 7942 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr(); 7943 switch (cast<CastExpr>(E)->getCastKind()) { 7944 case CK_LValueToRValue: 7945 case CK_NoOp: 7946 case CK_BaseToDerived: 7947 case CK_DerivedToBase: 7948 case CK_UncheckedDerivedToBase: 7949 case CK_Dynamic: 7950 case CK_CPointerToObjCPointerCast: 7951 case CK_BlockPointerToObjCPointerCast: 7952 case CK_AnyPointerToBlockPointerCast: 7953 return EvalAddr(SubExpr, refVars, ParentDecl); 7954 7955 case CK_ArrayToPointerDecay: 7956 return EvalVal(SubExpr, refVars, ParentDecl); 7957 7958 case CK_BitCast: 7959 if (SubExpr->getType()->isAnyPointerType() || 7960 SubExpr->getType()->isBlockPointerType() || 7961 SubExpr->getType()->isObjCQualifiedIdType()) 7962 return EvalAddr(SubExpr, refVars, ParentDecl); 7963 else 7964 return nullptr; 7965 7966 default: 7967 return nullptr; 7968 } 7969 } 7970 7971 case Stmt::MaterializeTemporaryExprClass: 7972 if (const Expr *Result = 7973 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 7974 refVars, ParentDecl)) 7975 return Result; 7976 return E; 7977 7978 // Everything else: we simply don't reason about them. 7979 default: 7980 return nullptr; 7981 } 7982 } 7983 7984 /// EvalVal - This function is complements EvalAddr in the mutual recursion. 7985 /// See the comments for EvalAddr for more details. 7986 static const Expr *EvalVal(const Expr *E, 7987 SmallVectorImpl<const DeclRefExpr *> &refVars, 7988 const Decl *ParentDecl) { 7989 do { 7990 // We should only be called for evaluating non-pointer expressions, or 7991 // expressions with a pointer type that are not used as references but 7992 // instead 7993 // are l-values (e.g., DeclRefExpr with a pointer type). 7994 7995 // Our "symbolic interpreter" is just a dispatch off the currently 7996 // viewed AST node. We then recursively traverse the AST by calling 7997 // EvalAddr and EvalVal appropriately. 7998 7999 E = E->IgnoreParens(); 8000 switch (E->getStmtClass()) { 8001 case Stmt::ImplicitCastExprClass: { 8002 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E); 8003 if (IE->getValueKind() == VK_LValue) { 8004 E = IE->getSubExpr(); 8005 continue; 8006 } 8007 return nullptr; 8008 } 8009 8010 case Stmt::ExprWithCleanupsClass: 8011 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars, 8012 ParentDecl); 8013 8014 case Stmt::DeclRefExprClass: { 8015 // When we hit a DeclRefExpr we are looking at code that refers to a 8016 // variable's name. If it's not a reference variable we check if it has 8017 // local storage within the function, and if so, return the expression. 8018 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 8019 8020 // If we leave the immediate function, the lifetime isn't about to end. 8021 if (DR->refersToEnclosingVariableOrCapture()) 8022 return nullptr; 8023 8024 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) { 8025 // Check if it refers to itself, e.g. "int& i = i;". 8026 if (V == ParentDecl) 8027 return DR; 8028 8029 if (V->hasLocalStorage()) { 8030 if (!V->getType()->isReferenceType()) 8031 return DR; 8032 8033 // Reference variable, follow through to the expression that 8034 // it points to. 8035 if (V->hasInit()) { 8036 // Add the reference variable to the "trail". 8037 refVars.push_back(DR); 8038 return EvalVal(V->getInit(), refVars, V); 8039 } 8040 } 8041 } 8042 8043 return nullptr; 8044 } 8045 8046 case Stmt::UnaryOperatorClass: { 8047 // The only unary operator that make sense to handle here 8048 // is Deref. All others don't resolve to a "name." This includes 8049 // handling all sorts of rvalues passed to a unary operator. 8050 const UnaryOperator *U = cast<UnaryOperator>(E); 8051 8052 if (U->getOpcode() == UO_Deref) 8053 return EvalAddr(U->getSubExpr(), refVars, ParentDecl); 8054 8055 return nullptr; 8056 } 8057 8058 case Stmt::ArraySubscriptExprClass: { 8059 // Array subscripts are potential references to data on the stack. We 8060 // retrieve the DeclRefExpr* for the array variable if it indeed 8061 // has local storage. 8062 const auto *ASE = cast<ArraySubscriptExpr>(E); 8063 if (ASE->isTypeDependent()) 8064 return nullptr; 8065 return EvalAddr(ASE->getBase(), refVars, ParentDecl); 8066 } 8067 8068 case Stmt::OMPArraySectionExprClass: { 8069 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars, 8070 ParentDecl); 8071 } 8072 8073 case Stmt::ConditionalOperatorClass: { 8074 // For conditional operators we need to see if either the LHS or RHS are 8075 // non-NULL Expr's. If one is non-NULL, we return it. 8076 const ConditionalOperator *C = cast<ConditionalOperator>(E); 8077 8078 // Handle the GNU extension for missing LHS. 8079 if (const Expr *LHSExpr = C->getLHS()) { 8080 // In C++, we can have a throw-expression, which has 'void' type. 8081 if (!LHSExpr->getType()->isVoidType()) 8082 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl)) 8083 return LHS; 8084 } 8085 8086 // In C++, we can have a throw-expression, which has 'void' type. 8087 if (C->getRHS()->getType()->isVoidType()) 8088 return nullptr; 8089 8090 return EvalVal(C->getRHS(), refVars, ParentDecl); 8091 } 8092 8093 // Accesses to members are potential references to data on the stack. 8094 case Stmt::MemberExprClass: { 8095 const MemberExpr *M = cast<MemberExpr>(E); 8096 8097 // Check for indirect access. We only want direct field accesses. 8098 if (M->isArrow()) 8099 return nullptr; 8100 8101 // Check whether the member type is itself a reference, in which case 8102 // we're not going to refer to the member, but to what the member refers 8103 // to. 8104 if (M->getMemberDecl()->getType()->isReferenceType()) 8105 return nullptr; 8106 8107 return EvalVal(M->getBase(), refVars, ParentDecl); 8108 } 8109 8110 case Stmt::MaterializeTemporaryExprClass: 8111 if (const Expr *Result = 8112 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 8113 refVars, ParentDecl)) 8114 return Result; 8115 return E; 8116 8117 default: 8118 // Check that we don't return or take the address of a reference to a 8119 // temporary. This is only useful in C++. 8120 if (!E->isTypeDependent() && E->isRValue()) 8121 return E; 8122 8123 // Everything else: we simply don't reason about them. 8124 return nullptr; 8125 } 8126 } while (true); 8127 } 8128 8129 void 8130 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 8131 SourceLocation ReturnLoc, 8132 bool isObjCMethod, 8133 const AttrVec *Attrs, 8134 const FunctionDecl *FD) { 8135 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc); 8136 8137 // Check if the return value is null but should not be. 8138 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 8139 (!isObjCMethod && isNonNullType(Context, lhsType))) && 8140 CheckNonNullExpr(*this, RetValExp)) 8141 Diag(ReturnLoc, diag::warn_null_ret) 8142 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 8143 8144 // C++11 [basic.stc.dynamic.allocation]p4: 8145 // If an allocation function declared with a non-throwing 8146 // exception-specification fails to allocate storage, it shall return 8147 // a null pointer. Any other allocation function that fails to allocate 8148 // storage shall indicate failure only by throwing an exception [...] 8149 if (FD) { 8150 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 8151 if (Op == OO_New || Op == OO_Array_New) { 8152 const FunctionProtoType *Proto 8153 = FD->getType()->castAs<FunctionProtoType>(); 8154 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) && 8155 CheckNonNullExpr(*this, RetValExp)) 8156 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 8157 << FD << getLangOpts().CPlusPlus11; 8158 } 8159 } 8160 } 8161 8162 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 8163 8164 /// Check for comparisons of floating point operands using != and ==. 8165 /// Issue a warning if these are no self-comparisons, as they are not likely 8166 /// to do what the programmer intended. 8167 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 8168 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 8169 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 8170 8171 // Special case: check for x == x (which is OK). 8172 // Do not emit warnings for such cases. 8173 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 8174 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 8175 if (DRL->getDecl() == DRR->getDecl()) 8176 return; 8177 8178 // Special case: check for comparisons against literals that can be exactly 8179 // represented by APFloat. In such cases, do not emit a warning. This 8180 // is a heuristic: often comparison against such literals are used to 8181 // detect if a value in a variable has not changed. This clearly can 8182 // lead to false negatives. 8183 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 8184 if (FLL->isExact()) 8185 return; 8186 } else 8187 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 8188 if (FLR->isExact()) 8189 return; 8190 8191 // Check for comparisons with builtin types. 8192 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 8193 if (CL->getBuiltinCallee()) 8194 return; 8195 8196 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 8197 if (CR->getBuiltinCallee()) 8198 return; 8199 8200 // Emit the diagnostic. 8201 Diag(Loc, diag::warn_floatingpoint_eq) 8202 << LHS->getSourceRange() << RHS->getSourceRange(); 8203 } 8204 8205 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 8206 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 8207 8208 namespace { 8209 8210 /// Structure recording the 'active' range of an integer-valued 8211 /// expression. 8212 struct IntRange { 8213 /// The number of bits active in the int. 8214 unsigned Width; 8215 8216 /// True if the int is known not to have negative values. 8217 bool NonNegative; 8218 8219 IntRange(unsigned Width, bool NonNegative) 8220 : Width(Width), NonNegative(NonNegative) {} 8221 8222 /// Returns the range of the bool type. 8223 static IntRange forBoolType() { 8224 return IntRange(1, true); 8225 } 8226 8227 /// Returns the range of an opaque value of the given integral type. 8228 static IntRange forValueOfType(ASTContext &C, QualType T) { 8229 return forValueOfCanonicalType(C, 8230 T->getCanonicalTypeInternal().getTypePtr()); 8231 } 8232 8233 /// Returns the range of an opaque value of a canonical integral type. 8234 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 8235 assert(T->isCanonicalUnqualified()); 8236 8237 if (const VectorType *VT = dyn_cast<VectorType>(T)) 8238 T = VT->getElementType().getTypePtr(); 8239 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 8240 T = CT->getElementType().getTypePtr(); 8241 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 8242 T = AT->getValueType().getTypePtr(); 8243 8244 if (!C.getLangOpts().CPlusPlus) { 8245 // For enum types in C code, use the underlying datatype. 8246 if (const EnumType *ET = dyn_cast<EnumType>(T)) 8247 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 8248 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 8249 // For enum types in C++, use the known bit width of the enumerators. 8250 EnumDecl *Enum = ET->getDecl(); 8251 // In C++11, enums can have a fixed underlying type. Use this type to 8252 // compute the range. 8253 if (Enum->isFixed()) { 8254 return IntRange(C.getIntWidth(QualType(T, 0)), 8255 !ET->isSignedIntegerOrEnumerationType()); 8256 } 8257 8258 unsigned NumPositive = Enum->getNumPositiveBits(); 8259 unsigned NumNegative = Enum->getNumNegativeBits(); 8260 8261 if (NumNegative == 0) 8262 return IntRange(NumPositive, true/*NonNegative*/); 8263 else 8264 return IntRange(std::max(NumPositive + 1, NumNegative), 8265 false/*NonNegative*/); 8266 } 8267 8268 const BuiltinType *BT = cast<BuiltinType>(T); 8269 assert(BT->isInteger()); 8270 8271 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 8272 } 8273 8274 /// Returns the "target" range of a canonical integral type, i.e. 8275 /// the range of values expressible in the type. 8276 /// 8277 /// This matches forValueOfCanonicalType except that enums have the 8278 /// full range of their type, not the range of their enumerators. 8279 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 8280 assert(T->isCanonicalUnqualified()); 8281 8282 if (const VectorType *VT = dyn_cast<VectorType>(T)) 8283 T = VT->getElementType().getTypePtr(); 8284 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 8285 T = CT->getElementType().getTypePtr(); 8286 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 8287 T = AT->getValueType().getTypePtr(); 8288 if (const EnumType *ET = dyn_cast<EnumType>(T)) 8289 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 8290 8291 const BuiltinType *BT = cast<BuiltinType>(T); 8292 assert(BT->isInteger()); 8293 8294 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 8295 } 8296 8297 /// Returns the supremum of two ranges: i.e. their conservative merge. 8298 static IntRange join(IntRange L, IntRange R) { 8299 return IntRange(std::max(L.Width, R.Width), 8300 L.NonNegative && R.NonNegative); 8301 } 8302 8303 /// Returns the infinum of two ranges: i.e. their aggressive merge. 8304 static IntRange meet(IntRange L, IntRange R) { 8305 return IntRange(std::min(L.Width, R.Width), 8306 L.NonNegative || R.NonNegative); 8307 } 8308 }; 8309 8310 } // namespace 8311 8312 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 8313 unsigned MaxWidth) { 8314 if (value.isSigned() && value.isNegative()) 8315 return IntRange(value.getMinSignedBits(), false); 8316 8317 if (value.getBitWidth() > MaxWidth) 8318 value = value.trunc(MaxWidth); 8319 8320 // isNonNegative() just checks the sign bit without considering 8321 // signedness. 8322 return IntRange(value.getActiveBits(), true); 8323 } 8324 8325 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 8326 unsigned MaxWidth) { 8327 if (result.isInt()) 8328 return GetValueRange(C, result.getInt(), MaxWidth); 8329 8330 if (result.isVector()) { 8331 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 8332 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 8333 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 8334 R = IntRange::join(R, El); 8335 } 8336 return R; 8337 } 8338 8339 if (result.isComplexInt()) { 8340 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 8341 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 8342 return IntRange::join(R, I); 8343 } 8344 8345 // This can happen with lossless casts to intptr_t of "based" lvalues. 8346 // Assume it might use arbitrary bits. 8347 // FIXME: The only reason we need to pass the type in here is to get 8348 // the sign right on this one case. It would be nice if APValue 8349 // preserved this. 8350 assert(result.isLValue() || result.isAddrLabelDiff()); 8351 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 8352 } 8353 8354 static QualType GetExprType(const Expr *E) { 8355 QualType Ty = E->getType(); 8356 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 8357 Ty = AtomicRHS->getValueType(); 8358 return Ty; 8359 } 8360 8361 /// Pseudo-evaluate the given integer expression, estimating the 8362 /// range of values it might take. 8363 /// 8364 /// \param MaxWidth - the width to which the value will be truncated 8365 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) { 8366 E = E->IgnoreParens(); 8367 8368 // Try a full evaluation first. 8369 Expr::EvalResult result; 8370 if (E->EvaluateAsRValue(result, C)) 8371 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 8372 8373 // I think we only want to look through implicit casts here; if the 8374 // user has an explicit widening cast, we should treat the value as 8375 // being of the new, wider type. 8376 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 8377 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 8378 return GetExprRange(C, CE->getSubExpr(), MaxWidth); 8379 8380 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 8381 8382 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 8383 CE->getCastKind() == CK_BooleanToSignedIntegral; 8384 8385 // Assume that non-integer casts can span the full range of the type. 8386 if (!isIntegerCast) 8387 return OutputTypeRange; 8388 8389 IntRange SubRange 8390 = GetExprRange(C, CE->getSubExpr(), 8391 std::min(MaxWidth, OutputTypeRange.Width)); 8392 8393 // Bail out if the subexpr's range is as wide as the cast type. 8394 if (SubRange.Width >= OutputTypeRange.Width) 8395 return OutputTypeRange; 8396 8397 // Otherwise, we take the smaller width, and we're non-negative if 8398 // either the output type or the subexpr is. 8399 return IntRange(SubRange.Width, 8400 SubRange.NonNegative || OutputTypeRange.NonNegative); 8401 } 8402 8403 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 8404 // If we can fold the condition, just take that operand. 8405 bool CondResult; 8406 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 8407 return GetExprRange(C, CondResult ? CO->getTrueExpr() 8408 : CO->getFalseExpr(), 8409 MaxWidth); 8410 8411 // Otherwise, conservatively merge. 8412 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth); 8413 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth); 8414 return IntRange::join(L, R); 8415 } 8416 8417 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 8418 switch (BO->getOpcode()) { 8419 case BO_Cmp: 8420 llvm_unreachable("builtin <=> should have class type"); 8421 8422 // Boolean-valued operations are single-bit and positive. 8423 case BO_LAnd: 8424 case BO_LOr: 8425 case BO_LT: 8426 case BO_GT: 8427 case BO_LE: 8428 case BO_GE: 8429 case BO_EQ: 8430 case BO_NE: 8431 return IntRange::forBoolType(); 8432 8433 // The type of the assignments is the type of the LHS, so the RHS 8434 // is not necessarily the same type. 8435 case BO_MulAssign: 8436 case BO_DivAssign: 8437 case BO_RemAssign: 8438 case BO_AddAssign: 8439 case BO_SubAssign: 8440 case BO_XorAssign: 8441 case BO_OrAssign: 8442 // TODO: bitfields? 8443 return IntRange::forValueOfType(C, GetExprType(E)); 8444 8445 // Simple assignments just pass through the RHS, which will have 8446 // been coerced to the LHS type. 8447 case BO_Assign: 8448 // TODO: bitfields? 8449 return GetExprRange(C, BO->getRHS(), MaxWidth); 8450 8451 // Operations with opaque sources are black-listed. 8452 case BO_PtrMemD: 8453 case BO_PtrMemI: 8454 return IntRange::forValueOfType(C, GetExprType(E)); 8455 8456 // Bitwise-and uses the *infinum* of the two source ranges. 8457 case BO_And: 8458 case BO_AndAssign: 8459 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth), 8460 GetExprRange(C, BO->getRHS(), MaxWidth)); 8461 8462 // Left shift gets black-listed based on a judgement call. 8463 case BO_Shl: 8464 // ...except that we want to treat '1 << (blah)' as logically 8465 // positive. It's an important idiom. 8466 if (IntegerLiteral *I 8467 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 8468 if (I->getValue() == 1) { 8469 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 8470 return IntRange(R.Width, /*NonNegative*/ true); 8471 } 8472 } 8473 LLVM_FALLTHROUGH; 8474 8475 case BO_ShlAssign: 8476 return IntRange::forValueOfType(C, GetExprType(E)); 8477 8478 // Right shift by a constant can narrow its left argument. 8479 case BO_Shr: 8480 case BO_ShrAssign: { 8481 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 8482 8483 // If the shift amount is a positive constant, drop the width by 8484 // that much. 8485 llvm::APSInt shift; 8486 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 8487 shift.isNonNegative()) { 8488 unsigned zext = shift.getZExtValue(); 8489 if (zext >= L.Width) 8490 L.Width = (L.NonNegative ? 0 : 1); 8491 else 8492 L.Width -= zext; 8493 } 8494 8495 return L; 8496 } 8497 8498 // Comma acts as its right operand. 8499 case BO_Comma: 8500 return GetExprRange(C, BO->getRHS(), MaxWidth); 8501 8502 // Black-list pointer subtractions. 8503 case BO_Sub: 8504 if (BO->getLHS()->getType()->isPointerType()) 8505 return IntRange::forValueOfType(C, GetExprType(E)); 8506 break; 8507 8508 // The width of a division result is mostly determined by the size 8509 // of the LHS. 8510 case BO_Div: { 8511 // Don't 'pre-truncate' the operands. 8512 unsigned opWidth = C.getIntWidth(GetExprType(E)); 8513 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 8514 8515 // If the divisor is constant, use that. 8516 llvm::APSInt divisor; 8517 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 8518 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 8519 if (log2 >= L.Width) 8520 L.Width = (L.NonNegative ? 0 : 1); 8521 else 8522 L.Width = std::min(L.Width - log2, MaxWidth); 8523 return L; 8524 } 8525 8526 // Otherwise, just use the LHS's width. 8527 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 8528 return IntRange(L.Width, L.NonNegative && R.NonNegative); 8529 } 8530 8531 // The result of a remainder can't be larger than the result of 8532 // either side. 8533 case BO_Rem: { 8534 // Don't 'pre-truncate' the operands. 8535 unsigned opWidth = C.getIntWidth(GetExprType(E)); 8536 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 8537 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 8538 8539 IntRange meet = IntRange::meet(L, R); 8540 meet.Width = std::min(meet.Width, MaxWidth); 8541 return meet; 8542 } 8543 8544 // The default behavior is okay for these. 8545 case BO_Mul: 8546 case BO_Add: 8547 case BO_Xor: 8548 case BO_Or: 8549 break; 8550 } 8551 8552 // The default case is to treat the operation as if it were closed 8553 // on the narrowest type that encompasses both operands. 8554 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 8555 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth); 8556 return IntRange::join(L, R); 8557 } 8558 8559 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 8560 switch (UO->getOpcode()) { 8561 // Boolean-valued operations are white-listed. 8562 case UO_LNot: 8563 return IntRange::forBoolType(); 8564 8565 // Operations with opaque sources are black-listed. 8566 case UO_Deref: 8567 case UO_AddrOf: // should be impossible 8568 return IntRange::forValueOfType(C, GetExprType(E)); 8569 8570 default: 8571 return GetExprRange(C, UO->getSubExpr(), MaxWidth); 8572 } 8573 } 8574 8575 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 8576 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth); 8577 8578 if (const auto *BitField = E->getSourceBitField()) 8579 return IntRange(BitField->getBitWidthValue(C), 8580 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 8581 8582 return IntRange::forValueOfType(C, GetExprType(E)); 8583 } 8584 8585 static IntRange GetExprRange(ASTContext &C, const Expr *E) { 8586 return GetExprRange(C, E, C.getIntWidth(GetExprType(E))); 8587 } 8588 8589 /// Checks whether the given value, which currently has the given 8590 /// source semantics, has the same value when coerced through the 8591 /// target semantics. 8592 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 8593 const llvm::fltSemantics &Src, 8594 const llvm::fltSemantics &Tgt) { 8595 llvm::APFloat truncated = value; 8596 8597 bool ignored; 8598 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 8599 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 8600 8601 return truncated.bitwiseIsEqual(value); 8602 } 8603 8604 /// Checks whether the given value, which currently has the given 8605 /// source semantics, has the same value when coerced through the 8606 /// target semantics. 8607 /// 8608 /// The value might be a vector of floats (or a complex number). 8609 static bool IsSameFloatAfterCast(const APValue &value, 8610 const llvm::fltSemantics &Src, 8611 const llvm::fltSemantics &Tgt) { 8612 if (value.isFloat()) 8613 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 8614 8615 if (value.isVector()) { 8616 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 8617 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 8618 return false; 8619 return true; 8620 } 8621 8622 assert(value.isComplexFloat()); 8623 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 8624 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 8625 } 8626 8627 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC); 8628 8629 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 8630 // Suppress cases where we are comparing against an enum constant. 8631 if (const DeclRefExpr *DR = 8632 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 8633 if (isa<EnumConstantDecl>(DR->getDecl())) 8634 return true; 8635 8636 // Suppress cases where the '0' value is expanded from a macro. 8637 if (E->getLocStart().isMacroID()) 8638 return true; 8639 8640 return false; 8641 } 8642 8643 static bool isKnownToHaveUnsignedValue(Expr *E) { 8644 return E->getType()->isIntegerType() && 8645 (!E->getType()->isSignedIntegerType() || 8646 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 8647 } 8648 8649 namespace { 8650 /// The promoted range of values of a type. In general this has the 8651 /// following structure: 8652 /// 8653 /// |-----------| . . . |-----------| 8654 /// ^ ^ ^ ^ 8655 /// Min HoleMin HoleMax Max 8656 /// 8657 /// ... where there is only a hole if a signed type is promoted to unsigned 8658 /// (in which case Min and Max are the smallest and largest representable 8659 /// values). 8660 struct PromotedRange { 8661 // Min, or HoleMax if there is a hole. 8662 llvm::APSInt PromotedMin; 8663 // Max, or HoleMin if there is a hole. 8664 llvm::APSInt PromotedMax; 8665 8666 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 8667 if (R.Width == 0) 8668 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 8669 else if (R.Width >= BitWidth && !Unsigned) { 8670 // Promotion made the type *narrower*. This happens when promoting 8671 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 8672 // Treat all values of 'signed int' as being in range for now. 8673 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 8674 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 8675 } else { 8676 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 8677 .extOrTrunc(BitWidth); 8678 PromotedMin.setIsUnsigned(Unsigned); 8679 8680 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 8681 .extOrTrunc(BitWidth); 8682 PromotedMax.setIsUnsigned(Unsigned); 8683 } 8684 } 8685 8686 // Determine whether this range is contiguous (has no hole). 8687 bool isContiguous() const { return PromotedMin <= PromotedMax; } 8688 8689 // Where a constant value is within the range. 8690 enum ComparisonResult { 8691 LT = 0x1, 8692 LE = 0x2, 8693 GT = 0x4, 8694 GE = 0x8, 8695 EQ = 0x10, 8696 NE = 0x20, 8697 InRangeFlag = 0x40, 8698 8699 Less = LE | LT | NE, 8700 Min = LE | InRangeFlag, 8701 InRange = InRangeFlag, 8702 Max = GE | InRangeFlag, 8703 Greater = GE | GT | NE, 8704 8705 OnlyValue = LE | GE | EQ | InRangeFlag, 8706 InHole = NE 8707 }; 8708 8709 ComparisonResult compare(const llvm::APSInt &Value) const { 8710 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 8711 Value.isUnsigned() == PromotedMin.isUnsigned()); 8712 if (!isContiguous()) { 8713 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 8714 if (Value.isMinValue()) return Min; 8715 if (Value.isMaxValue()) return Max; 8716 if (Value >= PromotedMin) return InRange; 8717 if (Value <= PromotedMax) return InRange; 8718 return InHole; 8719 } 8720 8721 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 8722 case -1: return Less; 8723 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 8724 case 1: 8725 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 8726 case -1: return InRange; 8727 case 0: return Max; 8728 case 1: return Greater; 8729 } 8730 } 8731 8732 llvm_unreachable("impossible compare result"); 8733 } 8734 8735 static llvm::Optional<StringRef> 8736 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 8737 if (Op == BO_Cmp) { 8738 ComparisonResult LTFlag = LT, GTFlag = GT; 8739 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 8740 8741 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 8742 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 8743 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 8744 return llvm::None; 8745 } 8746 8747 ComparisonResult TrueFlag, FalseFlag; 8748 if (Op == BO_EQ) { 8749 TrueFlag = EQ; 8750 FalseFlag = NE; 8751 } else if (Op == BO_NE) { 8752 TrueFlag = NE; 8753 FalseFlag = EQ; 8754 } else { 8755 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 8756 TrueFlag = LT; 8757 FalseFlag = GE; 8758 } else { 8759 TrueFlag = GT; 8760 FalseFlag = LE; 8761 } 8762 if (Op == BO_GE || Op == BO_LE) 8763 std::swap(TrueFlag, FalseFlag); 8764 } 8765 if (R & TrueFlag) 8766 return StringRef("true"); 8767 if (R & FalseFlag) 8768 return StringRef("false"); 8769 return llvm::None; 8770 } 8771 }; 8772 } 8773 8774 static bool HasEnumType(Expr *E) { 8775 // Strip off implicit integral promotions. 8776 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 8777 if (ICE->getCastKind() != CK_IntegralCast && 8778 ICE->getCastKind() != CK_NoOp) 8779 break; 8780 E = ICE->getSubExpr(); 8781 } 8782 8783 return E->getType()->isEnumeralType(); 8784 } 8785 8786 static int classifyConstantValue(Expr *Constant) { 8787 // The values of this enumeration are used in the diagnostics 8788 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 8789 enum ConstantValueKind { 8790 Miscellaneous = 0, 8791 LiteralTrue, 8792 LiteralFalse 8793 }; 8794 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 8795 return BL->getValue() ? ConstantValueKind::LiteralTrue 8796 : ConstantValueKind::LiteralFalse; 8797 return ConstantValueKind::Miscellaneous; 8798 } 8799 8800 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 8801 Expr *Constant, Expr *Other, 8802 const llvm::APSInt &Value, 8803 bool RhsConstant) { 8804 if (S.inTemplateInstantiation()) 8805 return false; 8806 8807 Expr *OriginalOther = Other; 8808 8809 Constant = Constant->IgnoreParenImpCasts(); 8810 Other = Other->IgnoreParenImpCasts(); 8811 8812 // Suppress warnings on tautological comparisons between values of the same 8813 // enumeration type. There are only two ways we could warn on this: 8814 // - If the constant is outside the range of representable values of 8815 // the enumeration. In such a case, we should warn about the cast 8816 // to enumeration type, not about the comparison. 8817 // - If the constant is the maximum / minimum in-range value. For an 8818 // enumeratin type, such comparisons can be meaningful and useful. 8819 if (Constant->getType()->isEnumeralType() && 8820 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 8821 return false; 8822 8823 // TODO: Investigate using GetExprRange() to get tighter bounds 8824 // on the bit ranges. 8825 QualType OtherT = Other->getType(); 8826 if (const auto *AT = OtherT->getAs<AtomicType>()) 8827 OtherT = AT->getValueType(); 8828 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); 8829 8830 // Whether we're treating Other as being a bool because of the form of 8831 // expression despite it having another type (typically 'int' in C). 8832 bool OtherIsBooleanDespiteType = 8833 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 8834 if (OtherIsBooleanDespiteType) 8835 OtherRange = IntRange::forBoolType(); 8836 8837 // Determine the promoted range of the other type and see if a comparison of 8838 // the constant against that range is tautological. 8839 PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(), 8840 Value.isUnsigned()); 8841 auto Cmp = OtherPromotedRange.compare(Value); 8842 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 8843 if (!Result) 8844 return false; 8845 8846 // Suppress the diagnostic for an in-range comparison if the constant comes 8847 // from a macro or enumerator. We don't want to diagnose 8848 // 8849 // some_long_value <= INT_MAX 8850 // 8851 // when sizeof(int) == sizeof(long). 8852 bool InRange = Cmp & PromotedRange::InRangeFlag; 8853 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 8854 return false; 8855 8856 // If this is a comparison to an enum constant, include that 8857 // constant in the diagnostic. 8858 const EnumConstantDecl *ED = nullptr; 8859 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 8860 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 8861 8862 // Should be enough for uint128 (39 decimal digits) 8863 SmallString<64> PrettySourceValue; 8864 llvm::raw_svector_ostream OS(PrettySourceValue); 8865 if (ED) 8866 OS << '\'' << *ED << "' (" << Value << ")"; 8867 else 8868 OS << Value; 8869 8870 // FIXME: We use a somewhat different formatting for the in-range cases and 8871 // cases involving boolean values for historical reasons. We should pick a 8872 // consistent way of presenting these diagnostics. 8873 if (!InRange || Other->isKnownToHaveBooleanValue()) { 8874 S.DiagRuntimeBehavior( 8875 E->getOperatorLoc(), E, 8876 S.PDiag(!InRange ? diag::warn_out_of_range_compare 8877 : diag::warn_tautological_bool_compare) 8878 << OS.str() << classifyConstantValue(Constant) 8879 << OtherT << OtherIsBooleanDespiteType << *Result 8880 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 8881 } else { 8882 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 8883 ? (HasEnumType(OriginalOther) 8884 ? diag::warn_unsigned_enum_always_true_comparison 8885 : diag::warn_unsigned_always_true_comparison) 8886 : diag::warn_tautological_constant_compare; 8887 8888 S.Diag(E->getOperatorLoc(), Diag) 8889 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 8890 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 8891 } 8892 8893 return true; 8894 } 8895 8896 /// Analyze the operands of the given comparison. Implements the 8897 /// fallback case from AnalyzeComparison. 8898 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 8899 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 8900 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 8901 } 8902 8903 /// \brief Implements -Wsign-compare. 8904 /// 8905 /// \param E the binary operator to check for warnings 8906 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 8907 // The type the comparison is being performed in. 8908 QualType T = E->getLHS()->getType(); 8909 8910 // Only analyze comparison operators where both sides have been converted to 8911 // the same type. 8912 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 8913 return AnalyzeImpConvsInComparison(S, E); 8914 8915 // Don't analyze value-dependent comparisons directly. 8916 if (E->isValueDependent()) 8917 return AnalyzeImpConvsInComparison(S, E); 8918 8919 Expr *LHS = E->getLHS(); 8920 Expr *RHS = E->getRHS(); 8921 8922 if (T->isIntegralType(S.Context)) { 8923 llvm::APSInt RHSValue; 8924 llvm::APSInt LHSValue; 8925 8926 bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context); 8927 bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context); 8928 8929 // We don't care about expressions whose result is a constant. 8930 if (IsRHSIntegralLiteral && IsLHSIntegralLiteral) 8931 return AnalyzeImpConvsInComparison(S, E); 8932 8933 // We only care about expressions where just one side is literal 8934 if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) { 8935 // Is the constant on the RHS or LHS? 8936 const bool RhsConstant = IsRHSIntegralLiteral; 8937 Expr *Const = RhsConstant ? RHS : LHS; 8938 Expr *Other = RhsConstant ? LHS : RHS; 8939 const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue; 8940 8941 // Check whether an integer constant comparison results in a value 8942 // of 'true' or 'false'. 8943 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 8944 return AnalyzeImpConvsInComparison(S, E); 8945 } 8946 } 8947 8948 if (!T->hasUnsignedIntegerRepresentation()) { 8949 // We don't do anything special if this isn't an unsigned integral 8950 // comparison: we're only interested in integral comparisons, and 8951 // signed comparisons only happen in cases we don't care to warn about. 8952 return AnalyzeImpConvsInComparison(S, E); 8953 } 8954 8955 LHS = LHS->IgnoreParenImpCasts(); 8956 RHS = RHS->IgnoreParenImpCasts(); 8957 8958 // Check to see if one of the (unmodified) operands is of different 8959 // signedness. 8960 Expr *signedOperand, *unsignedOperand; 8961 if (LHS->getType()->hasSignedIntegerRepresentation()) { 8962 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 8963 "unsigned comparison between two signed integer expressions?"); 8964 signedOperand = LHS; 8965 unsignedOperand = RHS; 8966 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 8967 signedOperand = RHS; 8968 unsignedOperand = LHS; 8969 } else { 8970 return AnalyzeImpConvsInComparison(S, E); 8971 } 8972 8973 // Otherwise, calculate the effective range of the signed operand. 8974 IntRange signedRange = GetExprRange(S.Context, signedOperand); 8975 8976 // Go ahead and analyze implicit conversions in the operands. Note 8977 // that we skip the implicit conversions on both sides. 8978 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 8979 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 8980 8981 // If the signed range is non-negative, -Wsign-compare won't fire. 8982 if (signedRange.NonNegative) 8983 return; 8984 8985 // For (in)equality comparisons, if the unsigned operand is a 8986 // constant which cannot collide with a overflowed signed operand, 8987 // then reinterpreting the signed operand as unsigned will not 8988 // change the result of the comparison. 8989 if (E->isEqualityOp()) { 8990 unsigned comparisonWidth = S.Context.getIntWidth(T); 8991 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand); 8992 8993 // We should never be unable to prove that the unsigned operand is 8994 // non-negative. 8995 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 8996 8997 if (unsignedRange.Width < comparisonWidth) 8998 return; 8999 } 9000 9001 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 9002 S.PDiag(diag::warn_mixed_sign_comparison) 9003 << LHS->getType() << RHS->getType() 9004 << LHS->getSourceRange() << RHS->getSourceRange()); 9005 } 9006 9007 /// Analyzes an attempt to assign the given value to a bitfield. 9008 /// 9009 /// Returns true if there was something fishy about the attempt. 9010 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 9011 SourceLocation InitLoc) { 9012 assert(Bitfield->isBitField()); 9013 if (Bitfield->isInvalidDecl()) 9014 return false; 9015 9016 // White-list bool bitfields. 9017 QualType BitfieldType = Bitfield->getType(); 9018 if (BitfieldType->isBooleanType()) 9019 return false; 9020 9021 if (BitfieldType->isEnumeralType()) { 9022 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl(); 9023 // If the underlying enum type was not explicitly specified as an unsigned 9024 // type and the enum contain only positive values, MSVC++ will cause an 9025 // inconsistency by storing this as a signed type. 9026 if (S.getLangOpts().CPlusPlus11 && 9027 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 9028 BitfieldEnumDecl->getNumPositiveBits() > 0 && 9029 BitfieldEnumDecl->getNumNegativeBits() == 0) { 9030 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 9031 << BitfieldEnumDecl->getNameAsString(); 9032 } 9033 } 9034 9035 if (Bitfield->getType()->isBooleanType()) 9036 return false; 9037 9038 // Ignore value- or type-dependent expressions. 9039 if (Bitfield->getBitWidth()->isValueDependent() || 9040 Bitfield->getBitWidth()->isTypeDependent() || 9041 Init->isValueDependent() || 9042 Init->isTypeDependent()) 9043 return false; 9044 9045 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 9046 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 9047 9048 llvm::APSInt Value; 9049 if (!OriginalInit->EvaluateAsInt(Value, S.Context, 9050 Expr::SE_AllowSideEffects)) { 9051 // The RHS is not constant. If the RHS has an enum type, make sure the 9052 // bitfield is wide enough to hold all the values of the enum without 9053 // truncation. 9054 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 9055 EnumDecl *ED = EnumTy->getDecl(); 9056 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 9057 9058 // Enum types are implicitly signed on Windows, so check if there are any 9059 // negative enumerators to see if the enum was intended to be signed or 9060 // not. 9061 bool SignedEnum = ED->getNumNegativeBits() > 0; 9062 9063 // Check for surprising sign changes when assigning enum values to a 9064 // bitfield of different signedness. If the bitfield is signed and we 9065 // have exactly the right number of bits to store this unsigned enum, 9066 // suggest changing the enum to an unsigned type. This typically happens 9067 // on Windows where unfixed enums always use an underlying type of 'int'. 9068 unsigned DiagID = 0; 9069 if (SignedEnum && !SignedBitfield) { 9070 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 9071 } else if (SignedBitfield && !SignedEnum && 9072 ED->getNumPositiveBits() == FieldWidth) { 9073 DiagID = diag::warn_signed_bitfield_enum_conversion; 9074 } 9075 9076 if (DiagID) { 9077 S.Diag(InitLoc, DiagID) << Bitfield << ED; 9078 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 9079 SourceRange TypeRange = 9080 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 9081 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 9082 << SignedEnum << TypeRange; 9083 } 9084 9085 // Compute the required bitwidth. If the enum has negative values, we need 9086 // one more bit than the normal number of positive bits to represent the 9087 // sign bit. 9088 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 9089 ED->getNumNegativeBits()) 9090 : ED->getNumPositiveBits(); 9091 9092 // Check the bitwidth. 9093 if (BitsNeeded > FieldWidth) { 9094 Expr *WidthExpr = Bitfield->getBitWidth(); 9095 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 9096 << Bitfield << ED; 9097 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 9098 << BitsNeeded << ED << WidthExpr->getSourceRange(); 9099 } 9100 } 9101 9102 return false; 9103 } 9104 9105 unsigned OriginalWidth = Value.getBitWidth(); 9106 9107 if (!Value.isSigned() || Value.isNegative()) 9108 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 9109 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 9110 OriginalWidth = Value.getMinSignedBits(); 9111 9112 if (OriginalWidth <= FieldWidth) 9113 return false; 9114 9115 // Compute the value which the bitfield will contain. 9116 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 9117 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 9118 9119 // Check whether the stored value is equal to the original value. 9120 TruncatedValue = TruncatedValue.extend(OriginalWidth); 9121 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 9122 return false; 9123 9124 // Special-case bitfields of width 1: booleans are naturally 0/1, and 9125 // therefore don't strictly fit into a signed bitfield of width 1. 9126 if (FieldWidth == 1 && Value == 1) 9127 return false; 9128 9129 std::string PrettyValue = Value.toString(10); 9130 std::string PrettyTrunc = TruncatedValue.toString(10); 9131 9132 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 9133 << PrettyValue << PrettyTrunc << OriginalInit->getType() 9134 << Init->getSourceRange(); 9135 9136 return true; 9137 } 9138 9139 /// Analyze the given simple or compound assignment for warning-worthy 9140 /// operations. 9141 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 9142 // Just recurse on the LHS. 9143 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 9144 9145 // We want to recurse on the RHS as normal unless we're assigning to 9146 // a bitfield. 9147 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 9148 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 9149 E->getOperatorLoc())) { 9150 // Recurse, ignoring any implicit conversions on the RHS. 9151 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 9152 E->getOperatorLoc()); 9153 } 9154 } 9155 9156 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 9157 } 9158 9159 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 9160 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 9161 SourceLocation CContext, unsigned diag, 9162 bool pruneControlFlow = false) { 9163 if (pruneControlFlow) { 9164 S.DiagRuntimeBehavior(E->getExprLoc(), E, 9165 S.PDiag(diag) 9166 << SourceType << T << E->getSourceRange() 9167 << SourceRange(CContext)); 9168 return; 9169 } 9170 S.Diag(E->getExprLoc(), diag) 9171 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 9172 } 9173 9174 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 9175 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 9176 SourceLocation CContext, 9177 unsigned diag, bool pruneControlFlow = false) { 9178 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 9179 } 9180 9181 9182 /// Diagnose an implicit cast from a floating point value to an integer value. 9183 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 9184 SourceLocation CContext) { 9185 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 9186 const bool PruneWarnings = S.inTemplateInstantiation(); 9187 9188 Expr *InnerE = E->IgnoreParenImpCasts(); 9189 // We also want to warn on, e.g., "int i = -1.234" 9190 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 9191 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 9192 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 9193 9194 const bool IsLiteral = 9195 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 9196 9197 llvm::APFloat Value(0.0); 9198 bool IsConstant = 9199 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 9200 if (!IsConstant) { 9201 return DiagnoseImpCast(S, E, T, CContext, 9202 diag::warn_impcast_float_integer, PruneWarnings); 9203 } 9204 9205 bool isExact = false; 9206 9207 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 9208 T->hasUnsignedIntegerRepresentation()); 9209 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero, 9210 &isExact) == llvm::APFloat::opOK && 9211 isExact) { 9212 if (IsLiteral) return; 9213 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 9214 PruneWarnings); 9215 } 9216 9217 unsigned DiagID = 0; 9218 if (IsLiteral) { 9219 // Warn on floating point literal to integer. 9220 DiagID = diag::warn_impcast_literal_float_to_integer; 9221 } else if (IntegerValue == 0) { 9222 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 9223 return DiagnoseImpCast(S, E, T, CContext, 9224 diag::warn_impcast_float_integer, PruneWarnings); 9225 } 9226 // Warn on non-zero to zero conversion. 9227 DiagID = diag::warn_impcast_float_to_integer_zero; 9228 } else { 9229 if (IntegerValue.isUnsigned()) { 9230 if (!IntegerValue.isMaxValue()) { 9231 return DiagnoseImpCast(S, E, T, CContext, 9232 diag::warn_impcast_float_integer, PruneWarnings); 9233 } 9234 } else { // IntegerValue.isSigned() 9235 if (!IntegerValue.isMaxSignedValue() && 9236 !IntegerValue.isMinSignedValue()) { 9237 return DiagnoseImpCast(S, E, T, CContext, 9238 diag::warn_impcast_float_integer, PruneWarnings); 9239 } 9240 } 9241 // Warn on evaluatable floating point expression to integer conversion. 9242 DiagID = diag::warn_impcast_float_to_integer; 9243 } 9244 9245 // FIXME: Force the precision of the source value down so we don't print 9246 // digits which are usually useless (we don't really care here if we 9247 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 9248 // would automatically print the shortest representation, but it's a bit 9249 // tricky to implement. 9250 SmallString<16> PrettySourceValue; 9251 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 9252 precision = (precision * 59 + 195) / 196; 9253 Value.toString(PrettySourceValue, precision); 9254 9255 SmallString<16> PrettyTargetValue; 9256 if (IsBool) 9257 PrettyTargetValue = Value.isZero() ? "false" : "true"; 9258 else 9259 IntegerValue.toString(PrettyTargetValue); 9260 9261 if (PruneWarnings) { 9262 S.DiagRuntimeBehavior(E->getExprLoc(), E, 9263 S.PDiag(DiagID) 9264 << E->getType() << T.getUnqualifiedType() 9265 << PrettySourceValue << PrettyTargetValue 9266 << E->getSourceRange() << SourceRange(CContext)); 9267 } else { 9268 S.Diag(E->getExprLoc(), DiagID) 9269 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 9270 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 9271 } 9272 } 9273 9274 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 9275 IntRange Range) { 9276 if (!Range.Width) return "0"; 9277 9278 llvm::APSInt ValueInRange = Value; 9279 ValueInRange.setIsSigned(!Range.NonNegative); 9280 ValueInRange = ValueInRange.trunc(Range.Width); 9281 return ValueInRange.toString(10); 9282 } 9283 9284 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 9285 if (!isa<ImplicitCastExpr>(Ex)) 9286 return false; 9287 9288 Expr *InnerE = Ex->IgnoreParenImpCasts(); 9289 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 9290 const Type *Source = 9291 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 9292 if (Target->isDependentType()) 9293 return false; 9294 9295 const BuiltinType *FloatCandidateBT = 9296 dyn_cast<BuiltinType>(ToBool ? Source : Target); 9297 const Type *BoolCandidateType = ToBool ? Target : Source; 9298 9299 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 9300 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 9301 } 9302 9303 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 9304 SourceLocation CC) { 9305 unsigned NumArgs = TheCall->getNumArgs(); 9306 for (unsigned i = 0; i < NumArgs; ++i) { 9307 Expr *CurrA = TheCall->getArg(i); 9308 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 9309 continue; 9310 9311 bool IsSwapped = ((i > 0) && 9312 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 9313 IsSwapped |= ((i < (NumArgs - 1)) && 9314 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 9315 if (IsSwapped) { 9316 // Warn on this floating-point to bool conversion. 9317 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 9318 CurrA->getType(), CC, 9319 diag::warn_impcast_floating_point_to_bool); 9320 } 9321 } 9322 } 9323 9324 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 9325 SourceLocation CC) { 9326 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 9327 E->getExprLoc())) 9328 return; 9329 9330 // Don't warn on functions which have return type nullptr_t. 9331 if (isa<CallExpr>(E)) 9332 return; 9333 9334 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 9335 const Expr::NullPointerConstantKind NullKind = 9336 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 9337 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 9338 return; 9339 9340 // Return if target type is a safe conversion. 9341 if (T->isAnyPointerType() || T->isBlockPointerType() || 9342 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 9343 return; 9344 9345 SourceLocation Loc = E->getSourceRange().getBegin(); 9346 9347 // Venture through the macro stacks to get to the source of macro arguments. 9348 // The new location is a better location than the complete location that was 9349 // passed in. 9350 while (S.SourceMgr.isMacroArgExpansion(Loc)) 9351 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc); 9352 9353 while (S.SourceMgr.isMacroArgExpansion(CC)) 9354 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC); 9355 9356 // __null is usually wrapped in a macro. Go up a macro if that is the case. 9357 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 9358 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 9359 Loc, S.SourceMgr, S.getLangOpts()); 9360 if (MacroName == "NULL") 9361 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first; 9362 } 9363 9364 // Only warn if the null and context location are in the same macro expansion. 9365 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 9366 return; 9367 9368 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 9369 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 9370 << FixItHint::CreateReplacement(Loc, 9371 S.getFixItZeroLiteralForType(T, Loc)); 9372 } 9373 9374 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 9375 ObjCArrayLiteral *ArrayLiteral); 9376 9377 static void 9378 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 9379 ObjCDictionaryLiteral *DictionaryLiteral); 9380 9381 /// Check a single element within a collection literal against the 9382 /// target element type. 9383 static void checkObjCCollectionLiteralElement(Sema &S, 9384 QualType TargetElementType, 9385 Expr *Element, 9386 unsigned ElementKind) { 9387 // Skip a bitcast to 'id' or qualified 'id'. 9388 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 9389 if (ICE->getCastKind() == CK_BitCast && 9390 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 9391 Element = ICE->getSubExpr(); 9392 } 9393 9394 QualType ElementType = Element->getType(); 9395 ExprResult ElementResult(Element); 9396 if (ElementType->getAs<ObjCObjectPointerType>() && 9397 S.CheckSingleAssignmentConstraints(TargetElementType, 9398 ElementResult, 9399 false, false) 9400 != Sema::Compatible) { 9401 S.Diag(Element->getLocStart(), 9402 diag::warn_objc_collection_literal_element) 9403 << ElementType << ElementKind << TargetElementType 9404 << Element->getSourceRange(); 9405 } 9406 9407 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 9408 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 9409 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 9410 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 9411 } 9412 9413 /// Check an Objective-C array literal being converted to the given 9414 /// target type. 9415 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 9416 ObjCArrayLiteral *ArrayLiteral) { 9417 if (!S.NSArrayDecl) 9418 return; 9419 9420 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 9421 if (!TargetObjCPtr) 9422 return; 9423 9424 if (TargetObjCPtr->isUnspecialized() || 9425 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 9426 != S.NSArrayDecl->getCanonicalDecl()) 9427 return; 9428 9429 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 9430 if (TypeArgs.size() != 1) 9431 return; 9432 9433 QualType TargetElementType = TypeArgs[0]; 9434 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 9435 checkObjCCollectionLiteralElement(S, TargetElementType, 9436 ArrayLiteral->getElement(I), 9437 0); 9438 } 9439 } 9440 9441 /// Check an Objective-C dictionary literal being converted to the given 9442 /// target type. 9443 static void 9444 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 9445 ObjCDictionaryLiteral *DictionaryLiteral) { 9446 if (!S.NSDictionaryDecl) 9447 return; 9448 9449 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 9450 if (!TargetObjCPtr) 9451 return; 9452 9453 if (TargetObjCPtr->isUnspecialized() || 9454 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 9455 != S.NSDictionaryDecl->getCanonicalDecl()) 9456 return; 9457 9458 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 9459 if (TypeArgs.size() != 2) 9460 return; 9461 9462 QualType TargetKeyType = TypeArgs[0]; 9463 QualType TargetObjectType = TypeArgs[1]; 9464 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 9465 auto Element = DictionaryLiteral->getKeyValueElement(I); 9466 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 9467 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 9468 } 9469 } 9470 9471 // Helper function to filter out cases for constant width constant conversion. 9472 // Don't warn on char array initialization or for non-decimal values. 9473 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 9474 SourceLocation CC) { 9475 // If initializing from a constant, and the constant starts with '0', 9476 // then it is a binary, octal, or hexadecimal. Allow these constants 9477 // to fill all the bits, even if there is a sign change. 9478 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 9479 const char FirstLiteralCharacter = 9480 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0]; 9481 if (FirstLiteralCharacter == '0') 9482 return false; 9483 } 9484 9485 // If the CC location points to a '{', and the type is char, then assume 9486 // assume it is an array initialization. 9487 if (CC.isValid() && T->isCharType()) { 9488 const char FirstContextCharacter = 9489 S.getSourceManager().getCharacterData(CC)[0]; 9490 if (FirstContextCharacter == '{') 9491 return false; 9492 } 9493 9494 return true; 9495 } 9496 9497 static void 9498 CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC, 9499 bool *ICContext = nullptr) { 9500 if (E->isTypeDependent() || E->isValueDependent()) return; 9501 9502 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 9503 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 9504 if (Source == Target) return; 9505 if (Target->isDependentType()) return; 9506 9507 // If the conversion context location is invalid don't complain. We also 9508 // don't want to emit a warning if the issue occurs from the expansion of 9509 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 9510 // delay this check as long as possible. Once we detect we are in that 9511 // scenario, we just return. 9512 if (CC.isInvalid()) 9513 return; 9514 9515 // Diagnose implicit casts to bool. 9516 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 9517 if (isa<StringLiteral>(E)) 9518 // Warn on string literal to bool. Checks for string literals in logical 9519 // and expressions, for instance, assert(0 && "error here"), are 9520 // prevented by a check in AnalyzeImplicitConversions(). 9521 return DiagnoseImpCast(S, E, T, CC, 9522 diag::warn_impcast_string_literal_to_bool); 9523 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 9524 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 9525 // This covers the literal expressions that evaluate to Objective-C 9526 // objects. 9527 return DiagnoseImpCast(S, E, T, CC, 9528 diag::warn_impcast_objective_c_literal_to_bool); 9529 } 9530 if (Source->isPointerType() || Source->canDecayToPointerType()) { 9531 // Warn on pointer to bool conversion that is always true. 9532 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 9533 SourceRange(CC)); 9534 } 9535 } 9536 9537 // Check implicit casts from Objective-C collection literals to specialized 9538 // collection types, e.g., NSArray<NSString *> *. 9539 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 9540 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 9541 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 9542 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 9543 9544 // Strip vector types. 9545 if (isa<VectorType>(Source)) { 9546 if (!isa<VectorType>(Target)) { 9547 if (S.SourceMgr.isInSystemMacro(CC)) 9548 return; 9549 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 9550 } 9551 9552 // If the vector cast is cast between two vectors of the same size, it is 9553 // a bitcast, not a conversion. 9554 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 9555 return; 9556 9557 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 9558 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 9559 } 9560 if (auto VecTy = dyn_cast<VectorType>(Target)) 9561 Target = VecTy->getElementType().getTypePtr(); 9562 9563 // Strip complex types. 9564 if (isa<ComplexType>(Source)) { 9565 if (!isa<ComplexType>(Target)) { 9566 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 9567 return; 9568 9569 return DiagnoseImpCast(S, E, T, CC, 9570 S.getLangOpts().CPlusPlus 9571 ? diag::err_impcast_complex_scalar 9572 : diag::warn_impcast_complex_scalar); 9573 } 9574 9575 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 9576 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 9577 } 9578 9579 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 9580 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 9581 9582 // If the source is floating point... 9583 if (SourceBT && SourceBT->isFloatingPoint()) { 9584 // ...and the target is floating point... 9585 if (TargetBT && TargetBT->isFloatingPoint()) { 9586 // ...then warn if we're dropping FP rank. 9587 9588 // Builtin FP kinds are ordered by increasing FP rank. 9589 if (SourceBT->getKind() > TargetBT->getKind()) { 9590 // Don't warn about float constants that are precisely 9591 // representable in the target type. 9592 Expr::EvalResult result; 9593 if (E->EvaluateAsRValue(result, S.Context)) { 9594 // Value might be a float, a float vector, or a float complex. 9595 if (IsSameFloatAfterCast(result.Val, 9596 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 9597 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 9598 return; 9599 } 9600 9601 if (S.SourceMgr.isInSystemMacro(CC)) 9602 return; 9603 9604 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 9605 } 9606 // ... or possibly if we're increasing rank, too 9607 else if (TargetBT->getKind() > SourceBT->getKind()) { 9608 if (S.SourceMgr.isInSystemMacro(CC)) 9609 return; 9610 9611 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 9612 } 9613 return; 9614 } 9615 9616 // If the target is integral, always warn. 9617 if (TargetBT && TargetBT->isInteger()) { 9618 if (S.SourceMgr.isInSystemMacro(CC)) 9619 return; 9620 9621 DiagnoseFloatingImpCast(S, E, T, CC); 9622 } 9623 9624 // Detect the case where a call result is converted from floating-point to 9625 // to bool, and the final argument to the call is converted from bool, to 9626 // discover this typo: 9627 // 9628 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 9629 // 9630 // FIXME: This is an incredibly special case; is there some more general 9631 // way to detect this class of misplaced-parentheses bug? 9632 if (Target->isBooleanType() && isa<CallExpr>(E)) { 9633 // Check last argument of function call to see if it is an 9634 // implicit cast from a type matching the type the result 9635 // is being cast to. 9636 CallExpr *CEx = cast<CallExpr>(E); 9637 if (unsigned NumArgs = CEx->getNumArgs()) { 9638 Expr *LastA = CEx->getArg(NumArgs - 1); 9639 Expr *InnerE = LastA->IgnoreParenImpCasts(); 9640 if (isa<ImplicitCastExpr>(LastA) && 9641 InnerE->getType()->isBooleanType()) { 9642 // Warn on this floating-point to bool conversion 9643 DiagnoseImpCast(S, E, T, CC, 9644 diag::warn_impcast_floating_point_to_bool); 9645 } 9646 } 9647 } 9648 return; 9649 } 9650 9651 DiagnoseNullConversion(S, E, T, CC); 9652 9653 S.DiscardMisalignedMemberAddress(Target, E); 9654 9655 if (!Source->isIntegerType() || !Target->isIntegerType()) 9656 return; 9657 9658 // TODO: remove this early return once the false positives for constant->bool 9659 // in templates, macros, etc, are reduced or removed. 9660 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 9661 return; 9662 9663 IntRange SourceRange = GetExprRange(S.Context, E); 9664 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 9665 9666 if (SourceRange.Width > TargetRange.Width) { 9667 // If the source is a constant, use a default-on diagnostic. 9668 // TODO: this should happen for bitfield stores, too. 9669 llvm::APSInt Value(32); 9670 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) { 9671 if (S.SourceMgr.isInSystemMacro(CC)) 9672 return; 9673 9674 std::string PrettySourceValue = Value.toString(10); 9675 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 9676 9677 S.DiagRuntimeBehavior(E->getExprLoc(), E, 9678 S.PDiag(diag::warn_impcast_integer_precision_constant) 9679 << PrettySourceValue << PrettyTargetValue 9680 << E->getType() << T << E->getSourceRange() 9681 << clang::SourceRange(CC)); 9682 return; 9683 } 9684 9685 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 9686 if (S.SourceMgr.isInSystemMacro(CC)) 9687 return; 9688 9689 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 9690 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 9691 /* pruneControlFlow */ true); 9692 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 9693 } 9694 9695 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative && 9696 SourceRange.NonNegative && Source->isSignedIntegerType()) { 9697 // Warn when doing a signed to signed conversion, warn if the positive 9698 // source value is exactly the width of the target type, which will 9699 // cause a negative value to be stored. 9700 9701 llvm::APSInt Value; 9702 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) && 9703 !S.SourceMgr.isInSystemMacro(CC)) { 9704 if (isSameWidthConstantConversion(S, E, T, CC)) { 9705 std::string PrettySourceValue = Value.toString(10); 9706 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 9707 9708 S.DiagRuntimeBehavior( 9709 E->getExprLoc(), E, 9710 S.PDiag(diag::warn_impcast_integer_precision_constant) 9711 << PrettySourceValue << PrettyTargetValue << E->getType() << T 9712 << E->getSourceRange() << clang::SourceRange(CC)); 9713 return; 9714 } 9715 } 9716 9717 // Fall through for non-constants to give a sign conversion warning. 9718 } 9719 9720 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 9721 (!TargetRange.NonNegative && SourceRange.NonNegative && 9722 SourceRange.Width == TargetRange.Width)) { 9723 if (S.SourceMgr.isInSystemMacro(CC)) 9724 return; 9725 9726 unsigned DiagID = diag::warn_impcast_integer_sign; 9727 9728 // Traditionally, gcc has warned about this under -Wsign-compare. 9729 // We also want to warn about it in -Wconversion. 9730 // So if -Wconversion is off, use a completely identical diagnostic 9731 // in the sign-compare group. 9732 // The conditional-checking code will 9733 if (ICContext) { 9734 DiagID = diag::warn_impcast_integer_sign_conditional; 9735 *ICContext = true; 9736 } 9737 9738 return DiagnoseImpCast(S, E, T, CC, DiagID); 9739 } 9740 9741 // Diagnose conversions between different enumeration types. 9742 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 9743 // type, to give us better diagnostics. 9744 QualType SourceType = E->getType(); 9745 if (!S.getLangOpts().CPlusPlus) { 9746 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 9747 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 9748 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 9749 SourceType = S.Context.getTypeDeclType(Enum); 9750 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 9751 } 9752 } 9753 9754 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 9755 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 9756 if (SourceEnum->getDecl()->hasNameForLinkage() && 9757 TargetEnum->getDecl()->hasNameForLinkage() && 9758 SourceEnum != TargetEnum) { 9759 if (S.SourceMgr.isInSystemMacro(CC)) 9760 return; 9761 9762 return DiagnoseImpCast(S, E, SourceType, T, CC, 9763 diag::warn_impcast_different_enum_types); 9764 } 9765 } 9766 9767 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 9768 SourceLocation CC, QualType T); 9769 9770 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 9771 SourceLocation CC, bool &ICContext) { 9772 E = E->IgnoreParenImpCasts(); 9773 9774 if (isa<ConditionalOperator>(E)) 9775 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T); 9776 9777 AnalyzeImplicitConversions(S, E, CC); 9778 if (E->getType() != T) 9779 return CheckImplicitConversion(S, E, T, CC, &ICContext); 9780 } 9781 9782 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 9783 SourceLocation CC, QualType T) { 9784 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 9785 9786 bool Suspicious = false; 9787 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 9788 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 9789 9790 // If -Wconversion would have warned about either of the candidates 9791 // for a signedness conversion to the context type... 9792 if (!Suspicious) return; 9793 9794 // ...but it's currently ignored... 9795 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 9796 return; 9797 9798 // ...then check whether it would have warned about either of the 9799 // candidates for a signedness conversion to the condition type. 9800 if (E->getType() == T) return; 9801 9802 Suspicious = false; 9803 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 9804 E->getType(), CC, &Suspicious); 9805 if (!Suspicious) 9806 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 9807 E->getType(), CC, &Suspicious); 9808 } 9809 9810 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 9811 /// Input argument E is a logical expression. 9812 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 9813 if (S.getLangOpts().Bool) 9814 return; 9815 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 9816 } 9817 9818 /// AnalyzeImplicitConversions - Find and report any interesting 9819 /// implicit conversions in the given expression. There are a couple 9820 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 9821 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, 9822 SourceLocation CC) { 9823 QualType T = OrigE->getType(); 9824 Expr *E = OrigE->IgnoreParenImpCasts(); 9825 9826 if (E->isTypeDependent() || E->isValueDependent()) 9827 return; 9828 9829 // For conditional operators, we analyze the arguments as if they 9830 // were being fed directly into the output. 9831 if (isa<ConditionalOperator>(E)) { 9832 ConditionalOperator *CO = cast<ConditionalOperator>(E); 9833 CheckConditionalOperator(S, CO, CC, T); 9834 return; 9835 } 9836 9837 // Check implicit argument conversions for function calls. 9838 if (CallExpr *Call = dyn_cast<CallExpr>(E)) 9839 CheckImplicitArgumentConversions(S, Call, CC); 9840 9841 // Go ahead and check any implicit conversions we might have skipped. 9842 // The non-canonical typecheck is just an optimization; 9843 // CheckImplicitConversion will filter out dead implicit conversions. 9844 if (E->getType() != T) 9845 CheckImplicitConversion(S, E, T, CC); 9846 9847 // Now continue drilling into this expression. 9848 9849 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 9850 // The bound subexpressions in a PseudoObjectExpr are not reachable 9851 // as transitive children. 9852 // FIXME: Use a more uniform representation for this. 9853 for (auto *SE : POE->semantics()) 9854 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 9855 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC); 9856 } 9857 9858 // Skip past explicit casts. 9859 if (isa<ExplicitCastExpr>(E)) { 9860 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts(); 9861 return AnalyzeImplicitConversions(S, E, CC); 9862 } 9863 9864 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 9865 // Do a somewhat different check with comparison operators. 9866 if (BO->isComparisonOp()) 9867 return AnalyzeComparison(S, BO); 9868 9869 // And with simple assignments. 9870 if (BO->getOpcode() == BO_Assign) 9871 return AnalyzeAssignment(S, BO); 9872 } 9873 9874 // These break the otherwise-useful invariant below. Fortunately, 9875 // we don't really need to recurse into them, because any internal 9876 // expressions should have been analyzed already when they were 9877 // built into statements. 9878 if (isa<StmtExpr>(E)) return; 9879 9880 // Don't descend into unevaluated contexts. 9881 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 9882 9883 // Now just recurse over the expression's children. 9884 CC = E->getExprLoc(); 9885 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 9886 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 9887 for (Stmt *SubStmt : E->children()) { 9888 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 9889 if (!ChildExpr) 9890 continue; 9891 9892 if (IsLogicalAndOperator && 9893 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 9894 // Ignore checking string literals that are in logical and operators. 9895 // This is a common pattern for asserts. 9896 continue; 9897 AnalyzeImplicitConversions(S, ChildExpr, CC); 9898 } 9899 9900 if (BO && BO->isLogicalOp()) { 9901 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 9902 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 9903 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 9904 9905 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 9906 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 9907 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 9908 } 9909 9910 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) 9911 if (U->getOpcode() == UO_LNot) 9912 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 9913 } 9914 9915 /// Diagnose integer type and any valid implicit convertion to it. 9916 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 9917 // Taking into account implicit conversions, 9918 // allow any integer. 9919 if (!E->getType()->isIntegerType()) { 9920 S.Diag(E->getLocStart(), 9921 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 9922 return true; 9923 } 9924 // Potentially emit standard warnings for implicit conversions if enabled 9925 // using -Wconversion. 9926 CheckImplicitConversion(S, E, IntT, E->getLocStart()); 9927 return false; 9928 } 9929 9930 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 9931 // Returns true when emitting a warning about taking the address of a reference. 9932 static bool CheckForReference(Sema &SemaRef, const Expr *E, 9933 const PartialDiagnostic &PD) { 9934 E = E->IgnoreParenImpCasts(); 9935 9936 const FunctionDecl *FD = nullptr; 9937 9938 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 9939 if (!DRE->getDecl()->getType()->isReferenceType()) 9940 return false; 9941 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 9942 if (!M->getMemberDecl()->getType()->isReferenceType()) 9943 return false; 9944 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 9945 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 9946 return false; 9947 FD = Call->getDirectCallee(); 9948 } else { 9949 return false; 9950 } 9951 9952 SemaRef.Diag(E->getExprLoc(), PD); 9953 9954 // If possible, point to location of function. 9955 if (FD) { 9956 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 9957 } 9958 9959 return true; 9960 } 9961 9962 // Returns true if the SourceLocation is expanded from any macro body. 9963 // Returns false if the SourceLocation is invalid, is from not in a macro 9964 // expansion, or is from expanded from a top-level macro argument. 9965 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 9966 if (Loc.isInvalid()) 9967 return false; 9968 9969 while (Loc.isMacroID()) { 9970 if (SM.isMacroBodyExpansion(Loc)) 9971 return true; 9972 Loc = SM.getImmediateMacroCallerLoc(Loc); 9973 } 9974 9975 return false; 9976 } 9977 9978 /// \brief Diagnose pointers that are always non-null. 9979 /// \param E the expression containing the pointer 9980 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 9981 /// compared to a null pointer 9982 /// \param IsEqual True when the comparison is equal to a null pointer 9983 /// \param Range Extra SourceRange to highlight in the diagnostic 9984 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 9985 Expr::NullPointerConstantKind NullKind, 9986 bool IsEqual, SourceRange Range) { 9987 if (!E) 9988 return; 9989 9990 // Don't warn inside macros. 9991 if (E->getExprLoc().isMacroID()) { 9992 const SourceManager &SM = getSourceManager(); 9993 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 9994 IsInAnyMacroBody(SM, Range.getBegin())) 9995 return; 9996 } 9997 E = E->IgnoreImpCasts(); 9998 9999 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 10000 10001 if (isa<CXXThisExpr>(E)) { 10002 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 10003 : diag::warn_this_bool_conversion; 10004 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 10005 return; 10006 } 10007 10008 bool IsAddressOf = false; 10009 10010 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 10011 if (UO->getOpcode() != UO_AddrOf) 10012 return; 10013 IsAddressOf = true; 10014 E = UO->getSubExpr(); 10015 } 10016 10017 if (IsAddressOf) { 10018 unsigned DiagID = IsCompare 10019 ? diag::warn_address_of_reference_null_compare 10020 : diag::warn_address_of_reference_bool_conversion; 10021 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 10022 << IsEqual; 10023 if (CheckForReference(*this, E, PD)) { 10024 return; 10025 } 10026 } 10027 10028 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 10029 bool IsParam = isa<NonNullAttr>(NonnullAttr); 10030 std::string Str; 10031 llvm::raw_string_ostream S(Str); 10032 E->printPretty(S, nullptr, getPrintingPolicy()); 10033 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 10034 : diag::warn_cast_nonnull_to_bool; 10035 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 10036 << E->getSourceRange() << Range << IsEqual; 10037 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 10038 }; 10039 10040 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 10041 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 10042 if (auto *Callee = Call->getDirectCallee()) { 10043 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 10044 ComplainAboutNonnullParamOrCall(A); 10045 return; 10046 } 10047 } 10048 } 10049 10050 // Expect to find a single Decl. Skip anything more complicated. 10051 ValueDecl *D = nullptr; 10052 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 10053 D = R->getDecl(); 10054 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 10055 D = M->getMemberDecl(); 10056 } 10057 10058 // Weak Decls can be null. 10059 if (!D || D->isWeak()) 10060 return; 10061 10062 // Check for parameter decl with nonnull attribute 10063 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 10064 if (getCurFunction() && 10065 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 10066 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 10067 ComplainAboutNonnullParamOrCall(A); 10068 return; 10069 } 10070 10071 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 10072 auto ParamIter = llvm::find(FD->parameters(), PV); 10073 assert(ParamIter != FD->param_end()); 10074 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 10075 10076 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 10077 if (!NonNull->args_size()) { 10078 ComplainAboutNonnullParamOrCall(NonNull); 10079 return; 10080 } 10081 10082 for (unsigned ArgNo : NonNull->args()) { 10083 if (ArgNo == ParamNo) { 10084 ComplainAboutNonnullParamOrCall(NonNull); 10085 return; 10086 } 10087 } 10088 } 10089 } 10090 } 10091 } 10092 10093 QualType T = D->getType(); 10094 const bool IsArray = T->isArrayType(); 10095 const bool IsFunction = T->isFunctionType(); 10096 10097 // Address of function is used to silence the function warning. 10098 if (IsAddressOf && IsFunction) { 10099 return; 10100 } 10101 10102 // Found nothing. 10103 if (!IsAddressOf && !IsFunction && !IsArray) 10104 return; 10105 10106 // Pretty print the expression for the diagnostic. 10107 std::string Str; 10108 llvm::raw_string_ostream S(Str); 10109 E->printPretty(S, nullptr, getPrintingPolicy()); 10110 10111 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 10112 : diag::warn_impcast_pointer_to_bool; 10113 enum { 10114 AddressOf, 10115 FunctionPointer, 10116 ArrayPointer 10117 } DiagType; 10118 if (IsAddressOf) 10119 DiagType = AddressOf; 10120 else if (IsFunction) 10121 DiagType = FunctionPointer; 10122 else if (IsArray) 10123 DiagType = ArrayPointer; 10124 else 10125 llvm_unreachable("Could not determine diagnostic."); 10126 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 10127 << Range << IsEqual; 10128 10129 if (!IsFunction) 10130 return; 10131 10132 // Suggest '&' to silence the function warning. 10133 Diag(E->getExprLoc(), diag::note_function_warning_silence) 10134 << FixItHint::CreateInsertion(E->getLocStart(), "&"); 10135 10136 // Check to see if '()' fixit should be emitted. 10137 QualType ReturnType; 10138 UnresolvedSet<4> NonTemplateOverloads; 10139 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 10140 if (ReturnType.isNull()) 10141 return; 10142 10143 if (IsCompare) { 10144 // There are two cases here. If there is null constant, the only suggest 10145 // for a pointer return type. If the null is 0, then suggest if the return 10146 // type is a pointer or an integer type. 10147 if (!ReturnType->isPointerType()) { 10148 if (NullKind == Expr::NPCK_ZeroExpression || 10149 NullKind == Expr::NPCK_ZeroLiteral) { 10150 if (!ReturnType->isIntegerType()) 10151 return; 10152 } else { 10153 return; 10154 } 10155 } 10156 } else { // !IsCompare 10157 // For function to bool, only suggest if the function pointer has bool 10158 // return type. 10159 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 10160 return; 10161 } 10162 Diag(E->getExprLoc(), diag::note_function_to_function_call) 10163 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()"); 10164 } 10165 10166 /// Diagnoses "dangerous" implicit conversions within the given 10167 /// expression (which is a full expression). Implements -Wconversion 10168 /// and -Wsign-compare. 10169 /// 10170 /// \param CC the "context" location of the implicit conversion, i.e. 10171 /// the most location of the syntactic entity requiring the implicit 10172 /// conversion 10173 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 10174 // Don't diagnose in unevaluated contexts. 10175 if (isUnevaluatedContext()) 10176 return; 10177 10178 // Don't diagnose for value- or type-dependent expressions. 10179 if (E->isTypeDependent() || E->isValueDependent()) 10180 return; 10181 10182 // Check for array bounds violations in cases where the check isn't triggered 10183 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 10184 // ArraySubscriptExpr is on the RHS of a variable initialization. 10185 CheckArrayAccess(E); 10186 10187 // This is not the right CC for (e.g.) a variable initialization. 10188 AnalyzeImplicitConversions(*this, E, CC); 10189 } 10190 10191 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 10192 /// Input argument E is a logical expression. 10193 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 10194 ::CheckBoolLikeConversion(*this, E, CC); 10195 } 10196 10197 /// Diagnose when expression is an integer constant expression and its evaluation 10198 /// results in integer overflow 10199 void Sema::CheckForIntOverflow (Expr *E) { 10200 // Use a work list to deal with nested struct initializers. 10201 SmallVector<Expr *, 2> Exprs(1, E); 10202 10203 do { 10204 Expr *E = Exprs.pop_back_val(); 10205 10206 if (isa<BinaryOperator>(E->IgnoreParenCasts())) { 10207 E->IgnoreParenCasts()->EvaluateForOverflow(Context); 10208 continue; 10209 } 10210 10211 if (auto InitList = dyn_cast<InitListExpr>(E)) 10212 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 10213 10214 if (isa<ObjCBoxedExpr>(E)) 10215 E->IgnoreParenCasts()->EvaluateForOverflow(Context); 10216 } while (!Exprs.empty()); 10217 } 10218 10219 namespace { 10220 10221 /// \brief Visitor for expressions which looks for unsequenced operations on the 10222 /// same object. 10223 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> { 10224 using Base = EvaluatedExprVisitor<SequenceChecker>; 10225 10226 /// \brief A tree of sequenced regions within an expression. Two regions are 10227 /// unsequenced if one is an ancestor or a descendent of the other. When we 10228 /// finish processing an expression with sequencing, such as a comma 10229 /// expression, we fold its tree nodes into its parent, since they are 10230 /// unsequenced with respect to nodes we will visit later. 10231 class SequenceTree { 10232 struct Value { 10233 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 10234 unsigned Parent : 31; 10235 unsigned Merged : 1; 10236 }; 10237 SmallVector<Value, 8> Values; 10238 10239 public: 10240 /// \brief A region within an expression which may be sequenced with respect 10241 /// to some other region. 10242 class Seq { 10243 friend class SequenceTree; 10244 10245 unsigned Index = 0; 10246 10247 explicit Seq(unsigned N) : Index(N) {} 10248 10249 public: 10250 Seq() = default; 10251 }; 10252 10253 SequenceTree() { Values.push_back(Value(0)); } 10254 Seq root() const { return Seq(0); } 10255 10256 /// \brief Create a new sequence of operations, which is an unsequenced 10257 /// subset of \p Parent. This sequence of operations is sequenced with 10258 /// respect to other children of \p Parent. 10259 Seq allocate(Seq Parent) { 10260 Values.push_back(Value(Parent.Index)); 10261 return Seq(Values.size() - 1); 10262 } 10263 10264 /// \brief Merge a sequence of operations into its parent. 10265 void merge(Seq S) { 10266 Values[S.Index].Merged = true; 10267 } 10268 10269 /// \brief Determine whether two operations are unsequenced. This operation 10270 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 10271 /// should have been merged into its parent as appropriate. 10272 bool isUnsequenced(Seq Cur, Seq Old) { 10273 unsigned C = representative(Cur.Index); 10274 unsigned Target = representative(Old.Index); 10275 while (C >= Target) { 10276 if (C == Target) 10277 return true; 10278 C = Values[C].Parent; 10279 } 10280 return false; 10281 } 10282 10283 private: 10284 /// \brief Pick a representative for a sequence. 10285 unsigned representative(unsigned K) { 10286 if (Values[K].Merged) 10287 // Perform path compression as we go. 10288 return Values[K].Parent = representative(Values[K].Parent); 10289 return K; 10290 } 10291 }; 10292 10293 /// An object for which we can track unsequenced uses. 10294 using Object = NamedDecl *; 10295 10296 /// Different flavors of object usage which we track. We only track the 10297 /// least-sequenced usage of each kind. 10298 enum UsageKind { 10299 /// A read of an object. Multiple unsequenced reads are OK. 10300 UK_Use, 10301 10302 /// A modification of an object which is sequenced before the value 10303 /// computation of the expression, such as ++n in C++. 10304 UK_ModAsValue, 10305 10306 /// A modification of an object which is not sequenced before the value 10307 /// computation of the expression, such as n++. 10308 UK_ModAsSideEffect, 10309 10310 UK_Count = UK_ModAsSideEffect + 1 10311 }; 10312 10313 struct Usage { 10314 Expr *Use = nullptr; 10315 SequenceTree::Seq Seq; 10316 10317 Usage() = default; 10318 }; 10319 10320 struct UsageInfo { 10321 Usage Uses[UK_Count]; 10322 10323 /// Have we issued a diagnostic for this variable already? 10324 bool Diagnosed = false; 10325 10326 UsageInfo() = default; 10327 }; 10328 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 10329 10330 Sema &SemaRef; 10331 10332 /// Sequenced regions within the expression. 10333 SequenceTree Tree; 10334 10335 /// Declaration modifications and references which we have seen. 10336 UsageInfoMap UsageMap; 10337 10338 /// The region we are currently within. 10339 SequenceTree::Seq Region; 10340 10341 /// Filled in with declarations which were modified as a side-effect 10342 /// (that is, post-increment operations). 10343 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 10344 10345 /// Expressions to check later. We defer checking these to reduce 10346 /// stack usage. 10347 SmallVectorImpl<Expr *> &WorkList; 10348 10349 /// RAII object wrapping the visitation of a sequenced subexpression of an 10350 /// expression. At the end of this process, the side-effects of the evaluation 10351 /// become sequenced with respect to the value computation of the result, so 10352 /// we downgrade any UK_ModAsSideEffect within the evaluation to 10353 /// UK_ModAsValue. 10354 struct SequencedSubexpression { 10355 SequencedSubexpression(SequenceChecker &Self) 10356 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 10357 Self.ModAsSideEffect = &ModAsSideEffect; 10358 } 10359 10360 ~SequencedSubexpression() { 10361 for (auto &M : llvm::reverse(ModAsSideEffect)) { 10362 UsageInfo &U = Self.UsageMap[M.first]; 10363 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect]; 10364 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue); 10365 SideEffectUsage = M.second; 10366 } 10367 Self.ModAsSideEffect = OldModAsSideEffect; 10368 } 10369 10370 SequenceChecker &Self; 10371 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 10372 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 10373 }; 10374 10375 /// RAII object wrapping the visitation of a subexpression which we might 10376 /// choose to evaluate as a constant. If any subexpression is evaluated and 10377 /// found to be non-constant, this allows us to suppress the evaluation of 10378 /// the outer expression. 10379 class EvaluationTracker { 10380 public: 10381 EvaluationTracker(SequenceChecker &Self) 10382 : Self(Self), Prev(Self.EvalTracker) { 10383 Self.EvalTracker = this; 10384 } 10385 10386 ~EvaluationTracker() { 10387 Self.EvalTracker = Prev; 10388 if (Prev) 10389 Prev->EvalOK &= EvalOK; 10390 } 10391 10392 bool evaluate(const Expr *E, bool &Result) { 10393 if (!EvalOK || E->isValueDependent()) 10394 return false; 10395 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context); 10396 return EvalOK; 10397 } 10398 10399 private: 10400 SequenceChecker &Self; 10401 EvaluationTracker *Prev; 10402 bool EvalOK = true; 10403 } *EvalTracker = nullptr; 10404 10405 /// \brief Find the object which is produced by the specified expression, 10406 /// if any. 10407 Object getObject(Expr *E, bool Mod) const { 10408 E = E->IgnoreParenCasts(); 10409 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 10410 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 10411 return getObject(UO->getSubExpr(), Mod); 10412 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 10413 if (BO->getOpcode() == BO_Comma) 10414 return getObject(BO->getRHS(), Mod); 10415 if (Mod && BO->isAssignmentOp()) 10416 return getObject(BO->getLHS(), Mod); 10417 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 10418 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 10419 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 10420 return ME->getMemberDecl(); 10421 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 10422 // FIXME: If this is a reference, map through to its value. 10423 return DRE->getDecl(); 10424 return nullptr; 10425 } 10426 10427 /// \brief Note that an object was modified or used by an expression. 10428 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) { 10429 Usage &U = UI.Uses[UK]; 10430 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) { 10431 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 10432 ModAsSideEffect->push_back(std::make_pair(O, U)); 10433 U.Use = Ref; 10434 U.Seq = Region; 10435 } 10436 } 10437 10438 /// \brief Check whether a modification or use conflicts with a prior usage. 10439 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind, 10440 bool IsModMod) { 10441 if (UI.Diagnosed) 10442 return; 10443 10444 const Usage &U = UI.Uses[OtherKind]; 10445 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) 10446 return; 10447 10448 Expr *Mod = U.Use; 10449 Expr *ModOrUse = Ref; 10450 if (OtherKind == UK_Use) 10451 std::swap(Mod, ModOrUse); 10452 10453 SemaRef.Diag(Mod->getExprLoc(), 10454 IsModMod ? diag::warn_unsequenced_mod_mod 10455 : diag::warn_unsequenced_mod_use) 10456 << O << SourceRange(ModOrUse->getExprLoc()); 10457 UI.Diagnosed = true; 10458 } 10459 10460 void notePreUse(Object O, Expr *Use) { 10461 UsageInfo &U = UsageMap[O]; 10462 // Uses conflict with other modifications. 10463 checkUsage(O, U, Use, UK_ModAsValue, false); 10464 } 10465 10466 void notePostUse(Object O, Expr *Use) { 10467 UsageInfo &U = UsageMap[O]; 10468 checkUsage(O, U, Use, UK_ModAsSideEffect, false); 10469 addUsage(U, O, Use, UK_Use); 10470 } 10471 10472 void notePreMod(Object O, Expr *Mod) { 10473 UsageInfo &U = UsageMap[O]; 10474 // Modifications conflict with other modifications and with uses. 10475 checkUsage(O, U, Mod, UK_ModAsValue, true); 10476 checkUsage(O, U, Mod, UK_Use, false); 10477 } 10478 10479 void notePostMod(Object O, Expr *Use, UsageKind UK) { 10480 UsageInfo &U = UsageMap[O]; 10481 checkUsage(O, U, Use, UK_ModAsSideEffect, true); 10482 addUsage(U, O, Use, UK); 10483 } 10484 10485 public: 10486 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList) 10487 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 10488 Visit(E); 10489 } 10490 10491 void VisitStmt(Stmt *S) { 10492 // Skip all statements which aren't expressions for now. 10493 } 10494 10495 void VisitExpr(Expr *E) { 10496 // By default, just recurse to evaluated subexpressions. 10497 Base::VisitStmt(E); 10498 } 10499 10500 void VisitCastExpr(CastExpr *E) { 10501 Object O = Object(); 10502 if (E->getCastKind() == CK_LValueToRValue) 10503 O = getObject(E->getSubExpr(), false); 10504 10505 if (O) 10506 notePreUse(O, E); 10507 VisitExpr(E); 10508 if (O) 10509 notePostUse(O, E); 10510 } 10511 10512 void VisitBinComma(BinaryOperator *BO) { 10513 // C++11 [expr.comma]p1: 10514 // Every value computation and side effect associated with the left 10515 // expression is sequenced before every value computation and side 10516 // effect associated with the right expression. 10517 SequenceTree::Seq LHS = Tree.allocate(Region); 10518 SequenceTree::Seq RHS = Tree.allocate(Region); 10519 SequenceTree::Seq OldRegion = Region; 10520 10521 { 10522 SequencedSubexpression SeqLHS(*this); 10523 Region = LHS; 10524 Visit(BO->getLHS()); 10525 } 10526 10527 Region = RHS; 10528 Visit(BO->getRHS()); 10529 10530 Region = OldRegion; 10531 10532 // Forget that LHS and RHS are sequenced. They are both unsequenced 10533 // with respect to other stuff. 10534 Tree.merge(LHS); 10535 Tree.merge(RHS); 10536 } 10537 10538 void VisitBinAssign(BinaryOperator *BO) { 10539 // The modification is sequenced after the value computation of the LHS 10540 // and RHS, so check it before inspecting the operands and update the 10541 // map afterwards. 10542 Object O = getObject(BO->getLHS(), true); 10543 if (!O) 10544 return VisitExpr(BO); 10545 10546 notePreMod(O, BO); 10547 10548 // C++11 [expr.ass]p7: 10549 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated 10550 // only once. 10551 // 10552 // Therefore, for a compound assignment operator, O is considered used 10553 // everywhere except within the evaluation of E1 itself. 10554 if (isa<CompoundAssignOperator>(BO)) 10555 notePreUse(O, BO); 10556 10557 Visit(BO->getLHS()); 10558 10559 if (isa<CompoundAssignOperator>(BO)) 10560 notePostUse(O, BO); 10561 10562 Visit(BO->getRHS()); 10563 10564 // C++11 [expr.ass]p1: 10565 // the assignment is sequenced [...] before the value computation of the 10566 // assignment expression. 10567 // C11 6.5.16/3 has no such rule. 10568 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 10569 : UK_ModAsSideEffect); 10570 } 10571 10572 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) { 10573 VisitBinAssign(CAO); 10574 } 10575 10576 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 10577 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 10578 void VisitUnaryPreIncDec(UnaryOperator *UO) { 10579 Object O = getObject(UO->getSubExpr(), true); 10580 if (!O) 10581 return VisitExpr(UO); 10582 10583 notePreMod(O, UO); 10584 Visit(UO->getSubExpr()); 10585 // C++11 [expr.pre.incr]p1: 10586 // the expression ++x is equivalent to x+=1 10587 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 10588 : UK_ModAsSideEffect); 10589 } 10590 10591 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 10592 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 10593 void VisitUnaryPostIncDec(UnaryOperator *UO) { 10594 Object O = getObject(UO->getSubExpr(), true); 10595 if (!O) 10596 return VisitExpr(UO); 10597 10598 notePreMod(O, UO); 10599 Visit(UO->getSubExpr()); 10600 notePostMod(O, UO, UK_ModAsSideEffect); 10601 } 10602 10603 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated. 10604 void VisitBinLOr(BinaryOperator *BO) { 10605 // The side-effects of the LHS of an '&&' are sequenced before the 10606 // value computation of the RHS, and hence before the value computation 10607 // of the '&&' itself, unless the LHS evaluates to zero. We treat them 10608 // as if they were unconditionally sequenced. 10609 EvaluationTracker Eval(*this); 10610 { 10611 SequencedSubexpression Sequenced(*this); 10612 Visit(BO->getLHS()); 10613 } 10614 10615 bool Result; 10616 if (Eval.evaluate(BO->getLHS(), Result)) { 10617 if (!Result) 10618 Visit(BO->getRHS()); 10619 } else { 10620 // Check for unsequenced operations in the RHS, treating it as an 10621 // entirely separate evaluation. 10622 // 10623 // FIXME: If there are operations in the RHS which are unsequenced 10624 // with respect to operations outside the RHS, and those operations 10625 // are unconditionally evaluated, diagnose them. 10626 WorkList.push_back(BO->getRHS()); 10627 } 10628 } 10629 void VisitBinLAnd(BinaryOperator *BO) { 10630 EvaluationTracker Eval(*this); 10631 { 10632 SequencedSubexpression Sequenced(*this); 10633 Visit(BO->getLHS()); 10634 } 10635 10636 bool Result; 10637 if (Eval.evaluate(BO->getLHS(), Result)) { 10638 if (Result) 10639 Visit(BO->getRHS()); 10640 } else { 10641 WorkList.push_back(BO->getRHS()); 10642 } 10643 } 10644 10645 // Only visit the condition, unless we can be sure which subexpression will 10646 // be chosen. 10647 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) { 10648 EvaluationTracker Eval(*this); 10649 { 10650 SequencedSubexpression Sequenced(*this); 10651 Visit(CO->getCond()); 10652 } 10653 10654 bool Result; 10655 if (Eval.evaluate(CO->getCond(), Result)) 10656 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr()); 10657 else { 10658 WorkList.push_back(CO->getTrueExpr()); 10659 WorkList.push_back(CO->getFalseExpr()); 10660 } 10661 } 10662 10663 void VisitCallExpr(CallExpr *CE) { 10664 // C++11 [intro.execution]p15: 10665 // When calling a function [...], every value computation and side effect 10666 // associated with any argument expression, or with the postfix expression 10667 // designating the called function, is sequenced before execution of every 10668 // expression or statement in the body of the function [and thus before 10669 // the value computation of its result]. 10670 SequencedSubexpression Sequenced(*this); 10671 Base::VisitCallExpr(CE); 10672 10673 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 10674 } 10675 10676 void VisitCXXConstructExpr(CXXConstructExpr *CCE) { 10677 // This is a call, so all subexpressions are sequenced before the result. 10678 SequencedSubexpression Sequenced(*this); 10679 10680 if (!CCE->isListInitialization()) 10681 return VisitExpr(CCE); 10682 10683 // In C++11, list initializations are sequenced. 10684 SmallVector<SequenceTree::Seq, 32> Elts; 10685 SequenceTree::Seq Parent = Region; 10686 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(), 10687 E = CCE->arg_end(); 10688 I != E; ++I) { 10689 Region = Tree.allocate(Parent); 10690 Elts.push_back(Region); 10691 Visit(*I); 10692 } 10693 10694 // Forget that the initializers are sequenced. 10695 Region = Parent; 10696 for (unsigned I = 0; I < Elts.size(); ++I) 10697 Tree.merge(Elts[I]); 10698 } 10699 10700 void VisitInitListExpr(InitListExpr *ILE) { 10701 if (!SemaRef.getLangOpts().CPlusPlus11) 10702 return VisitExpr(ILE); 10703 10704 // In C++11, list initializations are sequenced. 10705 SmallVector<SequenceTree::Seq, 32> Elts; 10706 SequenceTree::Seq Parent = Region; 10707 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 10708 Expr *E = ILE->getInit(I); 10709 if (!E) continue; 10710 Region = Tree.allocate(Parent); 10711 Elts.push_back(Region); 10712 Visit(E); 10713 } 10714 10715 // Forget that the initializers are sequenced. 10716 Region = Parent; 10717 for (unsigned I = 0; I < Elts.size(); ++I) 10718 Tree.merge(Elts[I]); 10719 } 10720 }; 10721 10722 } // namespace 10723 10724 void Sema::CheckUnsequencedOperations(Expr *E) { 10725 SmallVector<Expr *, 8> WorkList; 10726 WorkList.push_back(E); 10727 while (!WorkList.empty()) { 10728 Expr *Item = WorkList.pop_back_val(); 10729 SequenceChecker(*this, Item, WorkList); 10730 } 10731 } 10732 10733 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 10734 bool IsConstexpr) { 10735 CheckImplicitConversions(E, CheckLoc); 10736 if (!E->isInstantiationDependent()) 10737 CheckUnsequencedOperations(E); 10738 if (!IsConstexpr && !E->isValueDependent()) 10739 CheckForIntOverflow(E); 10740 DiagnoseMisalignedMembers(); 10741 } 10742 10743 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 10744 FieldDecl *BitField, 10745 Expr *Init) { 10746 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 10747 } 10748 10749 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 10750 SourceLocation Loc) { 10751 if (!PType->isVariablyModifiedType()) 10752 return; 10753 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 10754 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 10755 return; 10756 } 10757 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 10758 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 10759 return; 10760 } 10761 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 10762 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 10763 return; 10764 } 10765 10766 const ArrayType *AT = S.Context.getAsArrayType(PType); 10767 if (!AT) 10768 return; 10769 10770 if (AT->getSizeModifier() != ArrayType::Star) { 10771 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 10772 return; 10773 } 10774 10775 S.Diag(Loc, diag::err_array_star_in_function_definition); 10776 } 10777 10778 /// CheckParmsForFunctionDef - Check that the parameters of the given 10779 /// function are appropriate for the definition of a function. This 10780 /// takes care of any checks that cannot be performed on the 10781 /// declaration itself, e.g., that the types of each of the function 10782 /// parameters are complete. 10783 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 10784 bool CheckParameterNames) { 10785 bool HasInvalidParm = false; 10786 for (ParmVarDecl *Param : Parameters) { 10787 // C99 6.7.5.3p4: the parameters in a parameter type list in a 10788 // function declarator that is part of a function definition of 10789 // that function shall not have incomplete type. 10790 // 10791 // This is also C++ [dcl.fct]p6. 10792 if (!Param->isInvalidDecl() && 10793 RequireCompleteType(Param->getLocation(), Param->getType(), 10794 diag::err_typecheck_decl_incomplete_type)) { 10795 Param->setInvalidDecl(); 10796 HasInvalidParm = true; 10797 } 10798 10799 // C99 6.9.1p5: If the declarator includes a parameter type list, the 10800 // declaration of each parameter shall include an identifier. 10801 if (CheckParameterNames && 10802 Param->getIdentifier() == nullptr && 10803 !Param->isImplicit() && 10804 !getLangOpts().CPlusPlus) 10805 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 10806 10807 // C99 6.7.5.3p12: 10808 // If the function declarator is not part of a definition of that 10809 // function, parameters may have incomplete type and may use the [*] 10810 // notation in their sequences of declarator specifiers to specify 10811 // variable length array types. 10812 QualType PType = Param->getOriginalType(); 10813 // FIXME: This diagnostic should point the '[*]' if source-location 10814 // information is added for it. 10815 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 10816 10817 // MSVC destroys objects passed by value in the callee. Therefore a 10818 // function definition which takes such a parameter must be able to call the 10819 // object's destructor. However, we don't perform any direct access check 10820 // on the dtor. 10821 if (getLangOpts().CPlusPlus && Context.getTargetInfo() 10822 .getCXXABI() 10823 .areArgsDestroyedLeftToRightInCallee()) { 10824 if (!Param->isInvalidDecl()) { 10825 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) { 10826 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 10827 if (!ClassDecl->isInvalidDecl() && 10828 !ClassDecl->hasIrrelevantDestructor() && 10829 !ClassDecl->isDependentContext()) { 10830 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 10831 MarkFunctionReferenced(Param->getLocation(), Destructor); 10832 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 10833 } 10834 } 10835 } 10836 } 10837 10838 // Parameters with the pass_object_size attribute only need to be marked 10839 // constant at function definitions. Because we lack information about 10840 // whether we're on a declaration or definition when we're instantiating the 10841 // attribute, we need to check for constness here. 10842 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 10843 if (!Param->getType().isConstQualified()) 10844 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 10845 << Attr->getSpelling() << 1; 10846 } 10847 10848 return HasInvalidParm; 10849 } 10850 10851 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr 10852 /// or MemberExpr. 10853 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign, 10854 ASTContext &Context) { 10855 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 10856 return Context.getDeclAlign(DRE->getDecl()); 10857 10858 if (const auto *ME = dyn_cast<MemberExpr>(E)) 10859 return Context.getDeclAlign(ME->getMemberDecl()); 10860 10861 return TypeAlign; 10862 } 10863 10864 /// CheckCastAlign - Implements -Wcast-align, which warns when a 10865 /// pointer cast increases the alignment requirements. 10866 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 10867 // This is actually a lot of work to potentially be doing on every 10868 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 10869 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 10870 return; 10871 10872 // Ignore dependent types. 10873 if (T->isDependentType() || Op->getType()->isDependentType()) 10874 return; 10875 10876 // Require that the destination be a pointer type. 10877 const PointerType *DestPtr = T->getAs<PointerType>(); 10878 if (!DestPtr) return; 10879 10880 // If the destination has alignment 1, we're done. 10881 QualType DestPointee = DestPtr->getPointeeType(); 10882 if (DestPointee->isIncompleteType()) return; 10883 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 10884 if (DestAlign.isOne()) return; 10885 10886 // Require that the source be a pointer type. 10887 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 10888 if (!SrcPtr) return; 10889 QualType SrcPointee = SrcPtr->getPointeeType(); 10890 10891 // Whitelist casts from cv void*. We already implicitly 10892 // whitelisted casts to cv void*, since they have alignment 1. 10893 // Also whitelist casts involving incomplete types, which implicitly 10894 // includes 'void'. 10895 if (SrcPointee->isIncompleteType()) return; 10896 10897 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee); 10898 10899 if (auto *CE = dyn_cast<CastExpr>(Op)) { 10900 if (CE->getCastKind() == CK_ArrayToPointerDecay) 10901 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context); 10902 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) { 10903 if (UO->getOpcode() == UO_AddrOf) 10904 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context); 10905 } 10906 10907 if (SrcAlign >= DestAlign) return; 10908 10909 Diag(TRange.getBegin(), diag::warn_cast_align) 10910 << Op->getType() << T 10911 << static_cast<unsigned>(SrcAlign.getQuantity()) 10912 << static_cast<unsigned>(DestAlign.getQuantity()) 10913 << TRange << Op->getSourceRange(); 10914 } 10915 10916 /// \brief Check whether this array fits the idiom of a size-one tail padded 10917 /// array member of a struct. 10918 /// 10919 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 10920 /// commonly used to emulate flexible arrays in C89 code. 10921 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 10922 const NamedDecl *ND) { 10923 if (Size != 1 || !ND) return false; 10924 10925 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 10926 if (!FD) return false; 10927 10928 // Don't consider sizes resulting from macro expansions or template argument 10929 // substitution to form C89 tail-padded arrays. 10930 10931 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 10932 while (TInfo) { 10933 TypeLoc TL = TInfo->getTypeLoc(); 10934 // Look through typedefs. 10935 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 10936 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 10937 TInfo = TDL->getTypeSourceInfo(); 10938 continue; 10939 } 10940 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 10941 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 10942 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 10943 return false; 10944 } 10945 break; 10946 } 10947 10948 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 10949 if (!RD) return false; 10950 if (RD->isUnion()) return false; 10951 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 10952 if (!CRD->isStandardLayout()) return false; 10953 } 10954 10955 // See if this is the last field decl in the record. 10956 const Decl *D = FD; 10957 while ((D = D->getNextDeclInContext())) 10958 if (isa<FieldDecl>(D)) 10959 return false; 10960 return true; 10961 } 10962 10963 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 10964 const ArraySubscriptExpr *ASE, 10965 bool AllowOnePastEnd, bool IndexNegated) { 10966 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 10967 if (IndexExpr->isValueDependent()) 10968 return; 10969 10970 const Type *EffectiveType = 10971 BaseExpr->getType()->getPointeeOrArrayElementType(); 10972 BaseExpr = BaseExpr->IgnoreParenCasts(); 10973 const ConstantArrayType *ArrayTy = 10974 Context.getAsConstantArrayType(BaseExpr->getType()); 10975 if (!ArrayTy) 10976 return; 10977 10978 llvm::APSInt index; 10979 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects)) 10980 return; 10981 if (IndexNegated) 10982 index = -index; 10983 10984 const NamedDecl *ND = nullptr; 10985 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 10986 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 10987 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 10988 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 10989 10990 if (index.isUnsigned() || !index.isNegative()) { 10991 llvm::APInt size = ArrayTy->getSize(); 10992 if (!size.isStrictlyPositive()) 10993 return; 10994 10995 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType(); 10996 if (BaseType != EffectiveType) { 10997 // Make sure we're comparing apples to apples when comparing index to size 10998 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 10999 uint64_t array_typesize = Context.getTypeSize(BaseType); 11000 // Handle ptrarith_typesize being zero, such as when casting to void* 11001 if (!ptrarith_typesize) ptrarith_typesize = 1; 11002 if (ptrarith_typesize != array_typesize) { 11003 // There's a cast to a different size type involved 11004 uint64_t ratio = array_typesize / ptrarith_typesize; 11005 // TODO: Be smarter about handling cases where array_typesize is not a 11006 // multiple of ptrarith_typesize 11007 if (ptrarith_typesize * ratio == array_typesize) 11008 size *= llvm::APInt(size.getBitWidth(), ratio); 11009 } 11010 } 11011 11012 if (size.getBitWidth() > index.getBitWidth()) 11013 index = index.zext(size.getBitWidth()); 11014 else if (size.getBitWidth() < index.getBitWidth()) 11015 size = size.zext(index.getBitWidth()); 11016 11017 // For array subscripting the index must be less than size, but for pointer 11018 // arithmetic also allow the index (offset) to be equal to size since 11019 // computing the next address after the end of the array is legal and 11020 // commonly done e.g. in C++ iterators and range-based for loops. 11021 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 11022 return; 11023 11024 // Also don't warn for arrays of size 1 which are members of some 11025 // structure. These are often used to approximate flexible arrays in C89 11026 // code. 11027 if (IsTailPaddedMemberArray(*this, size, ND)) 11028 return; 11029 11030 // Suppress the warning if the subscript expression (as identified by the 11031 // ']' location) and the index expression are both from macro expansions 11032 // within a system header. 11033 if (ASE) { 11034 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 11035 ASE->getRBracketLoc()); 11036 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 11037 SourceLocation IndexLoc = SourceMgr.getSpellingLoc( 11038 IndexExpr->getLocStart()); 11039 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 11040 return; 11041 } 11042 } 11043 11044 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 11045 if (ASE) 11046 DiagID = diag::warn_array_index_exceeds_bounds; 11047 11048 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 11049 PDiag(DiagID) << index.toString(10, true) 11050 << size.toString(10, true) 11051 << (unsigned)size.getLimitedValue(~0U) 11052 << IndexExpr->getSourceRange()); 11053 } else { 11054 unsigned DiagID = diag::warn_array_index_precedes_bounds; 11055 if (!ASE) { 11056 DiagID = diag::warn_ptr_arith_precedes_bounds; 11057 if (index.isNegative()) index = -index; 11058 } 11059 11060 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 11061 PDiag(DiagID) << index.toString(10, true) 11062 << IndexExpr->getSourceRange()); 11063 } 11064 11065 if (!ND) { 11066 // Try harder to find a NamedDecl to point at in the note. 11067 while (const ArraySubscriptExpr *ASE = 11068 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 11069 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 11070 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 11071 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 11072 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 11073 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 11074 } 11075 11076 if (ND) 11077 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr, 11078 PDiag(diag::note_array_index_out_of_bounds) 11079 << ND->getDeclName()); 11080 } 11081 11082 void Sema::CheckArrayAccess(const Expr *expr) { 11083 int AllowOnePastEnd = 0; 11084 while (expr) { 11085 expr = expr->IgnoreParenImpCasts(); 11086 switch (expr->getStmtClass()) { 11087 case Stmt::ArraySubscriptExprClass: { 11088 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 11089 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 11090 AllowOnePastEnd > 0); 11091 return; 11092 } 11093 case Stmt::OMPArraySectionExprClass: { 11094 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 11095 if (ASE->getLowerBound()) 11096 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 11097 /*ASE=*/nullptr, AllowOnePastEnd > 0); 11098 return; 11099 } 11100 case Stmt::UnaryOperatorClass: { 11101 // Only unwrap the * and & unary operators 11102 const UnaryOperator *UO = cast<UnaryOperator>(expr); 11103 expr = UO->getSubExpr(); 11104 switch (UO->getOpcode()) { 11105 case UO_AddrOf: 11106 AllowOnePastEnd++; 11107 break; 11108 case UO_Deref: 11109 AllowOnePastEnd--; 11110 break; 11111 default: 11112 return; 11113 } 11114 break; 11115 } 11116 case Stmt::ConditionalOperatorClass: { 11117 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 11118 if (const Expr *lhs = cond->getLHS()) 11119 CheckArrayAccess(lhs); 11120 if (const Expr *rhs = cond->getRHS()) 11121 CheckArrayAccess(rhs); 11122 return; 11123 } 11124 case Stmt::CXXOperatorCallExprClass: { 11125 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 11126 for (const auto *Arg : OCE->arguments()) 11127 CheckArrayAccess(Arg); 11128 return; 11129 } 11130 default: 11131 return; 11132 } 11133 } 11134 } 11135 11136 //===--- CHECK: Objective-C retain cycles ----------------------------------// 11137 11138 namespace { 11139 11140 struct RetainCycleOwner { 11141 VarDecl *Variable = nullptr; 11142 SourceRange Range; 11143 SourceLocation Loc; 11144 bool Indirect = false; 11145 11146 RetainCycleOwner() = default; 11147 11148 void setLocsFrom(Expr *e) { 11149 Loc = e->getExprLoc(); 11150 Range = e->getSourceRange(); 11151 } 11152 }; 11153 11154 } // namespace 11155 11156 /// Consider whether capturing the given variable can possibly lead to 11157 /// a retain cycle. 11158 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 11159 // In ARC, it's captured strongly iff the variable has __strong 11160 // lifetime. In MRR, it's captured strongly if the variable is 11161 // __block and has an appropriate type. 11162 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 11163 return false; 11164 11165 owner.Variable = var; 11166 if (ref) 11167 owner.setLocsFrom(ref); 11168 return true; 11169 } 11170 11171 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 11172 while (true) { 11173 e = e->IgnoreParens(); 11174 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 11175 switch (cast->getCastKind()) { 11176 case CK_BitCast: 11177 case CK_LValueBitCast: 11178 case CK_LValueToRValue: 11179 case CK_ARCReclaimReturnedObject: 11180 e = cast->getSubExpr(); 11181 continue; 11182 11183 default: 11184 return false; 11185 } 11186 } 11187 11188 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 11189 ObjCIvarDecl *ivar = ref->getDecl(); 11190 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 11191 return false; 11192 11193 // Try to find a retain cycle in the base. 11194 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 11195 return false; 11196 11197 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 11198 owner.Indirect = true; 11199 return true; 11200 } 11201 11202 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 11203 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 11204 if (!var) return false; 11205 return considerVariable(var, ref, owner); 11206 } 11207 11208 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 11209 if (member->isArrow()) return false; 11210 11211 // Don't count this as an indirect ownership. 11212 e = member->getBase(); 11213 continue; 11214 } 11215 11216 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 11217 // Only pay attention to pseudo-objects on property references. 11218 ObjCPropertyRefExpr *pre 11219 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 11220 ->IgnoreParens()); 11221 if (!pre) return false; 11222 if (pre->isImplicitProperty()) return false; 11223 ObjCPropertyDecl *property = pre->getExplicitProperty(); 11224 if (!property->isRetaining() && 11225 !(property->getPropertyIvarDecl() && 11226 property->getPropertyIvarDecl()->getType() 11227 .getObjCLifetime() == Qualifiers::OCL_Strong)) 11228 return false; 11229 11230 owner.Indirect = true; 11231 if (pre->isSuperReceiver()) { 11232 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 11233 if (!owner.Variable) 11234 return false; 11235 owner.Loc = pre->getLocation(); 11236 owner.Range = pre->getSourceRange(); 11237 return true; 11238 } 11239 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 11240 ->getSourceExpr()); 11241 continue; 11242 } 11243 11244 // Array ivars? 11245 11246 return false; 11247 } 11248 } 11249 11250 namespace { 11251 11252 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 11253 ASTContext &Context; 11254 VarDecl *Variable; 11255 Expr *Capturer = nullptr; 11256 bool VarWillBeReased = false; 11257 11258 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 11259 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 11260 Context(Context), Variable(variable) {} 11261 11262 void VisitDeclRefExpr(DeclRefExpr *ref) { 11263 if (ref->getDecl() == Variable && !Capturer) 11264 Capturer = ref; 11265 } 11266 11267 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 11268 if (Capturer) return; 11269 Visit(ref->getBase()); 11270 if (Capturer && ref->isFreeIvar()) 11271 Capturer = ref; 11272 } 11273 11274 void VisitBlockExpr(BlockExpr *block) { 11275 // Look inside nested blocks 11276 if (block->getBlockDecl()->capturesVariable(Variable)) 11277 Visit(block->getBlockDecl()->getBody()); 11278 } 11279 11280 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 11281 if (Capturer) return; 11282 if (OVE->getSourceExpr()) 11283 Visit(OVE->getSourceExpr()); 11284 } 11285 11286 void VisitBinaryOperator(BinaryOperator *BinOp) { 11287 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 11288 return; 11289 Expr *LHS = BinOp->getLHS(); 11290 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 11291 if (DRE->getDecl() != Variable) 11292 return; 11293 if (Expr *RHS = BinOp->getRHS()) { 11294 RHS = RHS->IgnoreParenCasts(); 11295 llvm::APSInt Value; 11296 VarWillBeReased = 11297 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0); 11298 } 11299 } 11300 } 11301 }; 11302 11303 } // namespace 11304 11305 /// Check whether the given argument is a block which captures a 11306 /// variable. 11307 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 11308 assert(owner.Variable && owner.Loc.isValid()); 11309 11310 e = e->IgnoreParenCasts(); 11311 11312 // Look through [^{...} copy] and Block_copy(^{...}). 11313 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 11314 Selector Cmd = ME->getSelector(); 11315 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 11316 e = ME->getInstanceReceiver(); 11317 if (!e) 11318 return nullptr; 11319 e = e->IgnoreParenCasts(); 11320 } 11321 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 11322 if (CE->getNumArgs() == 1) { 11323 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 11324 if (Fn) { 11325 const IdentifierInfo *FnI = Fn->getIdentifier(); 11326 if (FnI && FnI->isStr("_Block_copy")) { 11327 e = CE->getArg(0)->IgnoreParenCasts(); 11328 } 11329 } 11330 } 11331 } 11332 11333 BlockExpr *block = dyn_cast<BlockExpr>(e); 11334 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 11335 return nullptr; 11336 11337 FindCaptureVisitor visitor(S.Context, owner.Variable); 11338 visitor.Visit(block->getBlockDecl()->getBody()); 11339 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 11340 } 11341 11342 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 11343 RetainCycleOwner &owner) { 11344 assert(capturer); 11345 assert(owner.Variable && owner.Loc.isValid()); 11346 11347 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 11348 << owner.Variable << capturer->getSourceRange(); 11349 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 11350 << owner.Indirect << owner.Range; 11351 } 11352 11353 /// Check for a keyword selector that starts with the word 'add' or 11354 /// 'set'. 11355 static bool isSetterLikeSelector(Selector sel) { 11356 if (sel.isUnarySelector()) return false; 11357 11358 StringRef str = sel.getNameForSlot(0); 11359 while (!str.empty() && str.front() == '_') str = str.substr(1); 11360 if (str.startswith("set")) 11361 str = str.substr(3); 11362 else if (str.startswith("add")) { 11363 // Specially whitelist 'addOperationWithBlock:'. 11364 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 11365 return false; 11366 str = str.substr(3); 11367 } 11368 else 11369 return false; 11370 11371 if (str.empty()) return true; 11372 return !isLowercase(str.front()); 11373 } 11374 11375 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 11376 ObjCMessageExpr *Message) { 11377 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 11378 Message->getReceiverInterface(), 11379 NSAPI::ClassId_NSMutableArray); 11380 if (!IsMutableArray) { 11381 return None; 11382 } 11383 11384 Selector Sel = Message->getSelector(); 11385 11386 Optional<NSAPI::NSArrayMethodKind> MKOpt = 11387 S.NSAPIObj->getNSArrayMethodKind(Sel); 11388 if (!MKOpt) { 11389 return None; 11390 } 11391 11392 NSAPI::NSArrayMethodKind MK = *MKOpt; 11393 11394 switch (MK) { 11395 case NSAPI::NSMutableArr_addObject: 11396 case NSAPI::NSMutableArr_insertObjectAtIndex: 11397 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 11398 return 0; 11399 case NSAPI::NSMutableArr_replaceObjectAtIndex: 11400 return 1; 11401 11402 default: 11403 return None; 11404 } 11405 11406 return None; 11407 } 11408 11409 static 11410 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 11411 ObjCMessageExpr *Message) { 11412 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 11413 Message->getReceiverInterface(), 11414 NSAPI::ClassId_NSMutableDictionary); 11415 if (!IsMutableDictionary) { 11416 return None; 11417 } 11418 11419 Selector Sel = Message->getSelector(); 11420 11421 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 11422 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 11423 if (!MKOpt) { 11424 return None; 11425 } 11426 11427 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 11428 11429 switch (MK) { 11430 case NSAPI::NSMutableDict_setObjectForKey: 11431 case NSAPI::NSMutableDict_setValueForKey: 11432 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 11433 return 0; 11434 11435 default: 11436 return None; 11437 } 11438 11439 return None; 11440 } 11441 11442 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 11443 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 11444 Message->getReceiverInterface(), 11445 NSAPI::ClassId_NSMutableSet); 11446 11447 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 11448 Message->getReceiverInterface(), 11449 NSAPI::ClassId_NSMutableOrderedSet); 11450 if (!IsMutableSet && !IsMutableOrderedSet) { 11451 return None; 11452 } 11453 11454 Selector Sel = Message->getSelector(); 11455 11456 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 11457 if (!MKOpt) { 11458 return None; 11459 } 11460 11461 NSAPI::NSSetMethodKind MK = *MKOpt; 11462 11463 switch (MK) { 11464 case NSAPI::NSMutableSet_addObject: 11465 case NSAPI::NSOrderedSet_setObjectAtIndex: 11466 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 11467 case NSAPI::NSOrderedSet_insertObjectAtIndex: 11468 return 0; 11469 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 11470 return 1; 11471 } 11472 11473 return None; 11474 } 11475 11476 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 11477 if (!Message->isInstanceMessage()) { 11478 return; 11479 } 11480 11481 Optional<int> ArgOpt; 11482 11483 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 11484 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 11485 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 11486 return; 11487 } 11488 11489 int ArgIndex = *ArgOpt; 11490 11491 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 11492 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 11493 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 11494 } 11495 11496 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 11497 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 11498 if (ArgRE->isObjCSelfExpr()) { 11499 Diag(Message->getSourceRange().getBegin(), 11500 diag::warn_objc_circular_container) 11501 << ArgRE->getDecl()->getName() << StringRef("super"); 11502 } 11503 } 11504 } else { 11505 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 11506 11507 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 11508 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 11509 } 11510 11511 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 11512 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 11513 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 11514 ValueDecl *Decl = ReceiverRE->getDecl(); 11515 Diag(Message->getSourceRange().getBegin(), 11516 diag::warn_objc_circular_container) 11517 << Decl->getName() << Decl->getName(); 11518 if (!ArgRE->isObjCSelfExpr()) { 11519 Diag(Decl->getLocation(), 11520 diag::note_objc_circular_container_declared_here) 11521 << Decl->getName(); 11522 } 11523 } 11524 } 11525 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 11526 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 11527 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 11528 ObjCIvarDecl *Decl = IvarRE->getDecl(); 11529 Diag(Message->getSourceRange().getBegin(), 11530 diag::warn_objc_circular_container) 11531 << Decl->getName() << Decl->getName(); 11532 Diag(Decl->getLocation(), 11533 diag::note_objc_circular_container_declared_here) 11534 << Decl->getName(); 11535 } 11536 } 11537 } 11538 } 11539 } 11540 11541 /// Check a message send to see if it's likely to cause a retain cycle. 11542 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 11543 // Only check instance methods whose selector looks like a setter. 11544 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 11545 return; 11546 11547 // Try to find a variable that the receiver is strongly owned by. 11548 RetainCycleOwner owner; 11549 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 11550 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 11551 return; 11552 } else { 11553 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 11554 owner.Variable = getCurMethodDecl()->getSelfDecl(); 11555 owner.Loc = msg->getSuperLoc(); 11556 owner.Range = msg->getSuperLoc(); 11557 } 11558 11559 // Check whether the receiver is captured by any of the arguments. 11560 const ObjCMethodDecl *MD = msg->getMethodDecl(); 11561 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 11562 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 11563 // noescape blocks should not be retained by the method. 11564 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 11565 continue; 11566 return diagnoseRetainCycle(*this, capturer, owner); 11567 } 11568 } 11569 } 11570 11571 /// Check a property assign to see if it's likely to cause a retain cycle. 11572 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 11573 RetainCycleOwner owner; 11574 if (!findRetainCycleOwner(*this, receiver, owner)) 11575 return; 11576 11577 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 11578 diagnoseRetainCycle(*this, capturer, owner); 11579 } 11580 11581 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 11582 RetainCycleOwner Owner; 11583 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 11584 return; 11585 11586 // Because we don't have an expression for the variable, we have to set the 11587 // location explicitly here. 11588 Owner.Loc = Var->getLocation(); 11589 Owner.Range = Var->getSourceRange(); 11590 11591 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 11592 diagnoseRetainCycle(*this, Capturer, Owner); 11593 } 11594 11595 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 11596 Expr *RHS, bool isProperty) { 11597 // Check if RHS is an Objective-C object literal, which also can get 11598 // immediately zapped in a weak reference. Note that we explicitly 11599 // allow ObjCStringLiterals, since those are designed to never really die. 11600 RHS = RHS->IgnoreParenImpCasts(); 11601 11602 // This enum needs to match with the 'select' in 11603 // warn_objc_arc_literal_assign (off-by-1). 11604 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 11605 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 11606 return false; 11607 11608 S.Diag(Loc, diag::warn_arc_literal_assign) 11609 << (unsigned) Kind 11610 << (isProperty ? 0 : 1) 11611 << RHS->getSourceRange(); 11612 11613 return true; 11614 } 11615 11616 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 11617 Qualifiers::ObjCLifetime LT, 11618 Expr *RHS, bool isProperty) { 11619 // Strip off any implicit cast added to get to the one ARC-specific. 11620 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 11621 if (cast->getCastKind() == CK_ARCConsumeObject) { 11622 S.Diag(Loc, diag::warn_arc_retained_assign) 11623 << (LT == Qualifiers::OCL_ExplicitNone) 11624 << (isProperty ? 0 : 1) 11625 << RHS->getSourceRange(); 11626 return true; 11627 } 11628 RHS = cast->getSubExpr(); 11629 } 11630 11631 if (LT == Qualifiers::OCL_Weak && 11632 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 11633 return true; 11634 11635 return false; 11636 } 11637 11638 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 11639 QualType LHS, Expr *RHS) { 11640 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 11641 11642 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 11643 return false; 11644 11645 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 11646 return true; 11647 11648 return false; 11649 } 11650 11651 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 11652 Expr *LHS, Expr *RHS) { 11653 QualType LHSType; 11654 // PropertyRef on LHS type need be directly obtained from 11655 // its declaration as it has a PseudoType. 11656 ObjCPropertyRefExpr *PRE 11657 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 11658 if (PRE && !PRE->isImplicitProperty()) { 11659 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 11660 if (PD) 11661 LHSType = PD->getType(); 11662 } 11663 11664 if (LHSType.isNull()) 11665 LHSType = LHS->getType(); 11666 11667 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 11668 11669 if (LT == Qualifiers::OCL_Weak) { 11670 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 11671 getCurFunction()->markSafeWeakUse(LHS); 11672 } 11673 11674 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 11675 return; 11676 11677 // FIXME. Check for other life times. 11678 if (LT != Qualifiers::OCL_None) 11679 return; 11680 11681 if (PRE) { 11682 if (PRE->isImplicitProperty()) 11683 return; 11684 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 11685 if (!PD) 11686 return; 11687 11688 unsigned Attributes = PD->getPropertyAttributes(); 11689 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) { 11690 // when 'assign' attribute was not explicitly specified 11691 // by user, ignore it and rely on property type itself 11692 // for lifetime info. 11693 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 11694 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) && 11695 LHSType->isObjCRetainableType()) 11696 return; 11697 11698 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 11699 if (cast->getCastKind() == CK_ARCConsumeObject) { 11700 Diag(Loc, diag::warn_arc_retained_property_assign) 11701 << RHS->getSourceRange(); 11702 return; 11703 } 11704 RHS = cast->getSubExpr(); 11705 } 11706 } 11707 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) { 11708 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 11709 return; 11710 } 11711 } 11712 } 11713 11714 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 11715 11716 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 11717 SourceLocation StmtLoc, 11718 const NullStmt *Body) { 11719 // Do not warn if the body is a macro that expands to nothing, e.g: 11720 // 11721 // #define CALL(x) 11722 // if (condition) 11723 // CALL(0); 11724 if (Body->hasLeadingEmptyMacro()) 11725 return false; 11726 11727 // Get line numbers of statement and body. 11728 bool StmtLineInvalid; 11729 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 11730 &StmtLineInvalid); 11731 if (StmtLineInvalid) 11732 return false; 11733 11734 bool BodyLineInvalid; 11735 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 11736 &BodyLineInvalid); 11737 if (BodyLineInvalid) 11738 return false; 11739 11740 // Warn if null statement and body are on the same line. 11741 if (StmtLine != BodyLine) 11742 return false; 11743 11744 return true; 11745 } 11746 11747 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 11748 const Stmt *Body, 11749 unsigned DiagID) { 11750 // Since this is a syntactic check, don't emit diagnostic for template 11751 // instantiations, this just adds noise. 11752 if (CurrentInstantiationScope) 11753 return; 11754 11755 // The body should be a null statement. 11756 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 11757 if (!NBody) 11758 return; 11759 11760 // Do the usual checks. 11761 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 11762 return; 11763 11764 Diag(NBody->getSemiLoc(), DiagID); 11765 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 11766 } 11767 11768 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 11769 const Stmt *PossibleBody) { 11770 assert(!CurrentInstantiationScope); // Ensured by caller 11771 11772 SourceLocation StmtLoc; 11773 const Stmt *Body; 11774 unsigned DiagID; 11775 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 11776 StmtLoc = FS->getRParenLoc(); 11777 Body = FS->getBody(); 11778 DiagID = diag::warn_empty_for_body; 11779 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 11780 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 11781 Body = WS->getBody(); 11782 DiagID = diag::warn_empty_while_body; 11783 } else 11784 return; // Neither `for' nor `while'. 11785 11786 // The body should be a null statement. 11787 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 11788 if (!NBody) 11789 return; 11790 11791 // Skip expensive checks if diagnostic is disabled. 11792 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 11793 return; 11794 11795 // Do the usual checks. 11796 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 11797 return; 11798 11799 // `for(...);' and `while(...);' are popular idioms, so in order to keep 11800 // noise level low, emit diagnostics only if for/while is followed by a 11801 // CompoundStmt, e.g.: 11802 // for (int i = 0; i < n; i++); 11803 // { 11804 // a(i); 11805 // } 11806 // or if for/while is followed by a statement with more indentation 11807 // than for/while itself: 11808 // for (int i = 0; i < n; i++); 11809 // a(i); 11810 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 11811 if (!ProbableTypo) { 11812 bool BodyColInvalid; 11813 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 11814 PossibleBody->getLocStart(), 11815 &BodyColInvalid); 11816 if (BodyColInvalid) 11817 return; 11818 11819 bool StmtColInvalid; 11820 unsigned StmtCol = SourceMgr.getPresumedColumnNumber( 11821 S->getLocStart(), 11822 &StmtColInvalid); 11823 if (StmtColInvalid) 11824 return; 11825 11826 if (BodyCol > StmtCol) 11827 ProbableTypo = true; 11828 } 11829 11830 if (ProbableTypo) { 11831 Diag(NBody->getSemiLoc(), DiagID); 11832 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 11833 } 11834 } 11835 11836 //===--- CHECK: Warn on self move with std::move. -------------------------===// 11837 11838 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 11839 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 11840 SourceLocation OpLoc) { 11841 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 11842 return; 11843 11844 if (inTemplateInstantiation()) 11845 return; 11846 11847 // Strip parens and casts away. 11848 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 11849 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 11850 11851 // Check for a call expression 11852 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 11853 if (!CE || CE->getNumArgs() != 1) 11854 return; 11855 11856 // Check for a call to std::move 11857 if (!CE->isCallToStdMove()) 11858 return; 11859 11860 // Get argument from std::move 11861 RHSExpr = CE->getArg(0); 11862 11863 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 11864 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 11865 11866 // Two DeclRefExpr's, check that the decls are the same. 11867 if (LHSDeclRef && RHSDeclRef) { 11868 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 11869 return; 11870 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 11871 RHSDeclRef->getDecl()->getCanonicalDecl()) 11872 return; 11873 11874 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 11875 << LHSExpr->getSourceRange() 11876 << RHSExpr->getSourceRange(); 11877 return; 11878 } 11879 11880 // Member variables require a different approach to check for self moves. 11881 // MemberExpr's are the same if every nested MemberExpr refers to the same 11882 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 11883 // the base Expr's are CXXThisExpr's. 11884 const Expr *LHSBase = LHSExpr; 11885 const Expr *RHSBase = RHSExpr; 11886 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 11887 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 11888 if (!LHSME || !RHSME) 11889 return; 11890 11891 while (LHSME && RHSME) { 11892 if (LHSME->getMemberDecl()->getCanonicalDecl() != 11893 RHSME->getMemberDecl()->getCanonicalDecl()) 11894 return; 11895 11896 LHSBase = LHSME->getBase(); 11897 RHSBase = RHSME->getBase(); 11898 LHSME = dyn_cast<MemberExpr>(LHSBase); 11899 RHSME = dyn_cast<MemberExpr>(RHSBase); 11900 } 11901 11902 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 11903 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 11904 if (LHSDeclRef && RHSDeclRef) { 11905 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 11906 return; 11907 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 11908 RHSDeclRef->getDecl()->getCanonicalDecl()) 11909 return; 11910 11911 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 11912 << LHSExpr->getSourceRange() 11913 << RHSExpr->getSourceRange(); 11914 return; 11915 } 11916 11917 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 11918 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 11919 << LHSExpr->getSourceRange() 11920 << RHSExpr->getSourceRange(); 11921 } 11922 11923 //===--- Layout compatibility ----------------------------------------------// 11924 11925 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 11926 11927 /// \brief Check if two enumeration types are layout-compatible. 11928 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 11929 // C++11 [dcl.enum] p8: 11930 // Two enumeration types are layout-compatible if they have the same 11931 // underlying type. 11932 return ED1->isComplete() && ED2->isComplete() && 11933 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 11934 } 11935 11936 /// \brief Check if two fields are layout-compatible. 11937 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 11938 FieldDecl *Field2) { 11939 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 11940 return false; 11941 11942 if (Field1->isBitField() != Field2->isBitField()) 11943 return false; 11944 11945 if (Field1->isBitField()) { 11946 // Make sure that the bit-fields are the same length. 11947 unsigned Bits1 = Field1->getBitWidthValue(C); 11948 unsigned Bits2 = Field2->getBitWidthValue(C); 11949 11950 if (Bits1 != Bits2) 11951 return false; 11952 } 11953 11954 return true; 11955 } 11956 11957 /// \brief Check if two standard-layout structs are layout-compatible. 11958 /// (C++11 [class.mem] p17) 11959 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 11960 RecordDecl *RD2) { 11961 // If both records are C++ classes, check that base classes match. 11962 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 11963 // If one of records is a CXXRecordDecl we are in C++ mode, 11964 // thus the other one is a CXXRecordDecl, too. 11965 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 11966 // Check number of base classes. 11967 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 11968 return false; 11969 11970 // Check the base classes. 11971 for (CXXRecordDecl::base_class_const_iterator 11972 Base1 = D1CXX->bases_begin(), 11973 BaseEnd1 = D1CXX->bases_end(), 11974 Base2 = D2CXX->bases_begin(); 11975 Base1 != BaseEnd1; 11976 ++Base1, ++Base2) { 11977 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 11978 return false; 11979 } 11980 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 11981 // If only RD2 is a C++ class, it should have zero base classes. 11982 if (D2CXX->getNumBases() > 0) 11983 return false; 11984 } 11985 11986 // Check the fields. 11987 RecordDecl::field_iterator Field2 = RD2->field_begin(), 11988 Field2End = RD2->field_end(), 11989 Field1 = RD1->field_begin(), 11990 Field1End = RD1->field_end(); 11991 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 11992 if (!isLayoutCompatible(C, *Field1, *Field2)) 11993 return false; 11994 } 11995 if (Field1 != Field1End || Field2 != Field2End) 11996 return false; 11997 11998 return true; 11999 } 12000 12001 /// \brief Check if two standard-layout unions are layout-compatible. 12002 /// (C++11 [class.mem] p18) 12003 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 12004 RecordDecl *RD2) { 12005 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 12006 for (auto *Field2 : RD2->fields()) 12007 UnmatchedFields.insert(Field2); 12008 12009 for (auto *Field1 : RD1->fields()) { 12010 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 12011 I = UnmatchedFields.begin(), 12012 E = UnmatchedFields.end(); 12013 12014 for ( ; I != E; ++I) { 12015 if (isLayoutCompatible(C, Field1, *I)) { 12016 bool Result = UnmatchedFields.erase(*I); 12017 (void) Result; 12018 assert(Result); 12019 break; 12020 } 12021 } 12022 if (I == E) 12023 return false; 12024 } 12025 12026 return UnmatchedFields.empty(); 12027 } 12028 12029 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 12030 RecordDecl *RD2) { 12031 if (RD1->isUnion() != RD2->isUnion()) 12032 return false; 12033 12034 if (RD1->isUnion()) 12035 return isLayoutCompatibleUnion(C, RD1, RD2); 12036 else 12037 return isLayoutCompatibleStruct(C, RD1, RD2); 12038 } 12039 12040 /// \brief Check if two types are layout-compatible in C++11 sense. 12041 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 12042 if (T1.isNull() || T2.isNull()) 12043 return false; 12044 12045 // C++11 [basic.types] p11: 12046 // If two types T1 and T2 are the same type, then T1 and T2 are 12047 // layout-compatible types. 12048 if (C.hasSameType(T1, T2)) 12049 return true; 12050 12051 T1 = T1.getCanonicalType().getUnqualifiedType(); 12052 T2 = T2.getCanonicalType().getUnqualifiedType(); 12053 12054 const Type::TypeClass TC1 = T1->getTypeClass(); 12055 const Type::TypeClass TC2 = T2->getTypeClass(); 12056 12057 if (TC1 != TC2) 12058 return false; 12059 12060 if (TC1 == Type::Enum) { 12061 return isLayoutCompatible(C, 12062 cast<EnumType>(T1)->getDecl(), 12063 cast<EnumType>(T2)->getDecl()); 12064 } else if (TC1 == Type::Record) { 12065 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 12066 return false; 12067 12068 return isLayoutCompatible(C, 12069 cast<RecordType>(T1)->getDecl(), 12070 cast<RecordType>(T2)->getDecl()); 12071 } 12072 12073 return false; 12074 } 12075 12076 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 12077 12078 /// \brief Given a type tag expression find the type tag itself. 12079 /// 12080 /// \param TypeExpr Type tag expression, as it appears in user's code. 12081 /// 12082 /// \param VD Declaration of an identifier that appears in a type tag. 12083 /// 12084 /// \param MagicValue Type tag magic value. 12085 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 12086 const ValueDecl **VD, uint64_t *MagicValue) { 12087 while(true) { 12088 if (!TypeExpr) 12089 return false; 12090 12091 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 12092 12093 switch (TypeExpr->getStmtClass()) { 12094 case Stmt::UnaryOperatorClass: { 12095 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 12096 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 12097 TypeExpr = UO->getSubExpr(); 12098 continue; 12099 } 12100 return false; 12101 } 12102 12103 case Stmt::DeclRefExprClass: { 12104 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 12105 *VD = DRE->getDecl(); 12106 return true; 12107 } 12108 12109 case Stmt::IntegerLiteralClass: { 12110 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 12111 llvm::APInt MagicValueAPInt = IL->getValue(); 12112 if (MagicValueAPInt.getActiveBits() <= 64) { 12113 *MagicValue = MagicValueAPInt.getZExtValue(); 12114 return true; 12115 } else 12116 return false; 12117 } 12118 12119 case Stmt::BinaryConditionalOperatorClass: 12120 case Stmt::ConditionalOperatorClass: { 12121 const AbstractConditionalOperator *ACO = 12122 cast<AbstractConditionalOperator>(TypeExpr); 12123 bool Result; 12124 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) { 12125 if (Result) 12126 TypeExpr = ACO->getTrueExpr(); 12127 else 12128 TypeExpr = ACO->getFalseExpr(); 12129 continue; 12130 } 12131 return false; 12132 } 12133 12134 case Stmt::BinaryOperatorClass: { 12135 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 12136 if (BO->getOpcode() == BO_Comma) { 12137 TypeExpr = BO->getRHS(); 12138 continue; 12139 } 12140 return false; 12141 } 12142 12143 default: 12144 return false; 12145 } 12146 } 12147 } 12148 12149 /// \brief Retrieve the C type corresponding to type tag TypeExpr. 12150 /// 12151 /// \param TypeExpr Expression that specifies a type tag. 12152 /// 12153 /// \param MagicValues Registered magic values. 12154 /// 12155 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 12156 /// kind. 12157 /// 12158 /// \param TypeInfo Information about the corresponding C type. 12159 /// 12160 /// \returns true if the corresponding C type was found. 12161 static bool GetMatchingCType( 12162 const IdentifierInfo *ArgumentKind, 12163 const Expr *TypeExpr, const ASTContext &Ctx, 12164 const llvm::DenseMap<Sema::TypeTagMagicValue, 12165 Sema::TypeTagData> *MagicValues, 12166 bool &FoundWrongKind, 12167 Sema::TypeTagData &TypeInfo) { 12168 FoundWrongKind = false; 12169 12170 // Variable declaration that has type_tag_for_datatype attribute. 12171 const ValueDecl *VD = nullptr; 12172 12173 uint64_t MagicValue; 12174 12175 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue)) 12176 return false; 12177 12178 if (VD) { 12179 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 12180 if (I->getArgumentKind() != ArgumentKind) { 12181 FoundWrongKind = true; 12182 return false; 12183 } 12184 TypeInfo.Type = I->getMatchingCType(); 12185 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 12186 TypeInfo.MustBeNull = I->getMustBeNull(); 12187 return true; 12188 } 12189 return false; 12190 } 12191 12192 if (!MagicValues) 12193 return false; 12194 12195 llvm::DenseMap<Sema::TypeTagMagicValue, 12196 Sema::TypeTagData>::const_iterator I = 12197 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 12198 if (I == MagicValues->end()) 12199 return false; 12200 12201 TypeInfo = I->second; 12202 return true; 12203 } 12204 12205 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 12206 uint64_t MagicValue, QualType Type, 12207 bool LayoutCompatible, 12208 bool MustBeNull) { 12209 if (!TypeTagForDatatypeMagicValues) 12210 TypeTagForDatatypeMagicValues.reset( 12211 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 12212 12213 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 12214 (*TypeTagForDatatypeMagicValues)[Magic] = 12215 TypeTagData(Type, LayoutCompatible, MustBeNull); 12216 } 12217 12218 static bool IsSameCharType(QualType T1, QualType T2) { 12219 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 12220 if (!BT1) 12221 return false; 12222 12223 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 12224 if (!BT2) 12225 return false; 12226 12227 BuiltinType::Kind T1Kind = BT1->getKind(); 12228 BuiltinType::Kind T2Kind = BT2->getKind(); 12229 12230 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 12231 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 12232 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 12233 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 12234 } 12235 12236 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 12237 const ArrayRef<const Expr *> ExprArgs, 12238 SourceLocation CallSiteLoc) { 12239 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 12240 bool IsPointerAttr = Attr->getIsPointer(); 12241 12242 // Retrieve the argument representing the 'type_tag'. 12243 if (Attr->getTypeTagIdx() >= ExprArgs.size()) { 12244 // Add 1 to display the user's specified value. 12245 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 12246 << 0 << Attr->getTypeTagIdx() + 1; 12247 return; 12248 } 12249 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()]; 12250 bool FoundWrongKind; 12251 TypeTagData TypeInfo; 12252 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 12253 TypeTagForDatatypeMagicValues.get(), 12254 FoundWrongKind, TypeInfo)) { 12255 if (FoundWrongKind) 12256 Diag(TypeTagExpr->getExprLoc(), 12257 diag::warn_type_tag_for_datatype_wrong_kind) 12258 << TypeTagExpr->getSourceRange(); 12259 return; 12260 } 12261 12262 // Retrieve the argument representing the 'arg_idx'. 12263 if (Attr->getArgumentIdx() >= ExprArgs.size()) { 12264 // Add 1 to display the user's specified value. 12265 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 12266 << 1 << Attr->getArgumentIdx() + 1; 12267 return; 12268 } 12269 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()]; 12270 if (IsPointerAttr) { 12271 // Skip implicit cast of pointer to `void *' (as a function argument). 12272 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 12273 if (ICE->getType()->isVoidPointerType() && 12274 ICE->getCastKind() == CK_BitCast) 12275 ArgumentExpr = ICE->getSubExpr(); 12276 } 12277 QualType ArgumentType = ArgumentExpr->getType(); 12278 12279 // Passing a `void*' pointer shouldn't trigger a warning. 12280 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 12281 return; 12282 12283 if (TypeInfo.MustBeNull) { 12284 // Type tag with matching void type requires a null pointer. 12285 if (!ArgumentExpr->isNullPointerConstant(Context, 12286 Expr::NPC_ValueDependentIsNotNull)) { 12287 Diag(ArgumentExpr->getExprLoc(), 12288 diag::warn_type_safety_null_pointer_required) 12289 << ArgumentKind->getName() 12290 << ArgumentExpr->getSourceRange() 12291 << TypeTagExpr->getSourceRange(); 12292 } 12293 return; 12294 } 12295 12296 QualType RequiredType = TypeInfo.Type; 12297 if (IsPointerAttr) 12298 RequiredType = Context.getPointerType(RequiredType); 12299 12300 bool mismatch = false; 12301 if (!TypeInfo.LayoutCompatible) { 12302 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 12303 12304 // C++11 [basic.fundamental] p1: 12305 // Plain char, signed char, and unsigned char are three distinct types. 12306 // 12307 // But we treat plain `char' as equivalent to `signed char' or `unsigned 12308 // char' depending on the current char signedness mode. 12309 if (mismatch) 12310 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 12311 RequiredType->getPointeeType())) || 12312 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 12313 mismatch = false; 12314 } else 12315 if (IsPointerAttr) 12316 mismatch = !isLayoutCompatible(Context, 12317 ArgumentType->getPointeeType(), 12318 RequiredType->getPointeeType()); 12319 else 12320 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 12321 12322 if (mismatch) 12323 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 12324 << ArgumentType << ArgumentKind 12325 << TypeInfo.LayoutCompatible << RequiredType 12326 << ArgumentExpr->getSourceRange() 12327 << TypeTagExpr->getSourceRange(); 12328 } 12329 12330 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 12331 CharUnits Alignment) { 12332 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 12333 } 12334 12335 void Sema::DiagnoseMisalignedMembers() { 12336 for (MisalignedMember &m : MisalignedMembers) { 12337 const NamedDecl *ND = m.RD; 12338 if (ND->getName().empty()) { 12339 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 12340 ND = TD; 12341 } 12342 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member) 12343 << m.MD << ND << m.E->getSourceRange(); 12344 } 12345 MisalignedMembers.clear(); 12346 } 12347 12348 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 12349 E = E->IgnoreParens(); 12350 if (!T->isPointerType() && !T->isIntegerType()) 12351 return; 12352 if (isa<UnaryOperator>(E) && 12353 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 12354 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 12355 if (isa<MemberExpr>(Op)) { 12356 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(), 12357 MisalignedMember(Op)); 12358 if (MA != MisalignedMembers.end() && 12359 (T->isIntegerType() || 12360 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 12361 Context.getTypeAlignInChars( 12362 T->getPointeeType()) <= MA->Alignment)))) 12363 MisalignedMembers.erase(MA); 12364 } 12365 } 12366 } 12367 12368 void Sema::RefersToMemberWithReducedAlignment( 12369 Expr *E, 12370 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 12371 Action) { 12372 const auto *ME = dyn_cast<MemberExpr>(E); 12373 if (!ME) 12374 return; 12375 12376 // No need to check expressions with an __unaligned-qualified type. 12377 if (E->getType().getQualifiers().hasUnaligned()) 12378 return; 12379 12380 // For a chain of MemberExpr like "a.b.c.d" this list 12381 // will keep FieldDecl's like [d, c, b]. 12382 SmallVector<FieldDecl *, 4> ReverseMemberChain; 12383 const MemberExpr *TopME = nullptr; 12384 bool AnyIsPacked = false; 12385 do { 12386 QualType BaseType = ME->getBase()->getType(); 12387 if (ME->isArrow()) 12388 BaseType = BaseType->getPointeeType(); 12389 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl(); 12390 if (RD->isInvalidDecl()) 12391 return; 12392 12393 ValueDecl *MD = ME->getMemberDecl(); 12394 auto *FD = dyn_cast<FieldDecl>(MD); 12395 // We do not care about non-data members. 12396 if (!FD || FD->isInvalidDecl()) 12397 return; 12398 12399 AnyIsPacked = 12400 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 12401 ReverseMemberChain.push_back(FD); 12402 12403 TopME = ME; 12404 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 12405 } while (ME); 12406 assert(TopME && "We did not compute a topmost MemberExpr!"); 12407 12408 // Not the scope of this diagnostic. 12409 if (!AnyIsPacked) 12410 return; 12411 12412 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 12413 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 12414 // TODO: The innermost base of the member expression may be too complicated. 12415 // For now, just disregard these cases. This is left for future 12416 // improvement. 12417 if (!DRE && !isa<CXXThisExpr>(TopBase)) 12418 return; 12419 12420 // Alignment expected by the whole expression. 12421 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 12422 12423 // No need to do anything else with this case. 12424 if (ExpectedAlignment.isOne()) 12425 return; 12426 12427 // Synthesize offset of the whole access. 12428 CharUnits Offset; 12429 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 12430 I++) { 12431 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 12432 } 12433 12434 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 12435 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 12436 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 12437 12438 // The base expression of the innermost MemberExpr may give 12439 // stronger guarantees than the class containing the member. 12440 if (DRE && !TopME->isArrow()) { 12441 const ValueDecl *VD = DRE->getDecl(); 12442 if (!VD->getType()->isReferenceType()) 12443 CompleteObjectAlignment = 12444 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 12445 } 12446 12447 // Check if the synthesized offset fulfills the alignment. 12448 if (Offset % ExpectedAlignment != 0 || 12449 // It may fulfill the offset it but the effective alignment may still be 12450 // lower than the expected expression alignment. 12451 CompleteObjectAlignment < ExpectedAlignment) { 12452 // If this happens, we want to determine a sensible culprit of this. 12453 // Intuitively, watching the chain of member expressions from right to 12454 // left, we start with the required alignment (as required by the field 12455 // type) but some packed attribute in that chain has reduced the alignment. 12456 // It may happen that another packed structure increases it again. But if 12457 // we are here such increase has not been enough. So pointing the first 12458 // FieldDecl that either is packed or else its RecordDecl is, 12459 // seems reasonable. 12460 FieldDecl *FD = nullptr; 12461 CharUnits Alignment; 12462 for (FieldDecl *FDI : ReverseMemberChain) { 12463 if (FDI->hasAttr<PackedAttr>() || 12464 FDI->getParent()->hasAttr<PackedAttr>()) { 12465 FD = FDI; 12466 Alignment = std::min( 12467 Context.getTypeAlignInChars(FD->getType()), 12468 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 12469 break; 12470 } 12471 } 12472 assert(FD && "We did not find a packed FieldDecl!"); 12473 Action(E, FD->getParent(), FD, Alignment); 12474 } 12475 } 12476 12477 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 12478 using namespace std::placeholders; 12479 12480 RefersToMemberWithReducedAlignment( 12481 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 12482 _2, _3, _4)); 12483 } 12484