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/NonTrivialTypeVisitor.h" 32 #include "clang/AST/OperationKinds.h" 33 #include "clang/AST/Stmt.h" 34 #include "clang/AST/TemplateBase.h" 35 #include "clang/AST/Type.h" 36 #include "clang/AST/TypeLoc.h" 37 #include "clang/AST/UnresolvedSet.h" 38 #include "clang/Analysis/Analyses/FormatString.h" 39 #include "clang/Basic/AddressSpaces.h" 40 #include "clang/Basic/CharInfo.h" 41 #include "clang/Basic/Diagnostic.h" 42 #include "clang/Basic/IdentifierTable.h" 43 #include "clang/Basic/LLVM.h" 44 #include "clang/Basic/LangOptions.h" 45 #include "clang/Basic/OpenCLOptions.h" 46 #include "clang/Basic/OperatorKinds.h" 47 #include "clang/Basic/PartialDiagnostic.h" 48 #include "clang/Basic/SourceLocation.h" 49 #include "clang/Basic/SourceManager.h" 50 #include "clang/Basic/Specifiers.h" 51 #include "clang/Basic/SyncScope.h" 52 #include "clang/Basic/TargetBuiltins.h" 53 #include "clang/Basic/TargetCXXABI.h" 54 #include "clang/Basic/TargetInfo.h" 55 #include "clang/Basic/TypeTraits.h" 56 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 57 #include "clang/Sema/Initialization.h" 58 #include "clang/Sema/Lookup.h" 59 #include "clang/Sema/Ownership.h" 60 #include "clang/Sema/Scope.h" 61 #include "clang/Sema/ScopeInfo.h" 62 #include "clang/Sema/Sema.h" 63 #include "clang/Sema/SemaInternal.h" 64 #include "llvm/ADT/APFloat.h" 65 #include "llvm/ADT/APInt.h" 66 #include "llvm/ADT/APSInt.h" 67 #include "llvm/ADT/ArrayRef.h" 68 #include "llvm/ADT/DenseMap.h" 69 #include "llvm/ADT/FoldingSet.h" 70 #include "llvm/ADT/None.h" 71 #include "llvm/ADT/Optional.h" 72 #include "llvm/ADT/STLExtras.h" 73 #include "llvm/ADT/SmallBitVector.h" 74 #include "llvm/ADT/SmallPtrSet.h" 75 #include "llvm/ADT/SmallString.h" 76 #include "llvm/ADT/SmallVector.h" 77 #include "llvm/ADT/StringRef.h" 78 #include "llvm/ADT/StringSwitch.h" 79 #include "llvm/ADT/Triple.h" 80 #include "llvm/Support/AtomicOrdering.h" 81 #include "llvm/Support/Casting.h" 82 #include "llvm/Support/Compiler.h" 83 #include "llvm/Support/ConvertUTF.h" 84 #include "llvm/Support/ErrorHandling.h" 85 #include "llvm/Support/Format.h" 86 #include "llvm/Support/Locale.h" 87 #include "llvm/Support/MathExtras.h" 88 #include "llvm/Support/raw_ostream.h" 89 #include <algorithm> 90 #include <cassert> 91 #include <cstddef> 92 #include <cstdint> 93 #include <functional> 94 #include <limits> 95 #include <string> 96 #include <tuple> 97 #include <utility> 98 99 using namespace clang; 100 using namespace sema; 101 102 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 103 unsigned ByteNo) const { 104 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts, 105 Context.getTargetInfo()); 106 } 107 108 /// Checks that a call expression's argument count is the desired number. 109 /// This is useful when doing custom type-checking. Returns true on error. 110 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { 111 unsigned argCount = call->getNumArgs(); 112 if (argCount == desiredArgCount) return false; 113 114 if (argCount < desiredArgCount) 115 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args) 116 << 0 /*function call*/ << desiredArgCount << argCount 117 << call->getSourceRange(); 118 119 // Highlight all the excess arguments. 120 SourceRange range(call->getArg(desiredArgCount)->getLocStart(), 121 call->getArg(argCount - 1)->getLocEnd()); 122 123 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) 124 << 0 /*function call*/ << desiredArgCount << argCount 125 << call->getArg(1)->getSourceRange(); 126 } 127 128 /// Check that the first argument to __builtin_annotation is an integer 129 /// and the second argument is a non-wide string literal. 130 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) { 131 if (checkArgCount(S, TheCall, 2)) 132 return true; 133 134 // First argument should be an integer. 135 Expr *ValArg = TheCall->getArg(0); 136 QualType Ty = ValArg->getType(); 137 if (!Ty->isIntegerType()) { 138 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg) 139 << ValArg->getSourceRange(); 140 return true; 141 } 142 143 // Second argument should be a constant string. 144 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts(); 145 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg); 146 if (!Literal || !Literal->isAscii()) { 147 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg) 148 << StrArg->getSourceRange(); 149 return true; 150 } 151 152 TheCall->setType(Ty); 153 return false; 154 } 155 156 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) { 157 // We need at least one argument. 158 if (TheCall->getNumArgs() < 1) { 159 S.Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 160 << 0 << 1 << TheCall->getNumArgs() 161 << TheCall->getCallee()->getSourceRange(); 162 return true; 163 } 164 165 // All arguments should be wide string literals. 166 for (Expr *Arg : TheCall->arguments()) { 167 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 168 if (!Literal || !Literal->isWide()) { 169 S.Diag(Arg->getLocStart(), diag::err_msvc_annotation_wide_str) 170 << Arg->getSourceRange(); 171 return true; 172 } 173 } 174 175 return false; 176 } 177 178 /// Check that the argument to __builtin_addressof is a glvalue, and set the 179 /// result type to the corresponding pointer type. 180 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) { 181 if (checkArgCount(S, TheCall, 1)) 182 return true; 183 184 ExprResult Arg(TheCall->getArg(0)); 185 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart()); 186 if (ResultType.isNull()) 187 return true; 188 189 TheCall->setArg(0, Arg.get()); 190 TheCall->setType(ResultType); 191 return false; 192 } 193 194 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) { 195 if (checkArgCount(S, TheCall, 3)) 196 return true; 197 198 // First two arguments should be integers. 199 for (unsigned I = 0; I < 2; ++I) { 200 Expr *Arg = TheCall->getArg(I); 201 QualType Ty = Arg->getType(); 202 if (!Ty->isIntegerType()) { 203 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int) 204 << Ty << Arg->getSourceRange(); 205 return true; 206 } 207 } 208 209 // Third argument should be a pointer to a non-const integer. 210 // IRGen correctly handles volatile, restrict, and address spaces, and 211 // the other qualifiers aren't possible. 212 { 213 Expr *Arg = TheCall->getArg(2); 214 QualType Ty = Arg->getType(); 215 const auto *PtrTy = Ty->getAs<PointerType>(); 216 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() && 217 !PtrTy->getPointeeType().isConstQualified())) { 218 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int) 219 << Ty << Arg->getSourceRange(); 220 return true; 221 } 222 } 223 224 return false; 225 } 226 227 static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl, 228 CallExpr *TheCall, unsigned SizeIdx, 229 unsigned DstSizeIdx) { 230 if (TheCall->getNumArgs() <= SizeIdx || 231 TheCall->getNumArgs() <= DstSizeIdx) 232 return; 233 234 const Expr *SizeArg = TheCall->getArg(SizeIdx); 235 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx); 236 237 llvm::APSInt Size, DstSize; 238 239 // find out if both sizes are known at compile time 240 if (!SizeArg->EvaluateAsInt(Size, S.Context) || 241 !DstSizeArg->EvaluateAsInt(DstSize, S.Context)) 242 return; 243 244 if (Size.ule(DstSize)) 245 return; 246 247 // confirmed overflow so generate the diagnostic. 248 IdentifierInfo *FnName = FDecl->getIdentifier(); 249 SourceLocation SL = TheCall->getLocStart(); 250 SourceRange SR = TheCall->getSourceRange(); 251 252 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName; 253 } 254 255 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { 256 if (checkArgCount(S, BuiltinCall, 2)) 257 return true; 258 259 SourceLocation BuiltinLoc = BuiltinCall->getLocStart(); 260 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); 261 Expr *Call = BuiltinCall->getArg(0); 262 Expr *Chain = BuiltinCall->getArg(1); 263 264 if (Call->getStmtClass() != Stmt::CallExprClass) { 265 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) 266 << Call->getSourceRange(); 267 return true; 268 } 269 270 auto CE = cast<CallExpr>(Call); 271 if (CE->getCallee()->getType()->isBlockPointerType()) { 272 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) 273 << Call->getSourceRange(); 274 return true; 275 } 276 277 const Decl *TargetDecl = CE->getCalleeDecl(); 278 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 279 if (FD->getBuiltinID()) { 280 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) 281 << Call->getSourceRange(); 282 return true; 283 } 284 285 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { 286 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) 287 << Call->getSourceRange(); 288 return true; 289 } 290 291 ExprResult ChainResult = S.UsualUnaryConversions(Chain); 292 if (ChainResult.isInvalid()) 293 return true; 294 if (!ChainResult.get()->getType()->isPointerType()) { 295 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) 296 << Chain->getSourceRange(); 297 return true; 298 } 299 300 QualType ReturnTy = CE->getCallReturnType(S.Context); 301 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; 302 QualType BuiltinTy = S.Context.getFunctionType( 303 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); 304 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); 305 306 Builtin = 307 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); 308 309 BuiltinCall->setType(CE->getType()); 310 BuiltinCall->setValueKind(CE->getValueKind()); 311 BuiltinCall->setObjectKind(CE->getObjectKind()); 312 BuiltinCall->setCallee(Builtin); 313 BuiltinCall->setArg(1, ChainResult.get()); 314 315 return false; 316 } 317 318 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 319 Scope::ScopeFlags NeededScopeFlags, 320 unsigned DiagID) { 321 // Scopes aren't available during instantiation. Fortunately, builtin 322 // functions cannot be template args so they cannot be formed through template 323 // instantiation. Therefore checking once during the parse is sufficient. 324 if (SemaRef.inTemplateInstantiation()) 325 return false; 326 327 Scope *S = SemaRef.getCurScope(); 328 while (S && !S->isSEHExceptScope()) 329 S = S->getParent(); 330 if (!S || !(S->getFlags() & NeededScopeFlags)) { 331 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 332 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 333 << DRE->getDecl()->getIdentifier(); 334 return true; 335 } 336 337 return false; 338 } 339 340 static inline bool isBlockPointer(Expr *Arg) { 341 return Arg->getType()->isBlockPointerType(); 342 } 343 344 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local 345 /// void*, which is a requirement of device side enqueue. 346 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { 347 const BlockPointerType *BPT = 348 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 349 ArrayRef<QualType> Params = 350 BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes(); 351 unsigned ArgCounter = 0; 352 bool IllegalParams = false; 353 // Iterate through the block parameters until either one is found that is not 354 // a local void*, or the block is valid. 355 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); 356 I != E; ++I, ++ArgCounter) { 357 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || 358 (*I)->getPointeeType().getQualifiers().getAddressSpace() != 359 LangAS::opencl_local) { 360 // Get the location of the error. If a block literal has been passed 361 // (BlockExpr) then we can point straight to the offending argument, 362 // else we just point to the variable reference. 363 SourceLocation ErrorLoc; 364 if (isa<BlockExpr>(BlockArg)) { 365 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); 366 ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart(); 367 } else if (isa<DeclRefExpr>(BlockArg)) { 368 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart(); 369 } 370 S.Diag(ErrorLoc, 371 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); 372 IllegalParams = true; 373 } 374 } 375 376 return IllegalParams; 377 } 378 379 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) { 380 if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) { 381 S.Diag(Call->getLocStart(), diag::err_opencl_requires_extension) 382 << 1 << Call->getDirectCallee() << "cl_khr_subgroups"; 383 return true; 384 } 385 return false; 386 } 387 388 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) { 389 if (checkArgCount(S, TheCall, 2)) 390 return true; 391 392 if (checkOpenCLSubgroupExt(S, TheCall)) 393 return true; 394 395 // First argument is an ndrange_t type. 396 Expr *NDRangeArg = TheCall->getArg(0); 397 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 398 S.Diag(NDRangeArg->getLocStart(), 399 diag::err_opencl_builtin_expected_type) 400 << TheCall->getDirectCallee() << "'ndrange_t'"; 401 return true; 402 } 403 404 Expr *BlockArg = TheCall->getArg(1); 405 if (!isBlockPointer(BlockArg)) { 406 S.Diag(BlockArg->getLocStart(), 407 diag::err_opencl_builtin_expected_type) 408 << TheCall->getDirectCallee() << "block"; 409 return true; 410 } 411 return checkOpenCLBlockArgs(S, BlockArg); 412 } 413 414 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the 415 /// get_kernel_work_group_size 416 /// and get_kernel_preferred_work_group_size_multiple builtin functions. 417 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { 418 if (checkArgCount(S, TheCall, 1)) 419 return true; 420 421 Expr *BlockArg = TheCall->getArg(0); 422 if (!isBlockPointer(BlockArg)) { 423 S.Diag(BlockArg->getLocStart(), 424 diag::err_opencl_builtin_expected_type) 425 << TheCall->getDirectCallee() << "block"; 426 return true; 427 } 428 return checkOpenCLBlockArgs(S, BlockArg); 429 } 430 431 /// Diagnose integer type and any valid implicit conversion to it. 432 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, 433 const QualType &IntType); 434 435 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 436 unsigned Start, unsigned End) { 437 bool IllegalParams = false; 438 for (unsigned I = Start; I <= End; ++I) 439 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), 440 S.Context.getSizeType()); 441 return IllegalParams; 442 } 443 444 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 445 /// 'local void*' parameter of passed block. 446 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 447 Expr *BlockArg, 448 unsigned NumNonVarArgs) { 449 const BlockPointerType *BPT = 450 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 451 unsigned NumBlockParams = 452 BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams(); 453 unsigned TotalNumArgs = TheCall->getNumArgs(); 454 455 // For each argument passed to the block, a corresponding uint needs to 456 // be passed to describe the size of the local memory. 457 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 458 S.Diag(TheCall->getLocStart(), 459 diag::err_opencl_enqueue_kernel_local_size_args); 460 return true; 461 } 462 463 // Check that the sizes of the local memory are specified by integers. 464 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 465 TotalNumArgs - 1); 466 } 467 468 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 469 /// overload formats specified in Table 6.13.17.1. 470 /// int enqueue_kernel(queue_t queue, 471 /// kernel_enqueue_flags_t flags, 472 /// const ndrange_t ndrange, 473 /// void (^block)(void)) 474 /// int enqueue_kernel(queue_t queue, 475 /// kernel_enqueue_flags_t flags, 476 /// const ndrange_t ndrange, 477 /// uint num_events_in_wait_list, 478 /// clk_event_t *event_wait_list, 479 /// clk_event_t *event_ret, 480 /// void (^block)(void)) 481 /// int enqueue_kernel(queue_t queue, 482 /// kernel_enqueue_flags_t flags, 483 /// const ndrange_t ndrange, 484 /// void (^block)(local void*, ...), 485 /// uint size0, ...) 486 /// int enqueue_kernel(queue_t queue, 487 /// kernel_enqueue_flags_t flags, 488 /// const ndrange_t ndrange, 489 /// uint num_events_in_wait_list, 490 /// clk_event_t *event_wait_list, 491 /// clk_event_t *event_ret, 492 /// void (^block)(local void*, ...), 493 /// uint size0, ...) 494 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 495 unsigned NumArgs = TheCall->getNumArgs(); 496 497 if (NumArgs < 4) { 498 S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args); 499 return true; 500 } 501 502 Expr *Arg0 = TheCall->getArg(0); 503 Expr *Arg1 = TheCall->getArg(1); 504 Expr *Arg2 = TheCall->getArg(2); 505 Expr *Arg3 = TheCall->getArg(3); 506 507 // First argument always needs to be a queue_t type. 508 if (!Arg0->getType()->isQueueT()) { 509 S.Diag(TheCall->getArg(0)->getLocStart(), 510 diag::err_opencl_builtin_expected_type) 511 << TheCall->getDirectCallee() << S.Context.OCLQueueTy; 512 return true; 513 } 514 515 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 516 if (!Arg1->getType()->isIntegerType()) { 517 S.Diag(TheCall->getArg(1)->getLocStart(), 518 diag::err_opencl_builtin_expected_type) 519 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)"; 520 return true; 521 } 522 523 // Third argument is always an ndrange_t type. 524 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 525 S.Diag(TheCall->getArg(2)->getLocStart(), 526 diag::err_opencl_builtin_expected_type) 527 << TheCall->getDirectCallee() << "'ndrange_t'"; 528 return true; 529 } 530 531 // With four arguments, there is only one form that the function could be 532 // called in: no events and no variable arguments. 533 if (NumArgs == 4) { 534 // check that the last argument is the right block type. 535 if (!isBlockPointer(Arg3)) { 536 S.Diag(Arg3->getLocStart(), diag::err_opencl_builtin_expected_type) 537 << TheCall->getDirectCallee() << "block"; 538 return true; 539 } 540 // we have a block type, check the prototype 541 const BlockPointerType *BPT = 542 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 543 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) { 544 S.Diag(Arg3->getLocStart(), 545 diag::err_opencl_enqueue_kernel_blocks_no_args); 546 return true; 547 } 548 return false; 549 } 550 // we can have block + varargs. 551 if (isBlockPointer(Arg3)) 552 return (checkOpenCLBlockArgs(S, Arg3) || 553 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 554 // last two cases with either exactly 7 args or 7 args and varargs. 555 if (NumArgs >= 7) { 556 // check common block argument. 557 Expr *Arg6 = TheCall->getArg(6); 558 if (!isBlockPointer(Arg6)) { 559 S.Diag(Arg6->getLocStart(), diag::err_opencl_builtin_expected_type) 560 << TheCall->getDirectCallee() << "block"; 561 return true; 562 } 563 if (checkOpenCLBlockArgs(S, Arg6)) 564 return true; 565 566 // Forth argument has to be any integer type. 567 if (!Arg3->getType()->isIntegerType()) { 568 S.Diag(TheCall->getArg(3)->getLocStart(), 569 diag::err_opencl_builtin_expected_type) 570 << TheCall->getDirectCallee() << "integer"; 571 return true; 572 } 573 // check remaining common arguments. 574 Expr *Arg4 = TheCall->getArg(4); 575 Expr *Arg5 = TheCall->getArg(5); 576 577 // Fifth argument is always passed as a pointer to clk_event_t. 578 if (!Arg4->isNullPointerConstant(S.Context, 579 Expr::NPC_ValueDependentIsNotNull) && 580 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 581 S.Diag(TheCall->getArg(4)->getLocStart(), 582 diag::err_opencl_builtin_expected_type) 583 << TheCall->getDirectCallee() 584 << S.Context.getPointerType(S.Context.OCLClkEventTy); 585 return true; 586 } 587 588 // Sixth argument is always passed as a pointer to clk_event_t. 589 if (!Arg5->isNullPointerConstant(S.Context, 590 Expr::NPC_ValueDependentIsNotNull) && 591 !(Arg5->getType()->isPointerType() && 592 Arg5->getType()->getPointeeType()->isClkEventT())) { 593 S.Diag(TheCall->getArg(5)->getLocStart(), 594 diag::err_opencl_builtin_expected_type) 595 << TheCall->getDirectCallee() 596 << S.Context.getPointerType(S.Context.OCLClkEventTy); 597 return true; 598 } 599 600 if (NumArgs == 7) 601 return false; 602 603 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 604 } 605 606 // None of the specific case has been detected, give generic error 607 S.Diag(TheCall->getLocStart(), 608 diag::err_opencl_enqueue_kernel_incorrect_args); 609 return true; 610 } 611 612 /// Returns OpenCL access qual. 613 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 614 return D->getAttr<OpenCLAccessAttr>(); 615 } 616 617 /// Returns true if pipe element type is different from the pointer. 618 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 619 const Expr *Arg0 = Call->getArg(0); 620 // First argument type should always be pipe. 621 if (!Arg0->getType()->isPipeType()) { 622 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg) 623 << Call->getDirectCallee() << Arg0->getSourceRange(); 624 return true; 625 } 626 OpenCLAccessAttr *AccessQual = 627 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 628 // Validates the access qualifier is compatible with the call. 629 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 630 // read_only and write_only, and assumed to be read_only if no qualifier is 631 // specified. 632 switch (Call->getDirectCallee()->getBuiltinID()) { 633 case Builtin::BIread_pipe: 634 case Builtin::BIreserve_read_pipe: 635 case Builtin::BIcommit_read_pipe: 636 case Builtin::BIwork_group_reserve_read_pipe: 637 case Builtin::BIsub_group_reserve_read_pipe: 638 case Builtin::BIwork_group_commit_read_pipe: 639 case Builtin::BIsub_group_commit_read_pipe: 640 if (!(!AccessQual || AccessQual->isReadOnly())) { 641 S.Diag(Arg0->getLocStart(), 642 diag::err_opencl_builtin_pipe_invalid_access_modifier) 643 << "read_only" << Arg0->getSourceRange(); 644 return true; 645 } 646 break; 647 case Builtin::BIwrite_pipe: 648 case Builtin::BIreserve_write_pipe: 649 case Builtin::BIcommit_write_pipe: 650 case Builtin::BIwork_group_reserve_write_pipe: 651 case Builtin::BIsub_group_reserve_write_pipe: 652 case Builtin::BIwork_group_commit_write_pipe: 653 case Builtin::BIsub_group_commit_write_pipe: 654 if (!(AccessQual && AccessQual->isWriteOnly())) { 655 S.Diag(Arg0->getLocStart(), 656 diag::err_opencl_builtin_pipe_invalid_access_modifier) 657 << "write_only" << Arg0->getSourceRange(); 658 return true; 659 } 660 break; 661 default: 662 break; 663 } 664 return false; 665 } 666 667 /// Returns true if pipe element type is different from the pointer. 668 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 669 const Expr *Arg0 = Call->getArg(0); 670 const Expr *ArgIdx = Call->getArg(Idx); 671 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 672 const QualType EltTy = PipeTy->getElementType(); 673 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 674 // The Idx argument should be a pointer and the type of the pointer and 675 // the type of pipe element should also be the same. 676 if (!ArgTy || 677 !S.Context.hasSameType( 678 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 679 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 680 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 681 << ArgIdx->getType() << ArgIdx->getSourceRange(); 682 return true; 683 } 684 return false; 685 } 686 687 // Performs semantic analysis for the read/write_pipe call. 688 // \param S Reference to the semantic analyzer. 689 // \param Call A pointer to the builtin call. 690 // \return True if a semantic error has been found, false otherwise. 691 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 692 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 693 // functions have two forms. 694 switch (Call->getNumArgs()) { 695 case 2: 696 if (checkOpenCLPipeArg(S, Call)) 697 return true; 698 // The call with 2 arguments should be 699 // read/write_pipe(pipe T, T*). 700 // Check packet type T. 701 if (checkOpenCLPipePacketType(S, Call, 1)) 702 return true; 703 break; 704 705 case 4: { 706 if (checkOpenCLPipeArg(S, Call)) 707 return true; 708 // The call with 4 arguments should be 709 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 710 // Check reserve_id_t. 711 if (!Call->getArg(1)->getType()->isReserveIDT()) { 712 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 713 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 714 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 715 return true; 716 } 717 718 // Check the index. 719 const Expr *Arg2 = Call->getArg(2); 720 if (!Arg2->getType()->isIntegerType() && 721 !Arg2->getType()->isUnsignedIntegerType()) { 722 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 723 << Call->getDirectCallee() << S.Context.UnsignedIntTy 724 << Arg2->getType() << Arg2->getSourceRange(); 725 return true; 726 } 727 728 // Check packet type T. 729 if (checkOpenCLPipePacketType(S, Call, 3)) 730 return true; 731 } break; 732 default: 733 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num) 734 << Call->getDirectCallee() << Call->getSourceRange(); 735 return true; 736 } 737 738 return false; 739 } 740 741 // Performs a semantic analysis on the {work_group_/sub_group_ 742 // /_}reserve_{read/write}_pipe 743 // \param S Reference to the semantic analyzer. 744 // \param Call The call to the builtin function to be analyzed. 745 // \return True if a semantic error was found, false otherwise. 746 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 747 if (checkArgCount(S, Call, 2)) 748 return true; 749 750 if (checkOpenCLPipeArg(S, Call)) 751 return true; 752 753 // Check the reserve size. 754 if (!Call->getArg(1)->getType()->isIntegerType() && 755 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 756 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 757 << Call->getDirectCallee() << S.Context.UnsignedIntTy 758 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 759 return true; 760 } 761 762 // Since return type of reserve_read/write_pipe built-in function is 763 // reserve_id_t, which is not defined in the builtin def file , we used int 764 // as return type and need to override the return type of these functions. 765 Call->setType(S.Context.OCLReserveIDTy); 766 767 return false; 768 } 769 770 // Performs a semantic analysis on {work_group_/sub_group_ 771 // /_}commit_{read/write}_pipe 772 // \param S Reference to the semantic analyzer. 773 // \param Call The call to the builtin function to be analyzed. 774 // \return True if a semantic error was found, false otherwise. 775 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 776 if (checkArgCount(S, Call, 2)) 777 return true; 778 779 if (checkOpenCLPipeArg(S, Call)) 780 return true; 781 782 // Check reserve_id_t. 783 if (!Call->getArg(1)->getType()->isReserveIDT()) { 784 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 785 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 786 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 787 return true; 788 } 789 790 return false; 791 } 792 793 // Performs a semantic analysis on the call to built-in Pipe 794 // Query Functions. 795 // \param S Reference to the semantic analyzer. 796 // \param Call The call to the builtin function to be analyzed. 797 // \return True if a semantic error was found, false otherwise. 798 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 799 if (checkArgCount(S, Call, 1)) 800 return true; 801 802 if (!Call->getArg(0)->getType()->isPipeType()) { 803 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg) 804 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 805 return true; 806 } 807 808 return false; 809 } 810 811 // OpenCL v2.0 s6.13.9 - Address space qualifier functions. 812 // Performs semantic analysis for the to_global/local/private call. 813 // \param S Reference to the semantic analyzer. 814 // \param BuiltinID ID of the builtin function. 815 // \param Call A pointer to the builtin call. 816 // \return True if a semantic error has been found, false otherwise. 817 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 818 CallExpr *Call) { 819 if (Call->getNumArgs() != 1) { 820 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num) 821 << Call->getDirectCallee() << Call->getSourceRange(); 822 return true; 823 } 824 825 auto RT = Call->getArg(0)->getType(); 826 if (!RT->isPointerType() || RT->getPointeeType() 827 .getAddressSpace() == LangAS::opencl_constant) { 828 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg) 829 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 830 return true; 831 } 832 833 RT = RT->getPointeeType(); 834 auto Qual = RT.getQualifiers(); 835 switch (BuiltinID) { 836 case Builtin::BIto_global: 837 Qual.setAddressSpace(LangAS::opencl_global); 838 break; 839 case Builtin::BIto_local: 840 Qual.setAddressSpace(LangAS::opencl_local); 841 break; 842 case Builtin::BIto_private: 843 Qual.setAddressSpace(LangAS::opencl_private); 844 break; 845 default: 846 llvm_unreachable("Invalid builtin function"); 847 } 848 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 849 RT.getUnqualifiedType(), Qual))); 850 851 return false; 852 } 853 854 ExprResult 855 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 856 CallExpr *TheCall) { 857 ExprResult TheCallResult(TheCall); 858 859 // Find out if any arguments are required to be integer constant expressions. 860 unsigned ICEArguments = 0; 861 ASTContext::GetBuiltinTypeError Error; 862 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 863 if (Error != ASTContext::GE_None) 864 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 865 866 // If any arguments are required to be ICE's, check and diagnose. 867 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 868 // Skip arguments not required to be ICE's. 869 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 870 871 llvm::APSInt Result; 872 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 873 return true; 874 ICEArguments &= ~(1 << ArgNo); 875 } 876 877 switch (BuiltinID) { 878 case Builtin::BI__builtin___CFStringMakeConstantString: 879 assert(TheCall->getNumArgs() == 1 && 880 "Wrong # arguments to builtin CFStringMakeConstantString"); 881 if (CheckObjCString(TheCall->getArg(0))) 882 return ExprError(); 883 break; 884 case Builtin::BI__builtin_ms_va_start: 885 case Builtin::BI__builtin_stdarg_start: 886 case Builtin::BI__builtin_va_start: 887 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 888 return ExprError(); 889 break; 890 case Builtin::BI__va_start: { 891 switch (Context.getTargetInfo().getTriple().getArch()) { 892 case llvm::Triple::arm: 893 case llvm::Triple::thumb: 894 if (SemaBuiltinVAStartARMMicrosoft(TheCall)) 895 return ExprError(); 896 break; 897 default: 898 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 899 return ExprError(); 900 break; 901 } 902 break; 903 } 904 case Builtin::BI__builtin_isgreater: 905 case Builtin::BI__builtin_isgreaterequal: 906 case Builtin::BI__builtin_isless: 907 case Builtin::BI__builtin_islessequal: 908 case Builtin::BI__builtin_islessgreater: 909 case Builtin::BI__builtin_isunordered: 910 if (SemaBuiltinUnorderedCompare(TheCall)) 911 return ExprError(); 912 break; 913 case Builtin::BI__builtin_fpclassify: 914 if (SemaBuiltinFPClassification(TheCall, 6)) 915 return ExprError(); 916 break; 917 case Builtin::BI__builtin_isfinite: 918 case Builtin::BI__builtin_isinf: 919 case Builtin::BI__builtin_isinf_sign: 920 case Builtin::BI__builtin_isnan: 921 case Builtin::BI__builtin_isnormal: 922 if (SemaBuiltinFPClassification(TheCall, 1)) 923 return ExprError(); 924 break; 925 case Builtin::BI__builtin_shufflevector: 926 return SemaBuiltinShuffleVector(TheCall); 927 // TheCall will be freed by the smart pointer here, but that's fine, since 928 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 929 case Builtin::BI__builtin_prefetch: 930 if (SemaBuiltinPrefetch(TheCall)) 931 return ExprError(); 932 break; 933 case Builtin::BI__builtin_alloca_with_align: 934 if (SemaBuiltinAllocaWithAlign(TheCall)) 935 return ExprError(); 936 break; 937 case Builtin::BI__assume: 938 case Builtin::BI__builtin_assume: 939 if (SemaBuiltinAssume(TheCall)) 940 return ExprError(); 941 break; 942 case Builtin::BI__builtin_assume_aligned: 943 if (SemaBuiltinAssumeAligned(TheCall)) 944 return ExprError(); 945 break; 946 case Builtin::BI__builtin_object_size: 947 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 948 return ExprError(); 949 break; 950 case Builtin::BI__builtin_longjmp: 951 if (SemaBuiltinLongjmp(TheCall)) 952 return ExprError(); 953 break; 954 case Builtin::BI__builtin_setjmp: 955 if (SemaBuiltinSetjmp(TheCall)) 956 return ExprError(); 957 break; 958 case Builtin::BI_setjmp: 959 case Builtin::BI_setjmpex: 960 if (checkArgCount(*this, TheCall, 1)) 961 return true; 962 break; 963 case Builtin::BI__builtin_classify_type: 964 if (checkArgCount(*this, TheCall, 1)) return true; 965 TheCall->setType(Context.IntTy); 966 break; 967 case Builtin::BI__builtin_constant_p: 968 if (checkArgCount(*this, TheCall, 1)) return true; 969 TheCall->setType(Context.IntTy); 970 break; 971 case Builtin::BI__sync_fetch_and_add: 972 case Builtin::BI__sync_fetch_and_add_1: 973 case Builtin::BI__sync_fetch_and_add_2: 974 case Builtin::BI__sync_fetch_and_add_4: 975 case Builtin::BI__sync_fetch_and_add_8: 976 case Builtin::BI__sync_fetch_and_add_16: 977 case Builtin::BI__sync_fetch_and_sub: 978 case Builtin::BI__sync_fetch_and_sub_1: 979 case Builtin::BI__sync_fetch_and_sub_2: 980 case Builtin::BI__sync_fetch_and_sub_4: 981 case Builtin::BI__sync_fetch_and_sub_8: 982 case Builtin::BI__sync_fetch_and_sub_16: 983 case Builtin::BI__sync_fetch_and_or: 984 case Builtin::BI__sync_fetch_and_or_1: 985 case Builtin::BI__sync_fetch_and_or_2: 986 case Builtin::BI__sync_fetch_and_or_4: 987 case Builtin::BI__sync_fetch_and_or_8: 988 case Builtin::BI__sync_fetch_and_or_16: 989 case Builtin::BI__sync_fetch_and_and: 990 case Builtin::BI__sync_fetch_and_and_1: 991 case Builtin::BI__sync_fetch_and_and_2: 992 case Builtin::BI__sync_fetch_and_and_4: 993 case Builtin::BI__sync_fetch_and_and_8: 994 case Builtin::BI__sync_fetch_and_and_16: 995 case Builtin::BI__sync_fetch_and_xor: 996 case Builtin::BI__sync_fetch_and_xor_1: 997 case Builtin::BI__sync_fetch_and_xor_2: 998 case Builtin::BI__sync_fetch_and_xor_4: 999 case Builtin::BI__sync_fetch_and_xor_8: 1000 case Builtin::BI__sync_fetch_and_xor_16: 1001 case Builtin::BI__sync_fetch_and_nand: 1002 case Builtin::BI__sync_fetch_and_nand_1: 1003 case Builtin::BI__sync_fetch_and_nand_2: 1004 case Builtin::BI__sync_fetch_and_nand_4: 1005 case Builtin::BI__sync_fetch_and_nand_8: 1006 case Builtin::BI__sync_fetch_and_nand_16: 1007 case Builtin::BI__sync_add_and_fetch: 1008 case Builtin::BI__sync_add_and_fetch_1: 1009 case Builtin::BI__sync_add_and_fetch_2: 1010 case Builtin::BI__sync_add_and_fetch_4: 1011 case Builtin::BI__sync_add_and_fetch_8: 1012 case Builtin::BI__sync_add_and_fetch_16: 1013 case Builtin::BI__sync_sub_and_fetch: 1014 case Builtin::BI__sync_sub_and_fetch_1: 1015 case Builtin::BI__sync_sub_and_fetch_2: 1016 case Builtin::BI__sync_sub_and_fetch_4: 1017 case Builtin::BI__sync_sub_and_fetch_8: 1018 case Builtin::BI__sync_sub_and_fetch_16: 1019 case Builtin::BI__sync_and_and_fetch: 1020 case Builtin::BI__sync_and_and_fetch_1: 1021 case Builtin::BI__sync_and_and_fetch_2: 1022 case Builtin::BI__sync_and_and_fetch_4: 1023 case Builtin::BI__sync_and_and_fetch_8: 1024 case Builtin::BI__sync_and_and_fetch_16: 1025 case Builtin::BI__sync_or_and_fetch: 1026 case Builtin::BI__sync_or_and_fetch_1: 1027 case Builtin::BI__sync_or_and_fetch_2: 1028 case Builtin::BI__sync_or_and_fetch_4: 1029 case Builtin::BI__sync_or_and_fetch_8: 1030 case Builtin::BI__sync_or_and_fetch_16: 1031 case Builtin::BI__sync_xor_and_fetch: 1032 case Builtin::BI__sync_xor_and_fetch_1: 1033 case Builtin::BI__sync_xor_and_fetch_2: 1034 case Builtin::BI__sync_xor_and_fetch_4: 1035 case Builtin::BI__sync_xor_and_fetch_8: 1036 case Builtin::BI__sync_xor_and_fetch_16: 1037 case Builtin::BI__sync_nand_and_fetch: 1038 case Builtin::BI__sync_nand_and_fetch_1: 1039 case Builtin::BI__sync_nand_and_fetch_2: 1040 case Builtin::BI__sync_nand_and_fetch_4: 1041 case Builtin::BI__sync_nand_and_fetch_8: 1042 case Builtin::BI__sync_nand_and_fetch_16: 1043 case Builtin::BI__sync_val_compare_and_swap: 1044 case Builtin::BI__sync_val_compare_and_swap_1: 1045 case Builtin::BI__sync_val_compare_and_swap_2: 1046 case Builtin::BI__sync_val_compare_and_swap_4: 1047 case Builtin::BI__sync_val_compare_and_swap_8: 1048 case Builtin::BI__sync_val_compare_and_swap_16: 1049 case Builtin::BI__sync_bool_compare_and_swap: 1050 case Builtin::BI__sync_bool_compare_and_swap_1: 1051 case Builtin::BI__sync_bool_compare_and_swap_2: 1052 case Builtin::BI__sync_bool_compare_and_swap_4: 1053 case Builtin::BI__sync_bool_compare_and_swap_8: 1054 case Builtin::BI__sync_bool_compare_and_swap_16: 1055 case Builtin::BI__sync_lock_test_and_set: 1056 case Builtin::BI__sync_lock_test_and_set_1: 1057 case Builtin::BI__sync_lock_test_and_set_2: 1058 case Builtin::BI__sync_lock_test_and_set_4: 1059 case Builtin::BI__sync_lock_test_and_set_8: 1060 case Builtin::BI__sync_lock_test_and_set_16: 1061 case Builtin::BI__sync_lock_release: 1062 case Builtin::BI__sync_lock_release_1: 1063 case Builtin::BI__sync_lock_release_2: 1064 case Builtin::BI__sync_lock_release_4: 1065 case Builtin::BI__sync_lock_release_8: 1066 case Builtin::BI__sync_lock_release_16: 1067 case Builtin::BI__sync_swap: 1068 case Builtin::BI__sync_swap_1: 1069 case Builtin::BI__sync_swap_2: 1070 case Builtin::BI__sync_swap_4: 1071 case Builtin::BI__sync_swap_8: 1072 case Builtin::BI__sync_swap_16: 1073 return SemaBuiltinAtomicOverloaded(TheCallResult); 1074 case Builtin::BI__builtin_nontemporal_load: 1075 case Builtin::BI__builtin_nontemporal_store: 1076 return SemaBuiltinNontemporalOverloaded(TheCallResult); 1077 #define BUILTIN(ID, TYPE, ATTRS) 1078 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 1079 case Builtin::BI##ID: \ 1080 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 1081 #include "clang/Basic/Builtins.def" 1082 case Builtin::BI__annotation: 1083 if (SemaBuiltinMSVCAnnotation(*this, TheCall)) 1084 return ExprError(); 1085 break; 1086 case Builtin::BI__builtin_annotation: 1087 if (SemaBuiltinAnnotation(*this, TheCall)) 1088 return ExprError(); 1089 break; 1090 case Builtin::BI__builtin_addressof: 1091 if (SemaBuiltinAddressof(*this, TheCall)) 1092 return ExprError(); 1093 break; 1094 case Builtin::BI__builtin_add_overflow: 1095 case Builtin::BI__builtin_sub_overflow: 1096 case Builtin::BI__builtin_mul_overflow: 1097 if (SemaBuiltinOverflow(*this, TheCall)) 1098 return ExprError(); 1099 break; 1100 case Builtin::BI__builtin_operator_new: 1101 case Builtin::BI__builtin_operator_delete: { 1102 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete; 1103 ExprResult Res = 1104 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete); 1105 if (Res.isInvalid()) 1106 CorrectDelayedTyposInExpr(TheCallResult.get()); 1107 return Res; 1108 } 1109 case Builtin::BI__builtin_dump_struct: { 1110 // We first want to ensure we are called with 2 arguments 1111 if (checkArgCount(*this, TheCall, 2)) 1112 return ExprError(); 1113 // Ensure that the first argument is of type 'struct XX *' 1114 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts(); 1115 const QualType PtrArgType = PtrArg->getType(); 1116 if (!PtrArgType->isPointerType() || 1117 !PtrArgType->getPointeeType()->isRecordType()) { 1118 Diag(PtrArg->getLocStart(), diag::err_typecheck_convert_incompatible) 1119 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType 1120 << "structure pointer"; 1121 return ExprError(); 1122 } 1123 1124 // Ensure that the second argument is of type 'FunctionType' 1125 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts(); 1126 const QualType FnPtrArgType = FnPtrArg->getType(); 1127 if (!FnPtrArgType->isPointerType()) { 1128 Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible) 1129 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1130 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1131 return ExprError(); 1132 } 1133 1134 const auto *FuncType = 1135 FnPtrArgType->getPointeeType()->getAs<FunctionType>(); 1136 1137 if (!FuncType) { 1138 Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible) 1139 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1140 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1141 return ExprError(); 1142 } 1143 1144 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) { 1145 if (!FT->getNumParams()) { 1146 Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible) 1147 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1148 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1149 return ExprError(); 1150 } 1151 QualType PT = FT->getParamType(0); 1152 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy || 1153 !PT->isPointerType() || !PT->getPointeeType()->isCharType() || 1154 !PT->getPointeeType().isConstQualified()) { 1155 Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible) 1156 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1157 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1158 return ExprError(); 1159 } 1160 } 1161 1162 TheCall->setType(Context.IntTy); 1163 break; 1164 } 1165 1166 // check secure string manipulation functions where overflows 1167 // are detectable at compile time 1168 case Builtin::BI__builtin___memcpy_chk: 1169 case Builtin::BI__builtin___memmove_chk: 1170 case Builtin::BI__builtin___memset_chk: 1171 case Builtin::BI__builtin___strlcat_chk: 1172 case Builtin::BI__builtin___strlcpy_chk: 1173 case Builtin::BI__builtin___strncat_chk: 1174 case Builtin::BI__builtin___strncpy_chk: 1175 case Builtin::BI__builtin___stpncpy_chk: 1176 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3); 1177 break; 1178 case Builtin::BI__builtin___memccpy_chk: 1179 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4); 1180 break; 1181 case Builtin::BI__builtin___snprintf_chk: 1182 case Builtin::BI__builtin___vsnprintf_chk: 1183 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3); 1184 break; 1185 case Builtin::BI__builtin_call_with_static_chain: 1186 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 1187 return ExprError(); 1188 break; 1189 case Builtin::BI__exception_code: 1190 case Builtin::BI_exception_code: 1191 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1192 diag::err_seh___except_block)) 1193 return ExprError(); 1194 break; 1195 case Builtin::BI__exception_info: 1196 case Builtin::BI_exception_info: 1197 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1198 diag::err_seh___except_filter)) 1199 return ExprError(); 1200 break; 1201 case Builtin::BI__GetExceptionInfo: 1202 if (checkArgCount(*this, TheCall, 1)) 1203 return ExprError(); 1204 1205 if (CheckCXXThrowOperand( 1206 TheCall->getLocStart(), 1207 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1208 TheCall)) 1209 return ExprError(); 1210 1211 TheCall->setType(Context.VoidPtrTy); 1212 break; 1213 // OpenCL v2.0, s6.13.16 - Pipe functions 1214 case Builtin::BIread_pipe: 1215 case Builtin::BIwrite_pipe: 1216 // Since those two functions are declared with var args, we need a semantic 1217 // check for the argument. 1218 if (SemaBuiltinRWPipe(*this, TheCall)) 1219 return ExprError(); 1220 TheCall->setType(Context.IntTy); 1221 break; 1222 case Builtin::BIreserve_read_pipe: 1223 case Builtin::BIreserve_write_pipe: 1224 case Builtin::BIwork_group_reserve_read_pipe: 1225 case Builtin::BIwork_group_reserve_write_pipe: 1226 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1227 return ExprError(); 1228 break; 1229 case Builtin::BIsub_group_reserve_read_pipe: 1230 case Builtin::BIsub_group_reserve_write_pipe: 1231 if (checkOpenCLSubgroupExt(*this, TheCall) || 1232 SemaBuiltinReserveRWPipe(*this, TheCall)) 1233 return ExprError(); 1234 break; 1235 case Builtin::BIcommit_read_pipe: 1236 case Builtin::BIcommit_write_pipe: 1237 case Builtin::BIwork_group_commit_read_pipe: 1238 case Builtin::BIwork_group_commit_write_pipe: 1239 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1240 return ExprError(); 1241 break; 1242 case Builtin::BIsub_group_commit_read_pipe: 1243 case Builtin::BIsub_group_commit_write_pipe: 1244 if (checkOpenCLSubgroupExt(*this, TheCall) || 1245 SemaBuiltinCommitRWPipe(*this, TheCall)) 1246 return ExprError(); 1247 break; 1248 case Builtin::BIget_pipe_num_packets: 1249 case Builtin::BIget_pipe_max_packets: 1250 if (SemaBuiltinPipePackets(*this, TheCall)) 1251 return ExprError(); 1252 TheCall->setType(Context.UnsignedIntTy); 1253 break; 1254 case Builtin::BIto_global: 1255 case Builtin::BIto_local: 1256 case Builtin::BIto_private: 1257 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1258 return ExprError(); 1259 break; 1260 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1261 case Builtin::BIenqueue_kernel: 1262 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1263 return ExprError(); 1264 break; 1265 case Builtin::BIget_kernel_work_group_size: 1266 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1267 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1268 return ExprError(); 1269 break; 1270 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 1271 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 1272 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) 1273 return ExprError(); 1274 break; 1275 case Builtin::BI__builtin_os_log_format: 1276 case Builtin::BI__builtin_os_log_format_buffer_size: 1277 if (SemaBuiltinOSLogFormat(TheCall)) 1278 return ExprError(); 1279 break; 1280 } 1281 1282 // Since the target specific builtins for each arch overlap, only check those 1283 // of the arch we are compiling for. 1284 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 1285 switch (Context.getTargetInfo().getTriple().getArch()) { 1286 case llvm::Triple::arm: 1287 case llvm::Triple::armeb: 1288 case llvm::Triple::thumb: 1289 case llvm::Triple::thumbeb: 1290 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall)) 1291 return ExprError(); 1292 break; 1293 case llvm::Triple::aarch64: 1294 case llvm::Triple::aarch64_be: 1295 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall)) 1296 return ExprError(); 1297 break; 1298 case llvm::Triple::hexagon: 1299 if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall)) 1300 return ExprError(); 1301 break; 1302 case llvm::Triple::mips: 1303 case llvm::Triple::mipsel: 1304 case llvm::Triple::mips64: 1305 case llvm::Triple::mips64el: 1306 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall)) 1307 return ExprError(); 1308 break; 1309 case llvm::Triple::systemz: 1310 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall)) 1311 return ExprError(); 1312 break; 1313 case llvm::Triple::x86: 1314 case llvm::Triple::x86_64: 1315 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall)) 1316 return ExprError(); 1317 break; 1318 case llvm::Triple::ppc: 1319 case llvm::Triple::ppc64: 1320 case llvm::Triple::ppc64le: 1321 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall)) 1322 return ExprError(); 1323 break; 1324 default: 1325 break; 1326 } 1327 } 1328 1329 return TheCallResult; 1330 } 1331 1332 // Get the valid immediate range for the specified NEON type code. 1333 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 1334 NeonTypeFlags Type(t); 1335 int IsQuad = ForceQuad ? true : Type.isQuad(); 1336 switch (Type.getEltType()) { 1337 case NeonTypeFlags::Int8: 1338 case NeonTypeFlags::Poly8: 1339 return shift ? 7 : (8 << IsQuad) - 1; 1340 case NeonTypeFlags::Int16: 1341 case NeonTypeFlags::Poly16: 1342 return shift ? 15 : (4 << IsQuad) - 1; 1343 case NeonTypeFlags::Int32: 1344 return shift ? 31 : (2 << IsQuad) - 1; 1345 case NeonTypeFlags::Int64: 1346 case NeonTypeFlags::Poly64: 1347 return shift ? 63 : (1 << IsQuad) - 1; 1348 case NeonTypeFlags::Poly128: 1349 return shift ? 127 : (1 << IsQuad) - 1; 1350 case NeonTypeFlags::Float16: 1351 assert(!shift && "cannot shift float types!"); 1352 return (4 << IsQuad) - 1; 1353 case NeonTypeFlags::Float32: 1354 assert(!shift && "cannot shift float types!"); 1355 return (2 << IsQuad) - 1; 1356 case NeonTypeFlags::Float64: 1357 assert(!shift && "cannot shift float types!"); 1358 return (1 << IsQuad) - 1; 1359 } 1360 llvm_unreachable("Invalid NeonTypeFlag!"); 1361 } 1362 1363 /// getNeonEltType - Return the QualType corresponding to the elements of 1364 /// the vector type specified by the NeonTypeFlags. This is used to check 1365 /// the pointer arguments for Neon load/store intrinsics. 1366 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 1367 bool IsPolyUnsigned, bool IsInt64Long) { 1368 switch (Flags.getEltType()) { 1369 case NeonTypeFlags::Int8: 1370 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 1371 case NeonTypeFlags::Int16: 1372 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 1373 case NeonTypeFlags::Int32: 1374 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 1375 case NeonTypeFlags::Int64: 1376 if (IsInt64Long) 1377 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 1378 else 1379 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 1380 : Context.LongLongTy; 1381 case NeonTypeFlags::Poly8: 1382 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 1383 case NeonTypeFlags::Poly16: 1384 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 1385 case NeonTypeFlags::Poly64: 1386 if (IsInt64Long) 1387 return Context.UnsignedLongTy; 1388 else 1389 return Context.UnsignedLongLongTy; 1390 case NeonTypeFlags::Poly128: 1391 break; 1392 case NeonTypeFlags::Float16: 1393 return Context.HalfTy; 1394 case NeonTypeFlags::Float32: 1395 return Context.FloatTy; 1396 case NeonTypeFlags::Float64: 1397 return Context.DoubleTy; 1398 } 1399 llvm_unreachable("Invalid NeonTypeFlag!"); 1400 } 1401 1402 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1403 llvm::APSInt Result; 1404 uint64_t mask = 0; 1405 unsigned TV = 0; 1406 int PtrArgNum = -1; 1407 bool HasConstPtr = false; 1408 switch (BuiltinID) { 1409 #define GET_NEON_OVERLOAD_CHECK 1410 #include "clang/Basic/arm_neon.inc" 1411 #include "clang/Basic/arm_fp16.inc" 1412 #undef GET_NEON_OVERLOAD_CHECK 1413 } 1414 1415 // For NEON intrinsics which are overloaded on vector element type, validate 1416 // the immediate which specifies which variant to emit. 1417 unsigned ImmArg = TheCall->getNumArgs()-1; 1418 if (mask) { 1419 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 1420 return true; 1421 1422 TV = Result.getLimitedValue(64); 1423 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 1424 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code) 1425 << TheCall->getArg(ImmArg)->getSourceRange(); 1426 } 1427 1428 if (PtrArgNum >= 0) { 1429 // Check that pointer arguments have the specified type. 1430 Expr *Arg = TheCall->getArg(PtrArgNum); 1431 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 1432 Arg = ICE->getSubExpr(); 1433 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 1434 QualType RHSTy = RHS.get()->getType(); 1435 1436 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 1437 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 1438 Arch == llvm::Triple::aarch64_be; 1439 bool IsInt64Long = 1440 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong; 1441 QualType EltTy = 1442 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 1443 if (HasConstPtr) 1444 EltTy = EltTy.withConst(); 1445 QualType LHSTy = Context.getPointerType(EltTy); 1446 AssignConvertType ConvTy; 1447 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 1448 if (RHS.isInvalid()) 1449 return true; 1450 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy, 1451 RHS.get(), AA_Assigning)) 1452 return true; 1453 } 1454 1455 // For NEON intrinsics which take an immediate value as part of the 1456 // instruction, range check them here. 1457 unsigned i = 0, l = 0, u = 0; 1458 switch (BuiltinID) { 1459 default: 1460 return false; 1461 #define GET_NEON_IMMEDIATE_CHECK 1462 #include "clang/Basic/arm_neon.inc" 1463 #include "clang/Basic/arm_fp16.inc" 1464 #undef GET_NEON_IMMEDIATE_CHECK 1465 } 1466 1467 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1468 } 1469 1470 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 1471 unsigned MaxWidth) { 1472 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 1473 BuiltinID == ARM::BI__builtin_arm_ldaex || 1474 BuiltinID == ARM::BI__builtin_arm_strex || 1475 BuiltinID == ARM::BI__builtin_arm_stlex || 1476 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1477 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1478 BuiltinID == AArch64::BI__builtin_arm_strex || 1479 BuiltinID == AArch64::BI__builtin_arm_stlex) && 1480 "unexpected ARM builtin"); 1481 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 1482 BuiltinID == ARM::BI__builtin_arm_ldaex || 1483 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1484 BuiltinID == AArch64::BI__builtin_arm_ldaex; 1485 1486 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 1487 1488 // Ensure that we have the proper number of arguments. 1489 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 1490 return true; 1491 1492 // Inspect the pointer argument of the atomic builtin. This should always be 1493 // a pointer type, whose element is an integral scalar or pointer type. 1494 // Because it is a pointer type, we don't have to worry about any implicit 1495 // casts here. 1496 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 1497 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 1498 if (PointerArgRes.isInvalid()) 1499 return true; 1500 PointerArg = PointerArgRes.get(); 1501 1502 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 1503 if (!pointerType) { 1504 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 1505 << PointerArg->getType() << PointerArg->getSourceRange(); 1506 return true; 1507 } 1508 1509 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 1510 // task is to insert the appropriate casts into the AST. First work out just 1511 // what the appropriate type is. 1512 QualType ValType = pointerType->getPointeeType(); 1513 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 1514 if (IsLdrex) 1515 AddrType.addConst(); 1516 1517 // Issue a warning if the cast is dodgy. 1518 CastKind CastNeeded = CK_NoOp; 1519 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 1520 CastNeeded = CK_BitCast; 1521 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers) 1522 << PointerArg->getType() 1523 << Context.getPointerType(AddrType) 1524 << AA_Passing << PointerArg->getSourceRange(); 1525 } 1526 1527 // Finally, do the cast and replace the argument with the corrected version. 1528 AddrType = Context.getPointerType(AddrType); 1529 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 1530 if (PointerArgRes.isInvalid()) 1531 return true; 1532 PointerArg = PointerArgRes.get(); 1533 1534 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 1535 1536 // In general, we allow ints, floats and pointers to be loaded and stored. 1537 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 1538 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 1539 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 1540 << PointerArg->getType() << PointerArg->getSourceRange(); 1541 return true; 1542 } 1543 1544 // But ARM doesn't have instructions to deal with 128-bit versions. 1545 if (Context.getTypeSize(ValType) > MaxWidth) { 1546 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 1547 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size) 1548 << PointerArg->getType() << PointerArg->getSourceRange(); 1549 return true; 1550 } 1551 1552 switch (ValType.getObjCLifetime()) { 1553 case Qualifiers::OCL_None: 1554 case Qualifiers::OCL_ExplicitNone: 1555 // okay 1556 break; 1557 1558 case Qualifiers::OCL_Weak: 1559 case Qualifiers::OCL_Strong: 1560 case Qualifiers::OCL_Autoreleasing: 1561 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 1562 << ValType << PointerArg->getSourceRange(); 1563 return true; 1564 } 1565 1566 if (IsLdrex) { 1567 TheCall->setType(ValType); 1568 return false; 1569 } 1570 1571 // Initialize the argument to be stored. 1572 ExprResult ValArg = TheCall->getArg(0); 1573 InitializedEntity Entity = InitializedEntity::InitializeParameter( 1574 Context, ValType, /*consume*/ false); 1575 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 1576 if (ValArg.isInvalid()) 1577 return true; 1578 TheCall->setArg(0, ValArg.get()); 1579 1580 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 1581 // but the custom checker bypasses all default analysis. 1582 TheCall->setType(Context.IntTy); 1583 return false; 1584 } 1585 1586 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1587 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 1588 BuiltinID == ARM::BI__builtin_arm_ldaex || 1589 BuiltinID == ARM::BI__builtin_arm_strex || 1590 BuiltinID == ARM::BI__builtin_arm_stlex) { 1591 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 1592 } 1593 1594 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 1595 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1596 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 1597 } 1598 1599 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 1600 BuiltinID == ARM::BI__builtin_arm_wsr64) 1601 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 1602 1603 if (BuiltinID == ARM::BI__builtin_arm_rsr || 1604 BuiltinID == ARM::BI__builtin_arm_rsrp || 1605 BuiltinID == ARM::BI__builtin_arm_wsr || 1606 BuiltinID == ARM::BI__builtin_arm_wsrp) 1607 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1608 1609 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1610 return true; 1611 1612 // For intrinsics which take an immediate value as part of the instruction, 1613 // range check them here. 1614 // FIXME: VFP Intrinsics should error if VFP not present. 1615 switch (BuiltinID) { 1616 default: return false; 1617 case ARM::BI__builtin_arm_ssat: 1618 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32); 1619 case ARM::BI__builtin_arm_usat: 1620 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31); 1621 case ARM::BI__builtin_arm_ssat16: 1622 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 1623 case ARM::BI__builtin_arm_usat16: 1624 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 1625 case ARM::BI__builtin_arm_vcvtr_f: 1626 case ARM::BI__builtin_arm_vcvtr_d: 1627 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 1628 case ARM::BI__builtin_arm_dmb: 1629 case ARM::BI__builtin_arm_dsb: 1630 case ARM::BI__builtin_arm_isb: 1631 case ARM::BI__builtin_arm_dbg: 1632 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15); 1633 } 1634 } 1635 1636 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, 1637 CallExpr *TheCall) { 1638 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 1639 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1640 BuiltinID == AArch64::BI__builtin_arm_strex || 1641 BuiltinID == AArch64::BI__builtin_arm_stlex) { 1642 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 1643 } 1644 1645 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 1646 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1647 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 1648 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 1649 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 1650 } 1651 1652 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 1653 BuiltinID == AArch64::BI__builtin_arm_wsr64) 1654 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1655 1656 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 1657 BuiltinID == AArch64::BI__builtin_arm_rsrp || 1658 BuiltinID == AArch64::BI__builtin_arm_wsr || 1659 BuiltinID == AArch64::BI__builtin_arm_wsrp) 1660 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1661 1662 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1663 return true; 1664 1665 // For intrinsics which take an immediate value as part of the instruction, 1666 // range check them here. 1667 unsigned i = 0, l = 0, u = 0; 1668 switch (BuiltinID) { 1669 default: return false; 1670 case AArch64::BI__builtin_arm_dmb: 1671 case AArch64::BI__builtin_arm_dsb: 1672 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 1673 } 1674 1675 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1676 } 1677 1678 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, 1679 CallExpr *TheCall) { 1680 struct ArgInfo { 1681 ArgInfo(unsigned O, bool S, unsigned W, unsigned A) 1682 : OpNum(O), IsSigned(S), BitWidth(W), Align(A) {} 1683 unsigned OpNum = 0; 1684 bool IsSigned = false; 1685 unsigned BitWidth = 0; 1686 unsigned Align = 0; 1687 }; 1688 1689 static const std::map<unsigned, std::vector<ArgInfo>> Infos = { 1690 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} }, 1691 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} }, 1692 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} }, 1693 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 0 }} }, 1694 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} }, 1695 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} }, 1696 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} }, 1697 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} }, 1698 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} }, 1699 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} }, 1700 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} }, 1701 1702 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} }, 1703 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} }, 1704 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} }, 1705 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} }, 1706 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} }, 1707 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} }, 1708 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} }, 1709 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} }, 1710 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} }, 1711 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} }, 1712 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} }, 1713 1714 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} }, 1715 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} }, 1716 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} }, 1717 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} }, 1718 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} }, 1719 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} }, 1720 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} }, 1721 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} }, 1722 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} }, 1723 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} }, 1724 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} }, 1725 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} }, 1726 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} }, 1727 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} }, 1728 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} }, 1729 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} }, 1730 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} }, 1731 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} }, 1732 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} }, 1733 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} }, 1734 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} }, 1735 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} }, 1736 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} }, 1737 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} }, 1738 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} }, 1739 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} }, 1740 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} }, 1741 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} }, 1742 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} }, 1743 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} }, 1744 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} }, 1745 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} }, 1746 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} }, 1747 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} }, 1748 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} }, 1749 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} }, 1750 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} }, 1751 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} }, 1752 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} }, 1753 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} }, 1754 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} }, 1755 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} }, 1756 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} }, 1757 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} }, 1758 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} }, 1759 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} }, 1760 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} }, 1761 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} }, 1762 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} }, 1763 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} }, 1764 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} }, 1765 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax, 1766 {{ 1, false, 6, 0 }} }, 1767 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} }, 1768 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} }, 1769 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} }, 1770 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} }, 1771 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} }, 1772 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} }, 1773 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax, 1774 {{ 1, false, 5, 0 }} }, 1775 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} }, 1776 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} }, 1777 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} }, 1778 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} }, 1779 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} }, 1780 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 }, 1781 { 2, false, 5, 0 }} }, 1782 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 }, 1783 { 2, false, 6, 0 }} }, 1784 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 }, 1785 { 3, false, 5, 0 }} }, 1786 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 }, 1787 { 3, false, 6, 0 }} }, 1788 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} }, 1789 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} }, 1790 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} }, 1791 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} }, 1792 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} }, 1793 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} }, 1794 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} }, 1795 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} }, 1796 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} }, 1797 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} }, 1798 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} }, 1799 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} }, 1800 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} }, 1801 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} }, 1802 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} }, 1803 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax, 1804 {{ 2, false, 4, 0 }, 1805 { 3, false, 5, 0 }} }, 1806 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax, 1807 {{ 2, false, 4, 0 }, 1808 { 3, false, 5, 0 }} }, 1809 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax, 1810 {{ 2, false, 4, 0 }, 1811 { 3, false, 5, 0 }} }, 1812 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax, 1813 {{ 2, false, 4, 0 }, 1814 { 3, false, 5, 0 }} }, 1815 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} }, 1816 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} }, 1817 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} }, 1818 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} }, 1819 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} }, 1820 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} }, 1821 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} }, 1822 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} }, 1823 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} }, 1824 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} }, 1825 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 }, 1826 { 2, false, 5, 0 }} }, 1827 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 }, 1828 { 2, false, 6, 0 }} }, 1829 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} }, 1830 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} }, 1831 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} }, 1832 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} }, 1833 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} }, 1834 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} }, 1835 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} }, 1836 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} }, 1837 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax, 1838 {{ 1, false, 4, 0 }} }, 1839 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} }, 1840 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax, 1841 {{ 1, false, 4, 0 }} }, 1842 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} }, 1843 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} }, 1844 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} }, 1845 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} }, 1846 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} }, 1847 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} }, 1848 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} }, 1849 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} }, 1850 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} }, 1851 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} }, 1852 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} }, 1853 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} }, 1854 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} }, 1855 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} }, 1856 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} }, 1857 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} }, 1858 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} }, 1859 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} }, 1860 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} }, 1861 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, 1862 {{ 3, false, 1, 0 }} }, 1863 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} }, 1864 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} }, 1865 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} }, 1866 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, 1867 {{ 3, false, 1, 0 }} }, 1868 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} }, 1869 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} }, 1870 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} }, 1871 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, 1872 {{ 3, false, 1, 0 }} }, 1873 }; 1874 1875 auto F = Infos.find(BuiltinID); 1876 if (F == Infos.end()) 1877 return false; 1878 1879 bool Error = false; 1880 1881 for (const ArgInfo &A : F->second) { 1882 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth-1)) : 0; 1883 int32_t Max = (1 << (A.IsSigned ? A.BitWidth-1 : A.BitWidth)) - 1; 1884 if (!A.Align) { 1885 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 1886 } else { 1887 unsigned M = 1 << A.Align; 1888 Min *= M; 1889 Max *= M; 1890 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) | 1891 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M); 1892 } 1893 } 1894 return Error; 1895 } 1896 1897 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the 1898 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 1899 // ordering for DSP is unspecified. MSA is ordered by the data format used 1900 // by the underlying instruction i.e., df/m, df/n and then by size. 1901 // 1902 // FIXME: The size tests here should instead be tablegen'd along with the 1903 // definitions from include/clang/Basic/BuiltinsMips.def. 1904 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 1905 // be too. 1906 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1907 unsigned i = 0, l = 0, u = 0, m = 0; 1908 switch (BuiltinID) { 1909 default: return false; 1910 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 1911 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 1912 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 1913 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 1914 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 1915 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 1916 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 1917 // MSA instrinsics. Instructions (which the intrinsics maps to) which use the 1918 // df/m field. 1919 // These intrinsics take an unsigned 3 bit immediate. 1920 case Mips::BI__builtin_msa_bclri_b: 1921 case Mips::BI__builtin_msa_bnegi_b: 1922 case Mips::BI__builtin_msa_bseti_b: 1923 case Mips::BI__builtin_msa_sat_s_b: 1924 case Mips::BI__builtin_msa_sat_u_b: 1925 case Mips::BI__builtin_msa_slli_b: 1926 case Mips::BI__builtin_msa_srai_b: 1927 case Mips::BI__builtin_msa_srari_b: 1928 case Mips::BI__builtin_msa_srli_b: 1929 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 1930 case Mips::BI__builtin_msa_binsli_b: 1931 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 1932 // These intrinsics take an unsigned 4 bit immediate. 1933 case Mips::BI__builtin_msa_bclri_h: 1934 case Mips::BI__builtin_msa_bnegi_h: 1935 case Mips::BI__builtin_msa_bseti_h: 1936 case Mips::BI__builtin_msa_sat_s_h: 1937 case Mips::BI__builtin_msa_sat_u_h: 1938 case Mips::BI__builtin_msa_slli_h: 1939 case Mips::BI__builtin_msa_srai_h: 1940 case Mips::BI__builtin_msa_srari_h: 1941 case Mips::BI__builtin_msa_srli_h: 1942 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 1943 case Mips::BI__builtin_msa_binsli_h: 1944 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 1945 // These intrinsics take an unsigned 5 bit immediate. 1946 // The first block of intrinsics actually have an unsigned 5 bit field, 1947 // not a df/n field. 1948 case Mips::BI__builtin_msa_clei_u_b: 1949 case Mips::BI__builtin_msa_clei_u_h: 1950 case Mips::BI__builtin_msa_clei_u_w: 1951 case Mips::BI__builtin_msa_clei_u_d: 1952 case Mips::BI__builtin_msa_clti_u_b: 1953 case Mips::BI__builtin_msa_clti_u_h: 1954 case Mips::BI__builtin_msa_clti_u_w: 1955 case Mips::BI__builtin_msa_clti_u_d: 1956 case Mips::BI__builtin_msa_maxi_u_b: 1957 case Mips::BI__builtin_msa_maxi_u_h: 1958 case Mips::BI__builtin_msa_maxi_u_w: 1959 case Mips::BI__builtin_msa_maxi_u_d: 1960 case Mips::BI__builtin_msa_mini_u_b: 1961 case Mips::BI__builtin_msa_mini_u_h: 1962 case Mips::BI__builtin_msa_mini_u_w: 1963 case Mips::BI__builtin_msa_mini_u_d: 1964 case Mips::BI__builtin_msa_addvi_b: 1965 case Mips::BI__builtin_msa_addvi_h: 1966 case Mips::BI__builtin_msa_addvi_w: 1967 case Mips::BI__builtin_msa_addvi_d: 1968 case Mips::BI__builtin_msa_bclri_w: 1969 case Mips::BI__builtin_msa_bnegi_w: 1970 case Mips::BI__builtin_msa_bseti_w: 1971 case Mips::BI__builtin_msa_sat_s_w: 1972 case Mips::BI__builtin_msa_sat_u_w: 1973 case Mips::BI__builtin_msa_slli_w: 1974 case Mips::BI__builtin_msa_srai_w: 1975 case Mips::BI__builtin_msa_srari_w: 1976 case Mips::BI__builtin_msa_srli_w: 1977 case Mips::BI__builtin_msa_srlri_w: 1978 case Mips::BI__builtin_msa_subvi_b: 1979 case Mips::BI__builtin_msa_subvi_h: 1980 case Mips::BI__builtin_msa_subvi_w: 1981 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 1982 case Mips::BI__builtin_msa_binsli_w: 1983 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 1984 // These intrinsics take an unsigned 6 bit immediate. 1985 case Mips::BI__builtin_msa_bclri_d: 1986 case Mips::BI__builtin_msa_bnegi_d: 1987 case Mips::BI__builtin_msa_bseti_d: 1988 case Mips::BI__builtin_msa_sat_s_d: 1989 case Mips::BI__builtin_msa_sat_u_d: 1990 case Mips::BI__builtin_msa_slli_d: 1991 case Mips::BI__builtin_msa_srai_d: 1992 case Mips::BI__builtin_msa_srari_d: 1993 case Mips::BI__builtin_msa_srli_d: 1994 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 1995 case Mips::BI__builtin_msa_binsli_d: 1996 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 1997 // These intrinsics take a signed 5 bit immediate. 1998 case Mips::BI__builtin_msa_ceqi_b: 1999 case Mips::BI__builtin_msa_ceqi_h: 2000 case Mips::BI__builtin_msa_ceqi_w: 2001 case Mips::BI__builtin_msa_ceqi_d: 2002 case Mips::BI__builtin_msa_clti_s_b: 2003 case Mips::BI__builtin_msa_clti_s_h: 2004 case Mips::BI__builtin_msa_clti_s_w: 2005 case Mips::BI__builtin_msa_clti_s_d: 2006 case Mips::BI__builtin_msa_clei_s_b: 2007 case Mips::BI__builtin_msa_clei_s_h: 2008 case Mips::BI__builtin_msa_clei_s_w: 2009 case Mips::BI__builtin_msa_clei_s_d: 2010 case Mips::BI__builtin_msa_maxi_s_b: 2011 case Mips::BI__builtin_msa_maxi_s_h: 2012 case Mips::BI__builtin_msa_maxi_s_w: 2013 case Mips::BI__builtin_msa_maxi_s_d: 2014 case Mips::BI__builtin_msa_mini_s_b: 2015 case Mips::BI__builtin_msa_mini_s_h: 2016 case Mips::BI__builtin_msa_mini_s_w: 2017 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 2018 // These intrinsics take an unsigned 8 bit immediate. 2019 case Mips::BI__builtin_msa_andi_b: 2020 case Mips::BI__builtin_msa_nori_b: 2021 case Mips::BI__builtin_msa_ori_b: 2022 case Mips::BI__builtin_msa_shf_b: 2023 case Mips::BI__builtin_msa_shf_h: 2024 case Mips::BI__builtin_msa_shf_w: 2025 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 2026 case Mips::BI__builtin_msa_bseli_b: 2027 case Mips::BI__builtin_msa_bmnzi_b: 2028 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 2029 // df/n format 2030 // These intrinsics take an unsigned 4 bit immediate. 2031 case Mips::BI__builtin_msa_copy_s_b: 2032 case Mips::BI__builtin_msa_copy_u_b: 2033 case Mips::BI__builtin_msa_insve_b: 2034 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 2035 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 2036 // These intrinsics take an unsigned 3 bit immediate. 2037 case Mips::BI__builtin_msa_copy_s_h: 2038 case Mips::BI__builtin_msa_copy_u_h: 2039 case Mips::BI__builtin_msa_insve_h: 2040 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 2041 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 2042 // These intrinsics take an unsigned 2 bit immediate. 2043 case Mips::BI__builtin_msa_copy_s_w: 2044 case Mips::BI__builtin_msa_copy_u_w: 2045 case Mips::BI__builtin_msa_insve_w: 2046 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 2047 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 2048 // These intrinsics take an unsigned 1 bit immediate. 2049 case Mips::BI__builtin_msa_copy_s_d: 2050 case Mips::BI__builtin_msa_copy_u_d: 2051 case Mips::BI__builtin_msa_insve_d: 2052 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 2053 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 2054 // Memory offsets and immediate loads. 2055 // These intrinsics take a signed 10 bit immediate. 2056 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 2057 case Mips::BI__builtin_msa_ldi_h: 2058 case Mips::BI__builtin_msa_ldi_w: 2059 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 2060 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break; 2061 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break; 2062 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break; 2063 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break; 2064 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break; 2065 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break; 2066 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break; 2067 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break; 2068 } 2069 2070 if (!m) 2071 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 2072 2073 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 2074 SemaBuiltinConstantArgMultiple(TheCall, i, m); 2075 } 2076 2077 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2078 unsigned i = 0, l = 0, u = 0; 2079 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde || 2080 BuiltinID == PPC::BI__builtin_divdeu || 2081 BuiltinID == PPC::BI__builtin_bpermd; 2082 bool IsTarget64Bit = Context.getTargetInfo() 2083 .getTypeWidth(Context 2084 .getTargetInfo() 2085 .getIntPtrType()) == 64; 2086 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe || 2087 BuiltinID == PPC::BI__builtin_divweu || 2088 BuiltinID == PPC::BI__builtin_divde || 2089 BuiltinID == PPC::BI__builtin_divdeu; 2090 2091 if (Is64BitBltin && !IsTarget64Bit) 2092 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt) 2093 << TheCall->getSourceRange(); 2094 2095 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) || 2096 (BuiltinID == PPC::BI__builtin_bpermd && 2097 !Context.getTargetInfo().hasFeature("bpermd"))) 2098 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7) 2099 << TheCall->getSourceRange(); 2100 2101 switch (BuiltinID) { 2102 default: return false; 2103 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 2104 case PPC::BI__builtin_altivec_crypto_vshasigmad: 2105 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2106 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 2107 case PPC::BI__builtin_tbegin: 2108 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 2109 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 2110 case PPC::BI__builtin_tabortwc: 2111 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 2112 case PPC::BI__builtin_tabortwci: 2113 case PPC::BI__builtin_tabortdci: 2114 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 2115 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 2116 case PPC::BI__builtin_vsx_xxpermdi: 2117 case PPC::BI__builtin_vsx_xxsldwi: 2118 return SemaBuiltinVSX(TheCall); 2119 } 2120 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 2121 } 2122 2123 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 2124 CallExpr *TheCall) { 2125 if (BuiltinID == SystemZ::BI__builtin_tabort) { 2126 Expr *Arg = TheCall->getArg(0); 2127 llvm::APSInt AbortCode(32); 2128 if (Arg->isIntegerConstantExpr(AbortCode, Context) && 2129 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256) 2130 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code) 2131 << Arg->getSourceRange(); 2132 } 2133 2134 // For intrinsics which take an immediate value as part of the instruction, 2135 // range check them here. 2136 unsigned i = 0, l = 0, u = 0; 2137 switch (BuiltinID) { 2138 default: return false; 2139 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 2140 case SystemZ::BI__builtin_s390_verimb: 2141 case SystemZ::BI__builtin_s390_verimh: 2142 case SystemZ::BI__builtin_s390_verimf: 2143 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 2144 case SystemZ::BI__builtin_s390_vfaeb: 2145 case SystemZ::BI__builtin_s390_vfaeh: 2146 case SystemZ::BI__builtin_s390_vfaef: 2147 case SystemZ::BI__builtin_s390_vfaebs: 2148 case SystemZ::BI__builtin_s390_vfaehs: 2149 case SystemZ::BI__builtin_s390_vfaefs: 2150 case SystemZ::BI__builtin_s390_vfaezb: 2151 case SystemZ::BI__builtin_s390_vfaezh: 2152 case SystemZ::BI__builtin_s390_vfaezf: 2153 case SystemZ::BI__builtin_s390_vfaezbs: 2154 case SystemZ::BI__builtin_s390_vfaezhs: 2155 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 2156 case SystemZ::BI__builtin_s390_vfisb: 2157 case SystemZ::BI__builtin_s390_vfidb: 2158 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 2159 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 2160 case SystemZ::BI__builtin_s390_vftcisb: 2161 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 2162 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 2163 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 2164 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 2165 case SystemZ::BI__builtin_s390_vstrcb: 2166 case SystemZ::BI__builtin_s390_vstrch: 2167 case SystemZ::BI__builtin_s390_vstrcf: 2168 case SystemZ::BI__builtin_s390_vstrczb: 2169 case SystemZ::BI__builtin_s390_vstrczh: 2170 case SystemZ::BI__builtin_s390_vstrczf: 2171 case SystemZ::BI__builtin_s390_vstrcbs: 2172 case SystemZ::BI__builtin_s390_vstrchs: 2173 case SystemZ::BI__builtin_s390_vstrcfs: 2174 case SystemZ::BI__builtin_s390_vstrczbs: 2175 case SystemZ::BI__builtin_s390_vstrczhs: 2176 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 2177 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 2178 case SystemZ::BI__builtin_s390_vfminsb: 2179 case SystemZ::BI__builtin_s390_vfmaxsb: 2180 case SystemZ::BI__builtin_s390_vfmindb: 2181 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 2182 } 2183 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 2184 } 2185 2186 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 2187 /// This checks that the target supports __builtin_cpu_supports and 2188 /// that the string argument is constant and valid. 2189 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) { 2190 Expr *Arg = TheCall->getArg(0); 2191 2192 // Check if the argument is a string literal. 2193 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 2194 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal) 2195 << Arg->getSourceRange(); 2196 2197 // Check the contents of the string. 2198 StringRef Feature = 2199 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 2200 if (!S.Context.getTargetInfo().validateCpuSupports(Feature)) 2201 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports) 2202 << Arg->getSourceRange(); 2203 return false; 2204 } 2205 2206 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 2207 /// This checks that the target supports __builtin_cpu_is and 2208 /// that the string argument is constant and valid. 2209 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) { 2210 Expr *Arg = TheCall->getArg(0); 2211 2212 // Check if the argument is a string literal. 2213 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 2214 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal) 2215 << Arg->getSourceRange(); 2216 2217 // Check the contents of the string. 2218 StringRef Feature = 2219 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 2220 if (!S.Context.getTargetInfo().validateCpuIs(Feature)) 2221 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_is) 2222 << Arg->getSourceRange(); 2223 return false; 2224 } 2225 2226 // Check if the rounding mode is legal. 2227 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 2228 // Indicates if this instruction has rounding control or just SAE. 2229 bool HasRC = false; 2230 2231 unsigned ArgNum = 0; 2232 switch (BuiltinID) { 2233 default: 2234 return false; 2235 case X86::BI__builtin_ia32_vcvttsd2si32: 2236 case X86::BI__builtin_ia32_vcvttsd2si64: 2237 case X86::BI__builtin_ia32_vcvttsd2usi32: 2238 case X86::BI__builtin_ia32_vcvttsd2usi64: 2239 case X86::BI__builtin_ia32_vcvttss2si32: 2240 case X86::BI__builtin_ia32_vcvttss2si64: 2241 case X86::BI__builtin_ia32_vcvttss2usi32: 2242 case X86::BI__builtin_ia32_vcvttss2usi64: 2243 ArgNum = 1; 2244 break; 2245 case X86::BI__builtin_ia32_cvtps2pd512_mask: 2246 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 2247 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 2248 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 2249 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 2250 case X86::BI__builtin_ia32_cvttps2dq512_mask: 2251 case X86::BI__builtin_ia32_cvttps2qq512_mask: 2252 case X86::BI__builtin_ia32_cvttps2udq512_mask: 2253 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 2254 case X86::BI__builtin_ia32_exp2pd_mask: 2255 case X86::BI__builtin_ia32_exp2ps_mask: 2256 case X86::BI__builtin_ia32_getexppd512_mask: 2257 case X86::BI__builtin_ia32_getexpps512_mask: 2258 case X86::BI__builtin_ia32_rcp28pd_mask: 2259 case X86::BI__builtin_ia32_rcp28ps_mask: 2260 case X86::BI__builtin_ia32_rsqrt28pd_mask: 2261 case X86::BI__builtin_ia32_rsqrt28ps_mask: 2262 case X86::BI__builtin_ia32_vcomisd: 2263 case X86::BI__builtin_ia32_vcomiss: 2264 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 2265 ArgNum = 3; 2266 break; 2267 case X86::BI__builtin_ia32_cmppd512_mask: 2268 case X86::BI__builtin_ia32_cmpps512_mask: 2269 case X86::BI__builtin_ia32_cmpsd_mask: 2270 case X86::BI__builtin_ia32_cmpss_mask: 2271 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 2272 case X86::BI__builtin_ia32_getexpsd128_round_mask: 2273 case X86::BI__builtin_ia32_getexpss128_round_mask: 2274 case X86::BI__builtin_ia32_maxpd512_mask: 2275 case X86::BI__builtin_ia32_maxps512_mask: 2276 case X86::BI__builtin_ia32_maxsd_round_mask: 2277 case X86::BI__builtin_ia32_maxss_round_mask: 2278 case X86::BI__builtin_ia32_minpd512_mask: 2279 case X86::BI__builtin_ia32_minps512_mask: 2280 case X86::BI__builtin_ia32_minsd_round_mask: 2281 case X86::BI__builtin_ia32_minss_round_mask: 2282 case X86::BI__builtin_ia32_rcp28sd_round_mask: 2283 case X86::BI__builtin_ia32_rcp28ss_round_mask: 2284 case X86::BI__builtin_ia32_reducepd512_mask: 2285 case X86::BI__builtin_ia32_reduceps512_mask: 2286 case X86::BI__builtin_ia32_rndscalepd_mask: 2287 case X86::BI__builtin_ia32_rndscaleps_mask: 2288 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 2289 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 2290 ArgNum = 4; 2291 break; 2292 case X86::BI__builtin_ia32_fixupimmpd512_mask: 2293 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 2294 case X86::BI__builtin_ia32_fixupimmps512_mask: 2295 case X86::BI__builtin_ia32_fixupimmps512_maskz: 2296 case X86::BI__builtin_ia32_fixupimmsd_mask: 2297 case X86::BI__builtin_ia32_fixupimmsd_maskz: 2298 case X86::BI__builtin_ia32_fixupimmss_mask: 2299 case X86::BI__builtin_ia32_fixupimmss_maskz: 2300 case X86::BI__builtin_ia32_rangepd512_mask: 2301 case X86::BI__builtin_ia32_rangeps512_mask: 2302 case X86::BI__builtin_ia32_rangesd128_round_mask: 2303 case X86::BI__builtin_ia32_rangess128_round_mask: 2304 case X86::BI__builtin_ia32_reducesd_mask: 2305 case X86::BI__builtin_ia32_reducess_mask: 2306 case X86::BI__builtin_ia32_rndscalesd_round_mask: 2307 case X86::BI__builtin_ia32_rndscaless_round_mask: 2308 ArgNum = 5; 2309 break; 2310 case X86::BI__builtin_ia32_vcvtsd2si64: 2311 case X86::BI__builtin_ia32_vcvtsd2si32: 2312 case X86::BI__builtin_ia32_vcvtsd2usi32: 2313 case X86::BI__builtin_ia32_vcvtsd2usi64: 2314 case X86::BI__builtin_ia32_vcvtss2si32: 2315 case X86::BI__builtin_ia32_vcvtss2si64: 2316 case X86::BI__builtin_ia32_vcvtss2usi32: 2317 case X86::BI__builtin_ia32_vcvtss2usi64: 2318 ArgNum = 1; 2319 HasRC = true; 2320 break; 2321 case X86::BI__builtin_ia32_cvtsi2sd64: 2322 case X86::BI__builtin_ia32_cvtsi2ss32: 2323 case X86::BI__builtin_ia32_cvtsi2ss64: 2324 case X86::BI__builtin_ia32_cvtusi2sd64: 2325 case X86::BI__builtin_ia32_cvtusi2ss32: 2326 case X86::BI__builtin_ia32_cvtusi2ss64: 2327 ArgNum = 2; 2328 HasRC = true; 2329 break; 2330 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 2331 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 2332 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 2333 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 2334 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 2335 case X86::BI__builtin_ia32_cvtps2qq512_mask: 2336 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 2337 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 2338 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 2339 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 2340 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 2341 case X86::BI__builtin_ia32_sqrtpd512_mask: 2342 case X86::BI__builtin_ia32_sqrtps512_mask: 2343 case X86::BI__builtin_ia32_vfmaddpd512: 2344 case X86::BI__builtin_ia32_vfmaddps512: 2345 case X86::BI__builtin_ia32_vfmaddsubpd512: 2346 case X86::BI__builtin_ia32_vfmaddsubps512: 2347 ArgNum = 3; 2348 HasRC = true; 2349 break; 2350 case X86::BI__builtin_ia32_addpd512_mask: 2351 case X86::BI__builtin_ia32_addps512_mask: 2352 case X86::BI__builtin_ia32_divpd512_mask: 2353 case X86::BI__builtin_ia32_divps512_mask: 2354 case X86::BI__builtin_ia32_mulpd512_mask: 2355 case X86::BI__builtin_ia32_mulps512_mask: 2356 case X86::BI__builtin_ia32_subpd512_mask: 2357 case X86::BI__builtin_ia32_subps512_mask: 2358 case X86::BI__builtin_ia32_addss_round_mask: 2359 case X86::BI__builtin_ia32_addsd_round_mask: 2360 case X86::BI__builtin_ia32_divss_round_mask: 2361 case X86::BI__builtin_ia32_divsd_round_mask: 2362 case X86::BI__builtin_ia32_mulss_round_mask: 2363 case X86::BI__builtin_ia32_mulsd_round_mask: 2364 case X86::BI__builtin_ia32_subss_round_mask: 2365 case X86::BI__builtin_ia32_subsd_round_mask: 2366 case X86::BI__builtin_ia32_scalefpd512_mask: 2367 case X86::BI__builtin_ia32_scalefps512_mask: 2368 case X86::BI__builtin_ia32_scalefsd_round_mask: 2369 case X86::BI__builtin_ia32_scalefss_round_mask: 2370 case X86::BI__builtin_ia32_getmantpd512_mask: 2371 case X86::BI__builtin_ia32_getmantps512_mask: 2372 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 2373 case X86::BI__builtin_ia32_sqrtsd_round_mask: 2374 case X86::BI__builtin_ia32_sqrtss_round_mask: 2375 case X86::BI__builtin_ia32_vfmaddsd3_mask: 2376 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 2377 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 2378 case X86::BI__builtin_ia32_vfmaddss3_mask: 2379 case X86::BI__builtin_ia32_vfmaddss3_maskz: 2380 case X86::BI__builtin_ia32_vfmaddss3_mask3: 2381 ArgNum = 4; 2382 HasRC = true; 2383 break; 2384 case X86::BI__builtin_ia32_getmantsd_round_mask: 2385 case X86::BI__builtin_ia32_getmantss_round_mask: 2386 ArgNum = 5; 2387 HasRC = true; 2388 break; 2389 } 2390 2391 llvm::APSInt Result; 2392 2393 // We can't check the value of a dependent argument. 2394 Expr *Arg = TheCall->getArg(ArgNum); 2395 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2396 return false; 2397 2398 // Check constant-ness first. 2399 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 2400 return true; 2401 2402 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 2403 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 2404 // combined with ROUND_NO_EXC. 2405 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 2406 Result == 8/*ROUND_NO_EXC*/ || 2407 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 2408 return false; 2409 2410 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding) 2411 << Arg->getSourceRange(); 2412 } 2413 2414 // Check if the gather/scatter scale is legal. 2415 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 2416 CallExpr *TheCall) { 2417 unsigned ArgNum = 0; 2418 switch (BuiltinID) { 2419 default: 2420 return false; 2421 case X86::BI__builtin_ia32_gatherpfdpd: 2422 case X86::BI__builtin_ia32_gatherpfdps: 2423 case X86::BI__builtin_ia32_gatherpfqpd: 2424 case X86::BI__builtin_ia32_gatherpfqps: 2425 case X86::BI__builtin_ia32_scatterpfdpd: 2426 case X86::BI__builtin_ia32_scatterpfdps: 2427 case X86::BI__builtin_ia32_scatterpfqpd: 2428 case X86::BI__builtin_ia32_scatterpfqps: 2429 ArgNum = 3; 2430 break; 2431 case X86::BI__builtin_ia32_gatherd_pd: 2432 case X86::BI__builtin_ia32_gatherd_pd256: 2433 case X86::BI__builtin_ia32_gatherq_pd: 2434 case X86::BI__builtin_ia32_gatherq_pd256: 2435 case X86::BI__builtin_ia32_gatherd_ps: 2436 case X86::BI__builtin_ia32_gatherd_ps256: 2437 case X86::BI__builtin_ia32_gatherq_ps: 2438 case X86::BI__builtin_ia32_gatherq_ps256: 2439 case X86::BI__builtin_ia32_gatherd_q: 2440 case X86::BI__builtin_ia32_gatherd_q256: 2441 case X86::BI__builtin_ia32_gatherq_q: 2442 case X86::BI__builtin_ia32_gatherq_q256: 2443 case X86::BI__builtin_ia32_gatherd_d: 2444 case X86::BI__builtin_ia32_gatherd_d256: 2445 case X86::BI__builtin_ia32_gatherq_d: 2446 case X86::BI__builtin_ia32_gatherq_d256: 2447 case X86::BI__builtin_ia32_gather3div2df: 2448 case X86::BI__builtin_ia32_gather3div2di: 2449 case X86::BI__builtin_ia32_gather3div4df: 2450 case X86::BI__builtin_ia32_gather3div4di: 2451 case X86::BI__builtin_ia32_gather3div4sf: 2452 case X86::BI__builtin_ia32_gather3div4si: 2453 case X86::BI__builtin_ia32_gather3div8sf: 2454 case X86::BI__builtin_ia32_gather3div8si: 2455 case X86::BI__builtin_ia32_gather3siv2df: 2456 case X86::BI__builtin_ia32_gather3siv2di: 2457 case X86::BI__builtin_ia32_gather3siv4df: 2458 case X86::BI__builtin_ia32_gather3siv4di: 2459 case X86::BI__builtin_ia32_gather3siv4sf: 2460 case X86::BI__builtin_ia32_gather3siv4si: 2461 case X86::BI__builtin_ia32_gather3siv8sf: 2462 case X86::BI__builtin_ia32_gather3siv8si: 2463 case X86::BI__builtin_ia32_gathersiv8df: 2464 case X86::BI__builtin_ia32_gathersiv16sf: 2465 case X86::BI__builtin_ia32_gatherdiv8df: 2466 case X86::BI__builtin_ia32_gatherdiv16sf: 2467 case X86::BI__builtin_ia32_gathersiv8di: 2468 case X86::BI__builtin_ia32_gathersiv16si: 2469 case X86::BI__builtin_ia32_gatherdiv8di: 2470 case X86::BI__builtin_ia32_gatherdiv16si: 2471 case X86::BI__builtin_ia32_scatterdiv2df: 2472 case X86::BI__builtin_ia32_scatterdiv2di: 2473 case X86::BI__builtin_ia32_scatterdiv4df: 2474 case X86::BI__builtin_ia32_scatterdiv4di: 2475 case X86::BI__builtin_ia32_scatterdiv4sf: 2476 case X86::BI__builtin_ia32_scatterdiv4si: 2477 case X86::BI__builtin_ia32_scatterdiv8sf: 2478 case X86::BI__builtin_ia32_scatterdiv8si: 2479 case X86::BI__builtin_ia32_scattersiv2df: 2480 case X86::BI__builtin_ia32_scattersiv2di: 2481 case X86::BI__builtin_ia32_scattersiv4df: 2482 case X86::BI__builtin_ia32_scattersiv4di: 2483 case X86::BI__builtin_ia32_scattersiv4sf: 2484 case X86::BI__builtin_ia32_scattersiv4si: 2485 case X86::BI__builtin_ia32_scattersiv8sf: 2486 case X86::BI__builtin_ia32_scattersiv8si: 2487 case X86::BI__builtin_ia32_scattersiv8df: 2488 case X86::BI__builtin_ia32_scattersiv16sf: 2489 case X86::BI__builtin_ia32_scatterdiv8df: 2490 case X86::BI__builtin_ia32_scatterdiv16sf: 2491 case X86::BI__builtin_ia32_scattersiv8di: 2492 case X86::BI__builtin_ia32_scattersiv16si: 2493 case X86::BI__builtin_ia32_scatterdiv8di: 2494 case X86::BI__builtin_ia32_scatterdiv16si: 2495 ArgNum = 4; 2496 break; 2497 } 2498 2499 llvm::APSInt Result; 2500 2501 // We can't check the value of a dependent argument. 2502 Expr *Arg = TheCall->getArg(ArgNum); 2503 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2504 return false; 2505 2506 // Check constant-ness first. 2507 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 2508 return true; 2509 2510 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 2511 return false; 2512 2513 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale) 2514 << Arg->getSourceRange(); 2515 } 2516 2517 static bool isX86_32Builtin(unsigned BuiltinID) { 2518 // These builtins only work on x86-32 targets. 2519 switch (BuiltinID) { 2520 case X86::BI__builtin_ia32_readeflags_u32: 2521 case X86::BI__builtin_ia32_writeeflags_u32: 2522 return true; 2523 } 2524 2525 return false; 2526 } 2527 2528 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2529 if (BuiltinID == X86::BI__builtin_cpu_supports) 2530 return SemaBuiltinCpuSupports(*this, TheCall); 2531 2532 if (BuiltinID == X86::BI__builtin_cpu_is) 2533 return SemaBuiltinCpuIs(*this, TheCall); 2534 2535 // Check for 32-bit only builtins on a 64-bit target. 2536 const llvm::Triple &TT = Context.getTargetInfo().getTriple(); 2537 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) 2538 return Diag(TheCall->getCallee()->getLocStart(), 2539 diag::err_32_bit_builtin_64_bit_tgt); 2540 2541 // If the intrinsic has rounding or SAE make sure its valid. 2542 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 2543 return true; 2544 2545 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 2546 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 2547 return true; 2548 2549 // For intrinsics which take an immediate value as part of the instruction, 2550 // range check them here. 2551 int i = 0, l = 0, u = 0; 2552 switch (BuiltinID) { 2553 default: 2554 return false; 2555 case X86::BI_mm_prefetch: 2556 i = 1; l = 0; u = 7; 2557 break; 2558 case X86::BI__builtin_ia32_sha1rnds4: 2559 i = 2; l = 0; u = 3; 2560 break; 2561 case X86::BI__builtin_ia32_vpermil2pd: 2562 case X86::BI__builtin_ia32_vpermil2pd256: 2563 case X86::BI__builtin_ia32_vpermil2ps: 2564 case X86::BI__builtin_ia32_vpermil2ps256: 2565 i = 3; l = 0; u = 3; 2566 break; 2567 case X86::BI__builtin_ia32_cmpb128_mask: 2568 case X86::BI__builtin_ia32_cmpw128_mask: 2569 case X86::BI__builtin_ia32_cmpd128_mask: 2570 case X86::BI__builtin_ia32_cmpq128_mask: 2571 case X86::BI__builtin_ia32_cmpb256_mask: 2572 case X86::BI__builtin_ia32_cmpw256_mask: 2573 case X86::BI__builtin_ia32_cmpd256_mask: 2574 case X86::BI__builtin_ia32_cmpq256_mask: 2575 case X86::BI__builtin_ia32_cmpb512_mask: 2576 case X86::BI__builtin_ia32_cmpw512_mask: 2577 case X86::BI__builtin_ia32_cmpd512_mask: 2578 case X86::BI__builtin_ia32_cmpq512_mask: 2579 case X86::BI__builtin_ia32_ucmpb128_mask: 2580 case X86::BI__builtin_ia32_ucmpw128_mask: 2581 case X86::BI__builtin_ia32_ucmpd128_mask: 2582 case X86::BI__builtin_ia32_ucmpq128_mask: 2583 case X86::BI__builtin_ia32_ucmpb256_mask: 2584 case X86::BI__builtin_ia32_ucmpw256_mask: 2585 case X86::BI__builtin_ia32_ucmpd256_mask: 2586 case X86::BI__builtin_ia32_ucmpq256_mask: 2587 case X86::BI__builtin_ia32_ucmpb512_mask: 2588 case X86::BI__builtin_ia32_ucmpw512_mask: 2589 case X86::BI__builtin_ia32_ucmpd512_mask: 2590 case X86::BI__builtin_ia32_ucmpq512_mask: 2591 case X86::BI__builtin_ia32_vpcomub: 2592 case X86::BI__builtin_ia32_vpcomuw: 2593 case X86::BI__builtin_ia32_vpcomud: 2594 case X86::BI__builtin_ia32_vpcomuq: 2595 case X86::BI__builtin_ia32_vpcomb: 2596 case X86::BI__builtin_ia32_vpcomw: 2597 case X86::BI__builtin_ia32_vpcomd: 2598 case X86::BI__builtin_ia32_vpcomq: 2599 i = 2; l = 0; u = 7; 2600 break; 2601 case X86::BI__builtin_ia32_roundps: 2602 case X86::BI__builtin_ia32_roundpd: 2603 case X86::BI__builtin_ia32_roundps256: 2604 case X86::BI__builtin_ia32_roundpd256: 2605 i = 1; l = 0; u = 15; 2606 break; 2607 case X86::BI__builtin_ia32_roundss: 2608 case X86::BI__builtin_ia32_roundsd: 2609 case X86::BI__builtin_ia32_rangepd128_mask: 2610 case X86::BI__builtin_ia32_rangepd256_mask: 2611 case X86::BI__builtin_ia32_rangepd512_mask: 2612 case X86::BI__builtin_ia32_rangeps128_mask: 2613 case X86::BI__builtin_ia32_rangeps256_mask: 2614 case X86::BI__builtin_ia32_rangeps512_mask: 2615 case X86::BI__builtin_ia32_getmantsd_round_mask: 2616 case X86::BI__builtin_ia32_getmantss_round_mask: 2617 i = 2; l = 0; u = 15; 2618 break; 2619 case X86::BI__builtin_ia32_cmpps: 2620 case X86::BI__builtin_ia32_cmpss: 2621 case X86::BI__builtin_ia32_cmppd: 2622 case X86::BI__builtin_ia32_cmpsd: 2623 case X86::BI__builtin_ia32_cmpps256: 2624 case X86::BI__builtin_ia32_cmppd256: 2625 case X86::BI__builtin_ia32_cmpps128_mask: 2626 case X86::BI__builtin_ia32_cmppd128_mask: 2627 case X86::BI__builtin_ia32_cmpps256_mask: 2628 case X86::BI__builtin_ia32_cmppd256_mask: 2629 case X86::BI__builtin_ia32_cmpps512_mask: 2630 case X86::BI__builtin_ia32_cmppd512_mask: 2631 case X86::BI__builtin_ia32_cmpsd_mask: 2632 case X86::BI__builtin_ia32_cmpss_mask: 2633 i = 2; l = 0; u = 31; 2634 break; 2635 case X86::BI__builtin_ia32_vcvtps2ph: 2636 case X86::BI__builtin_ia32_vcvtps2ph_mask: 2637 case X86::BI__builtin_ia32_vcvtps2ph256: 2638 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 2639 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 2640 case X86::BI__builtin_ia32_rndscaleps_128_mask: 2641 case X86::BI__builtin_ia32_rndscalepd_128_mask: 2642 case X86::BI__builtin_ia32_rndscaleps_256_mask: 2643 case X86::BI__builtin_ia32_rndscalepd_256_mask: 2644 case X86::BI__builtin_ia32_rndscaleps_mask: 2645 case X86::BI__builtin_ia32_rndscalepd_mask: 2646 case X86::BI__builtin_ia32_reducepd128_mask: 2647 case X86::BI__builtin_ia32_reducepd256_mask: 2648 case X86::BI__builtin_ia32_reducepd512_mask: 2649 case X86::BI__builtin_ia32_reduceps128_mask: 2650 case X86::BI__builtin_ia32_reduceps256_mask: 2651 case X86::BI__builtin_ia32_reduceps512_mask: 2652 case X86::BI__builtin_ia32_prold512_mask: 2653 case X86::BI__builtin_ia32_prolq512_mask: 2654 case X86::BI__builtin_ia32_prold128_mask: 2655 case X86::BI__builtin_ia32_prold256_mask: 2656 case X86::BI__builtin_ia32_prolq128_mask: 2657 case X86::BI__builtin_ia32_prolq256_mask: 2658 case X86::BI__builtin_ia32_prord128_mask: 2659 case X86::BI__builtin_ia32_prord256_mask: 2660 case X86::BI__builtin_ia32_prorq128_mask: 2661 case X86::BI__builtin_ia32_prorq256_mask: 2662 case X86::BI__builtin_ia32_fpclasspd128_mask: 2663 case X86::BI__builtin_ia32_fpclasspd256_mask: 2664 case X86::BI__builtin_ia32_fpclassps128_mask: 2665 case X86::BI__builtin_ia32_fpclassps256_mask: 2666 case X86::BI__builtin_ia32_fpclassps512_mask: 2667 case X86::BI__builtin_ia32_fpclasspd512_mask: 2668 case X86::BI__builtin_ia32_fpclasssd_mask: 2669 case X86::BI__builtin_ia32_fpclassss_mask: 2670 i = 1; l = 0; u = 255; 2671 break; 2672 case X86::BI__builtin_ia32_palignr128: 2673 case X86::BI__builtin_ia32_palignr256: 2674 case X86::BI__builtin_ia32_palignr512: 2675 case X86::BI__builtin_ia32_vcomisd: 2676 case X86::BI__builtin_ia32_vcomiss: 2677 case X86::BI__builtin_ia32_dbpsadbw128_mask: 2678 case X86::BI__builtin_ia32_dbpsadbw256_mask: 2679 case X86::BI__builtin_ia32_dbpsadbw512_mask: 2680 case X86::BI__builtin_ia32_vpshldd128_mask: 2681 case X86::BI__builtin_ia32_vpshldd256_mask: 2682 case X86::BI__builtin_ia32_vpshldd512_mask: 2683 case X86::BI__builtin_ia32_vpshldq128_mask: 2684 case X86::BI__builtin_ia32_vpshldq256_mask: 2685 case X86::BI__builtin_ia32_vpshldq512_mask: 2686 case X86::BI__builtin_ia32_vpshldw128_mask: 2687 case X86::BI__builtin_ia32_vpshldw256_mask: 2688 case X86::BI__builtin_ia32_vpshldw512_mask: 2689 case X86::BI__builtin_ia32_vpshrdd128_mask: 2690 case X86::BI__builtin_ia32_vpshrdd256_mask: 2691 case X86::BI__builtin_ia32_vpshrdd512_mask: 2692 case X86::BI__builtin_ia32_vpshrdq128_mask: 2693 case X86::BI__builtin_ia32_vpshrdq256_mask: 2694 case X86::BI__builtin_ia32_vpshrdq512_mask: 2695 case X86::BI__builtin_ia32_vpshrdw128_mask: 2696 case X86::BI__builtin_ia32_vpshrdw256_mask: 2697 case X86::BI__builtin_ia32_vpshrdw512_mask: 2698 i = 2; l = 0; u = 255; 2699 break; 2700 case X86::BI__builtin_ia32_fixupimmpd512_mask: 2701 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 2702 case X86::BI__builtin_ia32_fixupimmps512_mask: 2703 case X86::BI__builtin_ia32_fixupimmps512_maskz: 2704 case X86::BI__builtin_ia32_fixupimmsd_mask: 2705 case X86::BI__builtin_ia32_fixupimmsd_maskz: 2706 case X86::BI__builtin_ia32_fixupimmss_mask: 2707 case X86::BI__builtin_ia32_fixupimmss_maskz: 2708 case X86::BI__builtin_ia32_fixupimmpd128_mask: 2709 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 2710 case X86::BI__builtin_ia32_fixupimmpd256_mask: 2711 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 2712 case X86::BI__builtin_ia32_fixupimmps128_mask: 2713 case X86::BI__builtin_ia32_fixupimmps128_maskz: 2714 case X86::BI__builtin_ia32_fixupimmps256_mask: 2715 case X86::BI__builtin_ia32_fixupimmps256_maskz: 2716 case X86::BI__builtin_ia32_pternlogd512_mask: 2717 case X86::BI__builtin_ia32_pternlogd512_maskz: 2718 case X86::BI__builtin_ia32_pternlogq512_mask: 2719 case X86::BI__builtin_ia32_pternlogq512_maskz: 2720 case X86::BI__builtin_ia32_pternlogd128_mask: 2721 case X86::BI__builtin_ia32_pternlogd128_maskz: 2722 case X86::BI__builtin_ia32_pternlogd256_mask: 2723 case X86::BI__builtin_ia32_pternlogd256_maskz: 2724 case X86::BI__builtin_ia32_pternlogq128_mask: 2725 case X86::BI__builtin_ia32_pternlogq128_maskz: 2726 case X86::BI__builtin_ia32_pternlogq256_mask: 2727 case X86::BI__builtin_ia32_pternlogq256_maskz: 2728 i = 3; l = 0; u = 255; 2729 break; 2730 case X86::BI__builtin_ia32_gatherpfdpd: 2731 case X86::BI__builtin_ia32_gatherpfdps: 2732 case X86::BI__builtin_ia32_gatherpfqpd: 2733 case X86::BI__builtin_ia32_gatherpfqps: 2734 case X86::BI__builtin_ia32_scatterpfdpd: 2735 case X86::BI__builtin_ia32_scatterpfdps: 2736 case X86::BI__builtin_ia32_scatterpfqpd: 2737 case X86::BI__builtin_ia32_scatterpfqps: 2738 i = 4; l = 2; u = 3; 2739 break; 2740 case X86::BI__builtin_ia32_rndscalesd_round_mask: 2741 case X86::BI__builtin_ia32_rndscaless_round_mask: 2742 i = 4; l = 0; u = 255; 2743 break; 2744 } 2745 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 2746 } 2747 2748 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 2749 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 2750 /// Returns true when the format fits the function and the FormatStringInfo has 2751 /// been populated. 2752 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 2753 FormatStringInfo *FSI) { 2754 FSI->HasVAListArg = Format->getFirstArg() == 0; 2755 FSI->FormatIdx = Format->getFormatIdx() - 1; 2756 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 2757 2758 // The way the format attribute works in GCC, the implicit this argument 2759 // of member functions is counted. However, it doesn't appear in our own 2760 // lists, so decrement format_idx in that case. 2761 if (IsCXXMember) { 2762 if(FSI->FormatIdx == 0) 2763 return false; 2764 --FSI->FormatIdx; 2765 if (FSI->FirstDataArg != 0) 2766 --FSI->FirstDataArg; 2767 } 2768 return true; 2769 } 2770 2771 /// Checks if a the given expression evaluates to null. 2772 /// 2773 /// Returns true if the value evaluates to null. 2774 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 2775 // If the expression has non-null type, it doesn't evaluate to null. 2776 if (auto nullability 2777 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 2778 if (*nullability == NullabilityKind::NonNull) 2779 return false; 2780 } 2781 2782 // As a special case, transparent unions initialized with zero are 2783 // considered null for the purposes of the nonnull attribute. 2784 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 2785 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 2786 if (const CompoundLiteralExpr *CLE = 2787 dyn_cast<CompoundLiteralExpr>(Expr)) 2788 if (const InitListExpr *ILE = 2789 dyn_cast<InitListExpr>(CLE->getInitializer())) 2790 Expr = ILE->getInit(0); 2791 } 2792 2793 bool Result; 2794 return (!Expr->isValueDependent() && 2795 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 2796 !Result); 2797 } 2798 2799 static void CheckNonNullArgument(Sema &S, 2800 const Expr *ArgExpr, 2801 SourceLocation CallSiteLoc) { 2802 if (CheckNonNullExpr(S, ArgExpr)) 2803 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 2804 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange()); 2805 } 2806 2807 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 2808 FormatStringInfo FSI; 2809 if ((GetFormatStringType(Format) == FST_NSString) && 2810 getFormatStringInfo(Format, false, &FSI)) { 2811 Idx = FSI.FormatIdx; 2812 return true; 2813 } 2814 return false; 2815 } 2816 2817 /// Diagnose use of %s directive in an NSString which is being passed 2818 /// as formatting string to formatting method. 2819 static void 2820 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 2821 const NamedDecl *FDecl, 2822 Expr **Args, 2823 unsigned NumArgs) { 2824 unsigned Idx = 0; 2825 bool Format = false; 2826 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 2827 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 2828 Idx = 2; 2829 Format = true; 2830 } 2831 else 2832 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 2833 if (S.GetFormatNSStringIdx(I, Idx)) { 2834 Format = true; 2835 break; 2836 } 2837 } 2838 if (!Format || NumArgs <= Idx) 2839 return; 2840 const Expr *FormatExpr = Args[Idx]; 2841 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 2842 FormatExpr = CSCE->getSubExpr(); 2843 const StringLiteral *FormatString; 2844 if (const ObjCStringLiteral *OSL = 2845 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 2846 FormatString = OSL->getString(); 2847 else 2848 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 2849 if (!FormatString) 2850 return; 2851 if (S.FormatStringHasSArg(FormatString)) { 2852 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 2853 << "%s" << 1 << 1; 2854 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 2855 << FDecl->getDeclName(); 2856 } 2857 } 2858 2859 /// Determine whether the given type has a non-null nullability annotation. 2860 static bool isNonNullType(ASTContext &ctx, QualType type) { 2861 if (auto nullability = type->getNullability(ctx)) 2862 return *nullability == NullabilityKind::NonNull; 2863 2864 return false; 2865 } 2866 2867 static void CheckNonNullArguments(Sema &S, 2868 const NamedDecl *FDecl, 2869 const FunctionProtoType *Proto, 2870 ArrayRef<const Expr *> Args, 2871 SourceLocation CallSiteLoc) { 2872 assert((FDecl || Proto) && "Need a function declaration or prototype"); 2873 2874 // Check the attributes attached to the method/function itself. 2875 llvm::SmallBitVector NonNullArgs; 2876 if (FDecl) { 2877 // Handle the nonnull attribute on the function/method declaration itself. 2878 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 2879 if (!NonNull->args_size()) { 2880 // Easy case: all pointer arguments are nonnull. 2881 for (const auto *Arg : Args) 2882 if (S.isValidPointerAttrType(Arg->getType())) 2883 CheckNonNullArgument(S, Arg, CallSiteLoc); 2884 return; 2885 } 2886 2887 for (const ParamIdx &Idx : NonNull->args()) { 2888 unsigned IdxAST = Idx.getASTIndex(); 2889 if (IdxAST >= Args.size()) 2890 continue; 2891 if (NonNullArgs.empty()) 2892 NonNullArgs.resize(Args.size()); 2893 NonNullArgs.set(IdxAST); 2894 } 2895 } 2896 } 2897 2898 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 2899 // Handle the nonnull attribute on the parameters of the 2900 // function/method. 2901 ArrayRef<ParmVarDecl*> parms; 2902 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 2903 parms = FD->parameters(); 2904 else 2905 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 2906 2907 unsigned ParamIndex = 0; 2908 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 2909 I != E; ++I, ++ParamIndex) { 2910 const ParmVarDecl *PVD = *I; 2911 if (PVD->hasAttr<NonNullAttr>() || 2912 isNonNullType(S.Context, PVD->getType())) { 2913 if (NonNullArgs.empty()) 2914 NonNullArgs.resize(Args.size()); 2915 2916 NonNullArgs.set(ParamIndex); 2917 } 2918 } 2919 } else { 2920 // If we have a non-function, non-method declaration but no 2921 // function prototype, try to dig out the function prototype. 2922 if (!Proto) { 2923 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 2924 QualType type = VD->getType().getNonReferenceType(); 2925 if (auto pointerType = type->getAs<PointerType>()) 2926 type = pointerType->getPointeeType(); 2927 else if (auto blockType = type->getAs<BlockPointerType>()) 2928 type = blockType->getPointeeType(); 2929 // FIXME: data member pointers? 2930 2931 // Dig out the function prototype, if there is one. 2932 Proto = type->getAs<FunctionProtoType>(); 2933 } 2934 } 2935 2936 // Fill in non-null argument information from the nullability 2937 // information on the parameter types (if we have them). 2938 if (Proto) { 2939 unsigned Index = 0; 2940 for (auto paramType : Proto->getParamTypes()) { 2941 if (isNonNullType(S.Context, paramType)) { 2942 if (NonNullArgs.empty()) 2943 NonNullArgs.resize(Args.size()); 2944 2945 NonNullArgs.set(Index); 2946 } 2947 2948 ++Index; 2949 } 2950 } 2951 } 2952 2953 // Check for non-null arguments. 2954 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 2955 ArgIndex != ArgIndexEnd; ++ArgIndex) { 2956 if (NonNullArgs[ArgIndex]) 2957 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 2958 } 2959 } 2960 2961 /// Handles the checks for format strings, non-POD arguments to vararg 2962 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 2963 /// attributes. 2964 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 2965 const Expr *ThisArg, ArrayRef<const Expr *> Args, 2966 bool IsMemberFunction, SourceLocation Loc, 2967 SourceRange Range, VariadicCallType CallType) { 2968 // FIXME: We should check as much as we can in the template definition. 2969 if (CurContext->isDependentContext()) 2970 return; 2971 2972 // Printf and scanf checking. 2973 llvm::SmallBitVector CheckedVarArgs; 2974 if (FDecl) { 2975 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 2976 // Only create vector if there are format attributes. 2977 CheckedVarArgs.resize(Args.size()); 2978 2979 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 2980 CheckedVarArgs); 2981 } 2982 } 2983 2984 // Refuse POD arguments that weren't caught by the format string 2985 // checks above. 2986 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 2987 if (CallType != VariadicDoesNotApply && 2988 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 2989 unsigned NumParams = Proto ? Proto->getNumParams() 2990 : FDecl && isa<FunctionDecl>(FDecl) 2991 ? cast<FunctionDecl>(FDecl)->getNumParams() 2992 : FDecl && isa<ObjCMethodDecl>(FDecl) 2993 ? cast<ObjCMethodDecl>(FDecl)->param_size() 2994 : 0; 2995 2996 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 2997 // Args[ArgIdx] can be null in malformed code. 2998 if (const Expr *Arg = Args[ArgIdx]) { 2999 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 3000 checkVariadicArgument(Arg, CallType); 3001 } 3002 } 3003 } 3004 3005 if (FDecl || Proto) { 3006 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 3007 3008 // Type safety checking. 3009 if (FDecl) { 3010 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 3011 CheckArgumentWithTypeTag(I, Args, Loc); 3012 } 3013 } 3014 3015 if (FD) 3016 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 3017 } 3018 3019 /// CheckConstructorCall - Check a constructor call for correctness and safety 3020 /// properties not enforced by the C type system. 3021 void Sema::CheckConstructorCall(FunctionDecl *FDecl, 3022 ArrayRef<const Expr *> Args, 3023 const FunctionProtoType *Proto, 3024 SourceLocation Loc) { 3025 VariadicCallType CallType = 3026 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 3027 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 3028 Loc, SourceRange(), CallType); 3029 } 3030 3031 /// CheckFunctionCall - Check a direct function call for various correctness 3032 /// and safety properties not strictly enforced by the C type system. 3033 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 3034 const FunctionProtoType *Proto) { 3035 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 3036 isa<CXXMethodDecl>(FDecl); 3037 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 3038 IsMemberOperatorCall; 3039 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 3040 TheCall->getCallee()); 3041 Expr** Args = TheCall->getArgs(); 3042 unsigned NumArgs = TheCall->getNumArgs(); 3043 3044 Expr *ImplicitThis = nullptr; 3045 if (IsMemberOperatorCall) { 3046 // If this is a call to a member operator, hide the first argument 3047 // from checkCall. 3048 // FIXME: Our choice of AST representation here is less than ideal. 3049 ImplicitThis = Args[0]; 3050 ++Args; 3051 --NumArgs; 3052 } else if (IsMemberFunction) 3053 ImplicitThis = 3054 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 3055 3056 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 3057 IsMemberFunction, TheCall->getRParenLoc(), 3058 TheCall->getCallee()->getSourceRange(), CallType); 3059 3060 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 3061 // None of the checks below are needed for functions that don't have 3062 // simple names (e.g., C++ conversion functions). 3063 if (!FnInfo) 3064 return false; 3065 3066 CheckAbsoluteValueFunction(TheCall, FDecl); 3067 CheckMaxUnsignedZero(TheCall, FDecl); 3068 3069 if (getLangOpts().ObjC1) 3070 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 3071 3072 unsigned CMId = FDecl->getMemoryFunctionKind(); 3073 if (CMId == 0) 3074 return false; 3075 3076 // Handle memory setting and copying functions. 3077 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 3078 CheckStrlcpycatArguments(TheCall, FnInfo); 3079 else if (CMId == Builtin::BIstrncat) 3080 CheckStrncatArguments(TheCall, FnInfo); 3081 else 3082 CheckMemaccessArguments(TheCall, CMId, FnInfo); 3083 3084 return false; 3085 } 3086 3087 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 3088 ArrayRef<const Expr *> Args) { 3089 VariadicCallType CallType = 3090 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 3091 3092 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 3093 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 3094 CallType); 3095 3096 return false; 3097 } 3098 3099 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 3100 const FunctionProtoType *Proto) { 3101 QualType Ty; 3102 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 3103 Ty = V->getType().getNonReferenceType(); 3104 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 3105 Ty = F->getType().getNonReferenceType(); 3106 else 3107 return false; 3108 3109 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 3110 !Ty->isFunctionProtoType()) 3111 return false; 3112 3113 VariadicCallType CallType; 3114 if (!Proto || !Proto->isVariadic()) { 3115 CallType = VariadicDoesNotApply; 3116 } else if (Ty->isBlockPointerType()) { 3117 CallType = VariadicBlock; 3118 } else { // Ty->isFunctionPointerType() 3119 CallType = VariadicFunction; 3120 } 3121 3122 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 3123 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 3124 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 3125 TheCall->getCallee()->getSourceRange(), CallType); 3126 3127 return false; 3128 } 3129 3130 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 3131 /// such as function pointers returned from functions. 3132 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 3133 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 3134 TheCall->getCallee()); 3135 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 3136 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 3137 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 3138 TheCall->getCallee()->getSourceRange(), CallType); 3139 3140 return false; 3141 } 3142 3143 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 3144 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 3145 return false; 3146 3147 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 3148 switch (Op) { 3149 case AtomicExpr::AO__c11_atomic_init: 3150 case AtomicExpr::AO__opencl_atomic_init: 3151 llvm_unreachable("There is no ordering argument for an init"); 3152 3153 case AtomicExpr::AO__c11_atomic_load: 3154 case AtomicExpr::AO__opencl_atomic_load: 3155 case AtomicExpr::AO__atomic_load_n: 3156 case AtomicExpr::AO__atomic_load: 3157 return OrderingCABI != llvm::AtomicOrderingCABI::release && 3158 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 3159 3160 case AtomicExpr::AO__c11_atomic_store: 3161 case AtomicExpr::AO__opencl_atomic_store: 3162 case AtomicExpr::AO__atomic_store: 3163 case AtomicExpr::AO__atomic_store_n: 3164 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 3165 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 3166 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 3167 3168 default: 3169 return true; 3170 } 3171 } 3172 3173 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 3174 AtomicExpr::AtomicOp Op) { 3175 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 3176 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 3177 3178 // All the non-OpenCL operations take one of the following forms. 3179 // The OpenCL operations take the __c11 forms with one extra argument for 3180 // synchronization scope. 3181 enum { 3182 // C __c11_atomic_init(A *, C) 3183 Init, 3184 3185 // C __c11_atomic_load(A *, int) 3186 Load, 3187 3188 // void __atomic_load(A *, CP, int) 3189 LoadCopy, 3190 3191 // void __atomic_store(A *, CP, int) 3192 Copy, 3193 3194 // C __c11_atomic_add(A *, M, int) 3195 Arithmetic, 3196 3197 // C __atomic_exchange_n(A *, CP, int) 3198 Xchg, 3199 3200 // void __atomic_exchange(A *, C *, CP, int) 3201 GNUXchg, 3202 3203 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 3204 C11CmpXchg, 3205 3206 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 3207 GNUCmpXchg 3208 } Form = Init; 3209 3210 const unsigned NumForm = GNUCmpXchg + 1; 3211 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 3212 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 3213 // where: 3214 // C is an appropriate type, 3215 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 3216 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 3217 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 3218 // the int parameters are for orderings. 3219 3220 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 3221 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 3222 "need to update code for modified forms"); 3223 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 3224 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == 3225 AtomicExpr::AO__atomic_load, 3226 "need to update code for modified C11 atomics"); 3227 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 3228 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 3229 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 3230 Op <= AtomicExpr::AO__c11_atomic_fetch_xor) || 3231 IsOpenCL; 3232 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 3233 Op == AtomicExpr::AO__atomic_store_n || 3234 Op == AtomicExpr::AO__atomic_exchange_n || 3235 Op == AtomicExpr::AO__atomic_compare_exchange_n; 3236 bool IsAddSub = false; 3237 bool IsMinMax = false; 3238 3239 switch (Op) { 3240 case AtomicExpr::AO__c11_atomic_init: 3241 case AtomicExpr::AO__opencl_atomic_init: 3242 Form = Init; 3243 break; 3244 3245 case AtomicExpr::AO__c11_atomic_load: 3246 case AtomicExpr::AO__opencl_atomic_load: 3247 case AtomicExpr::AO__atomic_load_n: 3248 Form = Load; 3249 break; 3250 3251 case AtomicExpr::AO__atomic_load: 3252 Form = LoadCopy; 3253 break; 3254 3255 case AtomicExpr::AO__c11_atomic_store: 3256 case AtomicExpr::AO__opencl_atomic_store: 3257 case AtomicExpr::AO__atomic_store: 3258 case AtomicExpr::AO__atomic_store_n: 3259 Form = Copy; 3260 break; 3261 3262 case AtomicExpr::AO__c11_atomic_fetch_add: 3263 case AtomicExpr::AO__c11_atomic_fetch_sub: 3264 case AtomicExpr::AO__opencl_atomic_fetch_add: 3265 case AtomicExpr::AO__opencl_atomic_fetch_sub: 3266 case AtomicExpr::AO__opencl_atomic_fetch_min: 3267 case AtomicExpr::AO__opencl_atomic_fetch_max: 3268 case AtomicExpr::AO__atomic_fetch_add: 3269 case AtomicExpr::AO__atomic_fetch_sub: 3270 case AtomicExpr::AO__atomic_add_fetch: 3271 case AtomicExpr::AO__atomic_sub_fetch: 3272 IsAddSub = true; 3273 LLVM_FALLTHROUGH; 3274 case AtomicExpr::AO__c11_atomic_fetch_and: 3275 case AtomicExpr::AO__c11_atomic_fetch_or: 3276 case AtomicExpr::AO__c11_atomic_fetch_xor: 3277 case AtomicExpr::AO__opencl_atomic_fetch_and: 3278 case AtomicExpr::AO__opencl_atomic_fetch_or: 3279 case AtomicExpr::AO__opencl_atomic_fetch_xor: 3280 case AtomicExpr::AO__atomic_fetch_and: 3281 case AtomicExpr::AO__atomic_fetch_or: 3282 case AtomicExpr::AO__atomic_fetch_xor: 3283 case AtomicExpr::AO__atomic_fetch_nand: 3284 case AtomicExpr::AO__atomic_and_fetch: 3285 case AtomicExpr::AO__atomic_or_fetch: 3286 case AtomicExpr::AO__atomic_xor_fetch: 3287 case AtomicExpr::AO__atomic_nand_fetch: 3288 Form = Arithmetic; 3289 break; 3290 3291 case AtomicExpr::AO__atomic_fetch_min: 3292 case AtomicExpr::AO__atomic_fetch_max: 3293 IsMinMax = true; 3294 Form = Arithmetic; 3295 break; 3296 3297 case AtomicExpr::AO__c11_atomic_exchange: 3298 case AtomicExpr::AO__opencl_atomic_exchange: 3299 case AtomicExpr::AO__atomic_exchange_n: 3300 Form = Xchg; 3301 break; 3302 3303 case AtomicExpr::AO__atomic_exchange: 3304 Form = GNUXchg; 3305 break; 3306 3307 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 3308 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 3309 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 3310 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 3311 Form = C11CmpXchg; 3312 break; 3313 3314 case AtomicExpr::AO__atomic_compare_exchange: 3315 case AtomicExpr::AO__atomic_compare_exchange_n: 3316 Form = GNUCmpXchg; 3317 break; 3318 } 3319 3320 unsigned AdjustedNumArgs = NumArgs[Form]; 3321 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 3322 ++AdjustedNumArgs; 3323 // Check we have the right number of arguments. 3324 if (TheCall->getNumArgs() < AdjustedNumArgs) { 3325 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 3326 << 0 << AdjustedNumArgs << TheCall->getNumArgs() 3327 << TheCall->getCallee()->getSourceRange(); 3328 return ExprError(); 3329 } else if (TheCall->getNumArgs() > AdjustedNumArgs) { 3330 Diag(TheCall->getArg(AdjustedNumArgs)->getLocStart(), 3331 diag::err_typecheck_call_too_many_args) 3332 << 0 << AdjustedNumArgs << TheCall->getNumArgs() 3333 << TheCall->getCallee()->getSourceRange(); 3334 return ExprError(); 3335 } 3336 3337 // Inspect the first argument of the atomic operation. 3338 Expr *Ptr = TheCall->getArg(0); 3339 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 3340 if (ConvertedPtr.isInvalid()) 3341 return ExprError(); 3342 3343 Ptr = ConvertedPtr.get(); 3344 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 3345 if (!pointerType) { 3346 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 3347 << Ptr->getType() << Ptr->getSourceRange(); 3348 return ExprError(); 3349 } 3350 3351 // For a __c11 builtin, this should be a pointer to an _Atomic type. 3352 QualType AtomTy = pointerType->getPointeeType(); // 'A' 3353 QualType ValType = AtomTy; // 'C' 3354 if (IsC11) { 3355 if (!AtomTy->isAtomicType()) { 3356 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic) 3357 << Ptr->getType() << Ptr->getSourceRange(); 3358 return ExprError(); 3359 } 3360 if (AtomTy.isConstQualified() || 3361 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 3362 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic) 3363 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 3364 << Ptr->getSourceRange(); 3365 return ExprError(); 3366 } 3367 ValType = AtomTy->getAs<AtomicType>()->getValueType(); 3368 } else if (Form != Load && Form != LoadCopy) { 3369 if (ValType.isConstQualified()) { 3370 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer) 3371 << Ptr->getType() << Ptr->getSourceRange(); 3372 return ExprError(); 3373 } 3374 } 3375 3376 // For an arithmetic operation, the implied arithmetic must be well-formed. 3377 if (Form == Arithmetic) { 3378 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 3379 if (IsAddSub && !ValType->isIntegerType() 3380 && !ValType->isPointerType()) { 3381 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 3382 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 3383 return ExprError(); 3384 } 3385 if (IsMinMax) { 3386 const BuiltinType *BT = ValType->getAs<BuiltinType>(); 3387 if (!BT || (BT->getKind() != BuiltinType::Int && 3388 BT->getKind() != BuiltinType::UInt)) { 3389 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_int32_or_ptr); 3390 return ExprError(); 3391 } 3392 } 3393 if (!IsAddSub && !IsMinMax && !ValType->isIntegerType()) { 3394 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int) 3395 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 3396 return ExprError(); 3397 } 3398 if (IsC11 && ValType->isPointerType() && 3399 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(), 3400 diag::err_incomplete_type)) { 3401 return ExprError(); 3402 } 3403 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 3404 // For __atomic_*_n operations, the value type must be a scalar integral or 3405 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 3406 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 3407 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 3408 return ExprError(); 3409 } 3410 3411 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 3412 !AtomTy->isScalarType()) { 3413 // For GNU atomics, require a trivially-copyable type. This is not part of 3414 // the GNU atomics specification, but we enforce it for sanity. 3415 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy) 3416 << Ptr->getType() << Ptr->getSourceRange(); 3417 return ExprError(); 3418 } 3419 3420 switch (ValType.getObjCLifetime()) { 3421 case Qualifiers::OCL_None: 3422 case Qualifiers::OCL_ExplicitNone: 3423 // okay 3424 break; 3425 3426 case Qualifiers::OCL_Weak: 3427 case Qualifiers::OCL_Strong: 3428 case Qualifiers::OCL_Autoreleasing: 3429 // FIXME: Can this happen? By this point, ValType should be known 3430 // to be trivially copyable. 3431 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 3432 << ValType << Ptr->getSourceRange(); 3433 return ExprError(); 3434 } 3435 3436 // All atomic operations have an overload which takes a pointer to a volatile 3437 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself 3438 // into the result or the other operands. Similarly atomic_load takes a 3439 // pointer to a const 'A'. 3440 ValType.removeLocalVolatile(); 3441 ValType.removeLocalConst(); 3442 QualType ResultType = ValType; 3443 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 3444 Form == Init) 3445 ResultType = Context.VoidTy; 3446 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 3447 ResultType = Context.BoolTy; 3448 3449 // The type of a parameter passed 'by value'. In the GNU atomics, such 3450 // arguments are actually passed as pointers. 3451 QualType ByValType = ValType; // 'CP' 3452 bool IsPassedByAddress = false; 3453 if (!IsC11 && !IsN) { 3454 ByValType = Ptr->getType(); 3455 IsPassedByAddress = true; 3456 } 3457 3458 // The first argument's non-CV pointer type is used to deduce the type of 3459 // subsequent arguments, except for: 3460 // - weak flag (always converted to bool) 3461 // - memory order (always converted to int) 3462 // - scope (always converted to int) 3463 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) { 3464 QualType Ty; 3465 if (i < NumVals[Form] + 1) { 3466 switch (i) { 3467 case 0: 3468 // The first argument is always a pointer. It has a fixed type. 3469 // It is always dereferenced, a nullptr is undefined. 3470 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getLocStart()); 3471 // Nothing else to do: we already know all we want about this pointer. 3472 continue; 3473 case 1: 3474 // The second argument is the non-atomic operand. For arithmetic, this 3475 // is always passed by value, and for a compare_exchange it is always 3476 // passed by address. For the rest, GNU uses by-address and C11 uses 3477 // by-value. 3478 assert(Form != Load); 3479 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 3480 Ty = ValType; 3481 else if (Form == Copy || Form == Xchg) { 3482 if (IsPassedByAddress) 3483 // The value pointer is always dereferenced, a nullptr is undefined. 3484 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getLocStart()); 3485 Ty = ByValType; 3486 } else if (Form == Arithmetic) 3487 Ty = Context.getPointerDiffType(); 3488 else { 3489 Expr *ValArg = TheCall->getArg(i); 3490 // The value pointer is always dereferenced, a nullptr is undefined. 3491 CheckNonNullArgument(*this, ValArg, DRE->getLocStart()); 3492 LangAS AS = LangAS::Default; 3493 // Keep address space of non-atomic pointer type. 3494 if (const PointerType *PtrTy = 3495 ValArg->getType()->getAs<PointerType>()) { 3496 AS = PtrTy->getPointeeType().getAddressSpace(); 3497 } 3498 Ty = Context.getPointerType( 3499 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 3500 } 3501 break; 3502 case 2: 3503 // The third argument to compare_exchange / GNU exchange is the desired 3504 // value, either by-value (for the C11 and *_n variant) or as a pointer. 3505 if (IsPassedByAddress) 3506 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getLocStart()); 3507 Ty = ByValType; 3508 break; 3509 case 3: 3510 // The fourth argument to GNU compare_exchange is a 'weak' flag. 3511 Ty = Context.BoolTy; 3512 break; 3513 } 3514 } else { 3515 // The order(s) and scope are always converted to int. 3516 Ty = Context.IntTy; 3517 } 3518 3519 InitializedEntity Entity = 3520 InitializedEntity::InitializeParameter(Context, Ty, false); 3521 ExprResult Arg = TheCall->getArg(i); 3522 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 3523 if (Arg.isInvalid()) 3524 return true; 3525 TheCall->setArg(i, Arg.get()); 3526 } 3527 3528 // Permute the arguments into a 'consistent' order. 3529 SmallVector<Expr*, 5> SubExprs; 3530 SubExprs.push_back(Ptr); 3531 switch (Form) { 3532 case Init: 3533 // Note, AtomicExpr::getVal1() has a special case for this atomic. 3534 SubExprs.push_back(TheCall->getArg(1)); // Val1 3535 break; 3536 case Load: 3537 SubExprs.push_back(TheCall->getArg(1)); // Order 3538 break; 3539 case LoadCopy: 3540 case Copy: 3541 case Arithmetic: 3542 case Xchg: 3543 SubExprs.push_back(TheCall->getArg(2)); // Order 3544 SubExprs.push_back(TheCall->getArg(1)); // Val1 3545 break; 3546 case GNUXchg: 3547 // Note, AtomicExpr::getVal2() has a special case for this atomic. 3548 SubExprs.push_back(TheCall->getArg(3)); // Order 3549 SubExprs.push_back(TheCall->getArg(1)); // Val1 3550 SubExprs.push_back(TheCall->getArg(2)); // Val2 3551 break; 3552 case C11CmpXchg: 3553 SubExprs.push_back(TheCall->getArg(3)); // Order 3554 SubExprs.push_back(TheCall->getArg(1)); // Val1 3555 SubExprs.push_back(TheCall->getArg(4)); // OrderFail 3556 SubExprs.push_back(TheCall->getArg(2)); // Val2 3557 break; 3558 case GNUCmpXchg: 3559 SubExprs.push_back(TheCall->getArg(4)); // Order 3560 SubExprs.push_back(TheCall->getArg(1)); // Val1 3561 SubExprs.push_back(TheCall->getArg(5)); // OrderFail 3562 SubExprs.push_back(TheCall->getArg(2)); // Val2 3563 SubExprs.push_back(TheCall->getArg(3)); // Weak 3564 break; 3565 } 3566 3567 if (SubExprs.size() >= 2 && Form != Init) { 3568 llvm::APSInt Result(32); 3569 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) && 3570 !isValidOrderingForOp(Result.getSExtValue(), Op)) 3571 Diag(SubExprs[1]->getLocStart(), 3572 diag::warn_atomic_op_has_invalid_memory_order) 3573 << SubExprs[1]->getSourceRange(); 3574 } 3575 3576 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 3577 auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1); 3578 llvm::APSInt Result(32); 3579 if (Scope->isIntegerConstantExpr(Result, Context) && 3580 !ScopeModel->isValid(Result.getZExtValue())) { 3581 Diag(Scope->getLocStart(), diag::err_atomic_op_has_invalid_synch_scope) 3582 << Scope->getSourceRange(); 3583 } 3584 SubExprs.push_back(Scope); 3585 } 3586 3587 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(), 3588 SubExprs, ResultType, Op, 3589 TheCall->getRParenLoc()); 3590 3591 if ((Op == AtomicExpr::AO__c11_atomic_load || 3592 Op == AtomicExpr::AO__c11_atomic_store || 3593 Op == AtomicExpr::AO__opencl_atomic_load || 3594 Op == AtomicExpr::AO__opencl_atomic_store ) && 3595 Context.AtomicUsesUnsupportedLibcall(AE)) 3596 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) 3597 << ((Op == AtomicExpr::AO__c11_atomic_load || 3598 Op == AtomicExpr::AO__opencl_atomic_load) 3599 ? 0 : 1); 3600 3601 return AE; 3602 } 3603 3604 /// checkBuiltinArgument - Given a call to a builtin function, perform 3605 /// normal type-checking on the given argument, updating the call in 3606 /// place. This is useful when a builtin function requires custom 3607 /// type-checking for some of its arguments but not necessarily all of 3608 /// them. 3609 /// 3610 /// Returns true on error. 3611 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 3612 FunctionDecl *Fn = E->getDirectCallee(); 3613 assert(Fn && "builtin call without direct callee!"); 3614 3615 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 3616 InitializedEntity Entity = 3617 InitializedEntity::InitializeParameter(S.Context, Param); 3618 3619 ExprResult Arg = E->getArg(0); 3620 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 3621 if (Arg.isInvalid()) 3622 return true; 3623 3624 E->setArg(ArgIndex, Arg.get()); 3625 return false; 3626 } 3627 3628 /// SemaBuiltinAtomicOverloaded - We have a call to a function like 3629 /// __sync_fetch_and_add, which is an overloaded function based on the pointer 3630 /// type of its first argument. The main ActOnCallExpr routines have already 3631 /// promoted the types of arguments because all of these calls are prototyped as 3632 /// void(...). 3633 /// 3634 /// This function goes through and does final semantic checking for these 3635 /// builtins, 3636 ExprResult 3637 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 3638 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 3639 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 3640 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 3641 3642 // Ensure that we have at least one argument to do type inference from. 3643 if (TheCall->getNumArgs() < 1) { 3644 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 3645 << 0 << 1 << TheCall->getNumArgs() 3646 << TheCall->getCallee()->getSourceRange(); 3647 return ExprError(); 3648 } 3649 3650 // Inspect the first argument of the atomic builtin. This should always be 3651 // a pointer type, whose element is an integral scalar or pointer type. 3652 // Because it is a pointer type, we don't have to worry about any implicit 3653 // casts here. 3654 // FIXME: We don't allow floating point scalars as input. 3655 Expr *FirstArg = TheCall->getArg(0); 3656 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 3657 if (FirstArgResult.isInvalid()) 3658 return ExprError(); 3659 FirstArg = FirstArgResult.get(); 3660 TheCall->setArg(0, FirstArg); 3661 3662 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 3663 if (!pointerType) { 3664 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 3665 << FirstArg->getType() << FirstArg->getSourceRange(); 3666 return ExprError(); 3667 } 3668 3669 QualType ValType = pointerType->getPointeeType(); 3670 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 3671 !ValType->isBlockPointerType()) { 3672 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr) 3673 << FirstArg->getType() << FirstArg->getSourceRange(); 3674 return ExprError(); 3675 } 3676 3677 if (ValType.isConstQualified()) { 3678 Diag(DRE->getLocStart(), diag::err_atomic_builtin_cannot_be_const) 3679 << FirstArg->getType() << FirstArg->getSourceRange(); 3680 return ExprError(); 3681 } 3682 3683 switch (ValType.getObjCLifetime()) { 3684 case Qualifiers::OCL_None: 3685 case Qualifiers::OCL_ExplicitNone: 3686 // okay 3687 break; 3688 3689 case Qualifiers::OCL_Weak: 3690 case Qualifiers::OCL_Strong: 3691 case Qualifiers::OCL_Autoreleasing: 3692 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 3693 << ValType << FirstArg->getSourceRange(); 3694 return ExprError(); 3695 } 3696 3697 // Strip any qualifiers off ValType. 3698 ValType = ValType.getUnqualifiedType(); 3699 3700 // The majority of builtins return a value, but a few have special return 3701 // types, so allow them to override appropriately below. 3702 QualType ResultType = ValType; 3703 3704 // We need to figure out which concrete builtin this maps onto. For example, 3705 // __sync_fetch_and_add with a 2 byte object turns into 3706 // __sync_fetch_and_add_2. 3707 #define BUILTIN_ROW(x) \ 3708 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 3709 Builtin::BI##x##_8, Builtin::BI##x##_16 } 3710 3711 static const unsigned BuiltinIndices[][5] = { 3712 BUILTIN_ROW(__sync_fetch_and_add), 3713 BUILTIN_ROW(__sync_fetch_and_sub), 3714 BUILTIN_ROW(__sync_fetch_and_or), 3715 BUILTIN_ROW(__sync_fetch_and_and), 3716 BUILTIN_ROW(__sync_fetch_and_xor), 3717 BUILTIN_ROW(__sync_fetch_and_nand), 3718 3719 BUILTIN_ROW(__sync_add_and_fetch), 3720 BUILTIN_ROW(__sync_sub_and_fetch), 3721 BUILTIN_ROW(__sync_and_and_fetch), 3722 BUILTIN_ROW(__sync_or_and_fetch), 3723 BUILTIN_ROW(__sync_xor_and_fetch), 3724 BUILTIN_ROW(__sync_nand_and_fetch), 3725 3726 BUILTIN_ROW(__sync_val_compare_and_swap), 3727 BUILTIN_ROW(__sync_bool_compare_and_swap), 3728 BUILTIN_ROW(__sync_lock_test_and_set), 3729 BUILTIN_ROW(__sync_lock_release), 3730 BUILTIN_ROW(__sync_swap) 3731 }; 3732 #undef BUILTIN_ROW 3733 3734 // Determine the index of the size. 3735 unsigned SizeIndex; 3736 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 3737 case 1: SizeIndex = 0; break; 3738 case 2: SizeIndex = 1; break; 3739 case 4: SizeIndex = 2; break; 3740 case 8: SizeIndex = 3; break; 3741 case 16: SizeIndex = 4; break; 3742 default: 3743 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size) 3744 << FirstArg->getType() << FirstArg->getSourceRange(); 3745 return ExprError(); 3746 } 3747 3748 // Each of these builtins has one pointer argument, followed by some number of 3749 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 3750 // that we ignore. Find out which row of BuiltinIndices to read from as well 3751 // as the number of fixed args. 3752 unsigned BuiltinID = FDecl->getBuiltinID(); 3753 unsigned BuiltinIndex, NumFixed = 1; 3754 bool WarnAboutSemanticsChange = false; 3755 switch (BuiltinID) { 3756 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 3757 case Builtin::BI__sync_fetch_and_add: 3758 case Builtin::BI__sync_fetch_and_add_1: 3759 case Builtin::BI__sync_fetch_and_add_2: 3760 case Builtin::BI__sync_fetch_and_add_4: 3761 case Builtin::BI__sync_fetch_and_add_8: 3762 case Builtin::BI__sync_fetch_and_add_16: 3763 BuiltinIndex = 0; 3764 break; 3765 3766 case Builtin::BI__sync_fetch_and_sub: 3767 case Builtin::BI__sync_fetch_and_sub_1: 3768 case Builtin::BI__sync_fetch_and_sub_2: 3769 case Builtin::BI__sync_fetch_and_sub_4: 3770 case Builtin::BI__sync_fetch_and_sub_8: 3771 case Builtin::BI__sync_fetch_and_sub_16: 3772 BuiltinIndex = 1; 3773 break; 3774 3775 case Builtin::BI__sync_fetch_and_or: 3776 case Builtin::BI__sync_fetch_and_or_1: 3777 case Builtin::BI__sync_fetch_and_or_2: 3778 case Builtin::BI__sync_fetch_and_or_4: 3779 case Builtin::BI__sync_fetch_and_or_8: 3780 case Builtin::BI__sync_fetch_and_or_16: 3781 BuiltinIndex = 2; 3782 break; 3783 3784 case Builtin::BI__sync_fetch_and_and: 3785 case Builtin::BI__sync_fetch_and_and_1: 3786 case Builtin::BI__sync_fetch_and_and_2: 3787 case Builtin::BI__sync_fetch_and_and_4: 3788 case Builtin::BI__sync_fetch_and_and_8: 3789 case Builtin::BI__sync_fetch_and_and_16: 3790 BuiltinIndex = 3; 3791 break; 3792 3793 case Builtin::BI__sync_fetch_and_xor: 3794 case Builtin::BI__sync_fetch_and_xor_1: 3795 case Builtin::BI__sync_fetch_and_xor_2: 3796 case Builtin::BI__sync_fetch_and_xor_4: 3797 case Builtin::BI__sync_fetch_and_xor_8: 3798 case Builtin::BI__sync_fetch_and_xor_16: 3799 BuiltinIndex = 4; 3800 break; 3801 3802 case Builtin::BI__sync_fetch_and_nand: 3803 case Builtin::BI__sync_fetch_and_nand_1: 3804 case Builtin::BI__sync_fetch_and_nand_2: 3805 case Builtin::BI__sync_fetch_and_nand_4: 3806 case Builtin::BI__sync_fetch_and_nand_8: 3807 case Builtin::BI__sync_fetch_and_nand_16: 3808 BuiltinIndex = 5; 3809 WarnAboutSemanticsChange = true; 3810 break; 3811 3812 case Builtin::BI__sync_add_and_fetch: 3813 case Builtin::BI__sync_add_and_fetch_1: 3814 case Builtin::BI__sync_add_and_fetch_2: 3815 case Builtin::BI__sync_add_and_fetch_4: 3816 case Builtin::BI__sync_add_and_fetch_8: 3817 case Builtin::BI__sync_add_and_fetch_16: 3818 BuiltinIndex = 6; 3819 break; 3820 3821 case Builtin::BI__sync_sub_and_fetch: 3822 case Builtin::BI__sync_sub_and_fetch_1: 3823 case Builtin::BI__sync_sub_and_fetch_2: 3824 case Builtin::BI__sync_sub_and_fetch_4: 3825 case Builtin::BI__sync_sub_and_fetch_8: 3826 case Builtin::BI__sync_sub_and_fetch_16: 3827 BuiltinIndex = 7; 3828 break; 3829 3830 case Builtin::BI__sync_and_and_fetch: 3831 case Builtin::BI__sync_and_and_fetch_1: 3832 case Builtin::BI__sync_and_and_fetch_2: 3833 case Builtin::BI__sync_and_and_fetch_4: 3834 case Builtin::BI__sync_and_and_fetch_8: 3835 case Builtin::BI__sync_and_and_fetch_16: 3836 BuiltinIndex = 8; 3837 break; 3838 3839 case Builtin::BI__sync_or_and_fetch: 3840 case Builtin::BI__sync_or_and_fetch_1: 3841 case Builtin::BI__sync_or_and_fetch_2: 3842 case Builtin::BI__sync_or_and_fetch_4: 3843 case Builtin::BI__sync_or_and_fetch_8: 3844 case Builtin::BI__sync_or_and_fetch_16: 3845 BuiltinIndex = 9; 3846 break; 3847 3848 case Builtin::BI__sync_xor_and_fetch: 3849 case Builtin::BI__sync_xor_and_fetch_1: 3850 case Builtin::BI__sync_xor_and_fetch_2: 3851 case Builtin::BI__sync_xor_and_fetch_4: 3852 case Builtin::BI__sync_xor_and_fetch_8: 3853 case Builtin::BI__sync_xor_and_fetch_16: 3854 BuiltinIndex = 10; 3855 break; 3856 3857 case Builtin::BI__sync_nand_and_fetch: 3858 case Builtin::BI__sync_nand_and_fetch_1: 3859 case Builtin::BI__sync_nand_and_fetch_2: 3860 case Builtin::BI__sync_nand_and_fetch_4: 3861 case Builtin::BI__sync_nand_and_fetch_8: 3862 case Builtin::BI__sync_nand_and_fetch_16: 3863 BuiltinIndex = 11; 3864 WarnAboutSemanticsChange = true; 3865 break; 3866 3867 case Builtin::BI__sync_val_compare_and_swap: 3868 case Builtin::BI__sync_val_compare_and_swap_1: 3869 case Builtin::BI__sync_val_compare_and_swap_2: 3870 case Builtin::BI__sync_val_compare_and_swap_4: 3871 case Builtin::BI__sync_val_compare_and_swap_8: 3872 case Builtin::BI__sync_val_compare_and_swap_16: 3873 BuiltinIndex = 12; 3874 NumFixed = 2; 3875 break; 3876 3877 case Builtin::BI__sync_bool_compare_and_swap: 3878 case Builtin::BI__sync_bool_compare_and_swap_1: 3879 case Builtin::BI__sync_bool_compare_and_swap_2: 3880 case Builtin::BI__sync_bool_compare_and_swap_4: 3881 case Builtin::BI__sync_bool_compare_and_swap_8: 3882 case Builtin::BI__sync_bool_compare_and_swap_16: 3883 BuiltinIndex = 13; 3884 NumFixed = 2; 3885 ResultType = Context.BoolTy; 3886 break; 3887 3888 case Builtin::BI__sync_lock_test_and_set: 3889 case Builtin::BI__sync_lock_test_and_set_1: 3890 case Builtin::BI__sync_lock_test_and_set_2: 3891 case Builtin::BI__sync_lock_test_and_set_4: 3892 case Builtin::BI__sync_lock_test_and_set_8: 3893 case Builtin::BI__sync_lock_test_and_set_16: 3894 BuiltinIndex = 14; 3895 break; 3896 3897 case Builtin::BI__sync_lock_release: 3898 case Builtin::BI__sync_lock_release_1: 3899 case Builtin::BI__sync_lock_release_2: 3900 case Builtin::BI__sync_lock_release_4: 3901 case Builtin::BI__sync_lock_release_8: 3902 case Builtin::BI__sync_lock_release_16: 3903 BuiltinIndex = 15; 3904 NumFixed = 0; 3905 ResultType = Context.VoidTy; 3906 break; 3907 3908 case Builtin::BI__sync_swap: 3909 case Builtin::BI__sync_swap_1: 3910 case Builtin::BI__sync_swap_2: 3911 case Builtin::BI__sync_swap_4: 3912 case Builtin::BI__sync_swap_8: 3913 case Builtin::BI__sync_swap_16: 3914 BuiltinIndex = 16; 3915 break; 3916 } 3917 3918 // Now that we know how many fixed arguments we expect, first check that we 3919 // have at least that many. 3920 if (TheCall->getNumArgs() < 1+NumFixed) { 3921 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 3922 << 0 << 1+NumFixed << TheCall->getNumArgs() 3923 << TheCall->getCallee()->getSourceRange(); 3924 return ExprError(); 3925 } 3926 3927 if (WarnAboutSemanticsChange) { 3928 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change) 3929 << TheCall->getCallee()->getSourceRange(); 3930 } 3931 3932 // Get the decl for the concrete builtin from this, we can tell what the 3933 // concrete integer type we should convert to is. 3934 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 3935 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 3936 FunctionDecl *NewBuiltinDecl; 3937 if (NewBuiltinID == BuiltinID) 3938 NewBuiltinDecl = FDecl; 3939 else { 3940 // Perform builtin lookup to avoid redeclaring it. 3941 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 3942 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName); 3943 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 3944 assert(Res.getFoundDecl()); 3945 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 3946 if (!NewBuiltinDecl) 3947 return ExprError(); 3948 } 3949 3950 // The first argument --- the pointer --- has a fixed type; we 3951 // deduce the types of the rest of the arguments accordingly. Walk 3952 // the remaining arguments, converting them to the deduced value type. 3953 for (unsigned i = 0; i != NumFixed; ++i) { 3954 ExprResult Arg = TheCall->getArg(i+1); 3955 3956 // GCC does an implicit conversion to the pointer or integer ValType. This 3957 // can fail in some cases (1i -> int**), check for this error case now. 3958 // Initialize the argument. 3959 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 3960 ValType, /*consume*/ false); 3961 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 3962 if (Arg.isInvalid()) 3963 return ExprError(); 3964 3965 // Okay, we have something that *can* be converted to the right type. Check 3966 // to see if there is a potentially weird extension going on here. This can 3967 // happen when you do an atomic operation on something like an char* and 3968 // pass in 42. The 42 gets converted to char. This is even more strange 3969 // for things like 45.123 -> char, etc. 3970 // FIXME: Do this check. 3971 TheCall->setArg(i+1, Arg.get()); 3972 } 3973 3974 ASTContext& Context = this->getASTContext(); 3975 3976 // Create a new DeclRefExpr to refer to the new decl. 3977 DeclRefExpr* NewDRE = DeclRefExpr::Create( 3978 Context, 3979 DRE->getQualifierLoc(), 3980 SourceLocation(), 3981 NewBuiltinDecl, 3982 /*enclosing*/ false, 3983 DRE->getLocation(), 3984 Context.BuiltinFnTy, 3985 DRE->getValueKind()); 3986 3987 // Set the callee in the CallExpr. 3988 // FIXME: This loses syntactic information. 3989 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 3990 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 3991 CK_BuiltinFnToFnPtr); 3992 TheCall->setCallee(PromotedCall.get()); 3993 3994 // Change the result type of the call to match the original value type. This 3995 // is arbitrary, but the codegen for these builtins ins design to handle it 3996 // gracefully. 3997 TheCall->setType(ResultType); 3998 3999 return TheCallResult; 4000 } 4001 4002 /// SemaBuiltinNontemporalOverloaded - We have a call to 4003 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 4004 /// overloaded function based on the pointer type of its last argument. 4005 /// 4006 /// This function goes through and does final semantic checking for these 4007 /// builtins. 4008 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 4009 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 4010 DeclRefExpr *DRE = 4011 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4012 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 4013 unsigned BuiltinID = FDecl->getBuiltinID(); 4014 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 4015 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 4016 "Unexpected nontemporal load/store builtin!"); 4017 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 4018 unsigned numArgs = isStore ? 2 : 1; 4019 4020 // Ensure that we have the proper number of arguments. 4021 if (checkArgCount(*this, TheCall, numArgs)) 4022 return ExprError(); 4023 4024 // Inspect the last argument of the nontemporal builtin. This should always 4025 // be a pointer type, from which we imply the type of the memory access. 4026 // Because it is a pointer type, we don't have to worry about any implicit 4027 // casts here. 4028 Expr *PointerArg = TheCall->getArg(numArgs - 1); 4029 ExprResult PointerArgResult = 4030 DefaultFunctionArrayLvalueConversion(PointerArg); 4031 4032 if (PointerArgResult.isInvalid()) 4033 return ExprError(); 4034 PointerArg = PointerArgResult.get(); 4035 TheCall->setArg(numArgs - 1, PointerArg); 4036 4037 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 4038 if (!pointerType) { 4039 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer) 4040 << PointerArg->getType() << PointerArg->getSourceRange(); 4041 return ExprError(); 4042 } 4043 4044 QualType ValType = pointerType->getPointeeType(); 4045 4046 // Strip any qualifiers off ValType. 4047 ValType = ValType.getUnqualifiedType(); 4048 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 4049 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 4050 !ValType->isVectorType()) { 4051 Diag(DRE->getLocStart(), 4052 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 4053 << PointerArg->getType() << PointerArg->getSourceRange(); 4054 return ExprError(); 4055 } 4056 4057 if (!isStore) { 4058 TheCall->setType(ValType); 4059 return TheCallResult; 4060 } 4061 4062 ExprResult ValArg = TheCall->getArg(0); 4063 InitializedEntity Entity = InitializedEntity::InitializeParameter( 4064 Context, ValType, /*consume*/ false); 4065 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 4066 if (ValArg.isInvalid()) 4067 return ExprError(); 4068 4069 TheCall->setArg(0, ValArg.get()); 4070 TheCall->setType(Context.VoidTy); 4071 return TheCallResult; 4072 } 4073 4074 /// CheckObjCString - Checks that the argument to the builtin 4075 /// CFString constructor is correct 4076 /// Note: It might also make sense to do the UTF-16 conversion here (would 4077 /// simplify the backend). 4078 bool Sema::CheckObjCString(Expr *Arg) { 4079 Arg = Arg->IgnoreParenCasts(); 4080 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 4081 4082 if (!Literal || !Literal->isAscii()) { 4083 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant) 4084 << Arg->getSourceRange(); 4085 return true; 4086 } 4087 4088 if (Literal->containsNonAsciiOrNull()) { 4089 StringRef String = Literal->getString(); 4090 unsigned NumBytes = String.size(); 4091 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 4092 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 4093 llvm::UTF16 *ToPtr = &ToBuf[0]; 4094 4095 llvm::ConversionResult Result = 4096 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 4097 ToPtr + NumBytes, llvm::strictConversion); 4098 // Check for conversion failure. 4099 if (Result != llvm::conversionOK) 4100 Diag(Arg->getLocStart(), 4101 diag::warn_cfstring_truncated) << Arg->getSourceRange(); 4102 } 4103 return false; 4104 } 4105 4106 /// CheckObjCString - Checks that the format string argument to the os_log() 4107 /// and os_trace() functions is correct, and converts it to const char *. 4108 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 4109 Arg = Arg->IgnoreParenCasts(); 4110 auto *Literal = dyn_cast<StringLiteral>(Arg); 4111 if (!Literal) { 4112 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 4113 Literal = ObjcLiteral->getString(); 4114 } 4115 } 4116 4117 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 4118 return ExprError( 4119 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant) 4120 << Arg->getSourceRange()); 4121 } 4122 4123 ExprResult Result(Literal); 4124 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 4125 InitializedEntity Entity = 4126 InitializedEntity::InitializeParameter(Context, ResultTy, false); 4127 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 4128 return Result; 4129 } 4130 4131 /// Check that the user is calling the appropriate va_start builtin for the 4132 /// target and calling convention. 4133 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 4134 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 4135 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 4136 bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64; 4137 bool IsWindows = TT.isOSWindows(); 4138 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 4139 if (IsX64 || IsAArch64) { 4140 CallingConv CC = CC_C; 4141 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 4142 CC = FD->getType()->getAs<FunctionType>()->getCallConv(); 4143 if (IsMSVAStart) { 4144 // Don't allow this in System V ABI functions. 4145 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 4146 return S.Diag(Fn->getLocStart(), 4147 diag::err_ms_va_start_used_in_sysv_function); 4148 } else { 4149 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 4150 // On x64 Windows, don't allow this in System V ABI functions. 4151 // (Yes, that means there's no corresponding way to support variadic 4152 // System V ABI functions on Windows.) 4153 if ((IsWindows && CC == CC_X86_64SysV) || 4154 (!IsWindows && CC == CC_Win64)) 4155 return S.Diag(Fn->getLocStart(), 4156 diag::err_va_start_used_in_wrong_abi_function) 4157 << !IsWindows; 4158 } 4159 return false; 4160 } 4161 4162 if (IsMSVAStart) 4163 return S.Diag(Fn->getLocStart(), diag::err_builtin_x64_aarch64_only); 4164 return false; 4165 } 4166 4167 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 4168 ParmVarDecl **LastParam = nullptr) { 4169 // Determine whether the current function, block, or obj-c method is variadic 4170 // and get its parameter list. 4171 bool IsVariadic = false; 4172 ArrayRef<ParmVarDecl *> Params; 4173 DeclContext *Caller = S.CurContext; 4174 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 4175 IsVariadic = Block->isVariadic(); 4176 Params = Block->parameters(); 4177 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 4178 IsVariadic = FD->isVariadic(); 4179 Params = FD->parameters(); 4180 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 4181 IsVariadic = MD->isVariadic(); 4182 // FIXME: This isn't correct for methods (results in bogus warning). 4183 Params = MD->parameters(); 4184 } else if (isa<CapturedDecl>(Caller)) { 4185 // We don't support va_start in a CapturedDecl. 4186 S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt); 4187 return true; 4188 } else { 4189 // This must be some other declcontext that parses exprs. 4190 S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function); 4191 return true; 4192 } 4193 4194 if (!IsVariadic) { 4195 S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function); 4196 return true; 4197 } 4198 4199 if (LastParam) 4200 *LastParam = Params.empty() ? nullptr : Params.back(); 4201 4202 return false; 4203 } 4204 4205 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 4206 /// for validity. Emit an error and return true on failure; return false 4207 /// on success. 4208 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 4209 Expr *Fn = TheCall->getCallee(); 4210 4211 if (checkVAStartABI(*this, BuiltinID, Fn)) 4212 return true; 4213 4214 if (TheCall->getNumArgs() > 2) { 4215 Diag(TheCall->getArg(2)->getLocStart(), 4216 diag::err_typecheck_call_too_many_args) 4217 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 4218 << Fn->getSourceRange() 4219 << SourceRange(TheCall->getArg(2)->getLocStart(), 4220 (*(TheCall->arg_end()-1))->getLocEnd()); 4221 return true; 4222 } 4223 4224 if (TheCall->getNumArgs() < 2) { 4225 return Diag(TheCall->getLocEnd(), 4226 diag::err_typecheck_call_too_few_args_at_least) 4227 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 4228 } 4229 4230 // Type-check the first argument normally. 4231 if (checkBuiltinArgument(*this, TheCall, 0)) 4232 return true; 4233 4234 // Check that the current function is variadic, and get its last parameter. 4235 ParmVarDecl *LastParam; 4236 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 4237 return true; 4238 4239 // Verify that the second argument to the builtin is the last argument of the 4240 // current function or method. 4241 bool SecondArgIsLastNamedArgument = false; 4242 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 4243 4244 // These are valid if SecondArgIsLastNamedArgument is false after the next 4245 // block. 4246 QualType Type; 4247 SourceLocation ParamLoc; 4248 bool IsCRegister = false; 4249 4250 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 4251 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 4252 SecondArgIsLastNamedArgument = PV == LastParam; 4253 4254 Type = PV->getType(); 4255 ParamLoc = PV->getLocation(); 4256 IsCRegister = 4257 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 4258 } 4259 } 4260 4261 if (!SecondArgIsLastNamedArgument) 4262 Diag(TheCall->getArg(1)->getLocStart(), 4263 diag::warn_second_arg_of_va_start_not_last_named_param); 4264 else if (IsCRegister || Type->isReferenceType() || 4265 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 4266 // Promotable integers are UB, but enumerations need a bit of 4267 // extra checking to see what their promotable type actually is. 4268 if (!Type->isPromotableIntegerType()) 4269 return false; 4270 if (!Type->isEnumeralType()) 4271 return true; 4272 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl(); 4273 return !(ED && 4274 Context.typesAreCompatible(ED->getPromotionType(), Type)); 4275 }()) { 4276 unsigned Reason = 0; 4277 if (Type->isReferenceType()) Reason = 1; 4278 else if (IsCRegister) Reason = 2; 4279 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason; 4280 Diag(ParamLoc, diag::note_parameter_type) << Type; 4281 } 4282 4283 TheCall->setType(Context.VoidTy); 4284 return false; 4285 } 4286 4287 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 4288 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 4289 // const char *named_addr); 4290 4291 Expr *Func = Call->getCallee(); 4292 4293 if (Call->getNumArgs() < 3) 4294 return Diag(Call->getLocEnd(), 4295 diag::err_typecheck_call_too_few_args_at_least) 4296 << 0 /*function call*/ << 3 << Call->getNumArgs(); 4297 4298 // Type-check the first argument normally. 4299 if (checkBuiltinArgument(*this, Call, 0)) 4300 return true; 4301 4302 // Check that the current function is variadic. 4303 if (checkVAStartIsInVariadicFunction(*this, Func)) 4304 return true; 4305 4306 // __va_start on Windows does not validate the parameter qualifiers 4307 4308 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 4309 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 4310 4311 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 4312 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 4313 4314 const QualType &ConstCharPtrTy = 4315 Context.getPointerType(Context.CharTy.withConst()); 4316 if (!Arg1Ty->isPointerType() || 4317 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy) 4318 Diag(Arg1->getLocStart(), diag::err_typecheck_convert_incompatible) 4319 << Arg1->getType() << ConstCharPtrTy 4320 << 1 /* different class */ 4321 << 0 /* qualifier difference */ 4322 << 3 /* parameter mismatch */ 4323 << 2 << Arg1->getType() << ConstCharPtrTy; 4324 4325 const QualType SizeTy = Context.getSizeType(); 4326 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 4327 Diag(Arg2->getLocStart(), diag::err_typecheck_convert_incompatible) 4328 << Arg2->getType() << SizeTy 4329 << 1 /* different class */ 4330 << 0 /* qualifier difference */ 4331 << 3 /* parameter mismatch */ 4332 << 3 << Arg2->getType() << SizeTy; 4333 4334 return false; 4335 } 4336 4337 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 4338 /// friends. This is declared to take (...), so we have to check everything. 4339 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 4340 if (TheCall->getNumArgs() < 2) 4341 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 4342 << 0 << 2 << TheCall->getNumArgs()/*function call*/; 4343 if (TheCall->getNumArgs() > 2) 4344 return Diag(TheCall->getArg(2)->getLocStart(), 4345 diag::err_typecheck_call_too_many_args) 4346 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 4347 << SourceRange(TheCall->getArg(2)->getLocStart(), 4348 (*(TheCall->arg_end()-1))->getLocEnd()); 4349 4350 ExprResult OrigArg0 = TheCall->getArg(0); 4351 ExprResult OrigArg1 = TheCall->getArg(1); 4352 4353 // Do standard promotions between the two arguments, returning their common 4354 // type. 4355 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false); 4356 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 4357 return true; 4358 4359 // Make sure any conversions are pushed back into the call; this is 4360 // type safe since unordered compare builtins are declared as "_Bool 4361 // foo(...)". 4362 TheCall->setArg(0, OrigArg0.get()); 4363 TheCall->setArg(1, OrigArg1.get()); 4364 4365 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 4366 return false; 4367 4368 // If the common type isn't a real floating type, then the arguments were 4369 // invalid for this operation. 4370 if (Res.isNull() || !Res->isRealFloatingType()) 4371 return Diag(OrigArg0.get()->getLocStart(), 4372 diag::err_typecheck_call_invalid_ordered_compare) 4373 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 4374 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd()); 4375 4376 return false; 4377 } 4378 4379 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 4380 /// __builtin_isnan and friends. This is declared to take (...), so we have 4381 /// to check everything. We expect the last argument to be a floating point 4382 /// value. 4383 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 4384 if (TheCall->getNumArgs() < NumArgs) 4385 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 4386 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/; 4387 if (TheCall->getNumArgs() > NumArgs) 4388 return Diag(TheCall->getArg(NumArgs)->getLocStart(), 4389 diag::err_typecheck_call_too_many_args) 4390 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 4391 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(), 4392 (*(TheCall->arg_end()-1))->getLocEnd()); 4393 4394 Expr *OrigArg = TheCall->getArg(NumArgs-1); 4395 4396 if (OrigArg->isTypeDependent()) 4397 return false; 4398 4399 // This operation requires a non-_Complex floating-point number. 4400 if (!OrigArg->getType()->isRealFloatingType()) 4401 return Diag(OrigArg->getLocStart(), 4402 diag::err_typecheck_call_invalid_unary_fp) 4403 << OrigArg->getType() << OrigArg->getSourceRange(); 4404 4405 // If this is an implicit conversion from float -> float or double, remove it. 4406 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) { 4407 // Only remove standard FloatCasts, leaving other casts inplace 4408 if (Cast->getCastKind() == CK_FloatingCast) { 4409 Expr *CastArg = Cast->getSubExpr(); 4410 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) { 4411 assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) || 4412 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) && 4413 "promotion from float to either float or double is the only expected cast here"); 4414 Cast->setSubExpr(nullptr); 4415 TheCall->setArg(NumArgs-1, CastArg); 4416 } 4417 } 4418 } 4419 4420 return false; 4421 } 4422 4423 // Customized Sema Checking for VSX builtins that have the following signature: 4424 // vector [...] builtinName(vector [...], vector [...], const int); 4425 // Which takes the same type of vectors (any legal vector type) for the first 4426 // two arguments and takes compile time constant for the third argument. 4427 // Example builtins are : 4428 // vector double vec_xxpermdi(vector double, vector double, int); 4429 // vector short vec_xxsldwi(vector short, vector short, int); 4430 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 4431 unsigned ExpectedNumArgs = 3; 4432 if (TheCall->getNumArgs() < ExpectedNumArgs) 4433 return Diag(TheCall->getLocEnd(), 4434 diag::err_typecheck_call_too_few_args_at_least) 4435 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 4436 << TheCall->getSourceRange(); 4437 4438 if (TheCall->getNumArgs() > ExpectedNumArgs) 4439 return Diag(TheCall->getLocEnd(), 4440 diag::err_typecheck_call_too_many_args_at_most) 4441 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 4442 << TheCall->getSourceRange(); 4443 4444 // Check the third argument is a compile time constant 4445 llvm::APSInt Value; 4446 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context)) 4447 return Diag(TheCall->getLocStart(), 4448 diag::err_vsx_builtin_nonconstant_argument) 4449 << 3 /* argument index */ << TheCall->getDirectCallee() 4450 << SourceRange(TheCall->getArg(2)->getLocStart(), 4451 TheCall->getArg(2)->getLocEnd()); 4452 4453 QualType Arg1Ty = TheCall->getArg(0)->getType(); 4454 QualType Arg2Ty = TheCall->getArg(1)->getType(); 4455 4456 // Check the type of argument 1 and argument 2 are vectors. 4457 SourceLocation BuiltinLoc = TheCall->getLocStart(); 4458 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 4459 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 4460 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 4461 << TheCall->getDirectCallee() 4462 << SourceRange(TheCall->getArg(0)->getLocStart(), 4463 TheCall->getArg(1)->getLocEnd()); 4464 } 4465 4466 // Check the first two arguments are the same type. 4467 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 4468 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 4469 << TheCall->getDirectCallee() 4470 << SourceRange(TheCall->getArg(0)->getLocStart(), 4471 TheCall->getArg(1)->getLocEnd()); 4472 } 4473 4474 // When default clang type checking is turned off and the customized type 4475 // checking is used, the returning type of the function must be explicitly 4476 // set. Otherwise it is _Bool by default. 4477 TheCall->setType(Arg1Ty); 4478 4479 return false; 4480 } 4481 4482 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 4483 // This is declared to take (...), so we have to check everything. 4484 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 4485 if (TheCall->getNumArgs() < 2) 4486 return ExprError(Diag(TheCall->getLocEnd(), 4487 diag::err_typecheck_call_too_few_args_at_least) 4488 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 4489 << TheCall->getSourceRange()); 4490 4491 // Determine which of the following types of shufflevector we're checking: 4492 // 1) unary, vector mask: (lhs, mask) 4493 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 4494 QualType resType = TheCall->getArg(0)->getType(); 4495 unsigned numElements = 0; 4496 4497 if (!TheCall->getArg(0)->isTypeDependent() && 4498 !TheCall->getArg(1)->isTypeDependent()) { 4499 QualType LHSType = TheCall->getArg(0)->getType(); 4500 QualType RHSType = TheCall->getArg(1)->getType(); 4501 4502 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 4503 return ExprError(Diag(TheCall->getLocStart(), 4504 diag::err_vec_builtin_non_vector) 4505 << TheCall->getDirectCallee() 4506 << SourceRange(TheCall->getArg(0)->getLocStart(), 4507 TheCall->getArg(1)->getLocEnd())); 4508 4509 numElements = LHSType->getAs<VectorType>()->getNumElements(); 4510 unsigned numResElements = TheCall->getNumArgs() - 2; 4511 4512 // Check to see if we have a call with 2 vector arguments, the unary shuffle 4513 // with mask. If so, verify that RHS is an integer vector type with the 4514 // same number of elts as lhs. 4515 if (TheCall->getNumArgs() == 2) { 4516 if (!RHSType->hasIntegerRepresentation() || 4517 RHSType->getAs<VectorType>()->getNumElements() != numElements) 4518 return ExprError(Diag(TheCall->getLocStart(), 4519 diag::err_vec_builtin_incompatible_vector) 4520 << TheCall->getDirectCallee() 4521 << SourceRange(TheCall->getArg(1)->getLocStart(), 4522 TheCall->getArg(1)->getLocEnd())); 4523 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 4524 return ExprError(Diag(TheCall->getLocStart(), 4525 diag::err_vec_builtin_incompatible_vector) 4526 << TheCall->getDirectCallee() 4527 << SourceRange(TheCall->getArg(0)->getLocStart(), 4528 TheCall->getArg(1)->getLocEnd())); 4529 } else if (numElements != numResElements) { 4530 QualType eltType = LHSType->getAs<VectorType>()->getElementType(); 4531 resType = Context.getVectorType(eltType, numResElements, 4532 VectorType::GenericVector); 4533 } 4534 } 4535 4536 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 4537 if (TheCall->getArg(i)->isTypeDependent() || 4538 TheCall->getArg(i)->isValueDependent()) 4539 continue; 4540 4541 llvm::APSInt Result(32); 4542 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 4543 return ExprError(Diag(TheCall->getLocStart(), 4544 diag::err_shufflevector_nonconstant_argument) 4545 << TheCall->getArg(i)->getSourceRange()); 4546 4547 // Allow -1 which will be translated to undef in the IR. 4548 if (Result.isSigned() && Result.isAllOnesValue()) 4549 continue; 4550 4551 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 4552 return ExprError(Diag(TheCall->getLocStart(), 4553 diag::err_shufflevector_argument_too_large) 4554 << TheCall->getArg(i)->getSourceRange()); 4555 } 4556 4557 SmallVector<Expr*, 32> exprs; 4558 4559 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 4560 exprs.push_back(TheCall->getArg(i)); 4561 TheCall->setArg(i, nullptr); 4562 } 4563 4564 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 4565 TheCall->getCallee()->getLocStart(), 4566 TheCall->getRParenLoc()); 4567 } 4568 4569 /// SemaConvertVectorExpr - Handle __builtin_convertvector 4570 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 4571 SourceLocation BuiltinLoc, 4572 SourceLocation RParenLoc) { 4573 ExprValueKind VK = VK_RValue; 4574 ExprObjectKind OK = OK_Ordinary; 4575 QualType DstTy = TInfo->getType(); 4576 QualType SrcTy = E->getType(); 4577 4578 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 4579 return ExprError(Diag(BuiltinLoc, 4580 diag::err_convertvector_non_vector) 4581 << E->getSourceRange()); 4582 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 4583 return ExprError(Diag(BuiltinLoc, 4584 diag::err_convertvector_non_vector_type)); 4585 4586 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 4587 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements(); 4588 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements(); 4589 if (SrcElts != DstElts) 4590 return ExprError(Diag(BuiltinLoc, 4591 diag::err_convertvector_incompatible_vector) 4592 << E->getSourceRange()); 4593 } 4594 4595 return new (Context) 4596 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 4597 } 4598 4599 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 4600 // This is declared to take (const void*, ...) and can take two 4601 // optional constant int args. 4602 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 4603 unsigned NumArgs = TheCall->getNumArgs(); 4604 4605 if (NumArgs > 3) 4606 return Diag(TheCall->getLocEnd(), 4607 diag::err_typecheck_call_too_many_args_at_most) 4608 << 0 /*function call*/ << 3 << NumArgs 4609 << TheCall->getSourceRange(); 4610 4611 // Argument 0 is checked for us and the remaining arguments must be 4612 // constant integers. 4613 for (unsigned i = 1; i != NumArgs; ++i) 4614 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 4615 return true; 4616 4617 return false; 4618 } 4619 4620 /// SemaBuiltinAssume - Handle __assume (MS Extension). 4621 // __assume does not evaluate its arguments, and should warn if its argument 4622 // has side effects. 4623 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 4624 Expr *Arg = TheCall->getArg(0); 4625 if (Arg->isInstantiationDependent()) return false; 4626 4627 if (Arg->HasSideEffects(Context)) 4628 Diag(Arg->getLocStart(), diag::warn_assume_side_effects) 4629 << Arg->getSourceRange() 4630 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 4631 4632 return false; 4633 } 4634 4635 /// Handle __builtin_alloca_with_align. This is declared 4636 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 4637 /// than 8. 4638 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 4639 // The alignment must be a constant integer. 4640 Expr *Arg = TheCall->getArg(1); 4641 4642 // We can't check the value of a dependent argument. 4643 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 4644 if (const auto *UE = 4645 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 4646 if (UE->getKind() == UETT_AlignOf) 4647 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof) 4648 << Arg->getSourceRange(); 4649 4650 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 4651 4652 if (!Result.isPowerOf2()) 4653 return Diag(TheCall->getLocStart(), 4654 diag::err_alignment_not_power_of_two) 4655 << Arg->getSourceRange(); 4656 4657 if (Result < Context.getCharWidth()) 4658 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small) 4659 << (unsigned)Context.getCharWidth() 4660 << Arg->getSourceRange(); 4661 4662 if (Result > std::numeric_limits<int32_t>::max()) 4663 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big) 4664 << std::numeric_limits<int32_t>::max() 4665 << Arg->getSourceRange(); 4666 } 4667 4668 return false; 4669 } 4670 4671 /// Handle __builtin_assume_aligned. This is declared 4672 /// as (const void*, size_t, ...) and can take one optional constant int arg. 4673 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 4674 unsigned NumArgs = TheCall->getNumArgs(); 4675 4676 if (NumArgs > 3) 4677 return Diag(TheCall->getLocEnd(), 4678 diag::err_typecheck_call_too_many_args_at_most) 4679 << 0 /*function call*/ << 3 << NumArgs 4680 << TheCall->getSourceRange(); 4681 4682 // The alignment must be a constant integer. 4683 Expr *Arg = TheCall->getArg(1); 4684 4685 // We can't check the value of a dependent argument. 4686 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 4687 llvm::APSInt Result; 4688 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 4689 return true; 4690 4691 if (!Result.isPowerOf2()) 4692 return Diag(TheCall->getLocStart(), 4693 diag::err_alignment_not_power_of_two) 4694 << Arg->getSourceRange(); 4695 } 4696 4697 if (NumArgs > 2) { 4698 ExprResult Arg(TheCall->getArg(2)); 4699 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 4700 Context.getSizeType(), false); 4701 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4702 if (Arg.isInvalid()) return true; 4703 TheCall->setArg(2, Arg.get()); 4704 } 4705 4706 return false; 4707 } 4708 4709 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 4710 unsigned BuiltinID = 4711 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 4712 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 4713 4714 unsigned NumArgs = TheCall->getNumArgs(); 4715 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 4716 if (NumArgs < NumRequiredArgs) { 4717 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 4718 << 0 /* function call */ << NumRequiredArgs << NumArgs 4719 << TheCall->getSourceRange(); 4720 } 4721 if (NumArgs >= NumRequiredArgs + 0x100) { 4722 return Diag(TheCall->getLocEnd(), 4723 diag::err_typecheck_call_too_many_args_at_most) 4724 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 4725 << TheCall->getSourceRange(); 4726 } 4727 unsigned i = 0; 4728 4729 // For formatting call, check buffer arg. 4730 if (!IsSizeCall) { 4731 ExprResult Arg(TheCall->getArg(i)); 4732 InitializedEntity Entity = InitializedEntity::InitializeParameter( 4733 Context, Context.VoidPtrTy, false); 4734 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4735 if (Arg.isInvalid()) 4736 return true; 4737 TheCall->setArg(i, Arg.get()); 4738 i++; 4739 } 4740 4741 // Check string literal arg. 4742 unsigned FormatIdx = i; 4743 { 4744 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 4745 if (Arg.isInvalid()) 4746 return true; 4747 TheCall->setArg(i, Arg.get()); 4748 i++; 4749 } 4750 4751 // Make sure variadic args are scalar. 4752 unsigned FirstDataArg = i; 4753 while (i < NumArgs) { 4754 ExprResult Arg = DefaultVariadicArgumentPromotion( 4755 TheCall->getArg(i), VariadicFunction, nullptr); 4756 if (Arg.isInvalid()) 4757 return true; 4758 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 4759 if (ArgSize.getQuantity() >= 0x100) { 4760 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big) 4761 << i << (int)ArgSize.getQuantity() << 0xff 4762 << TheCall->getSourceRange(); 4763 } 4764 TheCall->setArg(i, Arg.get()); 4765 i++; 4766 } 4767 4768 // Check formatting specifiers. NOTE: We're only doing this for the non-size 4769 // call to avoid duplicate diagnostics. 4770 if (!IsSizeCall) { 4771 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 4772 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 4773 bool Success = CheckFormatArguments( 4774 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 4775 VariadicFunction, TheCall->getLocStart(), SourceRange(), 4776 CheckedVarArgs); 4777 if (!Success) 4778 return true; 4779 } 4780 4781 if (IsSizeCall) { 4782 TheCall->setType(Context.getSizeType()); 4783 } else { 4784 TheCall->setType(Context.VoidPtrTy); 4785 } 4786 return false; 4787 } 4788 4789 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 4790 /// TheCall is a constant expression. 4791 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 4792 llvm::APSInt &Result) { 4793 Expr *Arg = TheCall->getArg(ArgNum); 4794 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4795 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 4796 4797 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 4798 4799 if (!Arg->isIntegerConstantExpr(Result, Context)) 4800 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type) 4801 << FDecl->getDeclName() << Arg->getSourceRange(); 4802 4803 return false; 4804 } 4805 4806 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 4807 /// TheCall is a constant expression in the range [Low, High]. 4808 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 4809 int Low, int High) { 4810 llvm::APSInt Result; 4811 4812 // We can't check the value of a dependent argument. 4813 Expr *Arg = TheCall->getArg(ArgNum); 4814 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4815 return false; 4816 4817 // Check constant-ness first. 4818 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4819 return true; 4820 4821 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) 4822 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 4823 << Low << High << Arg->getSourceRange(); 4824 4825 return false; 4826 } 4827 4828 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 4829 /// TheCall is a constant expression is a multiple of Num.. 4830 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 4831 unsigned Num) { 4832 llvm::APSInt Result; 4833 4834 // We can't check the value of a dependent argument. 4835 Expr *Arg = TheCall->getArg(ArgNum); 4836 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4837 return false; 4838 4839 // Check constant-ness first. 4840 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4841 return true; 4842 4843 if (Result.getSExtValue() % Num != 0) 4844 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple) 4845 << Num << Arg->getSourceRange(); 4846 4847 return false; 4848 } 4849 4850 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 4851 /// TheCall is an ARM/AArch64 special register string literal. 4852 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 4853 int ArgNum, unsigned ExpectedFieldNum, 4854 bool AllowName) { 4855 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 4856 BuiltinID == ARM::BI__builtin_arm_wsr64 || 4857 BuiltinID == ARM::BI__builtin_arm_rsr || 4858 BuiltinID == ARM::BI__builtin_arm_rsrp || 4859 BuiltinID == ARM::BI__builtin_arm_wsr || 4860 BuiltinID == ARM::BI__builtin_arm_wsrp; 4861 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 4862 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 4863 BuiltinID == AArch64::BI__builtin_arm_rsr || 4864 BuiltinID == AArch64::BI__builtin_arm_rsrp || 4865 BuiltinID == AArch64::BI__builtin_arm_wsr || 4866 BuiltinID == AArch64::BI__builtin_arm_wsrp; 4867 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 4868 4869 // We can't check the value of a dependent argument. 4870 Expr *Arg = TheCall->getArg(ArgNum); 4871 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4872 return false; 4873 4874 // Check if the argument is a string literal. 4875 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 4876 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal) 4877 << Arg->getSourceRange(); 4878 4879 // Check the type of special register given. 4880 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 4881 SmallVector<StringRef, 6> Fields; 4882 Reg.split(Fields, ":"); 4883 4884 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 4885 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg) 4886 << Arg->getSourceRange(); 4887 4888 // If the string is the name of a register then we cannot check that it is 4889 // valid here but if the string is of one the forms described in ACLE then we 4890 // can check that the supplied fields are integers and within the valid 4891 // ranges. 4892 if (Fields.size() > 1) { 4893 bool FiveFields = Fields.size() == 5; 4894 4895 bool ValidString = true; 4896 if (IsARMBuiltin) { 4897 ValidString &= Fields[0].startswith_lower("cp") || 4898 Fields[0].startswith_lower("p"); 4899 if (ValidString) 4900 Fields[0] = 4901 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 4902 4903 ValidString &= Fields[2].startswith_lower("c"); 4904 if (ValidString) 4905 Fields[2] = Fields[2].drop_front(1); 4906 4907 if (FiveFields) { 4908 ValidString &= Fields[3].startswith_lower("c"); 4909 if (ValidString) 4910 Fields[3] = Fields[3].drop_front(1); 4911 } 4912 } 4913 4914 SmallVector<int, 5> Ranges; 4915 if (FiveFields) 4916 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 4917 else 4918 Ranges.append({15, 7, 15}); 4919 4920 for (unsigned i=0; i<Fields.size(); ++i) { 4921 int IntField; 4922 ValidString &= !Fields[i].getAsInteger(10, IntField); 4923 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 4924 } 4925 4926 if (!ValidString) 4927 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg) 4928 << Arg->getSourceRange(); 4929 } else if (IsAArch64Builtin && Fields.size() == 1) { 4930 // If the register name is one of those that appear in the condition below 4931 // and the special register builtin being used is one of the write builtins, 4932 // then we require that the argument provided for writing to the register 4933 // is an integer constant expression. This is because it will be lowered to 4934 // an MSR (immediate) instruction, so we need to know the immediate at 4935 // compile time. 4936 if (TheCall->getNumArgs() != 2) 4937 return false; 4938 4939 std::string RegLower = Reg.lower(); 4940 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 4941 RegLower != "pan" && RegLower != "uao") 4942 return false; 4943 4944 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 4945 } 4946 4947 return false; 4948 } 4949 4950 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 4951 /// This checks that the target supports __builtin_longjmp and 4952 /// that val is a constant 1. 4953 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 4954 if (!Context.getTargetInfo().hasSjLjLowering()) 4955 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported) 4956 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd()); 4957 4958 Expr *Arg = TheCall->getArg(1); 4959 llvm::APSInt Result; 4960 4961 // TODO: This is less than ideal. Overload this to take a value. 4962 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 4963 return true; 4964 4965 if (Result != 1) 4966 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val) 4967 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 4968 4969 return false; 4970 } 4971 4972 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 4973 /// This checks that the target supports __builtin_setjmp. 4974 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 4975 if (!Context.getTargetInfo().hasSjLjLowering()) 4976 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported) 4977 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd()); 4978 return false; 4979 } 4980 4981 namespace { 4982 4983 class UncoveredArgHandler { 4984 enum { Unknown = -1, AllCovered = -2 }; 4985 4986 signed FirstUncoveredArg = Unknown; 4987 SmallVector<const Expr *, 4> DiagnosticExprs; 4988 4989 public: 4990 UncoveredArgHandler() = default; 4991 4992 bool hasUncoveredArg() const { 4993 return (FirstUncoveredArg >= 0); 4994 } 4995 4996 unsigned getUncoveredArg() const { 4997 assert(hasUncoveredArg() && "no uncovered argument"); 4998 return FirstUncoveredArg; 4999 } 5000 5001 void setAllCovered() { 5002 // A string has been found with all arguments covered, so clear out 5003 // the diagnostics. 5004 DiagnosticExprs.clear(); 5005 FirstUncoveredArg = AllCovered; 5006 } 5007 5008 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 5009 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 5010 5011 // Don't update if a previous string covers all arguments. 5012 if (FirstUncoveredArg == AllCovered) 5013 return; 5014 5015 // UncoveredArgHandler tracks the highest uncovered argument index 5016 // and with it all the strings that match this index. 5017 if (NewFirstUncoveredArg == FirstUncoveredArg) 5018 DiagnosticExprs.push_back(StrExpr); 5019 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 5020 DiagnosticExprs.clear(); 5021 DiagnosticExprs.push_back(StrExpr); 5022 FirstUncoveredArg = NewFirstUncoveredArg; 5023 } 5024 } 5025 5026 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 5027 }; 5028 5029 enum StringLiteralCheckType { 5030 SLCT_NotALiteral, 5031 SLCT_UncheckedLiteral, 5032 SLCT_CheckedLiteral 5033 }; 5034 5035 } // namespace 5036 5037 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 5038 BinaryOperatorKind BinOpKind, 5039 bool AddendIsRight) { 5040 unsigned BitWidth = Offset.getBitWidth(); 5041 unsigned AddendBitWidth = Addend.getBitWidth(); 5042 // There might be negative interim results. 5043 if (Addend.isUnsigned()) { 5044 Addend = Addend.zext(++AddendBitWidth); 5045 Addend.setIsSigned(true); 5046 } 5047 // Adjust the bit width of the APSInts. 5048 if (AddendBitWidth > BitWidth) { 5049 Offset = Offset.sext(AddendBitWidth); 5050 BitWidth = AddendBitWidth; 5051 } else if (BitWidth > AddendBitWidth) { 5052 Addend = Addend.sext(BitWidth); 5053 } 5054 5055 bool Ov = false; 5056 llvm::APSInt ResOffset = Offset; 5057 if (BinOpKind == BO_Add) 5058 ResOffset = Offset.sadd_ov(Addend, Ov); 5059 else { 5060 assert(AddendIsRight && BinOpKind == BO_Sub && 5061 "operator must be add or sub with addend on the right"); 5062 ResOffset = Offset.ssub_ov(Addend, Ov); 5063 } 5064 5065 // We add an offset to a pointer here so we should support an offset as big as 5066 // possible. 5067 if (Ov) { 5068 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 5069 "index (intermediate) result too big"); 5070 Offset = Offset.sext(2 * BitWidth); 5071 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 5072 return; 5073 } 5074 5075 Offset = ResOffset; 5076 } 5077 5078 namespace { 5079 5080 // This is a wrapper class around StringLiteral to support offsetted string 5081 // literals as format strings. It takes the offset into account when returning 5082 // the string and its length or the source locations to display notes correctly. 5083 class FormatStringLiteral { 5084 const StringLiteral *FExpr; 5085 int64_t Offset; 5086 5087 public: 5088 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 5089 : FExpr(fexpr), Offset(Offset) {} 5090 5091 StringRef getString() const { 5092 return FExpr->getString().drop_front(Offset); 5093 } 5094 5095 unsigned getByteLength() const { 5096 return FExpr->getByteLength() - getCharByteWidth() * Offset; 5097 } 5098 5099 unsigned getLength() const { return FExpr->getLength() - Offset; } 5100 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 5101 5102 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 5103 5104 QualType getType() const { return FExpr->getType(); } 5105 5106 bool isAscii() const { return FExpr->isAscii(); } 5107 bool isWide() const { return FExpr->isWide(); } 5108 bool isUTF8() const { return FExpr->isUTF8(); } 5109 bool isUTF16() const { return FExpr->isUTF16(); } 5110 bool isUTF32() const { return FExpr->isUTF32(); } 5111 bool isPascal() const { return FExpr->isPascal(); } 5112 5113 SourceLocation getLocationOfByte( 5114 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 5115 const TargetInfo &Target, unsigned *StartToken = nullptr, 5116 unsigned *StartTokenByteOffset = nullptr) const { 5117 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 5118 StartToken, StartTokenByteOffset); 5119 } 5120 5121 SourceLocation getLocStart() const LLVM_READONLY { 5122 return FExpr->getLocStart().getLocWithOffset(Offset); 5123 } 5124 5125 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); } 5126 }; 5127 5128 } // namespace 5129 5130 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 5131 const Expr *OrigFormatExpr, 5132 ArrayRef<const Expr *> Args, 5133 bool HasVAListArg, unsigned format_idx, 5134 unsigned firstDataArg, 5135 Sema::FormatStringType Type, 5136 bool inFunctionCall, 5137 Sema::VariadicCallType CallType, 5138 llvm::SmallBitVector &CheckedVarArgs, 5139 UncoveredArgHandler &UncoveredArg); 5140 5141 // Determine if an expression is a string literal or constant string. 5142 // If this function returns false on the arguments to a function expecting a 5143 // format string, we will usually need to emit a warning. 5144 // True string literals are then checked by CheckFormatString. 5145 static StringLiteralCheckType 5146 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 5147 bool HasVAListArg, unsigned format_idx, 5148 unsigned firstDataArg, Sema::FormatStringType Type, 5149 Sema::VariadicCallType CallType, bool InFunctionCall, 5150 llvm::SmallBitVector &CheckedVarArgs, 5151 UncoveredArgHandler &UncoveredArg, 5152 llvm::APSInt Offset) { 5153 tryAgain: 5154 assert(Offset.isSigned() && "invalid offset"); 5155 5156 if (E->isTypeDependent() || E->isValueDependent()) 5157 return SLCT_NotALiteral; 5158 5159 E = E->IgnoreParenCasts(); 5160 5161 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 5162 // Technically -Wformat-nonliteral does not warn about this case. 5163 // The behavior of printf and friends in this case is implementation 5164 // dependent. Ideally if the format string cannot be null then 5165 // it should have a 'nonnull' attribute in the function prototype. 5166 return SLCT_UncheckedLiteral; 5167 5168 switch (E->getStmtClass()) { 5169 case Stmt::BinaryConditionalOperatorClass: 5170 case Stmt::ConditionalOperatorClass: { 5171 // The expression is a literal if both sub-expressions were, and it was 5172 // completely checked only if both sub-expressions were checked. 5173 const AbstractConditionalOperator *C = 5174 cast<AbstractConditionalOperator>(E); 5175 5176 // Determine whether it is necessary to check both sub-expressions, for 5177 // example, because the condition expression is a constant that can be 5178 // evaluated at compile time. 5179 bool CheckLeft = true, CheckRight = true; 5180 5181 bool Cond; 5182 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) { 5183 if (Cond) 5184 CheckRight = false; 5185 else 5186 CheckLeft = false; 5187 } 5188 5189 // We need to maintain the offsets for the right and the left hand side 5190 // separately to check if every possible indexed expression is a valid 5191 // string literal. They might have different offsets for different string 5192 // literals in the end. 5193 StringLiteralCheckType Left; 5194 if (!CheckLeft) 5195 Left = SLCT_UncheckedLiteral; 5196 else { 5197 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 5198 HasVAListArg, format_idx, firstDataArg, 5199 Type, CallType, InFunctionCall, 5200 CheckedVarArgs, UncoveredArg, Offset); 5201 if (Left == SLCT_NotALiteral || !CheckRight) { 5202 return Left; 5203 } 5204 } 5205 5206 StringLiteralCheckType Right = 5207 checkFormatStringExpr(S, C->getFalseExpr(), Args, 5208 HasVAListArg, format_idx, firstDataArg, 5209 Type, CallType, InFunctionCall, CheckedVarArgs, 5210 UncoveredArg, Offset); 5211 5212 return (CheckLeft && Left < Right) ? Left : Right; 5213 } 5214 5215 case Stmt::ImplicitCastExprClass: 5216 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 5217 goto tryAgain; 5218 5219 case Stmt::OpaqueValueExprClass: 5220 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 5221 E = src; 5222 goto tryAgain; 5223 } 5224 return SLCT_NotALiteral; 5225 5226 case Stmt::PredefinedExprClass: 5227 // While __func__, etc., are technically not string literals, they 5228 // cannot contain format specifiers and thus are not a security 5229 // liability. 5230 return SLCT_UncheckedLiteral; 5231 5232 case Stmt::DeclRefExprClass: { 5233 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 5234 5235 // As an exception, do not flag errors for variables binding to 5236 // const string literals. 5237 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 5238 bool isConstant = false; 5239 QualType T = DR->getType(); 5240 5241 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 5242 isConstant = AT->getElementType().isConstant(S.Context); 5243 } else if (const PointerType *PT = T->getAs<PointerType>()) { 5244 isConstant = T.isConstant(S.Context) && 5245 PT->getPointeeType().isConstant(S.Context); 5246 } else if (T->isObjCObjectPointerType()) { 5247 // In ObjC, there is usually no "const ObjectPointer" type, 5248 // so don't check if the pointee type is constant. 5249 isConstant = T.isConstant(S.Context); 5250 } 5251 5252 if (isConstant) { 5253 if (const Expr *Init = VD->getAnyInitializer()) { 5254 // Look through initializers like const char c[] = { "foo" } 5255 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 5256 if (InitList->isStringLiteralInit()) 5257 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 5258 } 5259 return checkFormatStringExpr(S, Init, Args, 5260 HasVAListArg, format_idx, 5261 firstDataArg, Type, CallType, 5262 /*InFunctionCall*/ false, CheckedVarArgs, 5263 UncoveredArg, Offset); 5264 } 5265 } 5266 5267 // For vprintf* functions (i.e., HasVAListArg==true), we add a 5268 // special check to see if the format string is a function parameter 5269 // of the function calling the printf function. If the function 5270 // has an attribute indicating it is a printf-like function, then we 5271 // should suppress warnings concerning non-literals being used in a call 5272 // to a vprintf function. For example: 5273 // 5274 // void 5275 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 5276 // va_list ap; 5277 // va_start(ap, fmt); 5278 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 5279 // ... 5280 // } 5281 if (HasVAListArg) { 5282 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 5283 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 5284 int PVIndex = PV->getFunctionScopeIndex() + 1; 5285 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 5286 // adjust for implicit parameter 5287 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 5288 if (MD->isInstance()) 5289 ++PVIndex; 5290 // We also check if the formats are compatible. 5291 // We can't pass a 'scanf' string to a 'printf' function. 5292 if (PVIndex == PVFormat->getFormatIdx() && 5293 Type == S.GetFormatStringType(PVFormat)) 5294 return SLCT_UncheckedLiteral; 5295 } 5296 } 5297 } 5298 } 5299 } 5300 5301 return SLCT_NotALiteral; 5302 } 5303 5304 case Stmt::CallExprClass: 5305 case Stmt::CXXMemberCallExprClass: { 5306 const CallExpr *CE = cast<CallExpr>(E); 5307 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 5308 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) { 5309 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 5310 return checkFormatStringExpr(S, Arg, Args, 5311 HasVAListArg, format_idx, firstDataArg, 5312 Type, CallType, InFunctionCall, 5313 CheckedVarArgs, UncoveredArg, Offset); 5314 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) { 5315 unsigned BuiltinID = FD->getBuiltinID(); 5316 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 5317 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 5318 const Expr *Arg = CE->getArg(0); 5319 return checkFormatStringExpr(S, Arg, Args, 5320 HasVAListArg, format_idx, 5321 firstDataArg, Type, CallType, 5322 InFunctionCall, CheckedVarArgs, 5323 UncoveredArg, Offset); 5324 } 5325 } 5326 } 5327 5328 return SLCT_NotALiteral; 5329 } 5330 case Stmt::ObjCMessageExprClass: { 5331 const auto *ME = cast<ObjCMessageExpr>(E); 5332 if (const auto *ND = ME->getMethodDecl()) { 5333 if (const auto *FA = ND->getAttr<FormatArgAttr>()) { 5334 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 5335 return checkFormatStringExpr( 5336 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 5337 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset); 5338 } 5339 } 5340 5341 return SLCT_NotALiteral; 5342 } 5343 case Stmt::ObjCStringLiteralClass: 5344 case Stmt::StringLiteralClass: { 5345 const StringLiteral *StrE = nullptr; 5346 5347 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 5348 StrE = ObjCFExpr->getString(); 5349 else 5350 StrE = cast<StringLiteral>(E); 5351 5352 if (StrE) { 5353 if (Offset.isNegative() || Offset > StrE->getLength()) { 5354 // TODO: It would be better to have an explicit warning for out of 5355 // bounds literals. 5356 return SLCT_NotALiteral; 5357 } 5358 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 5359 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 5360 firstDataArg, Type, InFunctionCall, CallType, 5361 CheckedVarArgs, UncoveredArg); 5362 return SLCT_CheckedLiteral; 5363 } 5364 5365 return SLCT_NotALiteral; 5366 } 5367 case Stmt::BinaryOperatorClass: { 5368 llvm::APSInt LResult; 5369 llvm::APSInt RResult; 5370 5371 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 5372 5373 // A string literal + an int offset is still a string literal. 5374 if (BinOp->isAdditiveOp()) { 5375 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context); 5376 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context); 5377 5378 if (LIsInt != RIsInt) { 5379 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 5380 5381 if (LIsInt) { 5382 if (BinOpKind == BO_Add) { 5383 sumOffsets(Offset, LResult, BinOpKind, RIsInt); 5384 E = BinOp->getRHS(); 5385 goto tryAgain; 5386 } 5387 } else { 5388 sumOffsets(Offset, RResult, BinOpKind, RIsInt); 5389 E = BinOp->getLHS(); 5390 goto tryAgain; 5391 } 5392 } 5393 } 5394 5395 return SLCT_NotALiteral; 5396 } 5397 case Stmt::UnaryOperatorClass: { 5398 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 5399 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 5400 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 5401 llvm::APSInt IndexResult; 5402 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) { 5403 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true); 5404 E = ASE->getBase(); 5405 goto tryAgain; 5406 } 5407 } 5408 5409 return SLCT_NotALiteral; 5410 } 5411 5412 default: 5413 return SLCT_NotALiteral; 5414 } 5415 } 5416 5417 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 5418 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 5419 .Case("scanf", FST_Scanf) 5420 .Cases("printf", "printf0", FST_Printf) 5421 .Cases("NSString", "CFString", FST_NSString) 5422 .Case("strftime", FST_Strftime) 5423 .Case("strfmon", FST_Strfmon) 5424 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 5425 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 5426 .Case("os_trace", FST_OSLog) 5427 .Case("os_log", FST_OSLog) 5428 .Default(FST_Unknown); 5429 } 5430 5431 /// CheckFormatArguments - Check calls to printf and scanf (and similar 5432 /// functions) for correct use of format strings. 5433 /// Returns true if a format string has been fully checked. 5434 bool Sema::CheckFormatArguments(const FormatAttr *Format, 5435 ArrayRef<const Expr *> Args, 5436 bool IsCXXMember, 5437 VariadicCallType CallType, 5438 SourceLocation Loc, SourceRange Range, 5439 llvm::SmallBitVector &CheckedVarArgs) { 5440 FormatStringInfo FSI; 5441 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 5442 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 5443 FSI.FirstDataArg, GetFormatStringType(Format), 5444 CallType, Loc, Range, CheckedVarArgs); 5445 return false; 5446 } 5447 5448 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 5449 bool HasVAListArg, unsigned format_idx, 5450 unsigned firstDataArg, FormatStringType Type, 5451 VariadicCallType CallType, 5452 SourceLocation Loc, SourceRange Range, 5453 llvm::SmallBitVector &CheckedVarArgs) { 5454 // CHECK: printf/scanf-like function is called with no format string. 5455 if (format_idx >= Args.size()) { 5456 Diag(Loc, diag::warn_missing_format_string) << Range; 5457 return false; 5458 } 5459 5460 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 5461 5462 // CHECK: format string is not a string literal. 5463 // 5464 // Dynamically generated format strings are difficult to 5465 // automatically vet at compile time. Requiring that format strings 5466 // are string literals: (1) permits the checking of format strings by 5467 // the compiler and thereby (2) can practically remove the source of 5468 // many format string exploits. 5469 5470 // Format string can be either ObjC string (e.g. @"%d") or 5471 // C string (e.g. "%d") 5472 // ObjC string uses the same format specifiers as C string, so we can use 5473 // the same format string checking logic for both ObjC and C strings. 5474 UncoveredArgHandler UncoveredArg; 5475 StringLiteralCheckType CT = 5476 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 5477 format_idx, firstDataArg, Type, CallType, 5478 /*IsFunctionCall*/ true, CheckedVarArgs, 5479 UncoveredArg, 5480 /*no string offset*/ llvm::APSInt(64, false) = 0); 5481 5482 // Generate a diagnostic where an uncovered argument is detected. 5483 if (UncoveredArg.hasUncoveredArg()) { 5484 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 5485 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 5486 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 5487 } 5488 5489 if (CT != SLCT_NotALiteral) 5490 // Literal format string found, check done! 5491 return CT == SLCT_CheckedLiteral; 5492 5493 // Strftime is particular as it always uses a single 'time' argument, 5494 // so it is safe to pass a non-literal string. 5495 if (Type == FST_Strftime) 5496 return false; 5497 5498 // Do not emit diag when the string param is a macro expansion and the 5499 // format is either NSString or CFString. This is a hack to prevent 5500 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 5501 // which are usually used in place of NS and CF string literals. 5502 SourceLocation FormatLoc = Args[format_idx]->getLocStart(); 5503 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 5504 return false; 5505 5506 // If there are no arguments specified, warn with -Wformat-security, otherwise 5507 // warn only with -Wformat-nonliteral. 5508 if (Args.size() == firstDataArg) { 5509 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 5510 << OrigFormatExpr->getSourceRange(); 5511 switch (Type) { 5512 default: 5513 break; 5514 case FST_Kprintf: 5515 case FST_FreeBSDKPrintf: 5516 case FST_Printf: 5517 Diag(FormatLoc, diag::note_format_security_fixit) 5518 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 5519 break; 5520 case FST_NSString: 5521 Diag(FormatLoc, diag::note_format_security_fixit) 5522 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 5523 break; 5524 } 5525 } else { 5526 Diag(FormatLoc, diag::warn_format_nonliteral) 5527 << OrigFormatExpr->getSourceRange(); 5528 } 5529 return false; 5530 } 5531 5532 namespace { 5533 5534 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 5535 protected: 5536 Sema &S; 5537 const FormatStringLiteral *FExpr; 5538 const Expr *OrigFormatExpr; 5539 const Sema::FormatStringType FSType; 5540 const unsigned FirstDataArg; 5541 const unsigned NumDataArgs; 5542 const char *Beg; // Start of format string. 5543 const bool HasVAListArg; 5544 ArrayRef<const Expr *> Args; 5545 unsigned FormatIdx; 5546 llvm::SmallBitVector CoveredArgs; 5547 bool usesPositionalArgs = false; 5548 bool atFirstArg = true; 5549 bool inFunctionCall; 5550 Sema::VariadicCallType CallType; 5551 llvm::SmallBitVector &CheckedVarArgs; 5552 UncoveredArgHandler &UncoveredArg; 5553 5554 public: 5555 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 5556 const Expr *origFormatExpr, 5557 const Sema::FormatStringType type, unsigned firstDataArg, 5558 unsigned numDataArgs, const char *beg, bool hasVAListArg, 5559 ArrayRef<const Expr *> Args, unsigned formatIdx, 5560 bool inFunctionCall, Sema::VariadicCallType callType, 5561 llvm::SmallBitVector &CheckedVarArgs, 5562 UncoveredArgHandler &UncoveredArg) 5563 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 5564 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 5565 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 5566 inFunctionCall(inFunctionCall), CallType(callType), 5567 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 5568 CoveredArgs.resize(numDataArgs); 5569 CoveredArgs.reset(); 5570 } 5571 5572 void DoneProcessing(); 5573 5574 void HandleIncompleteSpecifier(const char *startSpecifier, 5575 unsigned specifierLen) override; 5576 5577 void HandleInvalidLengthModifier( 5578 const analyze_format_string::FormatSpecifier &FS, 5579 const analyze_format_string::ConversionSpecifier &CS, 5580 const char *startSpecifier, unsigned specifierLen, 5581 unsigned DiagID); 5582 5583 void HandleNonStandardLengthModifier( 5584 const analyze_format_string::FormatSpecifier &FS, 5585 const char *startSpecifier, unsigned specifierLen); 5586 5587 void HandleNonStandardConversionSpecifier( 5588 const analyze_format_string::ConversionSpecifier &CS, 5589 const char *startSpecifier, unsigned specifierLen); 5590 5591 void HandlePosition(const char *startPos, unsigned posLen) override; 5592 5593 void HandleInvalidPosition(const char *startSpecifier, 5594 unsigned specifierLen, 5595 analyze_format_string::PositionContext p) override; 5596 5597 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 5598 5599 void HandleNullChar(const char *nullCharacter) override; 5600 5601 template <typename Range> 5602 static void 5603 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 5604 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 5605 bool IsStringLocation, Range StringRange, 5606 ArrayRef<FixItHint> Fixit = None); 5607 5608 protected: 5609 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 5610 const char *startSpec, 5611 unsigned specifierLen, 5612 const char *csStart, unsigned csLen); 5613 5614 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 5615 const char *startSpec, 5616 unsigned specifierLen); 5617 5618 SourceRange getFormatStringRange(); 5619 CharSourceRange getSpecifierRange(const char *startSpecifier, 5620 unsigned specifierLen); 5621 SourceLocation getLocationOfByte(const char *x); 5622 5623 const Expr *getDataArg(unsigned i) const; 5624 5625 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 5626 const analyze_format_string::ConversionSpecifier &CS, 5627 const char *startSpecifier, unsigned specifierLen, 5628 unsigned argIndex); 5629 5630 template <typename Range> 5631 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 5632 bool IsStringLocation, Range StringRange, 5633 ArrayRef<FixItHint> Fixit = None); 5634 }; 5635 5636 } // namespace 5637 5638 SourceRange CheckFormatHandler::getFormatStringRange() { 5639 return OrigFormatExpr->getSourceRange(); 5640 } 5641 5642 CharSourceRange CheckFormatHandler:: 5643 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 5644 SourceLocation Start = getLocationOfByte(startSpecifier); 5645 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 5646 5647 // Advance the end SourceLocation by one due to half-open ranges. 5648 End = End.getLocWithOffset(1); 5649 5650 return CharSourceRange::getCharRange(Start, End); 5651 } 5652 5653 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 5654 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 5655 S.getLangOpts(), S.Context.getTargetInfo()); 5656 } 5657 5658 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 5659 unsigned specifierLen){ 5660 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 5661 getLocationOfByte(startSpecifier), 5662 /*IsStringLocation*/true, 5663 getSpecifierRange(startSpecifier, specifierLen)); 5664 } 5665 5666 void CheckFormatHandler::HandleInvalidLengthModifier( 5667 const analyze_format_string::FormatSpecifier &FS, 5668 const analyze_format_string::ConversionSpecifier &CS, 5669 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 5670 using namespace analyze_format_string; 5671 5672 const LengthModifier &LM = FS.getLengthModifier(); 5673 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 5674 5675 // See if we know how to fix this length modifier. 5676 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 5677 if (FixedLM) { 5678 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 5679 getLocationOfByte(LM.getStart()), 5680 /*IsStringLocation*/true, 5681 getSpecifierRange(startSpecifier, specifierLen)); 5682 5683 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 5684 << FixedLM->toString() 5685 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 5686 5687 } else { 5688 FixItHint Hint; 5689 if (DiagID == diag::warn_format_nonsensical_length) 5690 Hint = FixItHint::CreateRemoval(LMRange); 5691 5692 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 5693 getLocationOfByte(LM.getStart()), 5694 /*IsStringLocation*/true, 5695 getSpecifierRange(startSpecifier, specifierLen), 5696 Hint); 5697 } 5698 } 5699 5700 void CheckFormatHandler::HandleNonStandardLengthModifier( 5701 const analyze_format_string::FormatSpecifier &FS, 5702 const char *startSpecifier, unsigned specifierLen) { 5703 using namespace analyze_format_string; 5704 5705 const LengthModifier &LM = FS.getLengthModifier(); 5706 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 5707 5708 // See if we know how to fix this length modifier. 5709 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 5710 if (FixedLM) { 5711 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5712 << LM.toString() << 0, 5713 getLocationOfByte(LM.getStart()), 5714 /*IsStringLocation*/true, 5715 getSpecifierRange(startSpecifier, specifierLen)); 5716 5717 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 5718 << FixedLM->toString() 5719 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 5720 5721 } else { 5722 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5723 << LM.toString() << 0, 5724 getLocationOfByte(LM.getStart()), 5725 /*IsStringLocation*/true, 5726 getSpecifierRange(startSpecifier, specifierLen)); 5727 } 5728 } 5729 5730 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 5731 const analyze_format_string::ConversionSpecifier &CS, 5732 const char *startSpecifier, unsigned specifierLen) { 5733 using namespace analyze_format_string; 5734 5735 // See if we know how to fix this conversion specifier. 5736 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 5737 if (FixedCS) { 5738 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5739 << CS.toString() << /*conversion specifier*/1, 5740 getLocationOfByte(CS.getStart()), 5741 /*IsStringLocation*/true, 5742 getSpecifierRange(startSpecifier, specifierLen)); 5743 5744 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 5745 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 5746 << FixedCS->toString() 5747 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 5748 } else { 5749 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5750 << CS.toString() << /*conversion specifier*/1, 5751 getLocationOfByte(CS.getStart()), 5752 /*IsStringLocation*/true, 5753 getSpecifierRange(startSpecifier, specifierLen)); 5754 } 5755 } 5756 5757 void CheckFormatHandler::HandlePosition(const char *startPos, 5758 unsigned posLen) { 5759 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 5760 getLocationOfByte(startPos), 5761 /*IsStringLocation*/true, 5762 getSpecifierRange(startPos, posLen)); 5763 } 5764 5765 void 5766 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 5767 analyze_format_string::PositionContext p) { 5768 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 5769 << (unsigned) p, 5770 getLocationOfByte(startPos), /*IsStringLocation*/true, 5771 getSpecifierRange(startPos, posLen)); 5772 } 5773 5774 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 5775 unsigned posLen) { 5776 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 5777 getLocationOfByte(startPos), 5778 /*IsStringLocation*/true, 5779 getSpecifierRange(startPos, posLen)); 5780 } 5781 5782 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 5783 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 5784 // The presence of a null character is likely an error. 5785 EmitFormatDiagnostic( 5786 S.PDiag(diag::warn_printf_format_string_contains_null_char), 5787 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 5788 getFormatStringRange()); 5789 } 5790 } 5791 5792 // Note that this may return NULL if there was an error parsing or building 5793 // one of the argument expressions. 5794 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 5795 return Args[FirstDataArg + i]; 5796 } 5797 5798 void CheckFormatHandler::DoneProcessing() { 5799 // Does the number of data arguments exceed the number of 5800 // format conversions in the format string? 5801 if (!HasVAListArg) { 5802 // Find any arguments that weren't covered. 5803 CoveredArgs.flip(); 5804 signed notCoveredArg = CoveredArgs.find_first(); 5805 if (notCoveredArg >= 0) { 5806 assert((unsigned)notCoveredArg < NumDataArgs); 5807 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 5808 } else { 5809 UncoveredArg.setAllCovered(); 5810 } 5811 } 5812 } 5813 5814 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 5815 const Expr *ArgExpr) { 5816 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 5817 "Invalid state"); 5818 5819 if (!ArgExpr) 5820 return; 5821 5822 SourceLocation Loc = ArgExpr->getLocStart(); 5823 5824 if (S.getSourceManager().isInSystemMacro(Loc)) 5825 return; 5826 5827 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 5828 for (auto E : DiagnosticExprs) 5829 PDiag << E->getSourceRange(); 5830 5831 CheckFormatHandler::EmitFormatDiagnostic( 5832 S, IsFunctionCall, DiagnosticExprs[0], 5833 PDiag, Loc, /*IsStringLocation*/false, 5834 DiagnosticExprs[0]->getSourceRange()); 5835 } 5836 5837 bool 5838 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 5839 SourceLocation Loc, 5840 const char *startSpec, 5841 unsigned specifierLen, 5842 const char *csStart, 5843 unsigned csLen) { 5844 bool keepGoing = true; 5845 if (argIndex < NumDataArgs) { 5846 // Consider the argument coverered, even though the specifier doesn't 5847 // make sense. 5848 CoveredArgs.set(argIndex); 5849 } 5850 else { 5851 // If argIndex exceeds the number of data arguments we 5852 // don't issue a warning because that is just a cascade of warnings (and 5853 // they may have intended '%%' anyway). We don't want to continue processing 5854 // the format string after this point, however, as we will like just get 5855 // gibberish when trying to match arguments. 5856 keepGoing = false; 5857 } 5858 5859 StringRef Specifier(csStart, csLen); 5860 5861 // If the specifier in non-printable, it could be the first byte of a UTF-8 5862 // sequence. In that case, print the UTF-8 code point. If not, print the byte 5863 // hex value. 5864 std::string CodePointStr; 5865 if (!llvm::sys::locale::isPrint(*csStart)) { 5866 llvm::UTF32 CodePoint; 5867 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 5868 const llvm::UTF8 *E = 5869 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 5870 llvm::ConversionResult Result = 5871 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 5872 5873 if (Result != llvm::conversionOK) { 5874 unsigned char FirstChar = *csStart; 5875 CodePoint = (llvm::UTF32)FirstChar; 5876 } 5877 5878 llvm::raw_string_ostream OS(CodePointStr); 5879 if (CodePoint < 256) 5880 OS << "\\x" << llvm::format("%02x", CodePoint); 5881 else if (CodePoint <= 0xFFFF) 5882 OS << "\\u" << llvm::format("%04x", CodePoint); 5883 else 5884 OS << "\\U" << llvm::format("%08x", CodePoint); 5885 OS.flush(); 5886 Specifier = CodePointStr; 5887 } 5888 5889 EmitFormatDiagnostic( 5890 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 5891 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 5892 5893 return keepGoing; 5894 } 5895 5896 void 5897 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 5898 const char *startSpec, 5899 unsigned specifierLen) { 5900 EmitFormatDiagnostic( 5901 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 5902 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 5903 } 5904 5905 bool 5906 CheckFormatHandler::CheckNumArgs( 5907 const analyze_format_string::FormatSpecifier &FS, 5908 const analyze_format_string::ConversionSpecifier &CS, 5909 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 5910 5911 if (argIndex >= NumDataArgs) { 5912 PartialDiagnostic PDiag = FS.usesPositionalArg() 5913 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 5914 << (argIndex+1) << NumDataArgs) 5915 : S.PDiag(diag::warn_printf_insufficient_data_args); 5916 EmitFormatDiagnostic( 5917 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 5918 getSpecifierRange(startSpecifier, specifierLen)); 5919 5920 // Since more arguments than conversion tokens are given, by extension 5921 // all arguments are covered, so mark this as so. 5922 UncoveredArg.setAllCovered(); 5923 return false; 5924 } 5925 return true; 5926 } 5927 5928 template<typename Range> 5929 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 5930 SourceLocation Loc, 5931 bool IsStringLocation, 5932 Range StringRange, 5933 ArrayRef<FixItHint> FixIt) { 5934 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 5935 Loc, IsStringLocation, StringRange, FixIt); 5936 } 5937 5938 /// If the format string is not within the function call, emit a note 5939 /// so that the function call and string are in diagnostic messages. 5940 /// 5941 /// \param InFunctionCall if true, the format string is within the function 5942 /// call and only one diagnostic message will be produced. Otherwise, an 5943 /// extra note will be emitted pointing to location of the format string. 5944 /// 5945 /// \param ArgumentExpr the expression that is passed as the format string 5946 /// argument in the function call. Used for getting locations when two 5947 /// diagnostics are emitted. 5948 /// 5949 /// \param PDiag the callee should already have provided any strings for the 5950 /// diagnostic message. This function only adds locations and fixits 5951 /// to diagnostics. 5952 /// 5953 /// \param Loc primary location for diagnostic. If two diagnostics are 5954 /// required, one will be at Loc and a new SourceLocation will be created for 5955 /// the other one. 5956 /// 5957 /// \param IsStringLocation if true, Loc points to the format string should be 5958 /// used for the note. Otherwise, Loc points to the argument list and will 5959 /// be used with PDiag. 5960 /// 5961 /// \param StringRange some or all of the string to highlight. This is 5962 /// templated so it can accept either a CharSourceRange or a SourceRange. 5963 /// 5964 /// \param FixIt optional fix it hint for the format string. 5965 template <typename Range> 5966 void CheckFormatHandler::EmitFormatDiagnostic( 5967 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 5968 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 5969 Range StringRange, ArrayRef<FixItHint> FixIt) { 5970 if (InFunctionCall) { 5971 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 5972 D << StringRange; 5973 D << FixIt; 5974 } else { 5975 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 5976 << ArgumentExpr->getSourceRange(); 5977 5978 const Sema::SemaDiagnosticBuilder &Note = 5979 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 5980 diag::note_format_string_defined); 5981 5982 Note << StringRange; 5983 Note << FixIt; 5984 } 5985 } 5986 5987 //===--- CHECK: Printf format string checking ------------------------------===// 5988 5989 namespace { 5990 5991 class CheckPrintfHandler : public CheckFormatHandler { 5992 public: 5993 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 5994 const Expr *origFormatExpr, 5995 const Sema::FormatStringType type, unsigned firstDataArg, 5996 unsigned numDataArgs, bool isObjC, const char *beg, 5997 bool hasVAListArg, ArrayRef<const Expr *> Args, 5998 unsigned formatIdx, bool inFunctionCall, 5999 Sema::VariadicCallType CallType, 6000 llvm::SmallBitVector &CheckedVarArgs, 6001 UncoveredArgHandler &UncoveredArg) 6002 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 6003 numDataArgs, beg, hasVAListArg, Args, formatIdx, 6004 inFunctionCall, CallType, CheckedVarArgs, 6005 UncoveredArg) {} 6006 6007 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 6008 6009 /// Returns true if '%@' specifiers are allowed in the format string. 6010 bool allowsObjCArg() const { 6011 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 6012 FSType == Sema::FST_OSTrace; 6013 } 6014 6015 bool HandleInvalidPrintfConversionSpecifier( 6016 const analyze_printf::PrintfSpecifier &FS, 6017 const char *startSpecifier, 6018 unsigned specifierLen) override; 6019 6020 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 6021 const char *startSpecifier, 6022 unsigned specifierLen) override; 6023 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 6024 const char *StartSpecifier, 6025 unsigned SpecifierLen, 6026 const Expr *E); 6027 6028 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 6029 const char *startSpecifier, unsigned specifierLen); 6030 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 6031 const analyze_printf::OptionalAmount &Amt, 6032 unsigned type, 6033 const char *startSpecifier, unsigned specifierLen); 6034 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 6035 const analyze_printf::OptionalFlag &flag, 6036 const char *startSpecifier, unsigned specifierLen); 6037 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 6038 const analyze_printf::OptionalFlag &ignoredFlag, 6039 const analyze_printf::OptionalFlag &flag, 6040 const char *startSpecifier, unsigned specifierLen); 6041 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 6042 const Expr *E); 6043 6044 void HandleEmptyObjCModifierFlag(const char *startFlag, 6045 unsigned flagLen) override; 6046 6047 void HandleInvalidObjCModifierFlag(const char *startFlag, 6048 unsigned flagLen) override; 6049 6050 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 6051 const char *flagsEnd, 6052 const char *conversionPosition) 6053 override; 6054 }; 6055 6056 } // namespace 6057 6058 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 6059 const analyze_printf::PrintfSpecifier &FS, 6060 const char *startSpecifier, 6061 unsigned specifierLen) { 6062 const analyze_printf::PrintfConversionSpecifier &CS = 6063 FS.getConversionSpecifier(); 6064 6065 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 6066 getLocationOfByte(CS.getStart()), 6067 startSpecifier, specifierLen, 6068 CS.getStart(), CS.getLength()); 6069 } 6070 6071 bool CheckPrintfHandler::HandleAmount( 6072 const analyze_format_string::OptionalAmount &Amt, 6073 unsigned k, const char *startSpecifier, 6074 unsigned specifierLen) { 6075 if (Amt.hasDataArgument()) { 6076 if (!HasVAListArg) { 6077 unsigned argIndex = Amt.getArgIndex(); 6078 if (argIndex >= NumDataArgs) { 6079 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 6080 << k, 6081 getLocationOfByte(Amt.getStart()), 6082 /*IsStringLocation*/true, 6083 getSpecifierRange(startSpecifier, specifierLen)); 6084 // Don't do any more checking. We will just emit 6085 // spurious errors. 6086 return false; 6087 } 6088 6089 // Type check the data argument. It should be an 'int'. 6090 // Although not in conformance with C99, we also allow the argument to be 6091 // an 'unsigned int' as that is a reasonably safe case. GCC also 6092 // doesn't emit a warning for that case. 6093 CoveredArgs.set(argIndex); 6094 const Expr *Arg = getDataArg(argIndex); 6095 if (!Arg) 6096 return false; 6097 6098 QualType T = Arg->getType(); 6099 6100 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 6101 assert(AT.isValid()); 6102 6103 if (!AT.matchesType(S.Context, T)) { 6104 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 6105 << k << AT.getRepresentativeTypeName(S.Context) 6106 << T << Arg->getSourceRange(), 6107 getLocationOfByte(Amt.getStart()), 6108 /*IsStringLocation*/true, 6109 getSpecifierRange(startSpecifier, specifierLen)); 6110 // Don't do any more checking. We will just emit 6111 // spurious errors. 6112 return false; 6113 } 6114 } 6115 } 6116 return true; 6117 } 6118 6119 void CheckPrintfHandler::HandleInvalidAmount( 6120 const analyze_printf::PrintfSpecifier &FS, 6121 const analyze_printf::OptionalAmount &Amt, 6122 unsigned type, 6123 const char *startSpecifier, 6124 unsigned specifierLen) { 6125 const analyze_printf::PrintfConversionSpecifier &CS = 6126 FS.getConversionSpecifier(); 6127 6128 FixItHint fixit = 6129 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 6130 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 6131 Amt.getConstantLength())) 6132 : FixItHint(); 6133 6134 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 6135 << type << CS.toString(), 6136 getLocationOfByte(Amt.getStart()), 6137 /*IsStringLocation*/true, 6138 getSpecifierRange(startSpecifier, specifierLen), 6139 fixit); 6140 } 6141 6142 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 6143 const analyze_printf::OptionalFlag &flag, 6144 const char *startSpecifier, 6145 unsigned specifierLen) { 6146 // Warn about pointless flag with a fixit removal. 6147 const analyze_printf::PrintfConversionSpecifier &CS = 6148 FS.getConversionSpecifier(); 6149 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 6150 << flag.toString() << CS.toString(), 6151 getLocationOfByte(flag.getPosition()), 6152 /*IsStringLocation*/true, 6153 getSpecifierRange(startSpecifier, specifierLen), 6154 FixItHint::CreateRemoval( 6155 getSpecifierRange(flag.getPosition(), 1))); 6156 } 6157 6158 void CheckPrintfHandler::HandleIgnoredFlag( 6159 const analyze_printf::PrintfSpecifier &FS, 6160 const analyze_printf::OptionalFlag &ignoredFlag, 6161 const analyze_printf::OptionalFlag &flag, 6162 const char *startSpecifier, 6163 unsigned specifierLen) { 6164 // Warn about ignored flag with a fixit removal. 6165 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 6166 << ignoredFlag.toString() << flag.toString(), 6167 getLocationOfByte(ignoredFlag.getPosition()), 6168 /*IsStringLocation*/true, 6169 getSpecifierRange(startSpecifier, specifierLen), 6170 FixItHint::CreateRemoval( 6171 getSpecifierRange(ignoredFlag.getPosition(), 1))); 6172 } 6173 6174 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 6175 unsigned flagLen) { 6176 // Warn about an empty flag. 6177 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 6178 getLocationOfByte(startFlag), 6179 /*IsStringLocation*/true, 6180 getSpecifierRange(startFlag, flagLen)); 6181 } 6182 6183 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 6184 unsigned flagLen) { 6185 // Warn about an invalid flag. 6186 auto Range = getSpecifierRange(startFlag, flagLen); 6187 StringRef flag(startFlag, flagLen); 6188 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 6189 getLocationOfByte(startFlag), 6190 /*IsStringLocation*/true, 6191 Range, FixItHint::CreateRemoval(Range)); 6192 } 6193 6194 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 6195 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 6196 // Warn about using '[...]' without a '@' conversion. 6197 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 6198 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 6199 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 6200 getLocationOfByte(conversionPosition), 6201 /*IsStringLocation*/true, 6202 Range, FixItHint::CreateRemoval(Range)); 6203 } 6204 6205 // Determines if the specified is a C++ class or struct containing 6206 // a member with the specified name and kind (e.g. a CXXMethodDecl named 6207 // "c_str()"). 6208 template<typename MemberKind> 6209 static llvm::SmallPtrSet<MemberKind*, 1> 6210 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 6211 const RecordType *RT = Ty->getAs<RecordType>(); 6212 llvm::SmallPtrSet<MemberKind*, 1> Results; 6213 6214 if (!RT) 6215 return Results; 6216 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 6217 if (!RD || !RD->getDefinition()) 6218 return Results; 6219 6220 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 6221 Sema::LookupMemberName); 6222 R.suppressDiagnostics(); 6223 6224 // We just need to include all members of the right kind turned up by the 6225 // filter, at this point. 6226 if (S.LookupQualifiedName(R, RT->getDecl())) 6227 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 6228 NamedDecl *decl = (*I)->getUnderlyingDecl(); 6229 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 6230 Results.insert(FK); 6231 } 6232 return Results; 6233 } 6234 6235 /// Check if we could call '.c_str()' on an object. 6236 /// 6237 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 6238 /// allow the call, or if it would be ambiguous). 6239 bool Sema::hasCStrMethod(const Expr *E) { 6240 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 6241 6242 MethodSet Results = 6243 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 6244 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 6245 MI != ME; ++MI) 6246 if ((*MI)->getMinRequiredArguments() == 0) 6247 return true; 6248 return false; 6249 } 6250 6251 // Check if a (w)string was passed when a (w)char* was needed, and offer a 6252 // better diagnostic if so. AT is assumed to be valid. 6253 // Returns true when a c_str() conversion method is found. 6254 bool CheckPrintfHandler::checkForCStrMembers( 6255 const analyze_printf::ArgType &AT, const Expr *E) { 6256 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 6257 6258 MethodSet Results = 6259 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 6260 6261 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 6262 MI != ME; ++MI) { 6263 const CXXMethodDecl *Method = *MI; 6264 if (Method->getMinRequiredArguments() == 0 && 6265 AT.matchesType(S.Context, Method->getReturnType())) { 6266 // FIXME: Suggest parens if the expression needs them. 6267 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd()); 6268 S.Diag(E->getLocStart(), diag::note_printf_c_str) 6269 << "c_str()" 6270 << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 6271 return true; 6272 } 6273 } 6274 6275 return false; 6276 } 6277 6278 bool 6279 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 6280 &FS, 6281 const char *startSpecifier, 6282 unsigned specifierLen) { 6283 using namespace analyze_format_string; 6284 using namespace analyze_printf; 6285 6286 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 6287 6288 if (FS.consumesDataArgument()) { 6289 if (atFirstArg) { 6290 atFirstArg = false; 6291 usesPositionalArgs = FS.usesPositionalArg(); 6292 } 6293 else if (usesPositionalArgs != FS.usesPositionalArg()) { 6294 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 6295 startSpecifier, specifierLen); 6296 return false; 6297 } 6298 } 6299 6300 // First check if the field width, precision, and conversion specifier 6301 // have matching data arguments. 6302 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 6303 startSpecifier, specifierLen)) { 6304 return false; 6305 } 6306 6307 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 6308 startSpecifier, specifierLen)) { 6309 return false; 6310 } 6311 6312 if (!CS.consumesDataArgument()) { 6313 // FIXME: Technically specifying a precision or field width here 6314 // makes no sense. Worth issuing a warning at some point. 6315 return true; 6316 } 6317 6318 // Consume the argument. 6319 unsigned argIndex = FS.getArgIndex(); 6320 if (argIndex < NumDataArgs) { 6321 // The check to see if the argIndex is valid will come later. 6322 // We set the bit here because we may exit early from this 6323 // function if we encounter some other error. 6324 CoveredArgs.set(argIndex); 6325 } 6326 6327 // FreeBSD kernel extensions. 6328 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 6329 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 6330 // We need at least two arguments. 6331 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 6332 return false; 6333 6334 // Claim the second argument. 6335 CoveredArgs.set(argIndex + 1); 6336 6337 // Type check the first argument (int for %b, pointer for %D) 6338 const Expr *Ex = getDataArg(argIndex); 6339 const analyze_printf::ArgType &AT = 6340 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 6341 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 6342 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 6343 EmitFormatDiagnostic( 6344 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 6345 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 6346 << false << Ex->getSourceRange(), 6347 Ex->getLocStart(), /*IsStringLocation*/false, 6348 getSpecifierRange(startSpecifier, specifierLen)); 6349 6350 // Type check the second argument (char * for both %b and %D) 6351 Ex = getDataArg(argIndex + 1); 6352 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 6353 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 6354 EmitFormatDiagnostic( 6355 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 6356 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 6357 << false << Ex->getSourceRange(), 6358 Ex->getLocStart(), /*IsStringLocation*/false, 6359 getSpecifierRange(startSpecifier, specifierLen)); 6360 6361 return true; 6362 } 6363 6364 // Check for using an Objective-C specific conversion specifier 6365 // in a non-ObjC literal. 6366 if (!allowsObjCArg() && CS.isObjCArg()) { 6367 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 6368 specifierLen); 6369 } 6370 6371 // %P can only be used with os_log. 6372 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 6373 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 6374 specifierLen); 6375 } 6376 6377 // %n is not allowed with os_log. 6378 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 6379 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 6380 getLocationOfByte(CS.getStart()), 6381 /*IsStringLocation*/ false, 6382 getSpecifierRange(startSpecifier, specifierLen)); 6383 6384 return true; 6385 } 6386 6387 // Only scalars are allowed for os_trace. 6388 if (FSType == Sema::FST_OSTrace && 6389 (CS.getKind() == ConversionSpecifier::PArg || 6390 CS.getKind() == ConversionSpecifier::sArg || 6391 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 6392 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 6393 specifierLen); 6394 } 6395 6396 // Check for use of public/private annotation outside of os_log(). 6397 if (FSType != Sema::FST_OSLog) { 6398 if (FS.isPublic().isSet()) { 6399 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 6400 << "public", 6401 getLocationOfByte(FS.isPublic().getPosition()), 6402 /*IsStringLocation*/ false, 6403 getSpecifierRange(startSpecifier, specifierLen)); 6404 } 6405 if (FS.isPrivate().isSet()) { 6406 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 6407 << "private", 6408 getLocationOfByte(FS.isPrivate().getPosition()), 6409 /*IsStringLocation*/ false, 6410 getSpecifierRange(startSpecifier, specifierLen)); 6411 } 6412 } 6413 6414 // Check for invalid use of field width 6415 if (!FS.hasValidFieldWidth()) { 6416 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 6417 startSpecifier, specifierLen); 6418 } 6419 6420 // Check for invalid use of precision 6421 if (!FS.hasValidPrecision()) { 6422 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 6423 startSpecifier, specifierLen); 6424 } 6425 6426 // Precision is mandatory for %P specifier. 6427 if (CS.getKind() == ConversionSpecifier::PArg && 6428 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 6429 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 6430 getLocationOfByte(startSpecifier), 6431 /*IsStringLocation*/ false, 6432 getSpecifierRange(startSpecifier, specifierLen)); 6433 } 6434 6435 // Check each flag does not conflict with any other component. 6436 if (!FS.hasValidThousandsGroupingPrefix()) 6437 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 6438 if (!FS.hasValidLeadingZeros()) 6439 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 6440 if (!FS.hasValidPlusPrefix()) 6441 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 6442 if (!FS.hasValidSpacePrefix()) 6443 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 6444 if (!FS.hasValidAlternativeForm()) 6445 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 6446 if (!FS.hasValidLeftJustified()) 6447 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 6448 6449 // Check that flags are not ignored by another flag 6450 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 6451 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 6452 startSpecifier, specifierLen); 6453 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 6454 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 6455 startSpecifier, specifierLen); 6456 6457 // Check the length modifier is valid with the given conversion specifier. 6458 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 6459 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6460 diag::warn_format_nonsensical_length); 6461 else if (!FS.hasStandardLengthModifier()) 6462 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 6463 else if (!FS.hasStandardLengthConversionCombination()) 6464 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6465 diag::warn_format_non_standard_conversion_spec); 6466 6467 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 6468 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 6469 6470 // The remaining checks depend on the data arguments. 6471 if (HasVAListArg) 6472 return true; 6473 6474 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 6475 return false; 6476 6477 const Expr *Arg = getDataArg(argIndex); 6478 if (!Arg) 6479 return true; 6480 6481 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 6482 } 6483 6484 static bool requiresParensToAddCast(const Expr *E) { 6485 // FIXME: We should have a general way to reason about operator 6486 // precedence and whether parens are actually needed here. 6487 // Take care of a few common cases where they aren't. 6488 const Expr *Inside = E->IgnoreImpCasts(); 6489 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 6490 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 6491 6492 switch (Inside->getStmtClass()) { 6493 case Stmt::ArraySubscriptExprClass: 6494 case Stmt::CallExprClass: 6495 case Stmt::CharacterLiteralClass: 6496 case Stmt::CXXBoolLiteralExprClass: 6497 case Stmt::DeclRefExprClass: 6498 case Stmt::FloatingLiteralClass: 6499 case Stmt::IntegerLiteralClass: 6500 case Stmt::MemberExprClass: 6501 case Stmt::ObjCArrayLiteralClass: 6502 case Stmt::ObjCBoolLiteralExprClass: 6503 case Stmt::ObjCBoxedExprClass: 6504 case Stmt::ObjCDictionaryLiteralClass: 6505 case Stmt::ObjCEncodeExprClass: 6506 case Stmt::ObjCIvarRefExprClass: 6507 case Stmt::ObjCMessageExprClass: 6508 case Stmt::ObjCPropertyRefExprClass: 6509 case Stmt::ObjCStringLiteralClass: 6510 case Stmt::ObjCSubscriptRefExprClass: 6511 case Stmt::ParenExprClass: 6512 case Stmt::StringLiteralClass: 6513 case Stmt::UnaryOperatorClass: 6514 return false; 6515 default: 6516 return true; 6517 } 6518 } 6519 6520 static std::pair<QualType, StringRef> 6521 shouldNotPrintDirectly(const ASTContext &Context, 6522 QualType IntendedTy, 6523 const Expr *E) { 6524 // Use a 'while' to peel off layers of typedefs. 6525 QualType TyTy = IntendedTy; 6526 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 6527 StringRef Name = UserTy->getDecl()->getName(); 6528 QualType CastTy = llvm::StringSwitch<QualType>(Name) 6529 .Case("CFIndex", Context.getNSIntegerType()) 6530 .Case("NSInteger", Context.getNSIntegerType()) 6531 .Case("NSUInteger", Context.getNSUIntegerType()) 6532 .Case("SInt32", Context.IntTy) 6533 .Case("UInt32", Context.UnsignedIntTy) 6534 .Default(QualType()); 6535 6536 if (!CastTy.isNull()) 6537 return std::make_pair(CastTy, Name); 6538 6539 TyTy = UserTy->desugar(); 6540 } 6541 6542 // Strip parens if necessary. 6543 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 6544 return shouldNotPrintDirectly(Context, 6545 PE->getSubExpr()->getType(), 6546 PE->getSubExpr()); 6547 6548 // If this is a conditional expression, then its result type is constructed 6549 // via usual arithmetic conversions and thus there might be no necessary 6550 // typedef sugar there. Recurse to operands to check for NSInteger & 6551 // Co. usage condition. 6552 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 6553 QualType TrueTy, FalseTy; 6554 StringRef TrueName, FalseName; 6555 6556 std::tie(TrueTy, TrueName) = 6557 shouldNotPrintDirectly(Context, 6558 CO->getTrueExpr()->getType(), 6559 CO->getTrueExpr()); 6560 std::tie(FalseTy, FalseName) = 6561 shouldNotPrintDirectly(Context, 6562 CO->getFalseExpr()->getType(), 6563 CO->getFalseExpr()); 6564 6565 if (TrueTy == FalseTy) 6566 return std::make_pair(TrueTy, TrueName); 6567 else if (TrueTy.isNull()) 6568 return std::make_pair(FalseTy, FalseName); 6569 else if (FalseTy.isNull()) 6570 return std::make_pair(TrueTy, TrueName); 6571 } 6572 6573 return std::make_pair(QualType(), StringRef()); 6574 } 6575 6576 bool 6577 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 6578 const char *StartSpecifier, 6579 unsigned SpecifierLen, 6580 const Expr *E) { 6581 using namespace analyze_format_string; 6582 using namespace analyze_printf; 6583 6584 // Now type check the data expression that matches the 6585 // format specifier. 6586 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 6587 if (!AT.isValid()) 6588 return true; 6589 6590 QualType ExprTy = E->getType(); 6591 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 6592 ExprTy = TET->getUnderlyingExpr()->getType(); 6593 } 6594 6595 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy); 6596 6597 if (match == analyze_printf::ArgType::Match) { 6598 return true; 6599 } 6600 6601 // Look through argument promotions for our error message's reported type. 6602 // This includes the integral and floating promotions, but excludes array 6603 // and function pointer decay; seeing that an argument intended to be a 6604 // string has type 'char [6]' is probably more confusing than 'char *'. 6605 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 6606 if (ICE->getCastKind() == CK_IntegralCast || 6607 ICE->getCastKind() == CK_FloatingCast) { 6608 E = ICE->getSubExpr(); 6609 ExprTy = E->getType(); 6610 6611 // Check if we didn't match because of an implicit cast from a 'char' 6612 // or 'short' to an 'int'. This is done because printf is a varargs 6613 // function. 6614 if (ICE->getType() == S.Context.IntTy || 6615 ICE->getType() == S.Context.UnsignedIntTy) { 6616 // All further checking is done on the subexpression. 6617 if (AT.matchesType(S.Context, ExprTy)) 6618 return true; 6619 } 6620 } 6621 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 6622 // Special case for 'a', which has type 'int' in C. 6623 // Note, however, that we do /not/ want to treat multibyte constants like 6624 // 'MooV' as characters! This form is deprecated but still exists. 6625 if (ExprTy == S.Context.IntTy) 6626 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 6627 ExprTy = S.Context.CharTy; 6628 } 6629 6630 // Look through enums to their underlying type. 6631 bool IsEnum = false; 6632 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 6633 ExprTy = EnumTy->getDecl()->getIntegerType(); 6634 IsEnum = true; 6635 } 6636 6637 // %C in an Objective-C context prints a unichar, not a wchar_t. 6638 // If the argument is an integer of some kind, believe the %C and suggest 6639 // a cast instead of changing the conversion specifier. 6640 QualType IntendedTy = ExprTy; 6641 if (isObjCContext() && 6642 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 6643 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 6644 !ExprTy->isCharType()) { 6645 // 'unichar' is defined as a typedef of unsigned short, but we should 6646 // prefer using the typedef if it is visible. 6647 IntendedTy = S.Context.UnsignedShortTy; 6648 6649 // While we are here, check if the value is an IntegerLiteral that happens 6650 // to be within the valid range. 6651 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 6652 const llvm::APInt &V = IL->getValue(); 6653 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 6654 return true; 6655 } 6656 6657 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(), 6658 Sema::LookupOrdinaryName); 6659 if (S.LookupName(Result, S.getCurScope())) { 6660 NamedDecl *ND = Result.getFoundDecl(); 6661 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 6662 if (TD->getUnderlyingType() == IntendedTy) 6663 IntendedTy = S.Context.getTypedefType(TD); 6664 } 6665 } 6666 } 6667 6668 // Special-case some of Darwin's platform-independence types by suggesting 6669 // casts to primitive types that are known to be large enough. 6670 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 6671 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 6672 QualType CastTy; 6673 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 6674 if (!CastTy.isNull()) { 6675 IntendedTy = CastTy; 6676 ShouldNotPrintDirectly = true; 6677 } 6678 } 6679 6680 // We may be able to offer a FixItHint if it is a supported type. 6681 PrintfSpecifier fixedFS = FS; 6682 bool success = 6683 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 6684 6685 if (success) { 6686 // Get the fix string from the fixed format specifier 6687 SmallString<16> buf; 6688 llvm::raw_svector_ostream os(buf); 6689 fixedFS.toString(os); 6690 6691 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 6692 6693 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 6694 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 6695 if (match == analyze_format_string::ArgType::NoMatchPedantic) { 6696 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 6697 } 6698 // In this case, the specifier is wrong and should be changed to match 6699 // the argument. 6700 EmitFormatDiagnostic(S.PDiag(diag) 6701 << AT.getRepresentativeTypeName(S.Context) 6702 << IntendedTy << IsEnum << E->getSourceRange(), 6703 E->getLocStart(), 6704 /*IsStringLocation*/ false, SpecRange, 6705 FixItHint::CreateReplacement(SpecRange, os.str())); 6706 } else { 6707 // The canonical type for formatting this value is different from the 6708 // actual type of the expression. (This occurs, for example, with Darwin's 6709 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 6710 // should be printed as 'long' for 64-bit compatibility.) 6711 // Rather than emitting a normal format/argument mismatch, we want to 6712 // add a cast to the recommended type (and correct the format string 6713 // if necessary). 6714 SmallString<16> CastBuf; 6715 llvm::raw_svector_ostream CastFix(CastBuf); 6716 CastFix << "("; 6717 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 6718 CastFix << ")"; 6719 6720 SmallVector<FixItHint,4> Hints; 6721 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 6722 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 6723 6724 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 6725 // If there's already a cast present, just replace it. 6726 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 6727 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 6728 6729 } else if (!requiresParensToAddCast(E)) { 6730 // If the expression has high enough precedence, 6731 // just write the C-style cast. 6732 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(), 6733 CastFix.str())); 6734 } else { 6735 // Otherwise, add parens around the expression as well as the cast. 6736 CastFix << "("; 6737 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(), 6738 CastFix.str())); 6739 6740 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd()); 6741 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 6742 } 6743 6744 if (ShouldNotPrintDirectly) { 6745 // The expression has a type that should not be printed directly. 6746 // We extract the name from the typedef because we don't want to show 6747 // the underlying type in the diagnostic. 6748 StringRef Name; 6749 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 6750 Name = TypedefTy->getDecl()->getName(); 6751 else 6752 Name = CastTyName; 6753 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast) 6754 << Name << IntendedTy << IsEnum 6755 << E->getSourceRange(), 6756 E->getLocStart(), /*IsStringLocation=*/false, 6757 SpecRange, Hints); 6758 } else { 6759 // In this case, the expression could be printed using a different 6760 // specifier, but we've decided that the specifier is probably correct 6761 // and we should cast instead. Just use the normal warning message. 6762 EmitFormatDiagnostic( 6763 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 6764 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 6765 << E->getSourceRange(), 6766 E->getLocStart(), /*IsStringLocation*/false, 6767 SpecRange, Hints); 6768 } 6769 } 6770 } else { 6771 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 6772 SpecifierLen); 6773 // Since the warning for passing non-POD types to variadic functions 6774 // was deferred until now, we emit a warning for non-POD 6775 // arguments here. 6776 switch (S.isValidVarArgType(ExprTy)) { 6777 case Sema::VAK_Valid: 6778 case Sema::VAK_ValidInCXX11: { 6779 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 6780 if (match == analyze_printf::ArgType::NoMatchPedantic) { 6781 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 6782 } 6783 6784 EmitFormatDiagnostic( 6785 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 6786 << IsEnum << CSR << E->getSourceRange(), 6787 E->getLocStart(), /*IsStringLocation*/ false, CSR); 6788 break; 6789 } 6790 case Sema::VAK_Undefined: 6791 case Sema::VAK_MSVCUndefined: 6792 EmitFormatDiagnostic( 6793 S.PDiag(diag::warn_non_pod_vararg_with_format_string) 6794 << S.getLangOpts().CPlusPlus11 6795 << ExprTy 6796 << CallType 6797 << AT.getRepresentativeTypeName(S.Context) 6798 << CSR 6799 << E->getSourceRange(), 6800 E->getLocStart(), /*IsStringLocation*/false, CSR); 6801 checkForCStrMembers(AT, E); 6802 break; 6803 6804 case Sema::VAK_Invalid: 6805 if (ExprTy->isObjCObjectType()) 6806 EmitFormatDiagnostic( 6807 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 6808 << S.getLangOpts().CPlusPlus11 6809 << ExprTy 6810 << CallType 6811 << AT.getRepresentativeTypeName(S.Context) 6812 << CSR 6813 << E->getSourceRange(), 6814 E->getLocStart(), /*IsStringLocation*/false, CSR); 6815 else 6816 // FIXME: If this is an initializer list, suggest removing the braces 6817 // or inserting a cast to the target type. 6818 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format) 6819 << isa<InitListExpr>(E) << ExprTy << CallType 6820 << AT.getRepresentativeTypeName(S.Context) 6821 << E->getSourceRange(); 6822 break; 6823 } 6824 6825 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 6826 "format string specifier index out of range"); 6827 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 6828 } 6829 6830 return true; 6831 } 6832 6833 //===--- CHECK: Scanf format string checking ------------------------------===// 6834 6835 namespace { 6836 6837 class CheckScanfHandler : public CheckFormatHandler { 6838 public: 6839 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 6840 const Expr *origFormatExpr, Sema::FormatStringType type, 6841 unsigned firstDataArg, unsigned numDataArgs, 6842 const char *beg, bool hasVAListArg, 6843 ArrayRef<const Expr *> Args, unsigned formatIdx, 6844 bool inFunctionCall, Sema::VariadicCallType CallType, 6845 llvm::SmallBitVector &CheckedVarArgs, 6846 UncoveredArgHandler &UncoveredArg) 6847 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 6848 numDataArgs, beg, hasVAListArg, Args, formatIdx, 6849 inFunctionCall, CallType, CheckedVarArgs, 6850 UncoveredArg) {} 6851 6852 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 6853 const char *startSpecifier, 6854 unsigned specifierLen) override; 6855 6856 bool HandleInvalidScanfConversionSpecifier( 6857 const analyze_scanf::ScanfSpecifier &FS, 6858 const char *startSpecifier, 6859 unsigned specifierLen) override; 6860 6861 void HandleIncompleteScanList(const char *start, const char *end) override; 6862 }; 6863 6864 } // namespace 6865 6866 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 6867 const char *end) { 6868 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 6869 getLocationOfByte(end), /*IsStringLocation*/true, 6870 getSpecifierRange(start, end - start)); 6871 } 6872 6873 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 6874 const analyze_scanf::ScanfSpecifier &FS, 6875 const char *startSpecifier, 6876 unsigned specifierLen) { 6877 const analyze_scanf::ScanfConversionSpecifier &CS = 6878 FS.getConversionSpecifier(); 6879 6880 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 6881 getLocationOfByte(CS.getStart()), 6882 startSpecifier, specifierLen, 6883 CS.getStart(), CS.getLength()); 6884 } 6885 6886 bool CheckScanfHandler::HandleScanfSpecifier( 6887 const analyze_scanf::ScanfSpecifier &FS, 6888 const char *startSpecifier, 6889 unsigned specifierLen) { 6890 using namespace analyze_scanf; 6891 using namespace analyze_format_string; 6892 6893 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 6894 6895 // Handle case where '%' and '*' don't consume an argument. These shouldn't 6896 // be used to decide if we are using positional arguments consistently. 6897 if (FS.consumesDataArgument()) { 6898 if (atFirstArg) { 6899 atFirstArg = false; 6900 usesPositionalArgs = FS.usesPositionalArg(); 6901 } 6902 else if (usesPositionalArgs != FS.usesPositionalArg()) { 6903 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 6904 startSpecifier, specifierLen); 6905 return false; 6906 } 6907 } 6908 6909 // Check if the field with is non-zero. 6910 const OptionalAmount &Amt = FS.getFieldWidth(); 6911 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 6912 if (Amt.getConstantAmount() == 0) { 6913 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 6914 Amt.getConstantLength()); 6915 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 6916 getLocationOfByte(Amt.getStart()), 6917 /*IsStringLocation*/true, R, 6918 FixItHint::CreateRemoval(R)); 6919 } 6920 } 6921 6922 if (!FS.consumesDataArgument()) { 6923 // FIXME: Technically specifying a precision or field width here 6924 // makes no sense. Worth issuing a warning at some point. 6925 return true; 6926 } 6927 6928 // Consume the argument. 6929 unsigned argIndex = FS.getArgIndex(); 6930 if (argIndex < NumDataArgs) { 6931 // The check to see if the argIndex is valid will come later. 6932 // We set the bit here because we may exit early from this 6933 // function if we encounter some other error. 6934 CoveredArgs.set(argIndex); 6935 } 6936 6937 // Check the length modifier is valid with the given conversion specifier. 6938 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 6939 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6940 diag::warn_format_nonsensical_length); 6941 else if (!FS.hasStandardLengthModifier()) 6942 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 6943 else if (!FS.hasStandardLengthConversionCombination()) 6944 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6945 diag::warn_format_non_standard_conversion_spec); 6946 6947 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 6948 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 6949 6950 // The remaining checks depend on the data arguments. 6951 if (HasVAListArg) 6952 return true; 6953 6954 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 6955 return false; 6956 6957 // Check that the argument type matches the format specifier. 6958 const Expr *Ex = getDataArg(argIndex); 6959 if (!Ex) 6960 return true; 6961 6962 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 6963 6964 if (!AT.isValid()) { 6965 return true; 6966 } 6967 6968 analyze_format_string::ArgType::MatchKind match = 6969 AT.matchesType(S.Context, Ex->getType()); 6970 if (match == analyze_format_string::ArgType::Match) { 6971 return true; 6972 } 6973 6974 ScanfSpecifier fixedFS = FS; 6975 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 6976 S.getLangOpts(), S.Context); 6977 6978 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 6979 if (match == analyze_format_string::ArgType::NoMatchPedantic) { 6980 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 6981 } 6982 6983 if (success) { 6984 // Get the fix string from the fixed format specifier. 6985 SmallString<128> buf; 6986 llvm::raw_svector_ostream os(buf); 6987 fixedFS.toString(os); 6988 6989 EmitFormatDiagnostic( 6990 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) 6991 << Ex->getType() << false << Ex->getSourceRange(), 6992 Ex->getLocStart(), 6993 /*IsStringLocation*/ false, 6994 getSpecifierRange(startSpecifier, specifierLen), 6995 FixItHint::CreateReplacement( 6996 getSpecifierRange(startSpecifier, specifierLen), os.str())); 6997 } else { 6998 EmitFormatDiagnostic(S.PDiag(diag) 6999 << AT.getRepresentativeTypeName(S.Context) 7000 << Ex->getType() << false << Ex->getSourceRange(), 7001 Ex->getLocStart(), 7002 /*IsStringLocation*/ false, 7003 getSpecifierRange(startSpecifier, specifierLen)); 7004 } 7005 7006 return true; 7007 } 7008 7009 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 7010 const Expr *OrigFormatExpr, 7011 ArrayRef<const Expr *> Args, 7012 bool HasVAListArg, unsigned format_idx, 7013 unsigned firstDataArg, 7014 Sema::FormatStringType Type, 7015 bool inFunctionCall, 7016 Sema::VariadicCallType CallType, 7017 llvm::SmallBitVector &CheckedVarArgs, 7018 UncoveredArgHandler &UncoveredArg) { 7019 // CHECK: is the format string a wide literal? 7020 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 7021 CheckFormatHandler::EmitFormatDiagnostic( 7022 S, inFunctionCall, Args[format_idx], 7023 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(), 7024 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 7025 return; 7026 } 7027 7028 // Str - The format string. NOTE: this is NOT null-terminated! 7029 StringRef StrRef = FExpr->getString(); 7030 const char *Str = StrRef.data(); 7031 // Account for cases where the string literal is truncated in a declaration. 7032 const ConstantArrayType *T = 7033 S.Context.getAsConstantArrayType(FExpr->getType()); 7034 assert(T && "String literal not of constant array type!"); 7035 size_t TypeSize = T->getSize().getZExtValue(); 7036 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 7037 const unsigned numDataArgs = Args.size() - firstDataArg; 7038 7039 // Emit a warning if the string literal is truncated and does not contain an 7040 // embedded null character. 7041 if (TypeSize <= StrRef.size() && 7042 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 7043 CheckFormatHandler::EmitFormatDiagnostic( 7044 S, inFunctionCall, Args[format_idx], 7045 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 7046 FExpr->getLocStart(), 7047 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 7048 return; 7049 } 7050 7051 // CHECK: empty format string? 7052 if (StrLen == 0 && numDataArgs > 0) { 7053 CheckFormatHandler::EmitFormatDiagnostic( 7054 S, inFunctionCall, Args[format_idx], 7055 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(), 7056 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 7057 return; 7058 } 7059 7060 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 7061 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 7062 Type == Sema::FST_OSTrace) { 7063 CheckPrintfHandler H( 7064 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 7065 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 7066 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 7067 CheckedVarArgs, UncoveredArg); 7068 7069 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 7070 S.getLangOpts(), 7071 S.Context.getTargetInfo(), 7072 Type == Sema::FST_FreeBSDKPrintf)) 7073 H.DoneProcessing(); 7074 } else if (Type == Sema::FST_Scanf) { 7075 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 7076 numDataArgs, Str, HasVAListArg, Args, format_idx, 7077 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 7078 7079 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 7080 S.getLangOpts(), 7081 S.Context.getTargetInfo())) 7082 H.DoneProcessing(); 7083 } // TODO: handle other formats 7084 } 7085 7086 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 7087 // Str - The format string. NOTE: this is NOT null-terminated! 7088 StringRef StrRef = FExpr->getString(); 7089 const char *Str = StrRef.data(); 7090 // Account for cases where the string literal is truncated in a declaration. 7091 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 7092 assert(T && "String literal not of constant array type!"); 7093 size_t TypeSize = T->getSize().getZExtValue(); 7094 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 7095 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 7096 getLangOpts(), 7097 Context.getTargetInfo()); 7098 } 7099 7100 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 7101 7102 // Returns the related absolute value function that is larger, of 0 if one 7103 // does not exist. 7104 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 7105 switch (AbsFunction) { 7106 default: 7107 return 0; 7108 7109 case Builtin::BI__builtin_abs: 7110 return Builtin::BI__builtin_labs; 7111 case Builtin::BI__builtin_labs: 7112 return Builtin::BI__builtin_llabs; 7113 case Builtin::BI__builtin_llabs: 7114 return 0; 7115 7116 case Builtin::BI__builtin_fabsf: 7117 return Builtin::BI__builtin_fabs; 7118 case Builtin::BI__builtin_fabs: 7119 return Builtin::BI__builtin_fabsl; 7120 case Builtin::BI__builtin_fabsl: 7121 return 0; 7122 7123 case Builtin::BI__builtin_cabsf: 7124 return Builtin::BI__builtin_cabs; 7125 case Builtin::BI__builtin_cabs: 7126 return Builtin::BI__builtin_cabsl; 7127 case Builtin::BI__builtin_cabsl: 7128 return 0; 7129 7130 case Builtin::BIabs: 7131 return Builtin::BIlabs; 7132 case Builtin::BIlabs: 7133 return Builtin::BIllabs; 7134 case Builtin::BIllabs: 7135 return 0; 7136 7137 case Builtin::BIfabsf: 7138 return Builtin::BIfabs; 7139 case Builtin::BIfabs: 7140 return Builtin::BIfabsl; 7141 case Builtin::BIfabsl: 7142 return 0; 7143 7144 case Builtin::BIcabsf: 7145 return Builtin::BIcabs; 7146 case Builtin::BIcabs: 7147 return Builtin::BIcabsl; 7148 case Builtin::BIcabsl: 7149 return 0; 7150 } 7151 } 7152 7153 // Returns the argument type of the absolute value function. 7154 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 7155 unsigned AbsType) { 7156 if (AbsType == 0) 7157 return QualType(); 7158 7159 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 7160 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 7161 if (Error != ASTContext::GE_None) 7162 return QualType(); 7163 7164 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 7165 if (!FT) 7166 return QualType(); 7167 7168 if (FT->getNumParams() != 1) 7169 return QualType(); 7170 7171 return FT->getParamType(0); 7172 } 7173 7174 // Returns the best absolute value function, or zero, based on type and 7175 // current absolute value function. 7176 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 7177 unsigned AbsFunctionKind) { 7178 unsigned BestKind = 0; 7179 uint64_t ArgSize = Context.getTypeSize(ArgType); 7180 for (unsigned Kind = AbsFunctionKind; Kind != 0; 7181 Kind = getLargerAbsoluteValueFunction(Kind)) { 7182 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 7183 if (Context.getTypeSize(ParamType) >= ArgSize) { 7184 if (BestKind == 0) 7185 BestKind = Kind; 7186 else if (Context.hasSameType(ParamType, ArgType)) { 7187 BestKind = Kind; 7188 break; 7189 } 7190 } 7191 } 7192 return BestKind; 7193 } 7194 7195 enum AbsoluteValueKind { 7196 AVK_Integer, 7197 AVK_Floating, 7198 AVK_Complex 7199 }; 7200 7201 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 7202 if (T->isIntegralOrEnumerationType()) 7203 return AVK_Integer; 7204 if (T->isRealFloatingType()) 7205 return AVK_Floating; 7206 if (T->isAnyComplexType()) 7207 return AVK_Complex; 7208 7209 llvm_unreachable("Type not integer, floating, or complex"); 7210 } 7211 7212 // Changes the absolute value function to a different type. Preserves whether 7213 // the function is a builtin. 7214 static unsigned changeAbsFunction(unsigned AbsKind, 7215 AbsoluteValueKind ValueKind) { 7216 switch (ValueKind) { 7217 case AVK_Integer: 7218 switch (AbsKind) { 7219 default: 7220 return 0; 7221 case Builtin::BI__builtin_fabsf: 7222 case Builtin::BI__builtin_fabs: 7223 case Builtin::BI__builtin_fabsl: 7224 case Builtin::BI__builtin_cabsf: 7225 case Builtin::BI__builtin_cabs: 7226 case Builtin::BI__builtin_cabsl: 7227 return Builtin::BI__builtin_abs; 7228 case Builtin::BIfabsf: 7229 case Builtin::BIfabs: 7230 case Builtin::BIfabsl: 7231 case Builtin::BIcabsf: 7232 case Builtin::BIcabs: 7233 case Builtin::BIcabsl: 7234 return Builtin::BIabs; 7235 } 7236 case AVK_Floating: 7237 switch (AbsKind) { 7238 default: 7239 return 0; 7240 case Builtin::BI__builtin_abs: 7241 case Builtin::BI__builtin_labs: 7242 case Builtin::BI__builtin_llabs: 7243 case Builtin::BI__builtin_cabsf: 7244 case Builtin::BI__builtin_cabs: 7245 case Builtin::BI__builtin_cabsl: 7246 return Builtin::BI__builtin_fabsf; 7247 case Builtin::BIabs: 7248 case Builtin::BIlabs: 7249 case Builtin::BIllabs: 7250 case Builtin::BIcabsf: 7251 case Builtin::BIcabs: 7252 case Builtin::BIcabsl: 7253 return Builtin::BIfabsf; 7254 } 7255 case AVK_Complex: 7256 switch (AbsKind) { 7257 default: 7258 return 0; 7259 case Builtin::BI__builtin_abs: 7260 case Builtin::BI__builtin_labs: 7261 case Builtin::BI__builtin_llabs: 7262 case Builtin::BI__builtin_fabsf: 7263 case Builtin::BI__builtin_fabs: 7264 case Builtin::BI__builtin_fabsl: 7265 return Builtin::BI__builtin_cabsf; 7266 case Builtin::BIabs: 7267 case Builtin::BIlabs: 7268 case Builtin::BIllabs: 7269 case Builtin::BIfabsf: 7270 case Builtin::BIfabs: 7271 case Builtin::BIfabsl: 7272 return Builtin::BIcabsf; 7273 } 7274 } 7275 llvm_unreachable("Unable to convert function"); 7276 } 7277 7278 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 7279 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 7280 if (!FnInfo) 7281 return 0; 7282 7283 switch (FDecl->getBuiltinID()) { 7284 default: 7285 return 0; 7286 case Builtin::BI__builtin_abs: 7287 case Builtin::BI__builtin_fabs: 7288 case Builtin::BI__builtin_fabsf: 7289 case Builtin::BI__builtin_fabsl: 7290 case Builtin::BI__builtin_labs: 7291 case Builtin::BI__builtin_llabs: 7292 case Builtin::BI__builtin_cabs: 7293 case Builtin::BI__builtin_cabsf: 7294 case Builtin::BI__builtin_cabsl: 7295 case Builtin::BIabs: 7296 case Builtin::BIlabs: 7297 case Builtin::BIllabs: 7298 case Builtin::BIfabs: 7299 case Builtin::BIfabsf: 7300 case Builtin::BIfabsl: 7301 case Builtin::BIcabs: 7302 case Builtin::BIcabsf: 7303 case Builtin::BIcabsl: 7304 return FDecl->getBuiltinID(); 7305 } 7306 llvm_unreachable("Unknown Builtin type"); 7307 } 7308 7309 // If the replacement is valid, emit a note with replacement function. 7310 // Additionally, suggest including the proper header if not already included. 7311 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 7312 unsigned AbsKind, QualType ArgType) { 7313 bool EmitHeaderHint = true; 7314 const char *HeaderName = nullptr; 7315 const char *FunctionName = nullptr; 7316 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 7317 FunctionName = "std::abs"; 7318 if (ArgType->isIntegralOrEnumerationType()) { 7319 HeaderName = "cstdlib"; 7320 } else if (ArgType->isRealFloatingType()) { 7321 HeaderName = "cmath"; 7322 } else { 7323 llvm_unreachable("Invalid Type"); 7324 } 7325 7326 // Lookup all std::abs 7327 if (NamespaceDecl *Std = S.getStdNamespace()) { 7328 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 7329 R.suppressDiagnostics(); 7330 S.LookupQualifiedName(R, Std); 7331 7332 for (const auto *I : R) { 7333 const FunctionDecl *FDecl = nullptr; 7334 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 7335 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 7336 } else { 7337 FDecl = dyn_cast<FunctionDecl>(I); 7338 } 7339 if (!FDecl) 7340 continue; 7341 7342 // Found std::abs(), check that they are the right ones. 7343 if (FDecl->getNumParams() != 1) 7344 continue; 7345 7346 // Check that the parameter type can handle the argument. 7347 QualType ParamType = FDecl->getParamDecl(0)->getType(); 7348 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 7349 S.Context.getTypeSize(ArgType) <= 7350 S.Context.getTypeSize(ParamType)) { 7351 // Found a function, don't need the header hint. 7352 EmitHeaderHint = false; 7353 break; 7354 } 7355 } 7356 } 7357 } else { 7358 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 7359 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 7360 7361 if (HeaderName) { 7362 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 7363 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 7364 R.suppressDiagnostics(); 7365 S.LookupName(R, S.getCurScope()); 7366 7367 if (R.isSingleResult()) { 7368 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 7369 if (FD && FD->getBuiltinID() == AbsKind) { 7370 EmitHeaderHint = false; 7371 } else { 7372 return; 7373 } 7374 } else if (!R.empty()) { 7375 return; 7376 } 7377 } 7378 } 7379 7380 S.Diag(Loc, diag::note_replace_abs_function) 7381 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 7382 7383 if (!HeaderName) 7384 return; 7385 7386 if (!EmitHeaderHint) 7387 return; 7388 7389 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 7390 << FunctionName; 7391 } 7392 7393 template <std::size_t StrLen> 7394 static bool IsStdFunction(const FunctionDecl *FDecl, 7395 const char (&Str)[StrLen]) { 7396 if (!FDecl) 7397 return false; 7398 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 7399 return false; 7400 if (!FDecl->isInStdNamespace()) 7401 return false; 7402 7403 return true; 7404 } 7405 7406 // Warn when using the wrong abs() function. 7407 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 7408 const FunctionDecl *FDecl) { 7409 if (Call->getNumArgs() != 1) 7410 return; 7411 7412 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 7413 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 7414 if (AbsKind == 0 && !IsStdAbs) 7415 return; 7416 7417 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 7418 QualType ParamType = Call->getArg(0)->getType(); 7419 7420 // Unsigned types cannot be negative. Suggest removing the absolute value 7421 // function call. 7422 if (ArgType->isUnsignedIntegerType()) { 7423 const char *FunctionName = 7424 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 7425 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 7426 Diag(Call->getExprLoc(), diag::note_remove_abs) 7427 << FunctionName 7428 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 7429 return; 7430 } 7431 7432 // Taking the absolute value of a pointer is very suspicious, they probably 7433 // wanted to index into an array, dereference a pointer, call a function, etc. 7434 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 7435 unsigned DiagType = 0; 7436 if (ArgType->isFunctionType()) 7437 DiagType = 1; 7438 else if (ArgType->isArrayType()) 7439 DiagType = 2; 7440 7441 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 7442 return; 7443 } 7444 7445 // std::abs has overloads which prevent most of the absolute value problems 7446 // from occurring. 7447 if (IsStdAbs) 7448 return; 7449 7450 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 7451 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 7452 7453 // The argument and parameter are the same kind. Check if they are the right 7454 // size. 7455 if (ArgValueKind == ParamValueKind) { 7456 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 7457 return; 7458 7459 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 7460 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 7461 << FDecl << ArgType << ParamType; 7462 7463 if (NewAbsKind == 0) 7464 return; 7465 7466 emitReplacement(*this, Call->getExprLoc(), 7467 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 7468 return; 7469 } 7470 7471 // ArgValueKind != ParamValueKind 7472 // The wrong type of absolute value function was used. Attempt to find the 7473 // proper one. 7474 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 7475 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 7476 if (NewAbsKind == 0) 7477 return; 7478 7479 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 7480 << FDecl << ParamValueKind << ArgValueKind; 7481 7482 emitReplacement(*this, Call->getExprLoc(), 7483 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 7484 } 7485 7486 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 7487 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 7488 const FunctionDecl *FDecl) { 7489 if (!Call || !FDecl) return; 7490 7491 // Ignore template specializations and macros. 7492 if (inTemplateInstantiation()) return; 7493 if (Call->getExprLoc().isMacroID()) return; 7494 7495 // Only care about the one template argument, two function parameter std::max 7496 if (Call->getNumArgs() != 2) return; 7497 if (!IsStdFunction(FDecl, "max")) return; 7498 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 7499 if (!ArgList) return; 7500 if (ArgList->size() != 1) return; 7501 7502 // Check that template type argument is unsigned integer. 7503 const auto& TA = ArgList->get(0); 7504 if (TA.getKind() != TemplateArgument::Type) return; 7505 QualType ArgType = TA.getAsType(); 7506 if (!ArgType->isUnsignedIntegerType()) return; 7507 7508 // See if either argument is a literal zero. 7509 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 7510 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 7511 if (!MTE) return false; 7512 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr()); 7513 if (!Num) return false; 7514 if (Num->getValue() != 0) return false; 7515 return true; 7516 }; 7517 7518 const Expr *FirstArg = Call->getArg(0); 7519 const Expr *SecondArg = Call->getArg(1); 7520 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 7521 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 7522 7523 // Only warn when exactly one argument is zero. 7524 if (IsFirstArgZero == IsSecondArgZero) return; 7525 7526 SourceRange FirstRange = FirstArg->getSourceRange(); 7527 SourceRange SecondRange = SecondArg->getSourceRange(); 7528 7529 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 7530 7531 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 7532 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 7533 7534 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 7535 SourceRange RemovalRange; 7536 if (IsFirstArgZero) { 7537 RemovalRange = SourceRange(FirstRange.getBegin(), 7538 SecondRange.getBegin().getLocWithOffset(-1)); 7539 } else { 7540 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 7541 SecondRange.getEnd()); 7542 } 7543 7544 Diag(Call->getExprLoc(), diag::note_remove_max_call) 7545 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 7546 << FixItHint::CreateRemoval(RemovalRange); 7547 } 7548 7549 //===--- CHECK: Standard memory functions ---------------------------------===// 7550 7551 /// Takes the expression passed to the size_t parameter of functions 7552 /// such as memcmp, strncat, etc and warns if it's a comparison. 7553 /// 7554 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 7555 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 7556 IdentifierInfo *FnName, 7557 SourceLocation FnLoc, 7558 SourceLocation RParenLoc) { 7559 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 7560 if (!Size) 7561 return false; 7562 7563 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 7564 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 7565 return false; 7566 7567 SourceRange SizeRange = Size->getSourceRange(); 7568 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 7569 << SizeRange << FnName; 7570 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 7571 << FnName << FixItHint::CreateInsertion( 7572 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")") 7573 << FixItHint::CreateRemoval(RParenLoc); 7574 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 7575 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 7576 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 7577 ")"); 7578 7579 return true; 7580 } 7581 7582 /// Determine whether the given type is or contains a dynamic class type 7583 /// (e.g., whether it has a vtable). 7584 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 7585 bool &IsContained) { 7586 // Look through array types while ignoring qualifiers. 7587 const Type *Ty = T->getBaseElementTypeUnsafe(); 7588 IsContained = false; 7589 7590 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 7591 RD = RD ? RD->getDefinition() : nullptr; 7592 if (!RD || RD->isInvalidDecl()) 7593 return nullptr; 7594 7595 if (RD->isDynamicClass()) 7596 return RD; 7597 7598 // Check all the fields. If any bases were dynamic, the class is dynamic. 7599 // It's impossible for a class to transitively contain itself by value, so 7600 // infinite recursion is impossible. 7601 for (auto *FD : RD->fields()) { 7602 bool SubContained; 7603 if (const CXXRecordDecl *ContainedRD = 7604 getContainedDynamicClass(FD->getType(), SubContained)) { 7605 IsContained = true; 7606 return ContainedRD; 7607 } 7608 } 7609 7610 return nullptr; 7611 } 7612 7613 /// If E is a sizeof expression, returns its argument expression, 7614 /// otherwise returns NULL. 7615 static const Expr *getSizeOfExprArg(const Expr *E) { 7616 if (const UnaryExprOrTypeTraitExpr *SizeOf = 7617 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 7618 if (SizeOf->getKind() == UETT_SizeOf && !SizeOf->isArgumentType()) 7619 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 7620 7621 return nullptr; 7622 } 7623 7624 /// If E is a sizeof expression, returns its argument type. 7625 static QualType getSizeOfArgType(const Expr *E) { 7626 if (const UnaryExprOrTypeTraitExpr *SizeOf = 7627 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 7628 if (SizeOf->getKind() == UETT_SizeOf) 7629 return SizeOf->getTypeOfArgument(); 7630 7631 return QualType(); 7632 } 7633 7634 namespace { 7635 7636 struct SearchNonTrivialToInitializeField 7637 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 7638 using Super = 7639 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 7640 7641 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 7642 7643 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 7644 SourceLocation SL) { 7645 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 7646 asDerived().visitArray(PDIK, AT, SL); 7647 return; 7648 } 7649 7650 Super::visitWithKind(PDIK, FT, SL); 7651 } 7652 7653 void visitARCStrong(QualType FT, SourceLocation SL) { 7654 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 7655 } 7656 void visitARCWeak(QualType FT, SourceLocation SL) { 7657 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 7658 } 7659 void visitStruct(QualType FT, SourceLocation SL) { 7660 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 7661 visit(FD->getType(), FD->getLocation()); 7662 } 7663 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 7664 const ArrayType *AT, SourceLocation SL) { 7665 visit(getContext().getBaseElementType(AT), SL); 7666 } 7667 void visitTrivial(QualType FT, SourceLocation SL) {} 7668 7669 static void diag(QualType RT, const Expr *E, Sema &S) { 7670 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 7671 } 7672 7673 ASTContext &getContext() { return S.getASTContext(); } 7674 7675 const Expr *E; 7676 Sema &S; 7677 }; 7678 7679 struct SearchNonTrivialToCopyField 7680 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 7681 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 7682 7683 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 7684 7685 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 7686 SourceLocation SL) { 7687 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 7688 asDerived().visitArray(PCK, AT, SL); 7689 return; 7690 } 7691 7692 Super::visitWithKind(PCK, FT, SL); 7693 } 7694 7695 void visitARCStrong(QualType FT, SourceLocation SL) { 7696 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 7697 } 7698 void visitARCWeak(QualType FT, SourceLocation SL) { 7699 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 7700 } 7701 void visitStruct(QualType FT, SourceLocation SL) { 7702 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 7703 visit(FD->getType(), FD->getLocation()); 7704 } 7705 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 7706 SourceLocation SL) { 7707 visit(getContext().getBaseElementType(AT), SL); 7708 } 7709 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 7710 SourceLocation SL) {} 7711 void visitTrivial(QualType FT, SourceLocation SL) {} 7712 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 7713 7714 static void diag(QualType RT, const Expr *E, Sema &S) { 7715 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 7716 } 7717 7718 ASTContext &getContext() { return S.getASTContext(); } 7719 7720 const Expr *E; 7721 Sema &S; 7722 }; 7723 7724 } 7725 7726 /// Check for dangerous or invalid arguments to memset(). 7727 /// 7728 /// This issues warnings on known problematic, dangerous or unspecified 7729 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 7730 /// function calls. 7731 /// 7732 /// \param Call The call expression to diagnose. 7733 void Sema::CheckMemaccessArguments(const CallExpr *Call, 7734 unsigned BId, 7735 IdentifierInfo *FnName) { 7736 assert(BId != 0); 7737 7738 // It is possible to have a non-standard definition of memset. Validate 7739 // we have enough arguments, and if not, abort further checking. 7740 unsigned ExpectedNumArgs = 7741 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 7742 if (Call->getNumArgs() < ExpectedNumArgs) 7743 return; 7744 7745 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 7746 BId == Builtin::BIstrndup ? 1 : 2); 7747 unsigned LenArg = 7748 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 7749 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 7750 7751 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 7752 Call->getLocStart(), Call->getRParenLoc())) 7753 return; 7754 7755 // We have special checking when the length is a sizeof expression. 7756 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 7757 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 7758 llvm::FoldingSetNodeID SizeOfArgID; 7759 7760 // Although widely used, 'bzero' is not a standard function. Be more strict 7761 // with the argument types before allowing diagnostics and only allow the 7762 // form bzero(ptr, sizeof(...)). 7763 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 7764 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 7765 return; 7766 7767 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 7768 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 7769 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 7770 7771 QualType DestTy = Dest->getType(); 7772 QualType PointeeTy; 7773 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 7774 PointeeTy = DestPtrTy->getPointeeType(); 7775 7776 // Never warn about void type pointers. This can be used to suppress 7777 // false positives. 7778 if (PointeeTy->isVoidType()) 7779 continue; 7780 7781 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 7782 // actually comparing the expressions for equality. Because computing the 7783 // expression IDs can be expensive, we only do this if the diagnostic is 7784 // enabled. 7785 if (SizeOfArg && 7786 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 7787 SizeOfArg->getExprLoc())) { 7788 // We only compute IDs for expressions if the warning is enabled, and 7789 // cache the sizeof arg's ID. 7790 if (SizeOfArgID == llvm::FoldingSetNodeID()) 7791 SizeOfArg->Profile(SizeOfArgID, Context, true); 7792 llvm::FoldingSetNodeID DestID; 7793 Dest->Profile(DestID, Context, true); 7794 if (DestID == SizeOfArgID) { 7795 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 7796 // over sizeof(src) as well. 7797 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 7798 StringRef ReadableName = FnName->getName(); 7799 7800 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 7801 if (UnaryOp->getOpcode() == UO_AddrOf) 7802 ActionIdx = 1; // If its an address-of operator, just remove it. 7803 if (!PointeeTy->isIncompleteType() && 7804 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 7805 ActionIdx = 2; // If the pointee's size is sizeof(char), 7806 // suggest an explicit length. 7807 7808 // If the function is defined as a builtin macro, do not show macro 7809 // expansion. 7810 SourceLocation SL = SizeOfArg->getExprLoc(); 7811 SourceRange DSR = Dest->getSourceRange(); 7812 SourceRange SSR = SizeOfArg->getSourceRange(); 7813 SourceManager &SM = getSourceManager(); 7814 7815 if (SM.isMacroArgExpansion(SL)) { 7816 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 7817 SL = SM.getSpellingLoc(SL); 7818 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 7819 SM.getSpellingLoc(DSR.getEnd())); 7820 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 7821 SM.getSpellingLoc(SSR.getEnd())); 7822 } 7823 7824 DiagRuntimeBehavior(SL, SizeOfArg, 7825 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 7826 << ReadableName 7827 << PointeeTy 7828 << DestTy 7829 << DSR 7830 << SSR); 7831 DiagRuntimeBehavior(SL, SizeOfArg, 7832 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 7833 << ActionIdx 7834 << SSR); 7835 7836 break; 7837 } 7838 } 7839 7840 // Also check for cases where the sizeof argument is the exact same 7841 // type as the memory argument, and where it points to a user-defined 7842 // record type. 7843 if (SizeOfArgTy != QualType()) { 7844 if (PointeeTy->isRecordType() && 7845 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 7846 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 7847 PDiag(diag::warn_sizeof_pointer_type_memaccess) 7848 << FnName << SizeOfArgTy << ArgIdx 7849 << PointeeTy << Dest->getSourceRange() 7850 << LenExpr->getSourceRange()); 7851 break; 7852 } 7853 } 7854 } else if (DestTy->isArrayType()) { 7855 PointeeTy = DestTy; 7856 } 7857 7858 if (PointeeTy == QualType()) 7859 continue; 7860 7861 // Always complain about dynamic classes. 7862 bool IsContained; 7863 if (const CXXRecordDecl *ContainedRD = 7864 getContainedDynamicClass(PointeeTy, IsContained)) { 7865 7866 unsigned OperationType = 0; 7867 // "overwritten" if we're warning about the destination for any call 7868 // but memcmp; otherwise a verb appropriate to the call. 7869 if (ArgIdx != 0 || BId == Builtin::BImemcmp) { 7870 if (BId == Builtin::BImemcpy) 7871 OperationType = 1; 7872 else if(BId == Builtin::BImemmove) 7873 OperationType = 2; 7874 else if (BId == Builtin::BImemcmp) 7875 OperationType = 3; 7876 } 7877 7878 DiagRuntimeBehavior( 7879 Dest->getExprLoc(), Dest, 7880 PDiag(diag::warn_dyn_class_memaccess) 7881 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx) 7882 << FnName << IsContained << ContainedRD << OperationType 7883 << Call->getCallee()->getSourceRange()); 7884 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 7885 BId != Builtin::BImemset) 7886 DiagRuntimeBehavior( 7887 Dest->getExprLoc(), Dest, 7888 PDiag(diag::warn_arc_object_memaccess) 7889 << ArgIdx << FnName << PointeeTy 7890 << Call->getCallee()->getSourceRange()); 7891 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 7892 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 7893 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 7894 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 7895 PDiag(diag::warn_cstruct_memaccess) 7896 << ArgIdx << FnName << PointeeTy << 0); 7897 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 7898 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 7899 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 7900 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 7901 PDiag(diag::warn_cstruct_memaccess) 7902 << ArgIdx << FnName << PointeeTy << 1); 7903 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 7904 } else { 7905 continue; 7906 } 7907 } else 7908 continue; 7909 7910 DiagRuntimeBehavior( 7911 Dest->getExprLoc(), Dest, 7912 PDiag(diag::note_bad_memaccess_silence) 7913 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 7914 break; 7915 } 7916 } 7917 7918 // A little helper routine: ignore addition and subtraction of integer literals. 7919 // This intentionally does not ignore all integer constant expressions because 7920 // we don't want to remove sizeof(). 7921 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 7922 Ex = Ex->IgnoreParenCasts(); 7923 7924 while (true) { 7925 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 7926 if (!BO || !BO->isAdditiveOp()) 7927 break; 7928 7929 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 7930 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 7931 7932 if (isa<IntegerLiteral>(RHS)) 7933 Ex = LHS; 7934 else if (isa<IntegerLiteral>(LHS)) 7935 Ex = RHS; 7936 else 7937 break; 7938 } 7939 7940 return Ex; 7941 } 7942 7943 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 7944 ASTContext &Context) { 7945 // Only handle constant-sized or VLAs, but not flexible members. 7946 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 7947 // Only issue the FIXIT for arrays of size > 1. 7948 if (CAT->getSize().getSExtValue() <= 1) 7949 return false; 7950 } else if (!Ty->isVariableArrayType()) { 7951 return false; 7952 } 7953 return true; 7954 } 7955 7956 // Warn if the user has made the 'size' argument to strlcpy or strlcat 7957 // be the size of the source, instead of the destination. 7958 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 7959 IdentifierInfo *FnName) { 7960 7961 // Don't crash if the user has the wrong number of arguments 7962 unsigned NumArgs = Call->getNumArgs(); 7963 if ((NumArgs != 3) && (NumArgs != 4)) 7964 return; 7965 7966 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 7967 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 7968 const Expr *CompareWithSrc = nullptr; 7969 7970 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 7971 Call->getLocStart(), Call->getRParenLoc())) 7972 return; 7973 7974 // Look for 'strlcpy(dst, x, sizeof(x))' 7975 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 7976 CompareWithSrc = Ex; 7977 else { 7978 // Look for 'strlcpy(dst, x, strlen(x))' 7979 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 7980 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 7981 SizeCall->getNumArgs() == 1) 7982 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 7983 } 7984 } 7985 7986 if (!CompareWithSrc) 7987 return; 7988 7989 // Determine if the argument to sizeof/strlen is equal to the source 7990 // argument. In principle there's all kinds of things you could do 7991 // here, for instance creating an == expression and evaluating it with 7992 // EvaluateAsBooleanCondition, but this uses a more direct technique: 7993 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 7994 if (!SrcArgDRE) 7995 return; 7996 7997 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 7998 if (!CompareWithSrcDRE || 7999 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 8000 return; 8001 8002 const Expr *OriginalSizeArg = Call->getArg(2); 8003 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size) 8004 << OriginalSizeArg->getSourceRange() << FnName; 8005 8006 // Output a FIXIT hint if the destination is an array (rather than a 8007 // pointer to an array). This could be enhanced to handle some 8008 // pointers if we know the actual size, like if DstArg is 'array+2' 8009 // we could say 'sizeof(array)-2'. 8010 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 8011 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 8012 return; 8013 8014 SmallString<128> sizeString; 8015 llvm::raw_svector_ostream OS(sizeString); 8016 OS << "sizeof("; 8017 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 8018 OS << ")"; 8019 8020 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size) 8021 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 8022 OS.str()); 8023 } 8024 8025 /// Check if two expressions refer to the same declaration. 8026 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 8027 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 8028 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 8029 return D1->getDecl() == D2->getDecl(); 8030 return false; 8031 } 8032 8033 static const Expr *getStrlenExprArg(const Expr *E) { 8034 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 8035 const FunctionDecl *FD = CE->getDirectCallee(); 8036 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 8037 return nullptr; 8038 return CE->getArg(0)->IgnoreParenCasts(); 8039 } 8040 return nullptr; 8041 } 8042 8043 // Warn on anti-patterns as the 'size' argument to strncat. 8044 // The correct size argument should look like following: 8045 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 8046 void Sema::CheckStrncatArguments(const CallExpr *CE, 8047 IdentifierInfo *FnName) { 8048 // Don't crash if the user has the wrong number of arguments. 8049 if (CE->getNumArgs() < 3) 8050 return; 8051 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 8052 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 8053 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 8054 8055 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(), 8056 CE->getRParenLoc())) 8057 return; 8058 8059 // Identify common expressions, which are wrongly used as the size argument 8060 // to strncat and may lead to buffer overflows. 8061 unsigned PatternType = 0; 8062 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 8063 // - sizeof(dst) 8064 if (referToTheSameDecl(SizeOfArg, DstArg)) 8065 PatternType = 1; 8066 // - sizeof(src) 8067 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 8068 PatternType = 2; 8069 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 8070 if (BE->getOpcode() == BO_Sub) { 8071 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 8072 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 8073 // - sizeof(dst) - strlen(dst) 8074 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 8075 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 8076 PatternType = 1; 8077 // - sizeof(src) - (anything) 8078 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 8079 PatternType = 2; 8080 } 8081 } 8082 8083 if (PatternType == 0) 8084 return; 8085 8086 // Generate the diagnostic. 8087 SourceLocation SL = LenArg->getLocStart(); 8088 SourceRange SR = LenArg->getSourceRange(); 8089 SourceManager &SM = getSourceManager(); 8090 8091 // If the function is defined as a builtin macro, do not show macro expansion. 8092 if (SM.isMacroArgExpansion(SL)) { 8093 SL = SM.getSpellingLoc(SL); 8094 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 8095 SM.getSpellingLoc(SR.getEnd())); 8096 } 8097 8098 // Check if the destination is an array (rather than a pointer to an array). 8099 QualType DstTy = DstArg->getType(); 8100 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 8101 Context); 8102 if (!isKnownSizeArray) { 8103 if (PatternType == 1) 8104 Diag(SL, diag::warn_strncat_wrong_size) << SR; 8105 else 8106 Diag(SL, diag::warn_strncat_src_size) << SR; 8107 return; 8108 } 8109 8110 if (PatternType == 1) 8111 Diag(SL, diag::warn_strncat_large_size) << SR; 8112 else 8113 Diag(SL, diag::warn_strncat_src_size) << SR; 8114 8115 SmallString<128> sizeString; 8116 llvm::raw_svector_ostream OS(sizeString); 8117 OS << "sizeof("; 8118 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 8119 OS << ") - "; 8120 OS << "strlen("; 8121 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 8122 OS << ") - 1"; 8123 8124 Diag(SL, diag::note_strncat_wrong_size) 8125 << FixItHint::CreateReplacement(SR, OS.str()); 8126 } 8127 8128 //===--- CHECK: Return Address of Stack Variable --------------------------===// 8129 8130 static const Expr *EvalVal(const Expr *E, 8131 SmallVectorImpl<const DeclRefExpr *> &refVars, 8132 const Decl *ParentDecl); 8133 static const Expr *EvalAddr(const Expr *E, 8134 SmallVectorImpl<const DeclRefExpr *> &refVars, 8135 const Decl *ParentDecl); 8136 8137 /// CheckReturnStackAddr - Check if a return statement returns the address 8138 /// of a stack variable. 8139 static void 8140 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType, 8141 SourceLocation ReturnLoc) { 8142 const Expr *stackE = nullptr; 8143 SmallVector<const DeclRefExpr *, 8> refVars; 8144 8145 // Perform checking for returned stack addresses, local blocks, 8146 // label addresses or references to temporaries. 8147 if (lhsType->isPointerType() || 8148 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) { 8149 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr); 8150 } else if (lhsType->isReferenceType()) { 8151 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr); 8152 } 8153 8154 if (!stackE) 8155 return; // Nothing suspicious was found. 8156 8157 // Parameters are initialized in the calling scope, so taking the address 8158 // of a parameter reference doesn't need a warning. 8159 for (auto *DRE : refVars) 8160 if (isa<ParmVarDecl>(DRE->getDecl())) 8161 return; 8162 8163 SourceLocation diagLoc; 8164 SourceRange diagRange; 8165 if (refVars.empty()) { 8166 diagLoc = stackE->getLocStart(); 8167 diagRange = stackE->getSourceRange(); 8168 } else { 8169 // We followed through a reference variable. 'stackE' contains the 8170 // problematic expression but we will warn at the return statement pointing 8171 // at the reference variable. We will later display the "trail" of 8172 // reference variables using notes. 8173 diagLoc = refVars[0]->getLocStart(); 8174 diagRange = refVars[0]->getSourceRange(); 8175 } 8176 8177 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { 8178 // address of local var 8179 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType() 8180 << DR->getDecl()->getDeclName() << diagRange; 8181 } else if (isa<BlockExpr>(stackE)) { // local block. 8182 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange; 8183 } else if (isa<AddrLabelExpr>(stackE)) { // address of label. 8184 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange; 8185 } else { // local temporary. 8186 // If there is an LValue->RValue conversion, then the value of the 8187 // reference type is used, not the reference. 8188 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) { 8189 if (ICE->getCastKind() == CK_LValueToRValue) { 8190 return; 8191 } 8192 } 8193 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref) 8194 << lhsType->isReferenceType() << diagRange; 8195 } 8196 8197 // Display the "trail" of reference variables that we followed until we 8198 // found the problematic expression using notes. 8199 for (unsigned i = 0, e = refVars.size(); i != e; ++i) { 8200 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl()); 8201 // If this var binds to another reference var, show the range of the next 8202 // var, otherwise the var binds to the problematic expression, in which case 8203 // show the range of the expression. 8204 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange() 8205 : stackE->getSourceRange(); 8206 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind) 8207 << VD->getDeclName() << range; 8208 } 8209 } 8210 8211 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that 8212 /// check if the expression in a return statement evaluates to an address 8213 /// to a location on the stack, a local block, an address of a label, or a 8214 /// reference to local temporary. The recursion is used to traverse the 8215 /// AST of the return expression, with recursion backtracking when we 8216 /// encounter a subexpression that (1) clearly does not lead to one of the 8217 /// above problematic expressions (2) is something we cannot determine leads to 8218 /// a problematic expression based on such local checking. 8219 /// 8220 /// Both EvalAddr and EvalVal follow through reference variables to evaluate 8221 /// the expression that they point to. Such variables are added to the 8222 /// 'refVars' vector so that we know what the reference variable "trail" was. 8223 /// 8224 /// EvalAddr processes expressions that are pointers that are used as 8225 /// references (and not L-values). EvalVal handles all other values. 8226 /// At the base case of the recursion is a check for the above problematic 8227 /// expressions. 8228 /// 8229 /// This implementation handles: 8230 /// 8231 /// * pointer-to-pointer casts 8232 /// * implicit conversions from array references to pointers 8233 /// * taking the address of fields 8234 /// * arbitrary interplay between "&" and "*" operators 8235 /// * pointer arithmetic from an address of a stack variable 8236 /// * taking the address of an array element where the array is on the stack 8237 static const Expr *EvalAddr(const Expr *E, 8238 SmallVectorImpl<const DeclRefExpr *> &refVars, 8239 const Decl *ParentDecl) { 8240 if (E->isTypeDependent()) 8241 return nullptr; 8242 8243 // We should only be called for evaluating pointer expressions. 8244 assert((E->getType()->isAnyPointerType() || 8245 E->getType()->isBlockPointerType() || 8246 E->getType()->isObjCQualifiedIdType()) && 8247 "EvalAddr only works on pointers"); 8248 8249 E = E->IgnoreParens(); 8250 8251 // Our "symbolic interpreter" is just a dispatch off the currently 8252 // viewed AST node. We then recursively traverse the AST by calling 8253 // EvalAddr and EvalVal appropriately. 8254 switch (E->getStmtClass()) { 8255 case Stmt::DeclRefExprClass: { 8256 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 8257 8258 // If we leave the immediate function, the lifetime isn't about to end. 8259 if (DR->refersToEnclosingVariableOrCapture()) 8260 return nullptr; 8261 8262 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) 8263 // If this is a reference variable, follow through to the expression that 8264 // it points to. 8265 if (V->hasLocalStorage() && 8266 V->getType()->isReferenceType() && V->hasInit()) { 8267 // Add the reference variable to the "trail". 8268 refVars.push_back(DR); 8269 return EvalAddr(V->getInit(), refVars, ParentDecl); 8270 } 8271 8272 return nullptr; 8273 } 8274 8275 case Stmt::UnaryOperatorClass: { 8276 // The only unary operator that make sense to handle here 8277 // is AddrOf. All others don't make sense as pointers. 8278 const UnaryOperator *U = cast<UnaryOperator>(E); 8279 8280 if (U->getOpcode() == UO_AddrOf) 8281 return EvalVal(U->getSubExpr(), refVars, ParentDecl); 8282 return nullptr; 8283 } 8284 8285 case Stmt::BinaryOperatorClass: { 8286 // Handle pointer arithmetic. All other binary operators are not valid 8287 // in this context. 8288 const BinaryOperator *B = cast<BinaryOperator>(E); 8289 BinaryOperatorKind op = B->getOpcode(); 8290 8291 if (op != BO_Add && op != BO_Sub) 8292 return nullptr; 8293 8294 const Expr *Base = B->getLHS(); 8295 8296 // Determine which argument is the real pointer base. It could be 8297 // the RHS argument instead of the LHS. 8298 if (!Base->getType()->isPointerType()) 8299 Base = B->getRHS(); 8300 8301 assert(Base->getType()->isPointerType()); 8302 return EvalAddr(Base, refVars, ParentDecl); 8303 } 8304 8305 // For conditional operators we need to see if either the LHS or RHS are 8306 // valid DeclRefExpr*s. If one of them is valid, we return it. 8307 case Stmt::ConditionalOperatorClass: { 8308 const ConditionalOperator *C = cast<ConditionalOperator>(E); 8309 8310 // Handle the GNU extension for missing LHS. 8311 // FIXME: That isn't a ConditionalOperator, so doesn't get here. 8312 if (const Expr *LHSExpr = C->getLHS()) { 8313 // In C++, we can have a throw-expression, which has 'void' type. 8314 if (!LHSExpr->getType()->isVoidType()) 8315 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl)) 8316 return LHS; 8317 } 8318 8319 // In C++, we can have a throw-expression, which has 'void' type. 8320 if (C->getRHS()->getType()->isVoidType()) 8321 return nullptr; 8322 8323 return EvalAddr(C->getRHS(), refVars, ParentDecl); 8324 } 8325 8326 case Stmt::BlockExprClass: 8327 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures()) 8328 return E; // local block. 8329 return nullptr; 8330 8331 case Stmt::AddrLabelExprClass: 8332 return E; // address of label. 8333 8334 case Stmt::ExprWithCleanupsClass: 8335 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars, 8336 ParentDecl); 8337 8338 // For casts, we need to handle conversions from arrays to 8339 // pointer values, and pointer-to-pointer conversions. 8340 case Stmt::ImplicitCastExprClass: 8341 case Stmt::CStyleCastExprClass: 8342 case Stmt::CXXFunctionalCastExprClass: 8343 case Stmt::ObjCBridgedCastExprClass: 8344 case Stmt::CXXStaticCastExprClass: 8345 case Stmt::CXXDynamicCastExprClass: 8346 case Stmt::CXXConstCastExprClass: 8347 case Stmt::CXXReinterpretCastExprClass: { 8348 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr(); 8349 switch (cast<CastExpr>(E)->getCastKind()) { 8350 case CK_LValueToRValue: 8351 case CK_NoOp: 8352 case CK_BaseToDerived: 8353 case CK_DerivedToBase: 8354 case CK_UncheckedDerivedToBase: 8355 case CK_Dynamic: 8356 case CK_CPointerToObjCPointerCast: 8357 case CK_BlockPointerToObjCPointerCast: 8358 case CK_AnyPointerToBlockPointerCast: 8359 return EvalAddr(SubExpr, refVars, ParentDecl); 8360 8361 case CK_ArrayToPointerDecay: 8362 return EvalVal(SubExpr, refVars, ParentDecl); 8363 8364 case CK_BitCast: 8365 if (SubExpr->getType()->isAnyPointerType() || 8366 SubExpr->getType()->isBlockPointerType() || 8367 SubExpr->getType()->isObjCQualifiedIdType()) 8368 return EvalAddr(SubExpr, refVars, ParentDecl); 8369 else 8370 return nullptr; 8371 8372 default: 8373 return nullptr; 8374 } 8375 } 8376 8377 case Stmt::MaterializeTemporaryExprClass: 8378 if (const Expr *Result = 8379 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 8380 refVars, ParentDecl)) 8381 return Result; 8382 return E; 8383 8384 // Everything else: we simply don't reason about them. 8385 default: 8386 return nullptr; 8387 } 8388 } 8389 8390 /// EvalVal - This function is complements EvalAddr in the mutual recursion. 8391 /// See the comments for EvalAddr for more details. 8392 static const Expr *EvalVal(const Expr *E, 8393 SmallVectorImpl<const DeclRefExpr *> &refVars, 8394 const Decl *ParentDecl) { 8395 do { 8396 // We should only be called for evaluating non-pointer expressions, or 8397 // expressions with a pointer type that are not used as references but 8398 // instead 8399 // are l-values (e.g., DeclRefExpr with a pointer type). 8400 8401 // Our "symbolic interpreter" is just a dispatch off the currently 8402 // viewed AST node. We then recursively traverse the AST by calling 8403 // EvalAddr and EvalVal appropriately. 8404 8405 E = E->IgnoreParens(); 8406 switch (E->getStmtClass()) { 8407 case Stmt::ImplicitCastExprClass: { 8408 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E); 8409 if (IE->getValueKind() == VK_LValue) { 8410 E = IE->getSubExpr(); 8411 continue; 8412 } 8413 return nullptr; 8414 } 8415 8416 case Stmt::ExprWithCleanupsClass: 8417 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars, 8418 ParentDecl); 8419 8420 case Stmt::DeclRefExprClass: { 8421 // When we hit a DeclRefExpr we are looking at code that refers to a 8422 // variable's name. If it's not a reference variable we check if it has 8423 // local storage within the function, and if so, return the expression. 8424 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 8425 8426 // If we leave the immediate function, the lifetime isn't about to end. 8427 if (DR->refersToEnclosingVariableOrCapture()) 8428 return nullptr; 8429 8430 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) { 8431 // Check if it refers to itself, e.g. "int& i = i;". 8432 if (V == ParentDecl) 8433 return DR; 8434 8435 if (V->hasLocalStorage()) { 8436 if (!V->getType()->isReferenceType()) 8437 return DR; 8438 8439 // Reference variable, follow through to the expression that 8440 // it points to. 8441 if (V->hasInit()) { 8442 // Add the reference variable to the "trail". 8443 refVars.push_back(DR); 8444 return EvalVal(V->getInit(), refVars, V); 8445 } 8446 } 8447 } 8448 8449 return nullptr; 8450 } 8451 8452 case Stmt::UnaryOperatorClass: { 8453 // The only unary operator that make sense to handle here 8454 // is Deref. All others don't resolve to a "name." This includes 8455 // handling all sorts of rvalues passed to a unary operator. 8456 const UnaryOperator *U = cast<UnaryOperator>(E); 8457 8458 if (U->getOpcode() == UO_Deref) 8459 return EvalAddr(U->getSubExpr(), refVars, ParentDecl); 8460 8461 return nullptr; 8462 } 8463 8464 case Stmt::ArraySubscriptExprClass: { 8465 // Array subscripts are potential references to data on the stack. We 8466 // retrieve the DeclRefExpr* for the array variable if it indeed 8467 // has local storage. 8468 const auto *ASE = cast<ArraySubscriptExpr>(E); 8469 if (ASE->isTypeDependent()) 8470 return nullptr; 8471 return EvalAddr(ASE->getBase(), refVars, ParentDecl); 8472 } 8473 8474 case Stmt::OMPArraySectionExprClass: { 8475 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars, 8476 ParentDecl); 8477 } 8478 8479 case Stmt::ConditionalOperatorClass: { 8480 // For conditional operators we need to see if either the LHS or RHS are 8481 // non-NULL Expr's. If one is non-NULL, we return it. 8482 const ConditionalOperator *C = cast<ConditionalOperator>(E); 8483 8484 // Handle the GNU extension for missing LHS. 8485 if (const Expr *LHSExpr = C->getLHS()) { 8486 // In C++, we can have a throw-expression, which has 'void' type. 8487 if (!LHSExpr->getType()->isVoidType()) 8488 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl)) 8489 return LHS; 8490 } 8491 8492 // In C++, we can have a throw-expression, which has 'void' type. 8493 if (C->getRHS()->getType()->isVoidType()) 8494 return nullptr; 8495 8496 return EvalVal(C->getRHS(), refVars, ParentDecl); 8497 } 8498 8499 // Accesses to members are potential references to data on the stack. 8500 case Stmt::MemberExprClass: { 8501 const MemberExpr *M = cast<MemberExpr>(E); 8502 8503 // Check for indirect access. We only want direct field accesses. 8504 if (M->isArrow()) 8505 return nullptr; 8506 8507 // Check whether the member type is itself a reference, in which case 8508 // we're not going to refer to the member, but to what the member refers 8509 // to. 8510 if (M->getMemberDecl()->getType()->isReferenceType()) 8511 return nullptr; 8512 8513 return EvalVal(M->getBase(), refVars, ParentDecl); 8514 } 8515 8516 case Stmt::MaterializeTemporaryExprClass: 8517 if (const Expr *Result = 8518 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 8519 refVars, ParentDecl)) 8520 return Result; 8521 return E; 8522 8523 default: 8524 // Check that we don't return or take the address of a reference to a 8525 // temporary. This is only useful in C++. 8526 if (!E->isTypeDependent() && E->isRValue()) 8527 return E; 8528 8529 // Everything else: we simply don't reason about them. 8530 return nullptr; 8531 } 8532 } while (true); 8533 } 8534 8535 void 8536 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 8537 SourceLocation ReturnLoc, 8538 bool isObjCMethod, 8539 const AttrVec *Attrs, 8540 const FunctionDecl *FD) { 8541 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc); 8542 8543 // Check if the return value is null but should not be. 8544 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 8545 (!isObjCMethod && isNonNullType(Context, lhsType))) && 8546 CheckNonNullExpr(*this, RetValExp)) 8547 Diag(ReturnLoc, diag::warn_null_ret) 8548 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 8549 8550 // C++11 [basic.stc.dynamic.allocation]p4: 8551 // If an allocation function declared with a non-throwing 8552 // exception-specification fails to allocate storage, it shall return 8553 // a null pointer. Any other allocation function that fails to allocate 8554 // storage shall indicate failure only by throwing an exception [...] 8555 if (FD) { 8556 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 8557 if (Op == OO_New || Op == OO_Array_New) { 8558 const FunctionProtoType *Proto 8559 = FD->getType()->castAs<FunctionProtoType>(); 8560 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 8561 CheckNonNullExpr(*this, RetValExp)) 8562 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 8563 << FD << getLangOpts().CPlusPlus11; 8564 } 8565 } 8566 } 8567 8568 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 8569 8570 /// Check for comparisons of floating point operands using != and ==. 8571 /// Issue a warning if these are no self-comparisons, as they are not likely 8572 /// to do what the programmer intended. 8573 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 8574 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 8575 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 8576 8577 // Special case: check for x == x (which is OK). 8578 // Do not emit warnings for such cases. 8579 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 8580 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 8581 if (DRL->getDecl() == DRR->getDecl()) 8582 return; 8583 8584 // Special case: check for comparisons against literals that can be exactly 8585 // represented by APFloat. In such cases, do not emit a warning. This 8586 // is a heuristic: often comparison against such literals are used to 8587 // detect if a value in a variable has not changed. This clearly can 8588 // lead to false negatives. 8589 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 8590 if (FLL->isExact()) 8591 return; 8592 } else 8593 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 8594 if (FLR->isExact()) 8595 return; 8596 8597 // Check for comparisons with builtin types. 8598 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 8599 if (CL->getBuiltinCallee()) 8600 return; 8601 8602 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 8603 if (CR->getBuiltinCallee()) 8604 return; 8605 8606 // Emit the diagnostic. 8607 Diag(Loc, diag::warn_floatingpoint_eq) 8608 << LHS->getSourceRange() << RHS->getSourceRange(); 8609 } 8610 8611 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 8612 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 8613 8614 namespace { 8615 8616 /// Structure recording the 'active' range of an integer-valued 8617 /// expression. 8618 struct IntRange { 8619 /// The number of bits active in the int. 8620 unsigned Width; 8621 8622 /// True if the int is known not to have negative values. 8623 bool NonNegative; 8624 8625 IntRange(unsigned Width, bool NonNegative) 8626 : Width(Width), NonNegative(NonNegative) {} 8627 8628 /// Returns the range of the bool type. 8629 static IntRange forBoolType() { 8630 return IntRange(1, true); 8631 } 8632 8633 /// Returns the range of an opaque value of the given integral type. 8634 static IntRange forValueOfType(ASTContext &C, QualType T) { 8635 return forValueOfCanonicalType(C, 8636 T->getCanonicalTypeInternal().getTypePtr()); 8637 } 8638 8639 /// Returns the range of an opaque value of a canonical integral type. 8640 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 8641 assert(T->isCanonicalUnqualified()); 8642 8643 if (const VectorType *VT = dyn_cast<VectorType>(T)) 8644 T = VT->getElementType().getTypePtr(); 8645 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 8646 T = CT->getElementType().getTypePtr(); 8647 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 8648 T = AT->getValueType().getTypePtr(); 8649 8650 if (!C.getLangOpts().CPlusPlus) { 8651 // For enum types in C code, use the underlying datatype. 8652 if (const EnumType *ET = dyn_cast<EnumType>(T)) 8653 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 8654 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 8655 // For enum types in C++, use the known bit width of the enumerators. 8656 EnumDecl *Enum = ET->getDecl(); 8657 // In C++11, enums can have a fixed underlying type. Use this type to 8658 // compute the range. 8659 if (Enum->isFixed()) { 8660 return IntRange(C.getIntWidth(QualType(T, 0)), 8661 !ET->isSignedIntegerOrEnumerationType()); 8662 } 8663 8664 unsigned NumPositive = Enum->getNumPositiveBits(); 8665 unsigned NumNegative = Enum->getNumNegativeBits(); 8666 8667 if (NumNegative == 0) 8668 return IntRange(NumPositive, true/*NonNegative*/); 8669 else 8670 return IntRange(std::max(NumPositive + 1, NumNegative), 8671 false/*NonNegative*/); 8672 } 8673 8674 const BuiltinType *BT = cast<BuiltinType>(T); 8675 assert(BT->isInteger()); 8676 8677 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 8678 } 8679 8680 /// Returns the "target" range of a canonical integral type, i.e. 8681 /// the range of values expressible in the type. 8682 /// 8683 /// This matches forValueOfCanonicalType except that enums have the 8684 /// full range of their type, not the range of their enumerators. 8685 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 8686 assert(T->isCanonicalUnqualified()); 8687 8688 if (const VectorType *VT = dyn_cast<VectorType>(T)) 8689 T = VT->getElementType().getTypePtr(); 8690 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 8691 T = CT->getElementType().getTypePtr(); 8692 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 8693 T = AT->getValueType().getTypePtr(); 8694 if (const EnumType *ET = dyn_cast<EnumType>(T)) 8695 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 8696 8697 const BuiltinType *BT = cast<BuiltinType>(T); 8698 assert(BT->isInteger()); 8699 8700 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 8701 } 8702 8703 /// Returns the supremum of two ranges: i.e. their conservative merge. 8704 static IntRange join(IntRange L, IntRange R) { 8705 return IntRange(std::max(L.Width, R.Width), 8706 L.NonNegative && R.NonNegative); 8707 } 8708 8709 /// Returns the infinum of two ranges: i.e. their aggressive merge. 8710 static IntRange meet(IntRange L, IntRange R) { 8711 return IntRange(std::min(L.Width, R.Width), 8712 L.NonNegative || R.NonNegative); 8713 } 8714 }; 8715 8716 } // namespace 8717 8718 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 8719 unsigned MaxWidth) { 8720 if (value.isSigned() && value.isNegative()) 8721 return IntRange(value.getMinSignedBits(), false); 8722 8723 if (value.getBitWidth() > MaxWidth) 8724 value = value.trunc(MaxWidth); 8725 8726 // isNonNegative() just checks the sign bit without considering 8727 // signedness. 8728 return IntRange(value.getActiveBits(), true); 8729 } 8730 8731 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 8732 unsigned MaxWidth) { 8733 if (result.isInt()) 8734 return GetValueRange(C, result.getInt(), MaxWidth); 8735 8736 if (result.isVector()) { 8737 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 8738 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 8739 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 8740 R = IntRange::join(R, El); 8741 } 8742 return R; 8743 } 8744 8745 if (result.isComplexInt()) { 8746 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 8747 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 8748 return IntRange::join(R, I); 8749 } 8750 8751 // This can happen with lossless casts to intptr_t of "based" lvalues. 8752 // Assume it might use arbitrary bits. 8753 // FIXME: The only reason we need to pass the type in here is to get 8754 // the sign right on this one case. It would be nice if APValue 8755 // preserved this. 8756 assert(result.isLValue() || result.isAddrLabelDiff()); 8757 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 8758 } 8759 8760 static QualType GetExprType(const Expr *E) { 8761 QualType Ty = E->getType(); 8762 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 8763 Ty = AtomicRHS->getValueType(); 8764 return Ty; 8765 } 8766 8767 /// Pseudo-evaluate the given integer expression, estimating the 8768 /// range of values it might take. 8769 /// 8770 /// \param MaxWidth - the width to which the value will be truncated 8771 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) { 8772 E = E->IgnoreParens(); 8773 8774 // Try a full evaluation first. 8775 Expr::EvalResult result; 8776 if (E->EvaluateAsRValue(result, C)) 8777 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 8778 8779 // I think we only want to look through implicit casts here; if the 8780 // user has an explicit widening cast, we should treat the value as 8781 // being of the new, wider type. 8782 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 8783 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 8784 return GetExprRange(C, CE->getSubExpr(), MaxWidth); 8785 8786 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 8787 8788 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 8789 CE->getCastKind() == CK_BooleanToSignedIntegral; 8790 8791 // Assume that non-integer casts can span the full range of the type. 8792 if (!isIntegerCast) 8793 return OutputTypeRange; 8794 8795 IntRange SubRange 8796 = GetExprRange(C, CE->getSubExpr(), 8797 std::min(MaxWidth, OutputTypeRange.Width)); 8798 8799 // Bail out if the subexpr's range is as wide as the cast type. 8800 if (SubRange.Width >= OutputTypeRange.Width) 8801 return OutputTypeRange; 8802 8803 // Otherwise, we take the smaller width, and we're non-negative if 8804 // either the output type or the subexpr is. 8805 return IntRange(SubRange.Width, 8806 SubRange.NonNegative || OutputTypeRange.NonNegative); 8807 } 8808 8809 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 8810 // If we can fold the condition, just take that operand. 8811 bool CondResult; 8812 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 8813 return GetExprRange(C, CondResult ? CO->getTrueExpr() 8814 : CO->getFalseExpr(), 8815 MaxWidth); 8816 8817 // Otherwise, conservatively merge. 8818 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth); 8819 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth); 8820 return IntRange::join(L, R); 8821 } 8822 8823 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 8824 switch (BO->getOpcode()) { 8825 case BO_Cmp: 8826 llvm_unreachable("builtin <=> should have class type"); 8827 8828 // Boolean-valued operations are single-bit and positive. 8829 case BO_LAnd: 8830 case BO_LOr: 8831 case BO_LT: 8832 case BO_GT: 8833 case BO_LE: 8834 case BO_GE: 8835 case BO_EQ: 8836 case BO_NE: 8837 return IntRange::forBoolType(); 8838 8839 // The type of the assignments is the type of the LHS, so the RHS 8840 // is not necessarily the same type. 8841 case BO_MulAssign: 8842 case BO_DivAssign: 8843 case BO_RemAssign: 8844 case BO_AddAssign: 8845 case BO_SubAssign: 8846 case BO_XorAssign: 8847 case BO_OrAssign: 8848 // TODO: bitfields? 8849 return IntRange::forValueOfType(C, GetExprType(E)); 8850 8851 // Simple assignments just pass through the RHS, which will have 8852 // been coerced to the LHS type. 8853 case BO_Assign: 8854 // TODO: bitfields? 8855 return GetExprRange(C, BO->getRHS(), MaxWidth); 8856 8857 // Operations with opaque sources are black-listed. 8858 case BO_PtrMemD: 8859 case BO_PtrMemI: 8860 return IntRange::forValueOfType(C, GetExprType(E)); 8861 8862 // Bitwise-and uses the *infinum* of the two source ranges. 8863 case BO_And: 8864 case BO_AndAssign: 8865 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth), 8866 GetExprRange(C, BO->getRHS(), MaxWidth)); 8867 8868 // Left shift gets black-listed based on a judgement call. 8869 case BO_Shl: 8870 // ...except that we want to treat '1 << (blah)' as logically 8871 // positive. It's an important idiom. 8872 if (IntegerLiteral *I 8873 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 8874 if (I->getValue() == 1) { 8875 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 8876 return IntRange(R.Width, /*NonNegative*/ true); 8877 } 8878 } 8879 LLVM_FALLTHROUGH; 8880 8881 case BO_ShlAssign: 8882 return IntRange::forValueOfType(C, GetExprType(E)); 8883 8884 // Right shift by a constant can narrow its left argument. 8885 case BO_Shr: 8886 case BO_ShrAssign: { 8887 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 8888 8889 // If the shift amount is a positive constant, drop the width by 8890 // that much. 8891 llvm::APSInt shift; 8892 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 8893 shift.isNonNegative()) { 8894 unsigned zext = shift.getZExtValue(); 8895 if (zext >= L.Width) 8896 L.Width = (L.NonNegative ? 0 : 1); 8897 else 8898 L.Width -= zext; 8899 } 8900 8901 return L; 8902 } 8903 8904 // Comma acts as its right operand. 8905 case BO_Comma: 8906 return GetExprRange(C, BO->getRHS(), MaxWidth); 8907 8908 // Black-list pointer subtractions. 8909 case BO_Sub: 8910 if (BO->getLHS()->getType()->isPointerType()) 8911 return IntRange::forValueOfType(C, GetExprType(E)); 8912 break; 8913 8914 // The width of a division result is mostly determined by the size 8915 // of the LHS. 8916 case BO_Div: { 8917 // Don't 'pre-truncate' the operands. 8918 unsigned opWidth = C.getIntWidth(GetExprType(E)); 8919 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 8920 8921 // If the divisor is constant, use that. 8922 llvm::APSInt divisor; 8923 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 8924 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 8925 if (log2 >= L.Width) 8926 L.Width = (L.NonNegative ? 0 : 1); 8927 else 8928 L.Width = std::min(L.Width - log2, MaxWidth); 8929 return L; 8930 } 8931 8932 // Otherwise, just use the LHS's width. 8933 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 8934 return IntRange(L.Width, L.NonNegative && R.NonNegative); 8935 } 8936 8937 // The result of a remainder can't be larger than the result of 8938 // either side. 8939 case BO_Rem: { 8940 // Don't 'pre-truncate' the operands. 8941 unsigned opWidth = C.getIntWidth(GetExprType(E)); 8942 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 8943 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 8944 8945 IntRange meet = IntRange::meet(L, R); 8946 meet.Width = std::min(meet.Width, MaxWidth); 8947 return meet; 8948 } 8949 8950 // The default behavior is okay for these. 8951 case BO_Mul: 8952 case BO_Add: 8953 case BO_Xor: 8954 case BO_Or: 8955 break; 8956 } 8957 8958 // The default case is to treat the operation as if it were closed 8959 // on the narrowest type that encompasses both operands. 8960 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 8961 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth); 8962 return IntRange::join(L, R); 8963 } 8964 8965 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 8966 switch (UO->getOpcode()) { 8967 // Boolean-valued operations are white-listed. 8968 case UO_LNot: 8969 return IntRange::forBoolType(); 8970 8971 // Operations with opaque sources are black-listed. 8972 case UO_Deref: 8973 case UO_AddrOf: // should be impossible 8974 return IntRange::forValueOfType(C, GetExprType(E)); 8975 8976 default: 8977 return GetExprRange(C, UO->getSubExpr(), MaxWidth); 8978 } 8979 } 8980 8981 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 8982 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth); 8983 8984 if (const auto *BitField = E->getSourceBitField()) 8985 return IntRange(BitField->getBitWidthValue(C), 8986 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 8987 8988 return IntRange::forValueOfType(C, GetExprType(E)); 8989 } 8990 8991 static IntRange GetExprRange(ASTContext &C, const Expr *E) { 8992 return GetExprRange(C, E, C.getIntWidth(GetExprType(E))); 8993 } 8994 8995 /// Checks whether the given value, which currently has the given 8996 /// source semantics, has the same value when coerced through the 8997 /// target semantics. 8998 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 8999 const llvm::fltSemantics &Src, 9000 const llvm::fltSemantics &Tgt) { 9001 llvm::APFloat truncated = value; 9002 9003 bool ignored; 9004 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 9005 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 9006 9007 return truncated.bitwiseIsEqual(value); 9008 } 9009 9010 /// Checks whether the given value, which currently has the given 9011 /// source semantics, has the same value when coerced through the 9012 /// target semantics. 9013 /// 9014 /// The value might be a vector of floats (or a complex number). 9015 static bool IsSameFloatAfterCast(const APValue &value, 9016 const llvm::fltSemantics &Src, 9017 const llvm::fltSemantics &Tgt) { 9018 if (value.isFloat()) 9019 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 9020 9021 if (value.isVector()) { 9022 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 9023 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 9024 return false; 9025 return true; 9026 } 9027 9028 assert(value.isComplexFloat()); 9029 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 9030 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 9031 } 9032 9033 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC); 9034 9035 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 9036 // Suppress cases where we are comparing against an enum constant. 9037 if (const DeclRefExpr *DR = 9038 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 9039 if (isa<EnumConstantDecl>(DR->getDecl())) 9040 return true; 9041 9042 // Suppress cases where the '0' value is expanded from a macro. 9043 if (E->getLocStart().isMacroID()) 9044 return true; 9045 9046 return false; 9047 } 9048 9049 static bool isKnownToHaveUnsignedValue(Expr *E) { 9050 return E->getType()->isIntegerType() && 9051 (!E->getType()->isSignedIntegerType() || 9052 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 9053 } 9054 9055 namespace { 9056 /// The promoted range of values of a type. In general this has the 9057 /// following structure: 9058 /// 9059 /// |-----------| . . . |-----------| 9060 /// ^ ^ ^ ^ 9061 /// Min HoleMin HoleMax Max 9062 /// 9063 /// ... where there is only a hole if a signed type is promoted to unsigned 9064 /// (in which case Min and Max are the smallest and largest representable 9065 /// values). 9066 struct PromotedRange { 9067 // Min, or HoleMax if there is a hole. 9068 llvm::APSInt PromotedMin; 9069 // Max, or HoleMin if there is a hole. 9070 llvm::APSInt PromotedMax; 9071 9072 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 9073 if (R.Width == 0) 9074 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 9075 else if (R.Width >= BitWidth && !Unsigned) { 9076 // Promotion made the type *narrower*. This happens when promoting 9077 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 9078 // Treat all values of 'signed int' as being in range for now. 9079 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 9080 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 9081 } else { 9082 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 9083 .extOrTrunc(BitWidth); 9084 PromotedMin.setIsUnsigned(Unsigned); 9085 9086 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 9087 .extOrTrunc(BitWidth); 9088 PromotedMax.setIsUnsigned(Unsigned); 9089 } 9090 } 9091 9092 // Determine whether this range is contiguous (has no hole). 9093 bool isContiguous() const { return PromotedMin <= PromotedMax; } 9094 9095 // Where a constant value is within the range. 9096 enum ComparisonResult { 9097 LT = 0x1, 9098 LE = 0x2, 9099 GT = 0x4, 9100 GE = 0x8, 9101 EQ = 0x10, 9102 NE = 0x20, 9103 InRangeFlag = 0x40, 9104 9105 Less = LE | LT | NE, 9106 Min = LE | InRangeFlag, 9107 InRange = InRangeFlag, 9108 Max = GE | InRangeFlag, 9109 Greater = GE | GT | NE, 9110 9111 OnlyValue = LE | GE | EQ | InRangeFlag, 9112 InHole = NE 9113 }; 9114 9115 ComparisonResult compare(const llvm::APSInt &Value) const { 9116 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 9117 Value.isUnsigned() == PromotedMin.isUnsigned()); 9118 if (!isContiguous()) { 9119 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 9120 if (Value.isMinValue()) return Min; 9121 if (Value.isMaxValue()) return Max; 9122 if (Value >= PromotedMin) return InRange; 9123 if (Value <= PromotedMax) return InRange; 9124 return InHole; 9125 } 9126 9127 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 9128 case -1: return Less; 9129 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 9130 case 1: 9131 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 9132 case -1: return InRange; 9133 case 0: return Max; 9134 case 1: return Greater; 9135 } 9136 } 9137 9138 llvm_unreachable("impossible compare result"); 9139 } 9140 9141 static llvm::Optional<StringRef> 9142 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 9143 if (Op == BO_Cmp) { 9144 ComparisonResult LTFlag = LT, GTFlag = GT; 9145 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 9146 9147 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 9148 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 9149 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 9150 return llvm::None; 9151 } 9152 9153 ComparisonResult TrueFlag, FalseFlag; 9154 if (Op == BO_EQ) { 9155 TrueFlag = EQ; 9156 FalseFlag = NE; 9157 } else if (Op == BO_NE) { 9158 TrueFlag = NE; 9159 FalseFlag = EQ; 9160 } else { 9161 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 9162 TrueFlag = LT; 9163 FalseFlag = GE; 9164 } else { 9165 TrueFlag = GT; 9166 FalseFlag = LE; 9167 } 9168 if (Op == BO_GE || Op == BO_LE) 9169 std::swap(TrueFlag, FalseFlag); 9170 } 9171 if (R & TrueFlag) 9172 return StringRef("true"); 9173 if (R & FalseFlag) 9174 return StringRef("false"); 9175 return llvm::None; 9176 } 9177 }; 9178 } 9179 9180 static bool HasEnumType(Expr *E) { 9181 // Strip off implicit integral promotions. 9182 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 9183 if (ICE->getCastKind() != CK_IntegralCast && 9184 ICE->getCastKind() != CK_NoOp) 9185 break; 9186 E = ICE->getSubExpr(); 9187 } 9188 9189 return E->getType()->isEnumeralType(); 9190 } 9191 9192 static int classifyConstantValue(Expr *Constant) { 9193 // The values of this enumeration are used in the diagnostics 9194 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 9195 enum ConstantValueKind { 9196 Miscellaneous = 0, 9197 LiteralTrue, 9198 LiteralFalse 9199 }; 9200 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 9201 return BL->getValue() ? ConstantValueKind::LiteralTrue 9202 : ConstantValueKind::LiteralFalse; 9203 return ConstantValueKind::Miscellaneous; 9204 } 9205 9206 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 9207 Expr *Constant, Expr *Other, 9208 const llvm::APSInt &Value, 9209 bool RhsConstant) { 9210 if (S.inTemplateInstantiation()) 9211 return false; 9212 9213 Expr *OriginalOther = Other; 9214 9215 Constant = Constant->IgnoreParenImpCasts(); 9216 Other = Other->IgnoreParenImpCasts(); 9217 9218 // Suppress warnings on tautological comparisons between values of the same 9219 // enumeration type. There are only two ways we could warn on this: 9220 // - If the constant is outside the range of representable values of 9221 // the enumeration. In such a case, we should warn about the cast 9222 // to enumeration type, not about the comparison. 9223 // - If the constant is the maximum / minimum in-range value. For an 9224 // enumeratin type, such comparisons can be meaningful and useful. 9225 if (Constant->getType()->isEnumeralType() && 9226 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 9227 return false; 9228 9229 // TODO: Investigate using GetExprRange() to get tighter bounds 9230 // on the bit ranges. 9231 QualType OtherT = Other->getType(); 9232 if (const auto *AT = OtherT->getAs<AtomicType>()) 9233 OtherT = AT->getValueType(); 9234 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); 9235 9236 // Whether we're treating Other as being a bool because of the form of 9237 // expression despite it having another type (typically 'int' in C). 9238 bool OtherIsBooleanDespiteType = 9239 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 9240 if (OtherIsBooleanDespiteType) 9241 OtherRange = IntRange::forBoolType(); 9242 9243 // Determine the promoted range of the other type and see if a comparison of 9244 // the constant against that range is tautological. 9245 PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(), 9246 Value.isUnsigned()); 9247 auto Cmp = OtherPromotedRange.compare(Value); 9248 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 9249 if (!Result) 9250 return false; 9251 9252 // Suppress the diagnostic for an in-range comparison if the constant comes 9253 // from a macro or enumerator. We don't want to diagnose 9254 // 9255 // some_long_value <= INT_MAX 9256 // 9257 // when sizeof(int) == sizeof(long). 9258 bool InRange = Cmp & PromotedRange::InRangeFlag; 9259 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 9260 return false; 9261 9262 // If this is a comparison to an enum constant, include that 9263 // constant in the diagnostic. 9264 const EnumConstantDecl *ED = nullptr; 9265 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 9266 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 9267 9268 // Should be enough for uint128 (39 decimal digits) 9269 SmallString<64> PrettySourceValue; 9270 llvm::raw_svector_ostream OS(PrettySourceValue); 9271 if (ED) 9272 OS << '\'' << *ED << "' (" << Value << ")"; 9273 else 9274 OS << Value; 9275 9276 // FIXME: We use a somewhat different formatting for the in-range cases and 9277 // cases involving boolean values for historical reasons. We should pick a 9278 // consistent way of presenting these diagnostics. 9279 if (!InRange || Other->isKnownToHaveBooleanValue()) { 9280 S.DiagRuntimeBehavior( 9281 E->getOperatorLoc(), E, 9282 S.PDiag(!InRange ? diag::warn_out_of_range_compare 9283 : diag::warn_tautological_bool_compare) 9284 << OS.str() << classifyConstantValue(Constant) 9285 << OtherT << OtherIsBooleanDespiteType << *Result 9286 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 9287 } else { 9288 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 9289 ? (HasEnumType(OriginalOther) 9290 ? diag::warn_unsigned_enum_always_true_comparison 9291 : diag::warn_unsigned_always_true_comparison) 9292 : diag::warn_tautological_constant_compare; 9293 9294 S.Diag(E->getOperatorLoc(), Diag) 9295 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 9296 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 9297 } 9298 9299 return true; 9300 } 9301 9302 /// Analyze the operands of the given comparison. Implements the 9303 /// fallback case from AnalyzeComparison. 9304 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 9305 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 9306 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 9307 } 9308 9309 /// Implements -Wsign-compare. 9310 /// 9311 /// \param E the binary operator to check for warnings 9312 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 9313 // The type the comparison is being performed in. 9314 QualType T = E->getLHS()->getType(); 9315 9316 // Only analyze comparison operators where both sides have been converted to 9317 // the same type. 9318 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 9319 return AnalyzeImpConvsInComparison(S, E); 9320 9321 // Don't analyze value-dependent comparisons directly. 9322 if (E->isValueDependent()) 9323 return AnalyzeImpConvsInComparison(S, E); 9324 9325 Expr *LHS = E->getLHS(); 9326 Expr *RHS = E->getRHS(); 9327 9328 if (T->isIntegralType(S.Context)) { 9329 llvm::APSInt RHSValue; 9330 llvm::APSInt LHSValue; 9331 9332 bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context); 9333 bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context); 9334 9335 // We don't care about expressions whose result is a constant. 9336 if (IsRHSIntegralLiteral && IsLHSIntegralLiteral) 9337 return AnalyzeImpConvsInComparison(S, E); 9338 9339 // We only care about expressions where just one side is literal 9340 if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) { 9341 // Is the constant on the RHS or LHS? 9342 const bool RhsConstant = IsRHSIntegralLiteral; 9343 Expr *Const = RhsConstant ? RHS : LHS; 9344 Expr *Other = RhsConstant ? LHS : RHS; 9345 const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue; 9346 9347 // Check whether an integer constant comparison results in a value 9348 // of 'true' or 'false'. 9349 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 9350 return AnalyzeImpConvsInComparison(S, E); 9351 } 9352 } 9353 9354 if (!T->hasUnsignedIntegerRepresentation()) { 9355 // We don't do anything special if this isn't an unsigned integral 9356 // comparison: we're only interested in integral comparisons, and 9357 // signed comparisons only happen in cases we don't care to warn about. 9358 return AnalyzeImpConvsInComparison(S, E); 9359 } 9360 9361 LHS = LHS->IgnoreParenImpCasts(); 9362 RHS = RHS->IgnoreParenImpCasts(); 9363 9364 if (!S.getLangOpts().CPlusPlus) { 9365 // Avoid warning about comparison of integers with different signs when 9366 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 9367 // the type of `E`. 9368 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 9369 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 9370 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 9371 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 9372 } 9373 9374 // Check to see if one of the (unmodified) operands is of different 9375 // signedness. 9376 Expr *signedOperand, *unsignedOperand; 9377 if (LHS->getType()->hasSignedIntegerRepresentation()) { 9378 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 9379 "unsigned comparison between two signed integer expressions?"); 9380 signedOperand = LHS; 9381 unsignedOperand = RHS; 9382 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 9383 signedOperand = RHS; 9384 unsignedOperand = LHS; 9385 } else { 9386 return AnalyzeImpConvsInComparison(S, E); 9387 } 9388 9389 // Otherwise, calculate the effective range of the signed operand. 9390 IntRange signedRange = GetExprRange(S.Context, signedOperand); 9391 9392 // Go ahead and analyze implicit conversions in the operands. Note 9393 // that we skip the implicit conversions on both sides. 9394 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 9395 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 9396 9397 // If the signed range is non-negative, -Wsign-compare won't fire. 9398 if (signedRange.NonNegative) 9399 return; 9400 9401 // For (in)equality comparisons, if the unsigned operand is a 9402 // constant which cannot collide with a overflowed signed operand, 9403 // then reinterpreting the signed operand as unsigned will not 9404 // change the result of the comparison. 9405 if (E->isEqualityOp()) { 9406 unsigned comparisonWidth = S.Context.getIntWidth(T); 9407 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand); 9408 9409 // We should never be unable to prove that the unsigned operand is 9410 // non-negative. 9411 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 9412 9413 if (unsignedRange.Width < comparisonWidth) 9414 return; 9415 } 9416 9417 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 9418 S.PDiag(diag::warn_mixed_sign_comparison) 9419 << LHS->getType() << RHS->getType() 9420 << LHS->getSourceRange() << RHS->getSourceRange()); 9421 } 9422 9423 /// Analyzes an attempt to assign the given value to a bitfield. 9424 /// 9425 /// Returns true if there was something fishy about the attempt. 9426 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 9427 SourceLocation InitLoc) { 9428 assert(Bitfield->isBitField()); 9429 if (Bitfield->isInvalidDecl()) 9430 return false; 9431 9432 // White-list bool bitfields. 9433 QualType BitfieldType = Bitfield->getType(); 9434 if (BitfieldType->isBooleanType()) 9435 return false; 9436 9437 if (BitfieldType->isEnumeralType()) { 9438 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl(); 9439 // If the underlying enum type was not explicitly specified as an unsigned 9440 // type and the enum contain only positive values, MSVC++ will cause an 9441 // inconsistency by storing this as a signed type. 9442 if (S.getLangOpts().CPlusPlus11 && 9443 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 9444 BitfieldEnumDecl->getNumPositiveBits() > 0 && 9445 BitfieldEnumDecl->getNumNegativeBits() == 0) { 9446 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 9447 << BitfieldEnumDecl->getNameAsString(); 9448 } 9449 } 9450 9451 if (Bitfield->getType()->isBooleanType()) 9452 return false; 9453 9454 // Ignore value- or type-dependent expressions. 9455 if (Bitfield->getBitWidth()->isValueDependent() || 9456 Bitfield->getBitWidth()->isTypeDependent() || 9457 Init->isValueDependent() || 9458 Init->isTypeDependent()) 9459 return false; 9460 9461 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 9462 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 9463 9464 llvm::APSInt Value; 9465 if (!OriginalInit->EvaluateAsInt(Value, S.Context, 9466 Expr::SE_AllowSideEffects)) { 9467 // The RHS is not constant. If the RHS has an enum type, make sure the 9468 // bitfield is wide enough to hold all the values of the enum without 9469 // truncation. 9470 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 9471 EnumDecl *ED = EnumTy->getDecl(); 9472 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 9473 9474 // Enum types are implicitly signed on Windows, so check if there are any 9475 // negative enumerators to see if the enum was intended to be signed or 9476 // not. 9477 bool SignedEnum = ED->getNumNegativeBits() > 0; 9478 9479 // Check for surprising sign changes when assigning enum values to a 9480 // bitfield of different signedness. If the bitfield is signed and we 9481 // have exactly the right number of bits to store this unsigned enum, 9482 // suggest changing the enum to an unsigned type. This typically happens 9483 // on Windows where unfixed enums always use an underlying type of 'int'. 9484 unsigned DiagID = 0; 9485 if (SignedEnum && !SignedBitfield) { 9486 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 9487 } else if (SignedBitfield && !SignedEnum && 9488 ED->getNumPositiveBits() == FieldWidth) { 9489 DiagID = diag::warn_signed_bitfield_enum_conversion; 9490 } 9491 9492 if (DiagID) { 9493 S.Diag(InitLoc, DiagID) << Bitfield << ED; 9494 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 9495 SourceRange TypeRange = 9496 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 9497 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 9498 << SignedEnum << TypeRange; 9499 } 9500 9501 // Compute the required bitwidth. If the enum has negative values, we need 9502 // one more bit than the normal number of positive bits to represent the 9503 // sign bit. 9504 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 9505 ED->getNumNegativeBits()) 9506 : ED->getNumPositiveBits(); 9507 9508 // Check the bitwidth. 9509 if (BitsNeeded > FieldWidth) { 9510 Expr *WidthExpr = Bitfield->getBitWidth(); 9511 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 9512 << Bitfield << ED; 9513 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 9514 << BitsNeeded << ED << WidthExpr->getSourceRange(); 9515 } 9516 } 9517 9518 return false; 9519 } 9520 9521 unsigned OriginalWidth = Value.getBitWidth(); 9522 9523 if (!Value.isSigned() || Value.isNegative()) 9524 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 9525 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 9526 OriginalWidth = Value.getMinSignedBits(); 9527 9528 if (OriginalWidth <= FieldWidth) 9529 return false; 9530 9531 // Compute the value which the bitfield will contain. 9532 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 9533 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 9534 9535 // Check whether the stored value is equal to the original value. 9536 TruncatedValue = TruncatedValue.extend(OriginalWidth); 9537 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 9538 return false; 9539 9540 // Special-case bitfields of width 1: booleans are naturally 0/1, and 9541 // therefore don't strictly fit into a signed bitfield of width 1. 9542 if (FieldWidth == 1 && Value == 1) 9543 return false; 9544 9545 std::string PrettyValue = Value.toString(10); 9546 std::string PrettyTrunc = TruncatedValue.toString(10); 9547 9548 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 9549 << PrettyValue << PrettyTrunc << OriginalInit->getType() 9550 << Init->getSourceRange(); 9551 9552 return true; 9553 } 9554 9555 /// Analyze the given simple or compound assignment for warning-worthy 9556 /// operations. 9557 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 9558 // Just recurse on the LHS. 9559 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 9560 9561 // We want to recurse on the RHS as normal unless we're assigning to 9562 // a bitfield. 9563 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 9564 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 9565 E->getOperatorLoc())) { 9566 // Recurse, ignoring any implicit conversions on the RHS. 9567 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 9568 E->getOperatorLoc()); 9569 } 9570 } 9571 9572 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 9573 } 9574 9575 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 9576 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 9577 SourceLocation CContext, unsigned diag, 9578 bool pruneControlFlow = false) { 9579 if (pruneControlFlow) { 9580 S.DiagRuntimeBehavior(E->getExprLoc(), E, 9581 S.PDiag(diag) 9582 << SourceType << T << E->getSourceRange() 9583 << SourceRange(CContext)); 9584 return; 9585 } 9586 S.Diag(E->getExprLoc(), diag) 9587 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 9588 } 9589 9590 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 9591 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 9592 SourceLocation CContext, 9593 unsigned diag, bool pruneControlFlow = false) { 9594 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 9595 } 9596 9597 /// Analyze the given compound assignment for the possible losing of 9598 /// floating-point precision. 9599 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 9600 assert(isa<CompoundAssignOperator>(E) && 9601 "Must be compound assignment operation"); 9602 // Recurse on the LHS and RHS in here 9603 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 9604 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 9605 9606 // Now check the outermost expression 9607 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 9608 const auto *RBT = cast<CompoundAssignOperator>(E) 9609 ->getComputationResultType() 9610 ->getAs<BuiltinType>(); 9611 9612 // If both source and target are floating points. 9613 if (ResultBT && ResultBT->isFloatingPoint() && RBT && RBT->isFloatingPoint()) 9614 // Builtin FP kinds are ordered by increasing FP rank. 9615 if (ResultBT->getKind() < RBT->getKind()) 9616 // We don't want to warn for system macro. 9617 if (!S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 9618 // warn about dropping FP rank. 9619 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), 9620 E->getOperatorLoc(), 9621 diag::warn_impcast_float_result_precision); 9622 } 9623 9624 /// Diagnose an implicit cast from a floating point value to an integer value. 9625 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 9626 SourceLocation CContext) { 9627 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 9628 const bool PruneWarnings = S.inTemplateInstantiation(); 9629 9630 Expr *InnerE = E->IgnoreParenImpCasts(); 9631 // We also want to warn on, e.g., "int i = -1.234" 9632 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 9633 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 9634 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 9635 9636 const bool IsLiteral = 9637 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 9638 9639 llvm::APFloat Value(0.0); 9640 bool IsConstant = 9641 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 9642 if (!IsConstant) { 9643 return DiagnoseImpCast(S, E, T, CContext, 9644 diag::warn_impcast_float_integer, PruneWarnings); 9645 } 9646 9647 bool isExact = false; 9648 9649 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 9650 T->hasUnsignedIntegerRepresentation()); 9651 llvm::APFloat::opStatus Result = Value.convertToInteger( 9652 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 9653 9654 if (Result == llvm::APFloat::opOK && isExact) { 9655 if (IsLiteral) return; 9656 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 9657 PruneWarnings); 9658 } 9659 9660 // Conversion of a floating-point value to a non-bool integer where the 9661 // integral part cannot be represented by the integer type is undefined. 9662 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 9663 return DiagnoseImpCast( 9664 S, E, T, CContext, 9665 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 9666 : diag::warn_impcast_float_to_integer_out_of_range, 9667 PruneWarnings); 9668 9669 unsigned DiagID = 0; 9670 if (IsLiteral) { 9671 // Warn on floating point literal to integer. 9672 DiagID = diag::warn_impcast_literal_float_to_integer; 9673 } else if (IntegerValue == 0) { 9674 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 9675 return DiagnoseImpCast(S, E, T, CContext, 9676 diag::warn_impcast_float_integer, PruneWarnings); 9677 } 9678 // Warn on non-zero to zero conversion. 9679 DiagID = diag::warn_impcast_float_to_integer_zero; 9680 } else { 9681 if (IntegerValue.isUnsigned()) { 9682 if (!IntegerValue.isMaxValue()) { 9683 return DiagnoseImpCast(S, E, T, CContext, 9684 diag::warn_impcast_float_integer, PruneWarnings); 9685 } 9686 } else { // IntegerValue.isSigned() 9687 if (!IntegerValue.isMaxSignedValue() && 9688 !IntegerValue.isMinSignedValue()) { 9689 return DiagnoseImpCast(S, E, T, CContext, 9690 diag::warn_impcast_float_integer, PruneWarnings); 9691 } 9692 } 9693 // Warn on evaluatable floating point expression to integer conversion. 9694 DiagID = diag::warn_impcast_float_to_integer; 9695 } 9696 9697 // FIXME: Force the precision of the source value down so we don't print 9698 // digits which are usually useless (we don't really care here if we 9699 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 9700 // would automatically print the shortest representation, but it's a bit 9701 // tricky to implement. 9702 SmallString<16> PrettySourceValue; 9703 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 9704 precision = (precision * 59 + 195) / 196; 9705 Value.toString(PrettySourceValue, precision); 9706 9707 SmallString<16> PrettyTargetValue; 9708 if (IsBool) 9709 PrettyTargetValue = Value.isZero() ? "false" : "true"; 9710 else 9711 IntegerValue.toString(PrettyTargetValue); 9712 9713 if (PruneWarnings) { 9714 S.DiagRuntimeBehavior(E->getExprLoc(), E, 9715 S.PDiag(DiagID) 9716 << E->getType() << T.getUnqualifiedType() 9717 << PrettySourceValue << PrettyTargetValue 9718 << E->getSourceRange() << SourceRange(CContext)); 9719 } else { 9720 S.Diag(E->getExprLoc(), DiagID) 9721 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 9722 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 9723 } 9724 } 9725 9726 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 9727 IntRange Range) { 9728 if (!Range.Width) return "0"; 9729 9730 llvm::APSInt ValueInRange = Value; 9731 ValueInRange.setIsSigned(!Range.NonNegative); 9732 ValueInRange = ValueInRange.trunc(Range.Width); 9733 return ValueInRange.toString(10); 9734 } 9735 9736 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 9737 if (!isa<ImplicitCastExpr>(Ex)) 9738 return false; 9739 9740 Expr *InnerE = Ex->IgnoreParenImpCasts(); 9741 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 9742 const Type *Source = 9743 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 9744 if (Target->isDependentType()) 9745 return false; 9746 9747 const BuiltinType *FloatCandidateBT = 9748 dyn_cast<BuiltinType>(ToBool ? Source : Target); 9749 const Type *BoolCandidateType = ToBool ? Target : Source; 9750 9751 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 9752 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 9753 } 9754 9755 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 9756 SourceLocation CC) { 9757 unsigned NumArgs = TheCall->getNumArgs(); 9758 for (unsigned i = 0; i < NumArgs; ++i) { 9759 Expr *CurrA = TheCall->getArg(i); 9760 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 9761 continue; 9762 9763 bool IsSwapped = ((i > 0) && 9764 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 9765 IsSwapped |= ((i < (NumArgs - 1)) && 9766 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 9767 if (IsSwapped) { 9768 // Warn on this floating-point to bool conversion. 9769 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 9770 CurrA->getType(), CC, 9771 diag::warn_impcast_floating_point_to_bool); 9772 } 9773 } 9774 } 9775 9776 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 9777 SourceLocation CC) { 9778 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 9779 E->getExprLoc())) 9780 return; 9781 9782 // Don't warn on functions which have return type nullptr_t. 9783 if (isa<CallExpr>(E)) 9784 return; 9785 9786 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 9787 const Expr::NullPointerConstantKind NullKind = 9788 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 9789 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 9790 return; 9791 9792 // Return if target type is a safe conversion. 9793 if (T->isAnyPointerType() || T->isBlockPointerType() || 9794 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 9795 return; 9796 9797 SourceLocation Loc = E->getSourceRange().getBegin(); 9798 9799 // Venture through the macro stacks to get to the source of macro arguments. 9800 // The new location is a better location than the complete location that was 9801 // passed in. 9802 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 9803 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 9804 9805 // __null is usually wrapped in a macro. Go up a macro if that is the case. 9806 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 9807 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 9808 Loc, S.SourceMgr, S.getLangOpts()); 9809 if (MacroName == "NULL") 9810 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 9811 } 9812 9813 // Only warn if the null and context location are in the same macro expansion. 9814 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 9815 return; 9816 9817 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 9818 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 9819 << FixItHint::CreateReplacement(Loc, 9820 S.getFixItZeroLiteralForType(T, Loc)); 9821 } 9822 9823 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 9824 ObjCArrayLiteral *ArrayLiteral); 9825 9826 static void 9827 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 9828 ObjCDictionaryLiteral *DictionaryLiteral); 9829 9830 /// Check a single element within a collection literal against the 9831 /// target element type. 9832 static void checkObjCCollectionLiteralElement(Sema &S, 9833 QualType TargetElementType, 9834 Expr *Element, 9835 unsigned ElementKind) { 9836 // Skip a bitcast to 'id' or qualified 'id'. 9837 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 9838 if (ICE->getCastKind() == CK_BitCast && 9839 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 9840 Element = ICE->getSubExpr(); 9841 } 9842 9843 QualType ElementType = Element->getType(); 9844 ExprResult ElementResult(Element); 9845 if (ElementType->getAs<ObjCObjectPointerType>() && 9846 S.CheckSingleAssignmentConstraints(TargetElementType, 9847 ElementResult, 9848 false, false) 9849 != Sema::Compatible) { 9850 S.Diag(Element->getLocStart(), 9851 diag::warn_objc_collection_literal_element) 9852 << ElementType << ElementKind << TargetElementType 9853 << Element->getSourceRange(); 9854 } 9855 9856 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 9857 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 9858 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 9859 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 9860 } 9861 9862 /// Check an Objective-C array literal being converted to the given 9863 /// target type. 9864 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 9865 ObjCArrayLiteral *ArrayLiteral) { 9866 if (!S.NSArrayDecl) 9867 return; 9868 9869 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 9870 if (!TargetObjCPtr) 9871 return; 9872 9873 if (TargetObjCPtr->isUnspecialized() || 9874 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 9875 != S.NSArrayDecl->getCanonicalDecl()) 9876 return; 9877 9878 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 9879 if (TypeArgs.size() != 1) 9880 return; 9881 9882 QualType TargetElementType = TypeArgs[0]; 9883 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 9884 checkObjCCollectionLiteralElement(S, TargetElementType, 9885 ArrayLiteral->getElement(I), 9886 0); 9887 } 9888 } 9889 9890 /// Check an Objective-C dictionary literal being converted to the given 9891 /// target type. 9892 static void 9893 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 9894 ObjCDictionaryLiteral *DictionaryLiteral) { 9895 if (!S.NSDictionaryDecl) 9896 return; 9897 9898 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 9899 if (!TargetObjCPtr) 9900 return; 9901 9902 if (TargetObjCPtr->isUnspecialized() || 9903 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 9904 != S.NSDictionaryDecl->getCanonicalDecl()) 9905 return; 9906 9907 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 9908 if (TypeArgs.size() != 2) 9909 return; 9910 9911 QualType TargetKeyType = TypeArgs[0]; 9912 QualType TargetObjectType = TypeArgs[1]; 9913 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 9914 auto Element = DictionaryLiteral->getKeyValueElement(I); 9915 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 9916 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 9917 } 9918 } 9919 9920 // Helper function to filter out cases for constant width constant conversion. 9921 // Don't warn on char array initialization or for non-decimal values. 9922 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 9923 SourceLocation CC) { 9924 // If initializing from a constant, and the constant starts with '0', 9925 // then it is a binary, octal, or hexadecimal. Allow these constants 9926 // to fill all the bits, even if there is a sign change. 9927 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 9928 const char FirstLiteralCharacter = 9929 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0]; 9930 if (FirstLiteralCharacter == '0') 9931 return false; 9932 } 9933 9934 // If the CC location points to a '{', and the type is char, then assume 9935 // assume it is an array initialization. 9936 if (CC.isValid() && T->isCharType()) { 9937 const char FirstContextCharacter = 9938 S.getSourceManager().getCharacterData(CC)[0]; 9939 if (FirstContextCharacter == '{') 9940 return false; 9941 } 9942 9943 return true; 9944 } 9945 9946 static void 9947 CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC, 9948 bool *ICContext = nullptr) { 9949 if (E->isTypeDependent() || E->isValueDependent()) return; 9950 9951 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 9952 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 9953 if (Source == Target) return; 9954 if (Target->isDependentType()) return; 9955 9956 // If the conversion context location is invalid don't complain. We also 9957 // don't want to emit a warning if the issue occurs from the expansion of 9958 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 9959 // delay this check as long as possible. Once we detect we are in that 9960 // scenario, we just return. 9961 if (CC.isInvalid()) 9962 return; 9963 9964 // Diagnose implicit casts to bool. 9965 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 9966 if (isa<StringLiteral>(E)) 9967 // Warn on string literal to bool. Checks for string literals in logical 9968 // and expressions, for instance, assert(0 && "error here"), are 9969 // prevented by a check in AnalyzeImplicitConversions(). 9970 return DiagnoseImpCast(S, E, T, CC, 9971 diag::warn_impcast_string_literal_to_bool); 9972 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 9973 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 9974 // This covers the literal expressions that evaluate to Objective-C 9975 // objects. 9976 return DiagnoseImpCast(S, E, T, CC, 9977 diag::warn_impcast_objective_c_literal_to_bool); 9978 } 9979 if (Source->isPointerType() || Source->canDecayToPointerType()) { 9980 // Warn on pointer to bool conversion that is always true. 9981 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 9982 SourceRange(CC)); 9983 } 9984 } 9985 9986 // Check implicit casts from Objective-C collection literals to specialized 9987 // collection types, e.g., NSArray<NSString *> *. 9988 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 9989 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 9990 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 9991 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 9992 9993 // Strip vector types. 9994 if (isa<VectorType>(Source)) { 9995 if (!isa<VectorType>(Target)) { 9996 if (S.SourceMgr.isInSystemMacro(CC)) 9997 return; 9998 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 9999 } 10000 10001 // If the vector cast is cast between two vectors of the same size, it is 10002 // a bitcast, not a conversion. 10003 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 10004 return; 10005 10006 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 10007 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 10008 } 10009 if (auto VecTy = dyn_cast<VectorType>(Target)) 10010 Target = VecTy->getElementType().getTypePtr(); 10011 10012 // Strip complex types. 10013 if (isa<ComplexType>(Source)) { 10014 if (!isa<ComplexType>(Target)) { 10015 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 10016 return; 10017 10018 return DiagnoseImpCast(S, E, T, CC, 10019 S.getLangOpts().CPlusPlus 10020 ? diag::err_impcast_complex_scalar 10021 : diag::warn_impcast_complex_scalar); 10022 } 10023 10024 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 10025 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 10026 } 10027 10028 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 10029 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 10030 10031 // If the source is floating point... 10032 if (SourceBT && SourceBT->isFloatingPoint()) { 10033 // ...and the target is floating point... 10034 if (TargetBT && TargetBT->isFloatingPoint()) { 10035 // ...then warn if we're dropping FP rank. 10036 10037 // Builtin FP kinds are ordered by increasing FP rank. 10038 if (SourceBT->getKind() > TargetBT->getKind()) { 10039 // Don't warn about float constants that are precisely 10040 // representable in the target type. 10041 Expr::EvalResult result; 10042 if (E->EvaluateAsRValue(result, S.Context)) { 10043 // Value might be a float, a float vector, or a float complex. 10044 if (IsSameFloatAfterCast(result.Val, 10045 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 10046 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 10047 return; 10048 } 10049 10050 if (S.SourceMgr.isInSystemMacro(CC)) 10051 return; 10052 10053 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 10054 } 10055 // ... or possibly if we're increasing rank, too 10056 else if (TargetBT->getKind() > SourceBT->getKind()) { 10057 if (S.SourceMgr.isInSystemMacro(CC)) 10058 return; 10059 10060 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 10061 } 10062 return; 10063 } 10064 10065 // If the target is integral, always warn. 10066 if (TargetBT && TargetBT->isInteger()) { 10067 if (S.SourceMgr.isInSystemMacro(CC)) 10068 return; 10069 10070 DiagnoseFloatingImpCast(S, E, T, CC); 10071 } 10072 10073 // Detect the case where a call result is converted from floating-point to 10074 // to bool, and the final argument to the call is converted from bool, to 10075 // discover this typo: 10076 // 10077 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 10078 // 10079 // FIXME: This is an incredibly special case; is there some more general 10080 // way to detect this class of misplaced-parentheses bug? 10081 if (Target->isBooleanType() && isa<CallExpr>(E)) { 10082 // Check last argument of function call to see if it is an 10083 // implicit cast from a type matching the type the result 10084 // is being cast to. 10085 CallExpr *CEx = cast<CallExpr>(E); 10086 if (unsigned NumArgs = CEx->getNumArgs()) { 10087 Expr *LastA = CEx->getArg(NumArgs - 1); 10088 Expr *InnerE = LastA->IgnoreParenImpCasts(); 10089 if (isa<ImplicitCastExpr>(LastA) && 10090 InnerE->getType()->isBooleanType()) { 10091 // Warn on this floating-point to bool conversion 10092 DiagnoseImpCast(S, E, T, CC, 10093 diag::warn_impcast_floating_point_to_bool); 10094 } 10095 } 10096 } 10097 return; 10098 } 10099 10100 DiagnoseNullConversion(S, E, T, CC); 10101 10102 S.DiscardMisalignedMemberAddress(Target, E); 10103 10104 if (!Source->isIntegerType() || !Target->isIntegerType()) 10105 return; 10106 10107 // TODO: remove this early return once the false positives for constant->bool 10108 // in templates, macros, etc, are reduced or removed. 10109 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 10110 return; 10111 10112 IntRange SourceRange = GetExprRange(S.Context, E); 10113 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 10114 10115 if (SourceRange.Width > TargetRange.Width) { 10116 // If the source is a constant, use a default-on diagnostic. 10117 // TODO: this should happen for bitfield stores, too. 10118 llvm::APSInt Value(32); 10119 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) { 10120 if (S.SourceMgr.isInSystemMacro(CC)) 10121 return; 10122 10123 std::string PrettySourceValue = Value.toString(10); 10124 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 10125 10126 S.DiagRuntimeBehavior(E->getExprLoc(), E, 10127 S.PDiag(diag::warn_impcast_integer_precision_constant) 10128 << PrettySourceValue << PrettyTargetValue 10129 << E->getType() << T << E->getSourceRange() 10130 << clang::SourceRange(CC)); 10131 return; 10132 } 10133 10134 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 10135 if (S.SourceMgr.isInSystemMacro(CC)) 10136 return; 10137 10138 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 10139 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 10140 /* pruneControlFlow */ true); 10141 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 10142 } 10143 10144 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative && 10145 SourceRange.NonNegative && Source->isSignedIntegerType()) { 10146 // Warn when doing a signed to signed conversion, warn if the positive 10147 // source value is exactly the width of the target type, which will 10148 // cause a negative value to be stored. 10149 10150 llvm::APSInt Value; 10151 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) && 10152 !S.SourceMgr.isInSystemMacro(CC)) { 10153 if (isSameWidthConstantConversion(S, E, T, CC)) { 10154 std::string PrettySourceValue = Value.toString(10); 10155 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 10156 10157 S.DiagRuntimeBehavior( 10158 E->getExprLoc(), E, 10159 S.PDiag(diag::warn_impcast_integer_precision_constant) 10160 << PrettySourceValue << PrettyTargetValue << E->getType() << T 10161 << E->getSourceRange() << clang::SourceRange(CC)); 10162 return; 10163 } 10164 } 10165 10166 // Fall through for non-constants to give a sign conversion warning. 10167 } 10168 10169 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 10170 (!TargetRange.NonNegative && SourceRange.NonNegative && 10171 SourceRange.Width == TargetRange.Width)) { 10172 if (S.SourceMgr.isInSystemMacro(CC)) 10173 return; 10174 10175 unsigned DiagID = diag::warn_impcast_integer_sign; 10176 10177 // Traditionally, gcc has warned about this under -Wsign-compare. 10178 // We also want to warn about it in -Wconversion. 10179 // So if -Wconversion is off, use a completely identical diagnostic 10180 // in the sign-compare group. 10181 // The conditional-checking code will 10182 if (ICContext) { 10183 DiagID = diag::warn_impcast_integer_sign_conditional; 10184 *ICContext = true; 10185 } 10186 10187 return DiagnoseImpCast(S, E, T, CC, DiagID); 10188 } 10189 10190 // Diagnose conversions between different enumeration types. 10191 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 10192 // type, to give us better diagnostics. 10193 QualType SourceType = E->getType(); 10194 if (!S.getLangOpts().CPlusPlus) { 10195 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 10196 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 10197 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 10198 SourceType = S.Context.getTypeDeclType(Enum); 10199 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 10200 } 10201 } 10202 10203 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 10204 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 10205 if (SourceEnum->getDecl()->hasNameForLinkage() && 10206 TargetEnum->getDecl()->hasNameForLinkage() && 10207 SourceEnum != TargetEnum) { 10208 if (S.SourceMgr.isInSystemMacro(CC)) 10209 return; 10210 10211 return DiagnoseImpCast(S, E, SourceType, T, CC, 10212 diag::warn_impcast_different_enum_types); 10213 } 10214 } 10215 10216 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 10217 SourceLocation CC, QualType T); 10218 10219 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 10220 SourceLocation CC, bool &ICContext) { 10221 E = E->IgnoreParenImpCasts(); 10222 10223 if (isa<ConditionalOperator>(E)) 10224 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T); 10225 10226 AnalyzeImplicitConversions(S, E, CC); 10227 if (E->getType() != T) 10228 return CheckImplicitConversion(S, E, T, CC, &ICContext); 10229 } 10230 10231 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 10232 SourceLocation CC, QualType T) { 10233 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 10234 10235 bool Suspicious = false; 10236 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 10237 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 10238 10239 // If -Wconversion would have warned about either of the candidates 10240 // for a signedness conversion to the context type... 10241 if (!Suspicious) return; 10242 10243 // ...but it's currently ignored... 10244 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 10245 return; 10246 10247 // ...then check whether it would have warned about either of the 10248 // candidates for a signedness conversion to the condition type. 10249 if (E->getType() == T) return; 10250 10251 Suspicious = false; 10252 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 10253 E->getType(), CC, &Suspicious); 10254 if (!Suspicious) 10255 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 10256 E->getType(), CC, &Suspicious); 10257 } 10258 10259 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 10260 /// Input argument E is a logical expression. 10261 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 10262 if (S.getLangOpts().Bool) 10263 return; 10264 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 10265 } 10266 10267 /// AnalyzeImplicitConversions - Find and report any interesting 10268 /// implicit conversions in the given expression. There are a couple 10269 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 10270 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, 10271 SourceLocation CC) { 10272 QualType T = OrigE->getType(); 10273 Expr *E = OrigE->IgnoreParenImpCasts(); 10274 10275 if (E->isTypeDependent() || E->isValueDependent()) 10276 return; 10277 10278 // For conditional operators, we analyze the arguments as if they 10279 // were being fed directly into the output. 10280 if (isa<ConditionalOperator>(E)) { 10281 ConditionalOperator *CO = cast<ConditionalOperator>(E); 10282 CheckConditionalOperator(S, CO, CC, T); 10283 return; 10284 } 10285 10286 // Check implicit argument conversions for function calls. 10287 if (CallExpr *Call = dyn_cast<CallExpr>(E)) 10288 CheckImplicitArgumentConversions(S, Call, CC); 10289 10290 // Go ahead and check any implicit conversions we might have skipped. 10291 // The non-canonical typecheck is just an optimization; 10292 // CheckImplicitConversion will filter out dead implicit conversions. 10293 if (E->getType() != T) 10294 CheckImplicitConversion(S, E, T, CC); 10295 10296 // Now continue drilling into this expression. 10297 10298 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 10299 // The bound subexpressions in a PseudoObjectExpr are not reachable 10300 // as transitive children. 10301 // FIXME: Use a more uniform representation for this. 10302 for (auto *SE : POE->semantics()) 10303 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 10304 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC); 10305 } 10306 10307 // Skip past explicit casts. 10308 if (isa<ExplicitCastExpr>(E)) { 10309 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts(); 10310 return AnalyzeImplicitConversions(S, E, CC); 10311 } 10312 10313 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 10314 // Do a somewhat different check with comparison operators. 10315 if (BO->isComparisonOp()) 10316 return AnalyzeComparison(S, BO); 10317 10318 // And with simple assignments. 10319 if (BO->getOpcode() == BO_Assign) 10320 return AnalyzeAssignment(S, BO); 10321 // And with compound assignments. 10322 if (BO->isAssignmentOp()) 10323 return AnalyzeCompoundAssignment(S, BO); 10324 } 10325 10326 // These break the otherwise-useful invariant below. Fortunately, 10327 // we don't really need to recurse into them, because any internal 10328 // expressions should have been analyzed already when they were 10329 // built into statements. 10330 if (isa<StmtExpr>(E)) return; 10331 10332 // Don't descend into unevaluated contexts. 10333 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 10334 10335 // Now just recurse over the expression's children. 10336 CC = E->getExprLoc(); 10337 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 10338 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 10339 for (Stmt *SubStmt : E->children()) { 10340 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 10341 if (!ChildExpr) 10342 continue; 10343 10344 if (IsLogicalAndOperator && 10345 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 10346 // Ignore checking string literals that are in logical and operators. 10347 // This is a common pattern for asserts. 10348 continue; 10349 AnalyzeImplicitConversions(S, ChildExpr, CC); 10350 } 10351 10352 if (BO && BO->isLogicalOp()) { 10353 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 10354 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 10355 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 10356 10357 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 10358 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 10359 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 10360 } 10361 10362 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) 10363 if (U->getOpcode() == UO_LNot) 10364 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 10365 } 10366 10367 /// Diagnose integer type and any valid implicit conversion to it. 10368 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 10369 // Taking into account implicit conversions, 10370 // allow any integer. 10371 if (!E->getType()->isIntegerType()) { 10372 S.Diag(E->getLocStart(), 10373 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 10374 return true; 10375 } 10376 // Potentially emit standard warnings for implicit conversions if enabled 10377 // using -Wconversion. 10378 CheckImplicitConversion(S, E, IntT, E->getLocStart()); 10379 return false; 10380 } 10381 10382 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 10383 // Returns true when emitting a warning about taking the address of a reference. 10384 static bool CheckForReference(Sema &SemaRef, const Expr *E, 10385 const PartialDiagnostic &PD) { 10386 E = E->IgnoreParenImpCasts(); 10387 10388 const FunctionDecl *FD = nullptr; 10389 10390 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 10391 if (!DRE->getDecl()->getType()->isReferenceType()) 10392 return false; 10393 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 10394 if (!M->getMemberDecl()->getType()->isReferenceType()) 10395 return false; 10396 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 10397 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 10398 return false; 10399 FD = Call->getDirectCallee(); 10400 } else { 10401 return false; 10402 } 10403 10404 SemaRef.Diag(E->getExprLoc(), PD); 10405 10406 // If possible, point to location of function. 10407 if (FD) { 10408 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 10409 } 10410 10411 return true; 10412 } 10413 10414 // Returns true if the SourceLocation is expanded from any macro body. 10415 // Returns false if the SourceLocation is invalid, is from not in a macro 10416 // expansion, or is from expanded from a top-level macro argument. 10417 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 10418 if (Loc.isInvalid()) 10419 return false; 10420 10421 while (Loc.isMacroID()) { 10422 if (SM.isMacroBodyExpansion(Loc)) 10423 return true; 10424 Loc = SM.getImmediateMacroCallerLoc(Loc); 10425 } 10426 10427 return false; 10428 } 10429 10430 /// Diagnose pointers that are always non-null. 10431 /// \param E the expression containing the pointer 10432 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 10433 /// compared to a null pointer 10434 /// \param IsEqual True when the comparison is equal to a null pointer 10435 /// \param Range Extra SourceRange to highlight in the diagnostic 10436 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 10437 Expr::NullPointerConstantKind NullKind, 10438 bool IsEqual, SourceRange Range) { 10439 if (!E) 10440 return; 10441 10442 // Don't warn inside macros. 10443 if (E->getExprLoc().isMacroID()) { 10444 const SourceManager &SM = getSourceManager(); 10445 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 10446 IsInAnyMacroBody(SM, Range.getBegin())) 10447 return; 10448 } 10449 E = E->IgnoreImpCasts(); 10450 10451 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 10452 10453 if (isa<CXXThisExpr>(E)) { 10454 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 10455 : diag::warn_this_bool_conversion; 10456 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 10457 return; 10458 } 10459 10460 bool IsAddressOf = false; 10461 10462 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 10463 if (UO->getOpcode() != UO_AddrOf) 10464 return; 10465 IsAddressOf = true; 10466 E = UO->getSubExpr(); 10467 } 10468 10469 if (IsAddressOf) { 10470 unsigned DiagID = IsCompare 10471 ? diag::warn_address_of_reference_null_compare 10472 : diag::warn_address_of_reference_bool_conversion; 10473 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 10474 << IsEqual; 10475 if (CheckForReference(*this, E, PD)) { 10476 return; 10477 } 10478 } 10479 10480 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 10481 bool IsParam = isa<NonNullAttr>(NonnullAttr); 10482 std::string Str; 10483 llvm::raw_string_ostream S(Str); 10484 E->printPretty(S, nullptr, getPrintingPolicy()); 10485 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 10486 : diag::warn_cast_nonnull_to_bool; 10487 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 10488 << E->getSourceRange() << Range << IsEqual; 10489 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 10490 }; 10491 10492 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 10493 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 10494 if (auto *Callee = Call->getDirectCallee()) { 10495 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 10496 ComplainAboutNonnullParamOrCall(A); 10497 return; 10498 } 10499 } 10500 } 10501 10502 // Expect to find a single Decl. Skip anything more complicated. 10503 ValueDecl *D = nullptr; 10504 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 10505 D = R->getDecl(); 10506 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 10507 D = M->getMemberDecl(); 10508 } 10509 10510 // Weak Decls can be null. 10511 if (!D || D->isWeak()) 10512 return; 10513 10514 // Check for parameter decl with nonnull attribute 10515 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 10516 if (getCurFunction() && 10517 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 10518 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 10519 ComplainAboutNonnullParamOrCall(A); 10520 return; 10521 } 10522 10523 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 10524 auto ParamIter = llvm::find(FD->parameters(), PV); 10525 assert(ParamIter != FD->param_end()); 10526 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 10527 10528 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 10529 if (!NonNull->args_size()) { 10530 ComplainAboutNonnullParamOrCall(NonNull); 10531 return; 10532 } 10533 10534 for (const ParamIdx &ArgNo : NonNull->args()) { 10535 if (ArgNo.getASTIndex() == ParamNo) { 10536 ComplainAboutNonnullParamOrCall(NonNull); 10537 return; 10538 } 10539 } 10540 } 10541 } 10542 } 10543 } 10544 10545 QualType T = D->getType(); 10546 const bool IsArray = T->isArrayType(); 10547 const bool IsFunction = T->isFunctionType(); 10548 10549 // Address of function is used to silence the function warning. 10550 if (IsAddressOf && IsFunction) { 10551 return; 10552 } 10553 10554 // Found nothing. 10555 if (!IsAddressOf && !IsFunction && !IsArray) 10556 return; 10557 10558 // Pretty print the expression for the diagnostic. 10559 std::string Str; 10560 llvm::raw_string_ostream S(Str); 10561 E->printPretty(S, nullptr, getPrintingPolicy()); 10562 10563 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 10564 : diag::warn_impcast_pointer_to_bool; 10565 enum { 10566 AddressOf, 10567 FunctionPointer, 10568 ArrayPointer 10569 } DiagType; 10570 if (IsAddressOf) 10571 DiagType = AddressOf; 10572 else if (IsFunction) 10573 DiagType = FunctionPointer; 10574 else if (IsArray) 10575 DiagType = ArrayPointer; 10576 else 10577 llvm_unreachable("Could not determine diagnostic."); 10578 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 10579 << Range << IsEqual; 10580 10581 if (!IsFunction) 10582 return; 10583 10584 // Suggest '&' to silence the function warning. 10585 Diag(E->getExprLoc(), diag::note_function_warning_silence) 10586 << FixItHint::CreateInsertion(E->getLocStart(), "&"); 10587 10588 // Check to see if '()' fixit should be emitted. 10589 QualType ReturnType; 10590 UnresolvedSet<4> NonTemplateOverloads; 10591 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 10592 if (ReturnType.isNull()) 10593 return; 10594 10595 if (IsCompare) { 10596 // There are two cases here. If there is null constant, the only suggest 10597 // for a pointer return type. If the null is 0, then suggest if the return 10598 // type is a pointer or an integer type. 10599 if (!ReturnType->isPointerType()) { 10600 if (NullKind == Expr::NPCK_ZeroExpression || 10601 NullKind == Expr::NPCK_ZeroLiteral) { 10602 if (!ReturnType->isIntegerType()) 10603 return; 10604 } else { 10605 return; 10606 } 10607 } 10608 } else { // !IsCompare 10609 // For function to bool, only suggest if the function pointer has bool 10610 // return type. 10611 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 10612 return; 10613 } 10614 Diag(E->getExprLoc(), diag::note_function_to_function_call) 10615 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()"); 10616 } 10617 10618 /// Diagnoses "dangerous" implicit conversions within the given 10619 /// expression (which is a full expression). Implements -Wconversion 10620 /// and -Wsign-compare. 10621 /// 10622 /// \param CC the "context" location of the implicit conversion, i.e. 10623 /// the most location of the syntactic entity requiring the implicit 10624 /// conversion 10625 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 10626 // Don't diagnose in unevaluated contexts. 10627 if (isUnevaluatedContext()) 10628 return; 10629 10630 // Don't diagnose for value- or type-dependent expressions. 10631 if (E->isTypeDependent() || E->isValueDependent()) 10632 return; 10633 10634 // Check for array bounds violations in cases where the check isn't triggered 10635 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 10636 // ArraySubscriptExpr is on the RHS of a variable initialization. 10637 CheckArrayAccess(E); 10638 10639 // This is not the right CC for (e.g.) a variable initialization. 10640 AnalyzeImplicitConversions(*this, E, CC); 10641 } 10642 10643 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 10644 /// Input argument E is a logical expression. 10645 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 10646 ::CheckBoolLikeConversion(*this, E, CC); 10647 } 10648 10649 /// Diagnose when expression is an integer constant expression and its evaluation 10650 /// results in integer overflow 10651 void Sema::CheckForIntOverflow (Expr *E) { 10652 // Use a work list to deal with nested struct initializers. 10653 SmallVector<Expr *, 2> Exprs(1, E); 10654 10655 do { 10656 Expr *OriginalE = Exprs.pop_back_val(); 10657 Expr *E = OriginalE->IgnoreParenCasts(); 10658 10659 if (isa<BinaryOperator>(E)) { 10660 E->EvaluateForOverflow(Context); 10661 continue; 10662 } 10663 10664 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 10665 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 10666 else if (isa<ObjCBoxedExpr>(OriginalE)) 10667 E->EvaluateForOverflow(Context); 10668 else if (auto Call = dyn_cast<CallExpr>(E)) 10669 Exprs.append(Call->arg_begin(), Call->arg_end()); 10670 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 10671 Exprs.append(Message->arg_begin(), Message->arg_end()); 10672 } while (!Exprs.empty()); 10673 } 10674 10675 namespace { 10676 10677 /// Visitor for expressions which looks for unsequenced operations on the 10678 /// same object. 10679 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> { 10680 using Base = EvaluatedExprVisitor<SequenceChecker>; 10681 10682 /// A tree of sequenced regions within an expression. Two regions are 10683 /// unsequenced if one is an ancestor or a descendent of the other. When we 10684 /// finish processing an expression with sequencing, such as a comma 10685 /// expression, we fold its tree nodes into its parent, since they are 10686 /// unsequenced with respect to nodes we will visit later. 10687 class SequenceTree { 10688 struct Value { 10689 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 10690 unsigned Parent : 31; 10691 unsigned Merged : 1; 10692 }; 10693 SmallVector<Value, 8> Values; 10694 10695 public: 10696 /// A region within an expression which may be sequenced with respect 10697 /// to some other region. 10698 class Seq { 10699 friend class SequenceTree; 10700 10701 unsigned Index = 0; 10702 10703 explicit Seq(unsigned N) : Index(N) {} 10704 10705 public: 10706 Seq() = default; 10707 }; 10708 10709 SequenceTree() { Values.push_back(Value(0)); } 10710 Seq root() const { return Seq(0); } 10711 10712 /// Create a new sequence of operations, which is an unsequenced 10713 /// subset of \p Parent. This sequence of operations is sequenced with 10714 /// respect to other children of \p Parent. 10715 Seq allocate(Seq Parent) { 10716 Values.push_back(Value(Parent.Index)); 10717 return Seq(Values.size() - 1); 10718 } 10719 10720 /// Merge a sequence of operations into its parent. 10721 void merge(Seq S) { 10722 Values[S.Index].Merged = true; 10723 } 10724 10725 /// Determine whether two operations are unsequenced. This operation 10726 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 10727 /// should have been merged into its parent as appropriate. 10728 bool isUnsequenced(Seq Cur, Seq Old) { 10729 unsigned C = representative(Cur.Index); 10730 unsigned Target = representative(Old.Index); 10731 while (C >= Target) { 10732 if (C == Target) 10733 return true; 10734 C = Values[C].Parent; 10735 } 10736 return false; 10737 } 10738 10739 private: 10740 /// Pick a representative for a sequence. 10741 unsigned representative(unsigned K) { 10742 if (Values[K].Merged) 10743 // Perform path compression as we go. 10744 return Values[K].Parent = representative(Values[K].Parent); 10745 return K; 10746 } 10747 }; 10748 10749 /// An object for which we can track unsequenced uses. 10750 using Object = NamedDecl *; 10751 10752 /// Different flavors of object usage which we track. We only track the 10753 /// least-sequenced usage of each kind. 10754 enum UsageKind { 10755 /// A read of an object. Multiple unsequenced reads are OK. 10756 UK_Use, 10757 10758 /// A modification of an object which is sequenced before the value 10759 /// computation of the expression, such as ++n in C++. 10760 UK_ModAsValue, 10761 10762 /// A modification of an object which is not sequenced before the value 10763 /// computation of the expression, such as n++. 10764 UK_ModAsSideEffect, 10765 10766 UK_Count = UK_ModAsSideEffect + 1 10767 }; 10768 10769 struct Usage { 10770 Expr *Use = nullptr; 10771 SequenceTree::Seq Seq; 10772 10773 Usage() = default; 10774 }; 10775 10776 struct UsageInfo { 10777 Usage Uses[UK_Count]; 10778 10779 /// Have we issued a diagnostic for this variable already? 10780 bool Diagnosed = false; 10781 10782 UsageInfo() = default; 10783 }; 10784 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 10785 10786 Sema &SemaRef; 10787 10788 /// Sequenced regions within the expression. 10789 SequenceTree Tree; 10790 10791 /// Declaration modifications and references which we have seen. 10792 UsageInfoMap UsageMap; 10793 10794 /// The region we are currently within. 10795 SequenceTree::Seq Region; 10796 10797 /// Filled in with declarations which were modified as a side-effect 10798 /// (that is, post-increment operations). 10799 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 10800 10801 /// Expressions to check later. We defer checking these to reduce 10802 /// stack usage. 10803 SmallVectorImpl<Expr *> &WorkList; 10804 10805 /// RAII object wrapping the visitation of a sequenced subexpression of an 10806 /// expression. At the end of this process, the side-effects of the evaluation 10807 /// become sequenced with respect to the value computation of the result, so 10808 /// we downgrade any UK_ModAsSideEffect within the evaluation to 10809 /// UK_ModAsValue. 10810 struct SequencedSubexpression { 10811 SequencedSubexpression(SequenceChecker &Self) 10812 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 10813 Self.ModAsSideEffect = &ModAsSideEffect; 10814 } 10815 10816 ~SequencedSubexpression() { 10817 for (auto &M : llvm::reverse(ModAsSideEffect)) { 10818 UsageInfo &U = Self.UsageMap[M.first]; 10819 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect]; 10820 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue); 10821 SideEffectUsage = M.second; 10822 } 10823 Self.ModAsSideEffect = OldModAsSideEffect; 10824 } 10825 10826 SequenceChecker &Self; 10827 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 10828 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 10829 }; 10830 10831 /// RAII object wrapping the visitation of a subexpression which we might 10832 /// choose to evaluate as a constant. If any subexpression is evaluated and 10833 /// found to be non-constant, this allows us to suppress the evaluation of 10834 /// the outer expression. 10835 class EvaluationTracker { 10836 public: 10837 EvaluationTracker(SequenceChecker &Self) 10838 : Self(Self), Prev(Self.EvalTracker) { 10839 Self.EvalTracker = this; 10840 } 10841 10842 ~EvaluationTracker() { 10843 Self.EvalTracker = Prev; 10844 if (Prev) 10845 Prev->EvalOK &= EvalOK; 10846 } 10847 10848 bool evaluate(const Expr *E, bool &Result) { 10849 if (!EvalOK || E->isValueDependent()) 10850 return false; 10851 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context); 10852 return EvalOK; 10853 } 10854 10855 private: 10856 SequenceChecker &Self; 10857 EvaluationTracker *Prev; 10858 bool EvalOK = true; 10859 } *EvalTracker = nullptr; 10860 10861 /// Find the object which is produced by the specified expression, 10862 /// if any. 10863 Object getObject(Expr *E, bool Mod) const { 10864 E = E->IgnoreParenCasts(); 10865 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 10866 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 10867 return getObject(UO->getSubExpr(), Mod); 10868 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 10869 if (BO->getOpcode() == BO_Comma) 10870 return getObject(BO->getRHS(), Mod); 10871 if (Mod && BO->isAssignmentOp()) 10872 return getObject(BO->getLHS(), Mod); 10873 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 10874 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 10875 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 10876 return ME->getMemberDecl(); 10877 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 10878 // FIXME: If this is a reference, map through to its value. 10879 return DRE->getDecl(); 10880 return nullptr; 10881 } 10882 10883 /// Note that an object was modified or used by an expression. 10884 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) { 10885 Usage &U = UI.Uses[UK]; 10886 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) { 10887 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 10888 ModAsSideEffect->push_back(std::make_pair(O, U)); 10889 U.Use = Ref; 10890 U.Seq = Region; 10891 } 10892 } 10893 10894 /// Check whether a modification or use conflicts with a prior usage. 10895 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind, 10896 bool IsModMod) { 10897 if (UI.Diagnosed) 10898 return; 10899 10900 const Usage &U = UI.Uses[OtherKind]; 10901 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) 10902 return; 10903 10904 Expr *Mod = U.Use; 10905 Expr *ModOrUse = Ref; 10906 if (OtherKind == UK_Use) 10907 std::swap(Mod, ModOrUse); 10908 10909 SemaRef.Diag(Mod->getExprLoc(), 10910 IsModMod ? diag::warn_unsequenced_mod_mod 10911 : diag::warn_unsequenced_mod_use) 10912 << O << SourceRange(ModOrUse->getExprLoc()); 10913 UI.Diagnosed = true; 10914 } 10915 10916 void notePreUse(Object O, Expr *Use) { 10917 UsageInfo &U = UsageMap[O]; 10918 // Uses conflict with other modifications. 10919 checkUsage(O, U, Use, UK_ModAsValue, false); 10920 } 10921 10922 void notePostUse(Object O, Expr *Use) { 10923 UsageInfo &U = UsageMap[O]; 10924 checkUsage(O, U, Use, UK_ModAsSideEffect, false); 10925 addUsage(U, O, Use, UK_Use); 10926 } 10927 10928 void notePreMod(Object O, Expr *Mod) { 10929 UsageInfo &U = UsageMap[O]; 10930 // Modifications conflict with other modifications and with uses. 10931 checkUsage(O, U, Mod, UK_ModAsValue, true); 10932 checkUsage(O, U, Mod, UK_Use, false); 10933 } 10934 10935 void notePostMod(Object O, Expr *Use, UsageKind UK) { 10936 UsageInfo &U = UsageMap[O]; 10937 checkUsage(O, U, Use, UK_ModAsSideEffect, true); 10938 addUsage(U, O, Use, UK); 10939 } 10940 10941 public: 10942 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList) 10943 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 10944 Visit(E); 10945 } 10946 10947 void VisitStmt(Stmt *S) { 10948 // Skip all statements which aren't expressions for now. 10949 } 10950 10951 void VisitExpr(Expr *E) { 10952 // By default, just recurse to evaluated subexpressions. 10953 Base::VisitStmt(E); 10954 } 10955 10956 void VisitCastExpr(CastExpr *E) { 10957 Object O = Object(); 10958 if (E->getCastKind() == CK_LValueToRValue) 10959 O = getObject(E->getSubExpr(), false); 10960 10961 if (O) 10962 notePreUse(O, E); 10963 VisitExpr(E); 10964 if (O) 10965 notePostUse(O, E); 10966 } 10967 10968 void VisitBinComma(BinaryOperator *BO) { 10969 // C++11 [expr.comma]p1: 10970 // Every value computation and side effect associated with the left 10971 // expression is sequenced before every value computation and side 10972 // effect associated with the right expression. 10973 SequenceTree::Seq LHS = Tree.allocate(Region); 10974 SequenceTree::Seq RHS = Tree.allocate(Region); 10975 SequenceTree::Seq OldRegion = Region; 10976 10977 { 10978 SequencedSubexpression SeqLHS(*this); 10979 Region = LHS; 10980 Visit(BO->getLHS()); 10981 } 10982 10983 Region = RHS; 10984 Visit(BO->getRHS()); 10985 10986 Region = OldRegion; 10987 10988 // Forget that LHS and RHS are sequenced. They are both unsequenced 10989 // with respect to other stuff. 10990 Tree.merge(LHS); 10991 Tree.merge(RHS); 10992 } 10993 10994 void VisitBinAssign(BinaryOperator *BO) { 10995 // The modification is sequenced after the value computation of the LHS 10996 // and RHS, so check it before inspecting the operands and update the 10997 // map afterwards. 10998 Object O = getObject(BO->getLHS(), true); 10999 if (!O) 11000 return VisitExpr(BO); 11001 11002 notePreMod(O, BO); 11003 11004 // C++11 [expr.ass]p7: 11005 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated 11006 // only once. 11007 // 11008 // Therefore, for a compound assignment operator, O is considered used 11009 // everywhere except within the evaluation of E1 itself. 11010 if (isa<CompoundAssignOperator>(BO)) 11011 notePreUse(O, BO); 11012 11013 Visit(BO->getLHS()); 11014 11015 if (isa<CompoundAssignOperator>(BO)) 11016 notePostUse(O, BO); 11017 11018 Visit(BO->getRHS()); 11019 11020 // C++11 [expr.ass]p1: 11021 // the assignment is sequenced [...] before the value computation of the 11022 // assignment expression. 11023 // C11 6.5.16/3 has no such rule. 11024 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 11025 : UK_ModAsSideEffect); 11026 } 11027 11028 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) { 11029 VisitBinAssign(CAO); 11030 } 11031 11032 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 11033 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 11034 void VisitUnaryPreIncDec(UnaryOperator *UO) { 11035 Object O = getObject(UO->getSubExpr(), true); 11036 if (!O) 11037 return VisitExpr(UO); 11038 11039 notePreMod(O, UO); 11040 Visit(UO->getSubExpr()); 11041 // C++11 [expr.pre.incr]p1: 11042 // the expression ++x is equivalent to x+=1 11043 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 11044 : UK_ModAsSideEffect); 11045 } 11046 11047 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 11048 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 11049 void VisitUnaryPostIncDec(UnaryOperator *UO) { 11050 Object O = getObject(UO->getSubExpr(), true); 11051 if (!O) 11052 return VisitExpr(UO); 11053 11054 notePreMod(O, UO); 11055 Visit(UO->getSubExpr()); 11056 notePostMod(O, UO, UK_ModAsSideEffect); 11057 } 11058 11059 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated. 11060 void VisitBinLOr(BinaryOperator *BO) { 11061 // The side-effects of the LHS of an '&&' are sequenced before the 11062 // value computation of the RHS, and hence before the value computation 11063 // of the '&&' itself, unless the LHS evaluates to zero. We treat them 11064 // as if they were unconditionally sequenced. 11065 EvaluationTracker Eval(*this); 11066 { 11067 SequencedSubexpression Sequenced(*this); 11068 Visit(BO->getLHS()); 11069 } 11070 11071 bool Result; 11072 if (Eval.evaluate(BO->getLHS(), Result)) { 11073 if (!Result) 11074 Visit(BO->getRHS()); 11075 } else { 11076 // Check for unsequenced operations in the RHS, treating it as an 11077 // entirely separate evaluation. 11078 // 11079 // FIXME: If there are operations in the RHS which are unsequenced 11080 // with respect to operations outside the RHS, and those operations 11081 // are unconditionally evaluated, diagnose them. 11082 WorkList.push_back(BO->getRHS()); 11083 } 11084 } 11085 void VisitBinLAnd(BinaryOperator *BO) { 11086 EvaluationTracker Eval(*this); 11087 { 11088 SequencedSubexpression Sequenced(*this); 11089 Visit(BO->getLHS()); 11090 } 11091 11092 bool Result; 11093 if (Eval.evaluate(BO->getLHS(), Result)) { 11094 if (Result) 11095 Visit(BO->getRHS()); 11096 } else { 11097 WorkList.push_back(BO->getRHS()); 11098 } 11099 } 11100 11101 // Only visit the condition, unless we can be sure which subexpression will 11102 // be chosen. 11103 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) { 11104 EvaluationTracker Eval(*this); 11105 { 11106 SequencedSubexpression Sequenced(*this); 11107 Visit(CO->getCond()); 11108 } 11109 11110 bool Result; 11111 if (Eval.evaluate(CO->getCond(), Result)) 11112 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr()); 11113 else { 11114 WorkList.push_back(CO->getTrueExpr()); 11115 WorkList.push_back(CO->getFalseExpr()); 11116 } 11117 } 11118 11119 void VisitCallExpr(CallExpr *CE) { 11120 // C++11 [intro.execution]p15: 11121 // When calling a function [...], every value computation and side effect 11122 // associated with any argument expression, or with the postfix expression 11123 // designating the called function, is sequenced before execution of every 11124 // expression or statement in the body of the function [and thus before 11125 // the value computation of its result]. 11126 SequencedSubexpression Sequenced(*this); 11127 Base::VisitCallExpr(CE); 11128 11129 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 11130 } 11131 11132 void VisitCXXConstructExpr(CXXConstructExpr *CCE) { 11133 // This is a call, so all subexpressions are sequenced before the result. 11134 SequencedSubexpression Sequenced(*this); 11135 11136 if (!CCE->isListInitialization()) 11137 return VisitExpr(CCE); 11138 11139 // In C++11, list initializations are sequenced. 11140 SmallVector<SequenceTree::Seq, 32> Elts; 11141 SequenceTree::Seq Parent = Region; 11142 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(), 11143 E = CCE->arg_end(); 11144 I != E; ++I) { 11145 Region = Tree.allocate(Parent); 11146 Elts.push_back(Region); 11147 Visit(*I); 11148 } 11149 11150 // Forget that the initializers are sequenced. 11151 Region = Parent; 11152 for (unsigned I = 0; I < Elts.size(); ++I) 11153 Tree.merge(Elts[I]); 11154 } 11155 11156 void VisitInitListExpr(InitListExpr *ILE) { 11157 if (!SemaRef.getLangOpts().CPlusPlus11) 11158 return VisitExpr(ILE); 11159 11160 // In C++11, list initializations are sequenced. 11161 SmallVector<SequenceTree::Seq, 32> Elts; 11162 SequenceTree::Seq Parent = Region; 11163 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 11164 Expr *E = ILE->getInit(I); 11165 if (!E) continue; 11166 Region = Tree.allocate(Parent); 11167 Elts.push_back(Region); 11168 Visit(E); 11169 } 11170 11171 // Forget that the initializers are sequenced. 11172 Region = Parent; 11173 for (unsigned I = 0; I < Elts.size(); ++I) 11174 Tree.merge(Elts[I]); 11175 } 11176 }; 11177 11178 } // namespace 11179 11180 void Sema::CheckUnsequencedOperations(Expr *E) { 11181 SmallVector<Expr *, 8> WorkList; 11182 WorkList.push_back(E); 11183 while (!WorkList.empty()) { 11184 Expr *Item = WorkList.pop_back_val(); 11185 SequenceChecker(*this, Item, WorkList); 11186 } 11187 } 11188 11189 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 11190 bool IsConstexpr) { 11191 CheckImplicitConversions(E, CheckLoc); 11192 if (!E->isInstantiationDependent()) 11193 CheckUnsequencedOperations(E); 11194 if (!IsConstexpr && !E->isValueDependent()) 11195 CheckForIntOverflow(E); 11196 DiagnoseMisalignedMembers(); 11197 } 11198 11199 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 11200 FieldDecl *BitField, 11201 Expr *Init) { 11202 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 11203 } 11204 11205 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 11206 SourceLocation Loc) { 11207 if (!PType->isVariablyModifiedType()) 11208 return; 11209 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 11210 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 11211 return; 11212 } 11213 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 11214 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 11215 return; 11216 } 11217 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 11218 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 11219 return; 11220 } 11221 11222 const ArrayType *AT = S.Context.getAsArrayType(PType); 11223 if (!AT) 11224 return; 11225 11226 if (AT->getSizeModifier() != ArrayType::Star) { 11227 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 11228 return; 11229 } 11230 11231 S.Diag(Loc, diag::err_array_star_in_function_definition); 11232 } 11233 11234 /// CheckParmsForFunctionDef - Check that the parameters of the given 11235 /// function are appropriate for the definition of a function. This 11236 /// takes care of any checks that cannot be performed on the 11237 /// declaration itself, e.g., that the types of each of the function 11238 /// parameters are complete. 11239 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 11240 bool CheckParameterNames) { 11241 bool HasInvalidParm = false; 11242 for (ParmVarDecl *Param : Parameters) { 11243 // C99 6.7.5.3p4: the parameters in a parameter type list in a 11244 // function declarator that is part of a function definition of 11245 // that function shall not have incomplete type. 11246 // 11247 // This is also C++ [dcl.fct]p6. 11248 if (!Param->isInvalidDecl() && 11249 RequireCompleteType(Param->getLocation(), Param->getType(), 11250 diag::err_typecheck_decl_incomplete_type)) { 11251 Param->setInvalidDecl(); 11252 HasInvalidParm = true; 11253 } 11254 11255 // C99 6.9.1p5: If the declarator includes a parameter type list, the 11256 // declaration of each parameter shall include an identifier. 11257 if (CheckParameterNames && 11258 Param->getIdentifier() == nullptr && 11259 !Param->isImplicit() && 11260 !getLangOpts().CPlusPlus) 11261 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 11262 11263 // C99 6.7.5.3p12: 11264 // If the function declarator is not part of a definition of that 11265 // function, parameters may have incomplete type and may use the [*] 11266 // notation in their sequences of declarator specifiers to specify 11267 // variable length array types. 11268 QualType PType = Param->getOriginalType(); 11269 // FIXME: This diagnostic should point the '[*]' if source-location 11270 // information is added for it. 11271 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 11272 11273 // If the parameter is a c++ class type and it has to be destructed in the 11274 // callee function, declare the destructor so that it can be called by the 11275 // callee function. Do not perform any direct access check on the dtor here. 11276 if (!Param->isInvalidDecl()) { 11277 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 11278 if (!ClassDecl->isInvalidDecl() && 11279 !ClassDecl->hasIrrelevantDestructor() && 11280 !ClassDecl->isDependentContext() && 11281 ClassDecl->isParamDestroyedInCallee()) { 11282 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 11283 MarkFunctionReferenced(Param->getLocation(), Destructor); 11284 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 11285 } 11286 } 11287 } 11288 11289 // Parameters with the pass_object_size attribute only need to be marked 11290 // constant at function definitions. Because we lack information about 11291 // whether we're on a declaration or definition when we're instantiating the 11292 // attribute, we need to check for constness here. 11293 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 11294 if (!Param->getType().isConstQualified()) 11295 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 11296 << Attr->getSpelling() << 1; 11297 } 11298 11299 return HasInvalidParm; 11300 } 11301 11302 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr 11303 /// or MemberExpr. 11304 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign, 11305 ASTContext &Context) { 11306 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 11307 return Context.getDeclAlign(DRE->getDecl()); 11308 11309 if (const auto *ME = dyn_cast<MemberExpr>(E)) 11310 return Context.getDeclAlign(ME->getMemberDecl()); 11311 11312 return TypeAlign; 11313 } 11314 11315 /// CheckCastAlign - Implements -Wcast-align, which warns when a 11316 /// pointer cast increases the alignment requirements. 11317 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 11318 // This is actually a lot of work to potentially be doing on every 11319 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 11320 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 11321 return; 11322 11323 // Ignore dependent types. 11324 if (T->isDependentType() || Op->getType()->isDependentType()) 11325 return; 11326 11327 // Require that the destination be a pointer type. 11328 const PointerType *DestPtr = T->getAs<PointerType>(); 11329 if (!DestPtr) return; 11330 11331 // If the destination has alignment 1, we're done. 11332 QualType DestPointee = DestPtr->getPointeeType(); 11333 if (DestPointee->isIncompleteType()) return; 11334 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 11335 if (DestAlign.isOne()) return; 11336 11337 // Require that the source be a pointer type. 11338 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 11339 if (!SrcPtr) return; 11340 QualType SrcPointee = SrcPtr->getPointeeType(); 11341 11342 // Whitelist casts from cv void*. We already implicitly 11343 // whitelisted casts to cv void*, since they have alignment 1. 11344 // Also whitelist casts involving incomplete types, which implicitly 11345 // includes 'void'. 11346 if (SrcPointee->isIncompleteType()) return; 11347 11348 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee); 11349 11350 if (auto *CE = dyn_cast<CastExpr>(Op)) { 11351 if (CE->getCastKind() == CK_ArrayToPointerDecay) 11352 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context); 11353 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) { 11354 if (UO->getOpcode() == UO_AddrOf) 11355 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context); 11356 } 11357 11358 if (SrcAlign >= DestAlign) return; 11359 11360 Diag(TRange.getBegin(), diag::warn_cast_align) 11361 << Op->getType() << T 11362 << static_cast<unsigned>(SrcAlign.getQuantity()) 11363 << static_cast<unsigned>(DestAlign.getQuantity()) 11364 << TRange << Op->getSourceRange(); 11365 } 11366 11367 /// Check whether this array fits the idiom of a size-one tail padded 11368 /// array member of a struct. 11369 /// 11370 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 11371 /// commonly used to emulate flexible arrays in C89 code. 11372 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 11373 const NamedDecl *ND) { 11374 if (Size != 1 || !ND) return false; 11375 11376 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 11377 if (!FD) return false; 11378 11379 // Don't consider sizes resulting from macro expansions or template argument 11380 // substitution to form C89 tail-padded arrays. 11381 11382 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 11383 while (TInfo) { 11384 TypeLoc TL = TInfo->getTypeLoc(); 11385 // Look through typedefs. 11386 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 11387 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 11388 TInfo = TDL->getTypeSourceInfo(); 11389 continue; 11390 } 11391 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 11392 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 11393 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 11394 return false; 11395 } 11396 break; 11397 } 11398 11399 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 11400 if (!RD) return false; 11401 if (RD->isUnion()) return false; 11402 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 11403 if (!CRD->isStandardLayout()) return false; 11404 } 11405 11406 // See if this is the last field decl in the record. 11407 const Decl *D = FD; 11408 while ((D = D->getNextDeclInContext())) 11409 if (isa<FieldDecl>(D)) 11410 return false; 11411 return true; 11412 } 11413 11414 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 11415 const ArraySubscriptExpr *ASE, 11416 bool AllowOnePastEnd, bool IndexNegated) { 11417 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 11418 if (IndexExpr->isValueDependent()) 11419 return; 11420 11421 const Type *EffectiveType = 11422 BaseExpr->getType()->getPointeeOrArrayElementType(); 11423 BaseExpr = BaseExpr->IgnoreParenCasts(); 11424 const ConstantArrayType *ArrayTy = 11425 Context.getAsConstantArrayType(BaseExpr->getType()); 11426 if (!ArrayTy) 11427 return; 11428 11429 llvm::APSInt index; 11430 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects)) 11431 return; 11432 if (IndexNegated) 11433 index = -index; 11434 11435 const NamedDecl *ND = nullptr; 11436 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 11437 ND = DRE->getDecl(); 11438 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 11439 ND = ME->getMemberDecl(); 11440 11441 if (index.isUnsigned() || !index.isNegative()) { 11442 llvm::APInt size = ArrayTy->getSize(); 11443 if (!size.isStrictlyPositive()) 11444 return; 11445 11446 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType(); 11447 if (BaseType != EffectiveType) { 11448 // Make sure we're comparing apples to apples when comparing index to size 11449 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 11450 uint64_t array_typesize = Context.getTypeSize(BaseType); 11451 // Handle ptrarith_typesize being zero, such as when casting to void* 11452 if (!ptrarith_typesize) ptrarith_typesize = 1; 11453 if (ptrarith_typesize != array_typesize) { 11454 // There's a cast to a different size type involved 11455 uint64_t ratio = array_typesize / ptrarith_typesize; 11456 // TODO: Be smarter about handling cases where array_typesize is not a 11457 // multiple of ptrarith_typesize 11458 if (ptrarith_typesize * ratio == array_typesize) 11459 size *= llvm::APInt(size.getBitWidth(), ratio); 11460 } 11461 } 11462 11463 if (size.getBitWidth() > index.getBitWidth()) 11464 index = index.zext(size.getBitWidth()); 11465 else if (size.getBitWidth() < index.getBitWidth()) 11466 size = size.zext(index.getBitWidth()); 11467 11468 // For array subscripting the index must be less than size, but for pointer 11469 // arithmetic also allow the index (offset) to be equal to size since 11470 // computing the next address after the end of the array is legal and 11471 // commonly done e.g. in C++ iterators and range-based for loops. 11472 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 11473 return; 11474 11475 // Also don't warn for arrays of size 1 which are members of some 11476 // structure. These are often used to approximate flexible arrays in C89 11477 // code. 11478 if (IsTailPaddedMemberArray(*this, size, ND)) 11479 return; 11480 11481 // Suppress the warning if the subscript expression (as identified by the 11482 // ']' location) and the index expression are both from macro expansions 11483 // within a system header. 11484 if (ASE) { 11485 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 11486 ASE->getRBracketLoc()); 11487 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 11488 SourceLocation IndexLoc = SourceMgr.getSpellingLoc( 11489 IndexExpr->getLocStart()); 11490 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 11491 return; 11492 } 11493 } 11494 11495 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 11496 if (ASE) 11497 DiagID = diag::warn_array_index_exceeds_bounds; 11498 11499 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 11500 PDiag(DiagID) << index.toString(10, true) 11501 << size.toString(10, true) 11502 << (unsigned)size.getLimitedValue(~0U) 11503 << IndexExpr->getSourceRange()); 11504 } else { 11505 unsigned DiagID = diag::warn_array_index_precedes_bounds; 11506 if (!ASE) { 11507 DiagID = diag::warn_ptr_arith_precedes_bounds; 11508 if (index.isNegative()) index = -index; 11509 } 11510 11511 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 11512 PDiag(DiagID) << index.toString(10, true) 11513 << IndexExpr->getSourceRange()); 11514 } 11515 11516 if (!ND) { 11517 // Try harder to find a NamedDecl to point at in the note. 11518 while (const ArraySubscriptExpr *ASE = 11519 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 11520 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 11521 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 11522 ND = DRE->getDecl(); 11523 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 11524 ND = ME->getMemberDecl(); 11525 } 11526 11527 if (ND) 11528 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr, 11529 PDiag(diag::note_array_index_out_of_bounds) 11530 << ND->getDeclName()); 11531 } 11532 11533 void Sema::CheckArrayAccess(const Expr *expr) { 11534 int AllowOnePastEnd = 0; 11535 while (expr) { 11536 expr = expr->IgnoreParenImpCasts(); 11537 switch (expr->getStmtClass()) { 11538 case Stmt::ArraySubscriptExprClass: { 11539 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 11540 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 11541 AllowOnePastEnd > 0); 11542 expr = ASE->getBase(); 11543 break; 11544 } 11545 case Stmt::MemberExprClass: { 11546 expr = cast<MemberExpr>(expr)->getBase(); 11547 break; 11548 } 11549 case Stmt::OMPArraySectionExprClass: { 11550 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 11551 if (ASE->getLowerBound()) 11552 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 11553 /*ASE=*/nullptr, AllowOnePastEnd > 0); 11554 return; 11555 } 11556 case Stmt::UnaryOperatorClass: { 11557 // Only unwrap the * and & unary operators 11558 const UnaryOperator *UO = cast<UnaryOperator>(expr); 11559 expr = UO->getSubExpr(); 11560 switch (UO->getOpcode()) { 11561 case UO_AddrOf: 11562 AllowOnePastEnd++; 11563 break; 11564 case UO_Deref: 11565 AllowOnePastEnd--; 11566 break; 11567 default: 11568 return; 11569 } 11570 break; 11571 } 11572 case Stmt::ConditionalOperatorClass: { 11573 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 11574 if (const Expr *lhs = cond->getLHS()) 11575 CheckArrayAccess(lhs); 11576 if (const Expr *rhs = cond->getRHS()) 11577 CheckArrayAccess(rhs); 11578 return; 11579 } 11580 case Stmt::CXXOperatorCallExprClass: { 11581 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 11582 for (const auto *Arg : OCE->arguments()) 11583 CheckArrayAccess(Arg); 11584 return; 11585 } 11586 default: 11587 return; 11588 } 11589 } 11590 } 11591 11592 //===--- CHECK: Objective-C retain cycles ----------------------------------// 11593 11594 namespace { 11595 11596 struct RetainCycleOwner { 11597 VarDecl *Variable = nullptr; 11598 SourceRange Range; 11599 SourceLocation Loc; 11600 bool Indirect = false; 11601 11602 RetainCycleOwner() = default; 11603 11604 void setLocsFrom(Expr *e) { 11605 Loc = e->getExprLoc(); 11606 Range = e->getSourceRange(); 11607 } 11608 }; 11609 11610 } // namespace 11611 11612 /// Consider whether capturing the given variable can possibly lead to 11613 /// a retain cycle. 11614 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 11615 // In ARC, it's captured strongly iff the variable has __strong 11616 // lifetime. In MRR, it's captured strongly if the variable is 11617 // __block and has an appropriate type. 11618 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 11619 return false; 11620 11621 owner.Variable = var; 11622 if (ref) 11623 owner.setLocsFrom(ref); 11624 return true; 11625 } 11626 11627 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 11628 while (true) { 11629 e = e->IgnoreParens(); 11630 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 11631 switch (cast->getCastKind()) { 11632 case CK_BitCast: 11633 case CK_LValueBitCast: 11634 case CK_LValueToRValue: 11635 case CK_ARCReclaimReturnedObject: 11636 e = cast->getSubExpr(); 11637 continue; 11638 11639 default: 11640 return false; 11641 } 11642 } 11643 11644 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 11645 ObjCIvarDecl *ivar = ref->getDecl(); 11646 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 11647 return false; 11648 11649 // Try to find a retain cycle in the base. 11650 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 11651 return false; 11652 11653 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 11654 owner.Indirect = true; 11655 return true; 11656 } 11657 11658 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 11659 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 11660 if (!var) return false; 11661 return considerVariable(var, ref, owner); 11662 } 11663 11664 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 11665 if (member->isArrow()) return false; 11666 11667 // Don't count this as an indirect ownership. 11668 e = member->getBase(); 11669 continue; 11670 } 11671 11672 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 11673 // Only pay attention to pseudo-objects on property references. 11674 ObjCPropertyRefExpr *pre 11675 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 11676 ->IgnoreParens()); 11677 if (!pre) return false; 11678 if (pre->isImplicitProperty()) return false; 11679 ObjCPropertyDecl *property = pre->getExplicitProperty(); 11680 if (!property->isRetaining() && 11681 !(property->getPropertyIvarDecl() && 11682 property->getPropertyIvarDecl()->getType() 11683 .getObjCLifetime() == Qualifiers::OCL_Strong)) 11684 return false; 11685 11686 owner.Indirect = true; 11687 if (pre->isSuperReceiver()) { 11688 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 11689 if (!owner.Variable) 11690 return false; 11691 owner.Loc = pre->getLocation(); 11692 owner.Range = pre->getSourceRange(); 11693 return true; 11694 } 11695 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 11696 ->getSourceExpr()); 11697 continue; 11698 } 11699 11700 // Array ivars? 11701 11702 return false; 11703 } 11704 } 11705 11706 namespace { 11707 11708 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 11709 ASTContext &Context; 11710 VarDecl *Variable; 11711 Expr *Capturer = nullptr; 11712 bool VarWillBeReased = false; 11713 11714 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 11715 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 11716 Context(Context), Variable(variable) {} 11717 11718 void VisitDeclRefExpr(DeclRefExpr *ref) { 11719 if (ref->getDecl() == Variable && !Capturer) 11720 Capturer = ref; 11721 } 11722 11723 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 11724 if (Capturer) return; 11725 Visit(ref->getBase()); 11726 if (Capturer && ref->isFreeIvar()) 11727 Capturer = ref; 11728 } 11729 11730 void VisitBlockExpr(BlockExpr *block) { 11731 // Look inside nested blocks 11732 if (block->getBlockDecl()->capturesVariable(Variable)) 11733 Visit(block->getBlockDecl()->getBody()); 11734 } 11735 11736 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 11737 if (Capturer) return; 11738 if (OVE->getSourceExpr()) 11739 Visit(OVE->getSourceExpr()); 11740 } 11741 11742 void VisitBinaryOperator(BinaryOperator *BinOp) { 11743 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 11744 return; 11745 Expr *LHS = BinOp->getLHS(); 11746 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 11747 if (DRE->getDecl() != Variable) 11748 return; 11749 if (Expr *RHS = BinOp->getRHS()) { 11750 RHS = RHS->IgnoreParenCasts(); 11751 llvm::APSInt Value; 11752 VarWillBeReased = 11753 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0); 11754 } 11755 } 11756 } 11757 }; 11758 11759 } // namespace 11760 11761 /// Check whether the given argument is a block which captures a 11762 /// variable. 11763 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 11764 assert(owner.Variable && owner.Loc.isValid()); 11765 11766 e = e->IgnoreParenCasts(); 11767 11768 // Look through [^{...} copy] and Block_copy(^{...}). 11769 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 11770 Selector Cmd = ME->getSelector(); 11771 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 11772 e = ME->getInstanceReceiver(); 11773 if (!e) 11774 return nullptr; 11775 e = e->IgnoreParenCasts(); 11776 } 11777 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 11778 if (CE->getNumArgs() == 1) { 11779 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 11780 if (Fn) { 11781 const IdentifierInfo *FnI = Fn->getIdentifier(); 11782 if (FnI && FnI->isStr("_Block_copy")) { 11783 e = CE->getArg(0)->IgnoreParenCasts(); 11784 } 11785 } 11786 } 11787 } 11788 11789 BlockExpr *block = dyn_cast<BlockExpr>(e); 11790 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 11791 return nullptr; 11792 11793 FindCaptureVisitor visitor(S.Context, owner.Variable); 11794 visitor.Visit(block->getBlockDecl()->getBody()); 11795 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 11796 } 11797 11798 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 11799 RetainCycleOwner &owner) { 11800 assert(capturer); 11801 assert(owner.Variable && owner.Loc.isValid()); 11802 11803 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 11804 << owner.Variable << capturer->getSourceRange(); 11805 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 11806 << owner.Indirect << owner.Range; 11807 } 11808 11809 /// Check for a keyword selector that starts with the word 'add' or 11810 /// 'set'. 11811 static bool isSetterLikeSelector(Selector sel) { 11812 if (sel.isUnarySelector()) return false; 11813 11814 StringRef str = sel.getNameForSlot(0); 11815 while (!str.empty() && str.front() == '_') str = str.substr(1); 11816 if (str.startswith("set")) 11817 str = str.substr(3); 11818 else if (str.startswith("add")) { 11819 // Specially whitelist 'addOperationWithBlock:'. 11820 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 11821 return false; 11822 str = str.substr(3); 11823 } 11824 else 11825 return false; 11826 11827 if (str.empty()) return true; 11828 return !isLowercase(str.front()); 11829 } 11830 11831 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 11832 ObjCMessageExpr *Message) { 11833 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 11834 Message->getReceiverInterface(), 11835 NSAPI::ClassId_NSMutableArray); 11836 if (!IsMutableArray) { 11837 return None; 11838 } 11839 11840 Selector Sel = Message->getSelector(); 11841 11842 Optional<NSAPI::NSArrayMethodKind> MKOpt = 11843 S.NSAPIObj->getNSArrayMethodKind(Sel); 11844 if (!MKOpt) { 11845 return None; 11846 } 11847 11848 NSAPI::NSArrayMethodKind MK = *MKOpt; 11849 11850 switch (MK) { 11851 case NSAPI::NSMutableArr_addObject: 11852 case NSAPI::NSMutableArr_insertObjectAtIndex: 11853 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 11854 return 0; 11855 case NSAPI::NSMutableArr_replaceObjectAtIndex: 11856 return 1; 11857 11858 default: 11859 return None; 11860 } 11861 11862 return None; 11863 } 11864 11865 static 11866 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 11867 ObjCMessageExpr *Message) { 11868 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 11869 Message->getReceiverInterface(), 11870 NSAPI::ClassId_NSMutableDictionary); 11871 if (!IsMutableDictionary) { 11872 return None; 11873 } 11874 11875 Selector Sel = Message->getSelector(); 11876 11877 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 11878 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 11879 if (!MKOpt) { 11880 return None; 11881 } 11882 11883 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 11884 11885 switch (MK) { 11886 case NSAPI::NSMutableDict_setObjectForKey: 11887 case NSAPI::NSMutableDict_setValueForKey: 11888 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 11889 return 0; 11890 11891 default: 11892 return None; 11893 } 11894 11895 return None; 11896 } 11897 11898 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 11899 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 11900 Message->getReceiverInterface(), 11901 NSAPI::ClassId_NSMutableSet); 11902 11903 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 11904 Message->getReceiverInterface(), 11905 NSAPI::ClassId_NSMutableOrderedSet); 11906 if (!IsMutableSet && !IsMutableOrderedSet) { 11907 return None; 11908 } 11909 11910 Selector Sel = Message->getSelector(); 11911 11912 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 11913 if (!MKOpt) { 11914 return None; 11915 } 11916 11917 NSAPI::NSSetMethodKind MK = *MKOpt; 11918 11919 switch (MK) { 11920 case NSAPI::NSMutableSet_addObject: 11921 case NSAPI::NSOrderedSet_setObjectAtIndex: 11922 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 11923 case NSAPI::NSOrderedSet_insertObjectAtIndex: 11924 return 0; 11925 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 11926 return 1; 11927 } 11928 11929 return None; 11930 } 11931 11932 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 11933 if (!Message->isInstanceMessage()) { 11934 return; 11935 } 11936 11937 Optional<int> ArgOpt; 11938 11939 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 11940 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 11941 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 11942 return; 11943 } 11944 11945 int ArgIndex = *ArgOpt; 11946 11947 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 11948 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 11949 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 11950 } 11951 11952 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 11953 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 11954 if (ArgRE->isObjCSelfExpr()) { 11955 Diag(Message->getSourceRange().getBegin(), 11956 diag::warn_objc_circular_container) 11957 << ArgRE->getDecl() << StringRef("'super'"); 11958 } 11959 } 11960 } else { 11961 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 11962 11963 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 11964 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 11965 } 11966 11967 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 11968 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 11969 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 11970 ValueDecl *Decl = ReceiverRE->getDecl(); 11971 Diag(Message->getSourceRange().getBegin(), 11972 diag::warn_objc_circular_container) 11973 << Decl << Decl; 11974 if (!ArgRE->isObjCSelfExpr()) { 11975 Diag(Decl->getLocation(), 11976 diag::note_objc_circular_container_declared_here) 11977 << Decl; 11978 } 11979 } 11980 } 11981 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 11982 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 11983 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 11984 ObjCIvarDecl *Decl = IvarRE->getDecl(); 11985 Diag(Message->getSourceRange().getBegin(), 11986 diag::warn_objc_circular_container) 11987 << Decl << Decl; 11988 Diag(Decl->getLocation(), 11989 diag::note_objc_circular_container_declared_here) 11990 << Decl; 11991 } 11992 } 11993 } 11994 } 11995 } 11996 11997 /// Check a message send to see if it's likely to cause a retain cycle. 11998 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 11999 // Only check instance methods whose selector looks like a setter. 12000 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 12001 return; 12002 12003 // Try to find a variable that the receiver is strongly owned by. 12004 RetainCycleOwner owner; 12005 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 12006 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 12007 return; 12008 } else { 12009 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 12010 owner.Variable = getCurMethodDecl()->getSelfDecl(); 12011 owner.Loc = msg->getSuperLoc(); 12012 owner.Range = msg->getSuperLoc(); 12013 } 12014 12015 // Check whether the receiver is captured by any of the arguments. 12016 const ObjCMethodDecl *MD = msg->getMethodDecl(); 12017 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 12018 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 12019 // noescape blocks should not be retained by the method. 12020 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 12021 continue; 12022 return diagnoseRetainCycle(*this, capturer, owner); 12023 } 12024 } 12025 } 12026 12027 /// Check a property assign to see if it's likely to cause a retain cycle. 12028 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 12029 RetainCycleOwner owner; 12030 if (!findRetainCycleOwner(*this, receiver, owner)) 12031 return; 12032 12033 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 12034 diagnoseRetainCycle(*this, capturer, owner); 12035 } 12036 12037 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 12038 RetainCycleOwner Owner; 12039 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 12040 return; 12041 12042 // Because we don't have an expression for the variable, we have to set the 12043 // location explicitly here. 12044 Owner.Loc = Var->getLocation(); 12045 Owner.Range = Var->getSourceRange(); 12046 12047 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 12048 diagnoseRetainCycle(*this, Capturer, Owner); 12049 } 12050 12051 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 12052 Expr *RHS, bool isProperty) { 12053 // Check if RHS is an Objective-C object literal, which also can get 12054 // immediately zapped in a weak reference. Note that we explicitly 12055 // allow ObjCStringLiterals, since those are designed to never really die. 12056 RHS = RHS->IgnoreParenImpCasts(); 12057 12058 // This enum needs to match with the 'select' in 12059 // warn_objc_arc_literal_assign (off-by-1). 12060 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 12061 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 12062 return false; 12063 12064 S.Diag(Loc, diag::warn_arc_literal_assign) 12065 << (unsigned) Kind 12066 << (isProperty ? 0 : 1) 12067 << RHS->getSourceRange(); 12068 12069 return true; 12070 } 12071 12072 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 12073 Qualifiers::ObjCLifetime LT, 12074 Expr *RHS, bool isProperty) { 12075 // Strip off any implicit cast added to get to the one ARC-specific. 12076 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 12077 if (cast->getCastKind() == CK_ARCConsumeObject) { 12078 S.Diag(Loc, diag::warn_arc_retained_assign) 12079 << (LT == Qualifiers::OCL_ExplicitNone) 12080 << (isProperty ? 0 : 1) 12081 << RHS->getSourceRange(); 12082 return true; 12083 } 12084 RHS = cast->getSubExpr(); 12085 } 12086 12087 if (LT == Qualifiers::OCL_Weak && 12088 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 12089 return true; 12090 12091 return false; 12092 } 12093 12094 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 12095 QualType LHS, Expr *RHS) { 12096 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 12097 12098 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 12099 return false; 12100 12101 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 12102 return true; 12103 12104 return false; 12105 } 12106 12107 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 12108 Expr *LHS, Expr *RHS) { 12109 QualType LHSType; 12110 // PropertyRef on LHS type need be directly obtained from 12111 // its declaration as it has a PseudoType. 12112 ObjCPropertyRefExpr *PRE 12113 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 12114 if (PRE && !PRE->isImplicitProperty()) { 12115 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 12116 if (PD) 12117 LHSType = PD->getType(); 12118 } 12119 12120 if (LHSType.isNull()) 12121 LHSType = LHS->getType(); 12122 12123 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 12124 12125 if (LT == Qualifiers::OCL_Weak) { 12126 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 12127 getCurFunction()->markSafeWeakUse(LHS); 12128 } 12129 12130 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 12131 return; 12132 12133 // FIXME. Check for other life times. 12134 if (LT != Qualifiers::OCL_None) 12135 return; 12136 12137 if (PRE) { 12138 if (PRE->isImplicitProperty()) 12139 return; 12140 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 12141 if (!PD) 12142 return; 12143 12144 unsigned Attributes = PD->getPropertyAttributes(); 12145 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) { 12146 // when 'assign' attribute was not explicitly specified 12147 // by user, ignore it and rely on property type itself 12148 // for lifetime info. 12149 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 12150 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) && 12151 LHSType->isObjCRetainableType()) 12152 return; 12153 12154 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 12155 if (cast->getCastKind() == CK_ARCConsumeObject) { 12156 Diag(Loc, diag::warn_arc_retained_property_assign) 12157 << RHS->getSourceRange(); 12158 return; 12159 } 12160 RHS = cast->getSubExpr(); 12161 } 12162 } 12163 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) { 12164 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 12165 return; 12166 } 12167 } 12168 } 12169 12170 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 12171 12172 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 12173 SourceLocation StmtLoc, 12174 const NullStmt *Body) { 12175 // Do not warn if the body is a macro that expands to nothing, e.g: 12176 // 12177 // #define CALL(x) 12178 // if (condition) 12179 // CALL(0); 12180 if (Body->hasLeadingEmptyMacro()) 12181 return false; 12182 12183 // Get line numbers of statement and body. 12184 bool StmtLineInvalid; 12185 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 12186 &StmtLineInvalid); 12187 if (StmtLineInvalid) 12188 return false; 12189 12190 bool BodyLineInvalid; 12191 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 12192 &BodyLineInvalid); 12193 if (BodyLineInvalid) 12194 return false; 12195 12196 // Warn if null statement and body are on the same line. 12197 if (StmtLine != BodyLine) 12198 return false; 12199 12200 return true; 12201 } 12202 12203 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 12204 const Stmt *Body, 12205 unsigned DiagID) { 12206 // Since this is a syntactic check, don't emit diagnostic for template 12207 // instantiations, this just adds noise. 12208 if (CurrentInstantiationScope) 12209 return; 12210 12211 // The body should be a null statement. 12212 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 12213 if (!NBody) 12214 return; 12215 12216 // Do the usual checks. 12217 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 12218 return; 12219 12220 Diag(NBody->getSemiLoc(), DiagID); 12221 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 12222 } 12223 12224 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 12225 const Stmt *PossibleBody) { 12226 assert(!CurrentInstantiationScope); // Ensured by caller 12227 12228 SourceLocation StmtLoc; 12229 const Stmt *Body; 12230 unsigned DiagID; 12231 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 12232 StmtLoc = FS->getRParenLoc(); 12233 Body = FS->getBody(); 12234 DiagID = diag::warn_empty_for_body; 12235 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 12236 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 12237 Body = WS->getBody(); 12238 DiagID = diag::warn_empty_while_body; 12239 } else 12240 return; // Neither `for' nor `while'. 12241 12242 // The body should be a null statement. 12243 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 12244 if (!NBody) 12245 return; 12246 12247 // Skip expensive checks if diagnostic is disabled. 12248 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 12249 return; 12250 12251 // Do the usual checks. 12252 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 12253 return; 12254 12255 // `for(...);' and `while(...);' are popular idioms, so in order to keep 12256 // noise level low, emit diagnostics only if for/while is followed by a 12257 // CompoundStmt, e.g.: 12258 // for (int i = 0; i < n; i++); 12259 // { 12260 // a(i); 12261 // } 12262 // or if for/while is followed by a statement with more indentation 12263 // than for/while itself: 12264 // for (int i = 0; i < n; i++); 12265 // a(i); 12266 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 12267 if (!ProbableTypo) { 12268 bool BodyColInvalid; 12269 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 12270 PossibleBody->getLocStart(), 12271 &BodyColInvalid); 12272 if (BodyColInvalid) 12273 return; 12274 12275 bool StmtColInvalid; 12276 unsigned StmtCol = SourceMgr.getPresumedColumnNumber( 12277 S->getLocStart(), 12278 &StmtColInvalid); 12279 if (StmtColInvalid) 12280 return; 12281 12282 if (BodyCol > StmtCol) 12283 ProbableTypo = true; 12284 } 12285 12286 if (ProbableTypo) { 12287 Diag(NBody->getSemiLoc(), DiagID); 12288 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 12289 } 12290 } 12291 12292 //===--- CHECK: Warn on self move with std::move. -------------------------===// 12293 12294 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 12295 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 12296 SourceLocation OpLoc) { 12297 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 12298 return; 12299 12300 if (inTemplateInstantiation()) 12301 return; 12302 12303 // Strip parens and casts away. 12304 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 12305 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 12306 12307 // Check for a call expression 12308 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 12309 if (!CE || CE->getNumArgs() != 1) 12310 return; 12311 12312 // Check for a call to std::move 12313 if (!CE->isCallToStdMove()) 12314 return; 12315 12316 // Get argument from std::move 12317 RHSExpr = CE->getArg(0); 12318 12319 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 12320 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 12321 12322 // Two DeclRefExpr's, check that the decls are the same. 12323 if (LHSDeclRef && RHSDeclRef) { 12324 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 12325 return; 12326 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 12327 RHSDeclRef->getDecl()->getCanonicalDecl()) 12328 return; 12329 12330 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 12331 << LHSExpr->getSourceRange() 12332 << RHSExpr->getSourceRange(); 12333 return; 12334 } 12335 12336 // Member variables require a different approach to check for self moves. 12337 // MemberExpr's are the same if every nested MemberExpr refers to the same 12338 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 12339 // the base Expr's are CXXThisExpr's. 12340 const Expr *LHSBase = LHSExpr; 12341 const Expr *RHSBase = RHSExpr; 12342 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 12343 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 12344 if (!LHSME || !RHSME) 12345 return; 12346 12347 while (LHSME && RHSME) { 12348 if (LHSME->getMemberDecl()->getCanonicalDecl() != 12349 RHSME->getMemberDecl()->getCanonicalDecl()) 12350 return; 12351 12352 LHSBase = LHSME->getBase(); 12353 RHSBase = RHSME->getBase(); 12354 LHSME = dyn_cast<MemberExpr>(LHSBase); 12355 RHSME = dyn_cast<MemberExpr>(RHSBase); 12356 } 12357 12358 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 12359 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 12360 if (LHSDeclRef && RHSDeclRef) { 12361 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 12362 return; 12363 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 12364 RHSDeclRef->getDecl()->getCanonicalDecl()) 12365 return; 12366 12367 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 12368 << LHSExpr->getSourceRange() 12369 << RHSExpr->getSourceRange(); 12370 return; 12371 } 12372 12373 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 12374 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 12375 << LHSExpr->getSourceRange() 12376 << RHSExpr->getSourceRange(); 12377 } 12378 12379 //===--- Layout compatibility ----------------------------------------------// 12380 12381 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 12382 12383 /// Check if two enumeration types are layout-compatible. 12384 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 12385 // C++11 [dcl.enum] p8: 12386 // Two enumeration types are layout-compatible if they have the same 12387 // underlying type. 12388 return ED1->isComplete() && ED2->isComplete() && 12389 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 12390 } 12391 12392 /// Check if two fields are layout-compatible. 12393 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 12394 FieldDecl *Field2) { 12395 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 12396 return false; 12397 12398 if (Field1->isBitField() != Field2->isBitField()) 12399 return false; 12400 12401 if (Field1->isBitField()) { 12402 // Make sure that the bit-fields are the same length. 12403 unsigned Bits1 = Field1->getBitWidthValue(C); 12404 unsigned Bits2 = Field2->getBitWidthValue(C); 12405 12406 if (Bits1 != Bits2) 12407 return false; 12408 } 12409 12410 return true; 12411 } 12412 12413 /// Check if two standard-layout structs are layout-compatible. 12414 /// (C++11 [class.mem] p17) 12415 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 12416 RecordDecl *RD2) { 12417 // If both records are C++ classes, check that base classes match. 12418 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 12419 // If one of records is a CXXRecordDecl we are in C++ mode, 12420 // thus the other one is a CXXRecordDecl, too. 12421 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 12422 // Check number of base classes. 12423 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 12424 return false; 12425 12426 // Check the base classes. 12427 for (CXXRecordDecl::base_class_const_iterator 12428 Base1 = D1CXX->bases_begin(), 12429 BaseEnd1 = D1CXX->bases_end(), 12430 Base2 = D2CXX->bases_begin(); 12431 Base1 != BaseEnd1; 12432 ++Base1, ++Base2) { 12433 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 12434 return false; 12435 } 12436 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 12437 // If only RD2 is a C++ class, it should have zero base classes. 12438 if (D2CXX->getNumBases() > 0) 12439 return false; 12440 } 12441 12442 // Check the fields. 12443 RecordDecl::field_iterator Field2 = RD2->field_begin(), 12444 Field2End = RD2->field_end(), 12445 Field1 = RD1->field_begin(), 12446 Field1End = RD1->field_end(); 12447 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 12448 if (!isLayoutCompatible(C, *Field1, *Field2)) 12449 return false; 12450 } 12451 if (Field1 != Field1End || Field2 != Field2End) 12452 return false; 12453 12454 return true; 12455 } 12456 12457 /// Check if two standard-layout unions are layout-compatible. 12458 /// (C++11 [class.mem] p18) 12459 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 12460 RecordDecl *RD2) { 12461 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 12462 for (auto *Field2 : RD2->fields()) 12463 UnmatchedFields.insert(Field2); 12464 12465 for (auto *Field1 : RD1->fields()) { 12466 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 12467 I = UnmatchedFields.begin(), 12468 E = UnmatchedFields.end(); 12469 12470 for ( ; I != E; ++I) { 12471 if (isLayoutCompatible(C, Field1, *I)) { 12472 bool Result = UnmatchedFields.erase(*I); 12473 (void) Result; 12474 assert(Result); 12475 break; 12476 } 12477 } 12478 if (I == E) 12479 return false; 12480 } 12481 12482 return UnmatchedFields.empty(); 12483 } 12484 12485 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 12486 RecordDecl *RD2) { 12487 if (RD1->isUnion() != RD2->isUnion()) 12488 return false; 12489 12490 if (RD1->isUnion()) 12491 return isLayoutCompatibleUnion(C, RD1, RD2); 12492 else 12493 return isLayoutCompatibleStruct(C, RD1, RD2); 12494 } 12495 12496 /// Check if two types are layout-compatible in C++11 sense. 12497 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 12498 if (T1.isNull() || T2.isNull()) 12499 return false; 12500 12501 // C++11 [basic.types] p11: 12502 // If two types T1 and T2 are the same type, then T1 and T2 are 12503 // layout-compatible types. 12504 if (C.hasSameType(T1, T2)) 12505 return true; 12506 12507 T1 = T1.getCanonicalType().getUnqualifiedType(); 12508 T2 = T2.getCanonicalType().getUnqualifiedType(); 12509 12510 const Type::TypeClass TC1 = T1->getTypeClass(); 12511 const Type::TypeClass TC2 = T2->getTypeClass(); 12512 12513 if (TC1 != TC2) 12514 return false; 12515 12516 if (TC1 == Type::Enum) { 12517 return isLayoutCompatible(C, 12518 cast<EnumType>(T1)->getDecl(), 12519 cast<EnumType>(T2)->getDecl()); 12520 } else if (TC1 == Type::Record) { 12521 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 12522 return false; 12523 12524 return isLayoutCompatible(C, 12525 cast<RecordType>(T1)->getDecl(), 12526 cast<RecordType>(T2)->getDecl()); 12527 } 12528 12529 return false; 12530 } 12531 12532 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 12533 12534 /// Given a type tag expression find the type tag itself. 12535 /// 12536 /// \param TypeExpr Type tag expression, as it appears in user's code. 12537 /// 12538 /// \param VD Declaration of an identifier that appears in a type tag. 12539 /// 12540 /// \param MagicValue Type tag magic value. 12541 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 12542 const ValueDecl **VD, uint64_t *MagicValue) { 12543 while(true) { 12544 if (!TypeExpr) 12545 return false; 12546 12547 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 12548 12549 switch (TypeExpr->getStmtClass()) { 12550 case Stmt::UnaryOperatorClass: { 12551 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 12552 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 12553 TypeExpr = UO->getSubExpr(); 12554 continue; 12555 } 12556 return false; 12557 } 12558 12559 case Stmt::DeclRefExprClass: { 12560 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 12561 *VD = DRE->getDecl(); 12562 return true; 12563 } 12564 12565 case Stmt::IntegerLiteralClass: { 12566 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 12567 llvm::APInt MagicValueAPInt = IL->getValue(); 12568 if (MagicValueAPInt.getActiveBits() <= 64) { 12569 *MagicValue = MagicValueAPInt.getZExtValue(); 12570 return true; 12571 } else 12572 return false; 12573 } 12574 12575 case Stmt::BinaryConditionalOperatorClass: 12576 case Stmt::ConditionalOperatorClass: { 12577 const AbstractConditionalOperator *ACO = 12578 cast<AbstractConditionalOperator>(TypeExpr); 12579 bool Result; 12580 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) { 12581 if (Result) 12582 TypeExpr = ACO->getTrueExpr(); 12583 else 12584 TypeExpr = ACO->getFalseExpr(); 12585 continue; 12586 } 12587 return false; 12588 } 12589 12590 case Stmt::BinaryOperatorClass: { 12591 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 12592 if (BO->getOpcode() == BO_Comma) { 12593 TypeExpr = BO->getRHS(); 12594 continue; 12595 } 12596 return false; 12597 } 12598 12599 default: 12600 return false; 12601 } 12602 } 12603 } 12604 12605 /// Retrieve the C type corresponding to type tag TypeExpr. 12606 /// 12607 /// \param TypeExpr Expression that specifies a type tag. 12608 /// 12609 /// \param MagicValues Registered magic values. 12610 /// 12611 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 12612 /// kind. 12613 /// 12614 /// \param TypeInfo Information about the corresponding C type. 12615 /// 12616 /// \returns true if the corresponding C type was found. 12617 static bool GetMatchingCType( 12618 const IdentifierInfo *ArgumentKind, 12619 const Expr *TypeExpr, const ASTContext &Ctx, 12620 const llvm::DenseMap<Sema::TypeTagMagicValue, 12621 Sema::TypeTagData> *MagicValues, 12622 bool &FoundWrongKind, 12623 Sema::TypeTagData &TypeInfo) { 12624 FoundWrongKind = false; 12625 12626 // Variable declaration that has type_tag_for_datatype attribute. 12627 const ValueDecl *VD = nullptr; 12628 12629 uint64_t MagicValue; 12630 12631 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue)) 12632 return false; 12633 12634 if (VD) { 12635 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 12636 if (I->getArgumentKind() != ArgumentKind) { 12637 FoundWrongKind = true; 12638 return false; 12639 } 12640 TypeInfo.Type = I->getMatchingCType(); 12641 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 12642 TypeInfo.MustBeNull = I->getMustBeNull(); 12643 return true; 12644 } 12645 return false; 12646 } 12647 12648 if (!MagicValues) 12649 return false; 12650 12651 llvm::DenseMap<Sema::TypeTagMagicValue, 12652 Sema::TypeTagData>::const_iterator I = 12653 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 12654 if (I == MagicValues->end()) 12655 return false; 12656 12657 TypeInfo = I->second; 12658 return true; 12659 } 12660 12661 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 12662 uint64_t MagicValue, QualType Type, 12663 bool LayoutCompatible, 12664 bool MustBeNull) { 12665 if (!TypeTagForDatatypeMagicValues) 12666 TypeTagForDatatypeMagicValues.reset( 12667 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 12668 12669 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 12670 (*TypeTagForDatatypeMagicValues)[Magic] = 12671 TypeTagData(Type, LayoutCompatible, MustBeNull); 12672 } 12673 12674 static bool IsSameCharType(QualType T1, QualType T2) { 12675 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 12676 if (!BT1) 12677 return false; 12678 12679 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 12680 if (!BT2) 12681 return false; 12682 12683 BuiltinType::Kind T1Kind = BT1->getKind(); 12684 BuiltinType::Kind T2Kind = BT2->getKind(); 12685 12686 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 12687 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 12688 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 12689 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 12690 } 12691 12692 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 12693 const ArrayRef<const Expr *> ExprArgs, 12694 SourceLocation CallSiteLoc) { 12695 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 12696 bool IsPointerAttr = Attr->getIsPointer(); 12697 12698 // Retrieve the argument representing the 'type_tag'. 12699 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 12700 if (TypeTagIdxAST >= ExprArgs.size()) { 12701 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 12702 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 12703 return; 12704 } 12705 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 12706 bool FoundWrongKind; 12707 TypeTagData TypeInfo; 12708 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 12709 TypeTagForDatatypeMagicValues.get(), 12710 FoundWrongKind, TypeInfo)) { 12711 if (FoundWrongKind) 12712 Diag(TypeTagExpr->getExprLoc(), 12713 diag::warn_type_tag_for_datatype_wrong_kind) 12714 << TypeTagExpr->getSourceRange(); 12715 return; 12716 } 12717 12718 // Retrieve the argument representing the 'arg_idx'. 12719 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 12720 if (ArgumentIdxAST >= ExprArgs.size()) { 12721 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 12722 << 1 << Attr->getArgumentIdx().getSourceIndex(); 12723 return; 12724 } 12725 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 12726 if (IsPointerAttr) { 12727 // Skip implicit cast of pointer to `void *' (as a function argument). 12728 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 12729 if (ICE->getType()->isVoidPointerType() && 12730 ICE->getCastKind() == CK_BitCast) 12731 ArgumentExpr = ICE->getSubExpr(); 12732 } 12733 QualType ArgumentType = ArgumentExpr->getType(); 12734 12735 // Passing a `void*' pointer shouldn't trigger a warning. 12736 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 12737 return; 12738 12739 if (TypeInfo.MustBeNull) { 12740 // Type tag with matching void type requires a null pointer. 12741 if (!ArgumentExpr->isNullPointerConstant(Context, 12742 Expr::NPC_ValueDependentIsNotNull)) { 12743 Diag(ArgumentExpr->getExprLoc(), 12744 diag::warn_type_safety_null_pointer_required) 12745 << ArgumentKind->getName() 12746 << ArgumentExpr->getSourceRange() 12747 << TypeTagExpr->getSourceRange(); 12748 } 12749 return; 12750 } 12751 12752 QualType RequiredType = TypeInfo.Type; 12753 if (IsPointerAttr) 12754 RequiredType = Context.getPointerType(RequiredType); 12755 12756 bool mismatch = false; 12757 if (!TypeInfo.LayoutCompatible) { 12758 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 12759 12760 // C++11 [basic.fundamental] p1: 12761 // Plain char, signed char, and unsigned char are three distinct types. 12762 // 12763 // But we treat plain `char' as equivalent to `signed char' or `unsigned 12764 // char' depending on the current char signedness mode. 12765 if (mismatch) 12766 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 12767 RequiredType->getPointeeType())) || 12768 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 12769 mismatch = false; 12770 } else 12771 if (IsPointerAttr) 12772 mismatch = !isLayoutCompatible(Context, 12773 ArgumentType->getPointeeType(), 12774 RequiredType->getPointeeType()); 12775 else 12776 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 12777 12778 if (mismatch) 12779 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 12780 << ArgumentType << ArgumentKind 12781 << TypeInfo.LayoutCompatible << RequiredType 12782 << ArgumentExpr->getSourceRange() 12783 << TypeTagExpr->getSourceRange(); 12784 } 12785 12786 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 12787 CharUnits Alignment) { 12788 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 12789 } 12790 12791 void Sema::DiagnoseMisalignedMembers() { 12792 for (MisalignedMember &m : MisalignedMembers) { 12793 const NamedDecl *ND = m.RD; 12794 if (ND->getName().empty()) { 12795 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 12796 ND = TD; 12797 } 12798 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member) 12799 << m.MD << ND << m.E->getSourceRange(); 12800 } 12801 MisalignedMembers.clear(); 12802 } 12803 12804 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 12805 E = E->IgnoreParens(); 12806 if (!T->isPointerType() && !T->isIntegerType()) 12807 return; 12808 if (isa<UnaryOperator>(E) && 12809 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 12810 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 12811 if (isa<MemberExpr>(Op)) { 12812 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(), 12813 MisalignedMember(Op)); 12814 if (MA != MisalignedMembers.end() && 12815 (T->isIntegerType() || 12816 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 12817 Context.getTypeAlignInChars( 12818 T->getPointeeType()) <= MA->Alignment)))) 12819 MisalignedMembers.erase(MA); 12820 } 12821 } 12822 } 12823 12824 void Sema::RefersToMemberWithReducedAlignment( 12825 Expr *E, 12826 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 12827 Action) { 12828 const auto *ME = dyn_cast<MemberExpr>(E); 12829 if (!ME) 12830 return; 12831 12832 // No need to check expressions with an __unaligned-qualified type. 12833 if (E->getType().getQualifiers().hasUnaligned()) 12834 return; 12835 12836 // For a chain of MemberExpr like "a.b.c.d" this list 12837 // will keep FieldDecl's like [d, c, b]. 12838 SmallVector<FieldDecl *, 4> ReverseMemberChain; 12839 const MemberExpr *TopME = nullptr; 12840 bool AnyIsPacked = false; 12841 do { 12842 QualType BaseType = ME->getBase()->getType(); 12843 if (ME->isArrow()) 12844 BaseType = BaseType->getPointeeType(); 12845 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl(); 12846 if (RD->isInvalidDecl()) 12847 return; 12848 12849 ValueDecl *MD = ME->getMemberDecl(); 12850 auto *FD = dyn_cast<FieldDecl>(MD); 12851 // We do not care about non-data members. 12852 if (!FD || FD->isInvalidDecl()) 12853 return; 12854 12855 AnyIsPacked = 12856 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 12857 ReverseMemberChain.push_back(FD); 12858 12859 TopME = ME; 12860 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 12861 } while (ME); 12862 assert(TopME && "We did not compute a topmost MemberExpr!"); 12863 12864 // Not the scope of this diagnostic. 12865 if (!AnyIsPacked) 12866 return; 12867 12868 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 12869 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 12870 // TODO: The innermost base of the member expression may be too complicated. 12871 // For now, just disregard these cases. This is left for future 12872 // improvement. 12873 if (!DRE && !isa<CXXThisExpr>(TopBase)) 12874 return; 12875 12876 // Alignment expected by the whole expression. 12877 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 12878 12879 // No need to do anything else with this case. 12880 if (ExpectedAlignment.isOne()) 12881 return; 12882 12883 // Synthesize offset of the whole access. 12884 CharUnits Offset; 12885 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 12886 I++) { 12887 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 12888 } 12889 12890 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 12891 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 12892 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 12893 12894 // The base expression of the innermost MemberExpr may give 12895 // stronger guarantees than the class containing the member. 12896 if (DRE && !TopME->isArrow()) { 12897 const ValueDecl *VD = DRE->getDecl(); 12898 if (!VD->getType()->isReferenceType()) 12899 CompleteObjectAlignment = 12900 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 12901 } 12902 12903 // Check if the synthesized offset fulfills the alignment. 12904 if (Offset % ExpectedAlignment != 0 || 12905 // It may fulfill the offset it but the effective alignment may still be 12906 // lower than the expected expression alignment. 12907 CompleteObjectAlignment < ExpectedAlignment) { 12908 // If this happens, we want to determine a sensible culprit of this. 12909 // Intuitively, watching the chain of member expressions from right to 12910 // left, we start with the required alignment (as required by the field 12911 // type) but some packed attribute in that chain has reduced the alignment. 12912 // It may happen that another packed structure increases it again. But if 12913 // we are here such increase has not been enough. So pointing the first 12914 // FieldDecl that either is packed or else its RecordDecl is, 12915 // seems reasonable. 12916 FieldDecl *FD = nullptr; 12917 CharUnits Alignment; 12918 for (FieldDecl *FDI : ReverseMemberChain) { 12919 if (FDI->hasAttr<PackedAttr>() || 12920 FDI->getParent()->hasAttr<PackedAttr>()) { 12921 FD = FDI; 12922 Alignment = std::min( 12923 Context.getTypeAlignInChars(FD->getType()), 12924 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 12925 break; 12926 } 12927 } 12928 assert(FD && "We did not find a packed FieldDecl!"); 12929 Action(E, FD->getParent(), FD, Alignment); 12930 } 12931 } 12932 12933 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 12934 using namespace std::placeholders; 12935 12936 RefersToMemberWithReducedAlignment( 12937 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 12938 _2, _3, _4)); 12939 } 12940