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 ArgNum = 3; 2344 HasRC = true; 2345 break; 2346 case X86::BI__builtin_ia32_addpd512_mask: 2347 case X86::BI__builtin_ia32_addps512_mask: 2348 case X86::BI__builtin_ia32_divpd512_mask: 2349 case X86::BI__builtin_ia32_divps512_mask: 2350 case X86::BI__builtin_ia32_mulpd512_mask: 2351 case X86::BI__builtin_ia32_mulps512_mask: 2352 case X86::BI__builtin_ia32_subpd512_mask: 2353 case X86::BI__builtin_ia32_subps512_mask: 2354 case X86::BI__builtin_ia32_addss_round_mask: 2355 case X86::BI__builtin_ia32_addsd_round_mask: 2356 case X86::BI__builtin_ia32_divss_round_mask: 2357 case X86::BI__builtin_ia32_divsd_round_mask: 2358 case X86::BI__builtin_ia32_mulss_round_mask: 2359 case X86::BI__builtin_ia32_mulsd_round_mask: 2360 case X86::BI__builtin_ia32_subss_round_mask: 2361 case X86::BI__builtin_ia32_subsd_round_mask: 2362 case X86::BI__builtin_ia32_scalefpd512_mask: 2363 case X86::BI__builtin_ia32_scalefps512_mask: 2364 case X86::BI__builtin_ia32_scalefsd_round_mask: 2365 case X86::BI__builtin_ia32_scalefss_round_mask: 2366 case X86::BI__builtin_ia32_getmantpd512_mask: 2367 case X86::BI__builtin_ia32_getmantps512_mask: 2368 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 2369 case X86::BI__builtin_ia32_sqrtsd_round_mask: 2370 case X86::BI__builtin_ia32_sqrtss_round_mask: 2371 case X86::BI__builtin_ia32_vfmaddpd512_mask: 2372 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 2373 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 2374 case X86::BI__builtin_ia32_vfmaddps512_mask: 2375 case X86::BI__builtin_ia32_vfmaddps512_mask3: 2376 case X86::BI__builtin_ia32_vfmaddps512_maskz: 2377 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 2378 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 2379 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 2380 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 2381 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 2382 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 2383 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 2384 case X86::BI__builtin_ia32_vfmsubps512_mask3: 2385 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 2386 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 2387 case X86::BI__builtin_ia32_vfnmaddpd512_mask: 2388 case X86::BI__builtin_ia32_vfnmaddps512_mask: 2389 case X86::BI__builtin_ia32_vfnmsubpd512_mask: 2390 case X86::BI__builtin_ia32_vfnmsubpd512_mask3: 2391 case X86::BI__builtin_ia32_vfnmsubps512_mask: 2392 case X86::BI__builtin_ia32_vfnmsubps512_mask3: 2393 case X86::BI__builtin_ia32_vfmaddsd3_mask: 2394 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 2395 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 2396 case X86::BI__builtin_ia32_vfmaddss3_mask: 2397 case X86::BI__builtin_ia32_vfmaddss3_maskz: 2398 case X86::BI__builtin_ia32_vfmaddss3_mask3: 2399 ArgNum = 4; 2400 HasRC = true; 2401 break; 2402 case X86::BI__builtin_ia32_getmantsd_round_mask: 2403 case X86::BI__builtin_ia32_getmantss_round_mask: 2404 ArgNum = 5; 2405 HasRC = true; 2406 break; 2407 } 2408 2409 llvm::APSInt Result; 2410 2411 // We can't check the value of a dependent argument. 2412 Expr *Arg = TheCall->getArg(ArgNum); 2413 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2414 return false; 2415 2416 // Check constant-ness first. 2417 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 2418 return true; 2419 2420 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 2421 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 2422 // combined with ROUND_NO_EXC. 2423 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 2424 Result == 8/*ROUND_NO_EXC*/ || 2425 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 2426 return false; 2427 2428 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding) 2429 << Arg->getSourceRange(); 2430 } 2431 2432 // Check if the gather/scatter scale is legal. 2433 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 2434 CallExpr *TheCall) { 2435 unsigned ArgNum = 0; 2436 switch (BuiltinID) { 2437 default: 2438 return false; 2439 case X86::BI__builtin_ia32_gatherpfdpd: 2440 case X86::BI__builtin_ia32_gatherpfdps: 2441 case X86::BI__builtin_ia32_gatherpfqpd: 2442 case X86::BI__builtin_ia32_gatherpfqps: 2443 case X86::BI__builtin_ia32_scatterpfdpd: 2444 case X86::BI__builtin_ia32_scatterpfdps: 2445 case X86::BI__builtin_ia32_scatterpfqpd: 2446 case X86::BI__builtin_ia32_scatterpfqps: 2447 ArgNum = 3; 2448 break; 2449 case X86::BI__builtin_ia32_gatherd_pd: 2450 case X86::BI__builtin_ia32_gatherd_pd256: 2451 case X86::BI__builtin_ia32_gatherq_pd: 2452 case X86::BI__builtin_ia32_gatherq_pd256: 2453 case X86::BI__builtin_ia32_gatherd_ps: 2454 case X86::BI__builtin_ia32_gatherd_ps256: 2455 case X86::BI__builtin_ia32_gatherq_ps: 2456 case X86::BI__builtin_ia32_gatherq_ps256: 2457 case X86::BI__builtin_ia32_gatherd_q: 2458 case X86::BI__builtin_ia32_gatherd_q256: 2459 case X86::BI__builtin_ia32_gatherq_q: 2460 case X86::BI__builtin_ia32_gatherq_q256: 2461 case X86::BI__builtin_ia32_gatherd_d: 2462 case X86::BI__builtin_ia32_gatherd_d256: 2463 case X86::BI__builtin_ia32_gatherq_d: 2464 case X86::BI__builtin_ia32_gatherq_d256: 2465 case X86::BI__builtin_ia32_gather3div2df: 2466 case X86::BI__builtin_ia32_gather3div2di: 2467 case X86::BI__builtin_ia32_gather3div4df: 2468 case X86::BI__builtin_ia32_gather3div4di: 2469 case X86::BI__builtin_ia32_gather3div4sf: 2470 case X86::BI__builtin_ia32_gather3div4si: 2471 case X86::BI__builtin_ia32_gather3div8sf: 2472 case X86::BI__builtin_ia32_gather3div8si: 2473 case X86::BI__builtin_ia32_gather3siv2df: 2474 case X86::BI__builtin_ia32_gather3siv2di: 2475 case X86::BI__builtin_ia32_gather3siv4df: 2476 case X86::BI__builtin_ia32_gather3siv4di: 2477 case X86::BI__builtin_ia32_gather3siv4sf: 2478 case X86::BI__builtin_ia32_gather3siv4si: 2479 case X86::BI__builtin_ia32_gather3siv8sf: 2480 case X86::BI__builtin_ia32_gather3siv8si: 2481 case X86::BI__builtin_ia32_gathersiv8df: 2482 case X86::BI__builtin_ia32_gathersiv16sf: 2483 case X86::BI__builtin_ia32_gatherdiv8df: 2484 case X86::BI__builtin_ia32_gatherdiv16sf: 2485 case X86::BI__builtin_ia32_gathersiv8di: 2486 case X86::BI__builtin_ia32_gathersiv16si: 2487 case X86::BI__builtin_ia32_gatherdiv8di: 2488 case X86::BI__builtin_ia32_gatherdiv16si: 2489 case X86::BI__builtin_ia32_scatterdiv2df: 2490 case X86::BI__builtin_ia32_scatterdiv2di: 2491 case X86::BI__builtin_ia32_scatterdiv4df: 2492 case X86::BI__builtin_ia32_scatterdiv4di: 2493 case X86::BI__builtin_ia32_scatterdiv4sf: 2494 case X86::BI__builtin_ia32_scatterdiv4si: 2495 case X86::BI__builtin_ia32_scatterdiv8sf: 2496 case X86::BI__builtin_ia32_scatterdiv8si: 2497 case X86::BI__builtin_ia32_scattersiv2df: 2498 case X86::BI__builtin_ia32_scattersiv2di: 2499 case X86::BI__builtin_ia32_scattersiv4df: 2500 case X86::BI__builtin_ia32_scattersiv4di: 2501 case X86::BI__builtin_ia32_scattersiv4sf: 2502 case X86::BI__builtin_ia32_scattersiv4si: 2503 case X86::BI__builtin_ia32_scattersiv8sf: 2504 case X86::BI__builtin_ia32_scattersiv8si: 2505 case X86::BI__builtin_ia32_scattersiv8df: 2506 case X86::BI__builtin_ia32_scattersiv16sf: 2507 case X86::BI__builtin_ia32_scatterdiv8df: 2508 case X86::BI__builtin_ia32_scatterdiv16sf: 2509 case X86::BI__builtin_ia32_scattersiv8di: 2510 case X86::BI__builtin_ia32_scattersiv16si: 2511 case X86::BI__builtin_ia32_scatterdiv8di: 2512 case X86::BI__builtin_ia32_scatterdiv16si: 2513 ArgNum = 4; 2514 break; 2515 } 2516 2517 llvm::APSInt Result; 2518 2519 // We can't check the value of a dependent argument. 2520 Expr *Arg = TheCall->getArg(ArgNum); 2521 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2522 return false; 2523 2524 // Check constant-ness first. 2525 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 2526 return true; 2527 2528 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 2529 return false; 2530 2531 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale) 2532 << Arg->getSourceRange(); 2533 } 2534 2535 static bool isX86_32Builtin(unsigned BuiltinID) { 2536 // These builtins only work on x86-32 targets. 2537 switch (BuiltinID) { 2538 case X86::BI__builtin_ia32_readeflags_u32: 2539 case X86::BI__builtin_ia32_writeeflags_u32: 2540 return true; 2541 } 2542 2543 return false; 2544 } 2545 2546 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2547 if (BuiltinID == X86::BI__builtin_cpu_supports) 2548 return SemaBuiltinCpuSupports(*this, TheCall); 2549 2550 if (BuiltinID == X86::BI__builtin_cpu_is) 2551 return SemaBuiltinCpuIs(*this, TheCall); 2552 2553 // Check for 32-bit only builtins on a 64-bit target. 2554 const llvm::Triple &TT = Context.getTargetInfo().getTriple(); 2555 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) 2556 return Diag(TheCall->getCallee()->getLocStart(), 2557 diag::err_32_bit_builtin_64_bit_tgt); 2558 2559 // If the intrinsic has rounding or SAE make sure its valid. 2560 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 2561 return true; 2562 2563 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 2564 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 2565 return true; 2566 2567 // For intrinsics which take an immediate value as part of the instruction, 2568 // range check them here. 2569 int i = 0, l = 0, u = 0; 2570 switch (BuiltinID) { 2571 default: 2572 return false; 2573 case X86::BI_mm_prefetch: 2574 i = 1; l = 0; u = 7; 2575 break; 2576 case X86::BI__builtin_ia32_sha1rnds4: 2577 i = 2; l = 0; u = 3; 2578 break; 2579 case X86::BI__builtin_ia32_vpermil2pd: 2580 case X86::BI__builtin_ia32_vpermil2pd256: 2581 case X86::BI__builtin_ia32_vpermil2ps: 2582 case X86::BI__builtin_ia32_vpermil2ps256: 2583 i = 3; l = 0; u = 3; 2584 break; 2585 case X86::BI__builtin_ia32_cmpb128_mask: 2586 case X86::BI__builtin_ia32_cmpw128_mask: 2587 case X86::BI__builtin_ia32_cmpd128_mask: 2588 case X86::BI__builtin_ia32_cmpq128_mask: 2589 case X86::BI__builtin_ia32_cmpb256_mask: 2590 case X86::BI__builtin_ia32_cmpw256_mask: 2591 case X86::BI__builtin_ia32_cmpd256_mask: 2592 case X86::BI__builtin_ia32_cmpq256_mask: 2593 case X86::BI__builtin_ia32_cmpb512_mask: 2594 case X86::BI__builtin_ia32_cmpw512_mask: 2595 case X86::BI__builtin_ia32_cmpd512_mask: 2596 case X86::BI__builtin_ia32_cmpq512_mask: 2597 case X86::BI__builtin_ia32_ucmpb128_mask: 2598 case X86::BI__builtin_ia32_ucmpw128_mask: 2599 case X86::BI__builtin_ia32_ucmpd128_mask: 2600 case X86::BI__builtin_ia32_ucmpq128_mask: 2601 case X86::BI__builtin_ia32_ucmpb256_mask: 2602 case X86::BI__builtin_ia32_ucmpw256_mask: 2603 case X86::BI__builtin_ia32_ucmpd256_mask: 2604 case X86::BI__builtin_ia32_ucmpq256_mask: 2605 case X86::BI__builtin_ia32_ucmpb512_mask: 2606 case X86::BI__builtin_ia32_ucmpw512_mask: 2607 case X86::BI__builtin_ia32_ucmpd512_mask: 2608 case X86::BI__builtin_ia32_ucmpq512_mask: 2609 case X86::BI__builtin_ia32_vpcomub: 2610 case X86::BI__builtin_ia32_vpcomuw: 2611 case X86::BI__builtin_ia32_vpcomud: 2612 case X86::BI__builtin_ia32_vpcomuq: 2613 case X86::BI__builtin_ia32_vpcomb: 2614 case X86::BI__builtin_ia32_vpcomw: 2615 case X86::BI__builtin_ia32_vpcomd: 2616 case X86::BI__builtin_ia32_vpcomq: 2617 i = 2; l = 0; u = 7; 2618 break; 2619 case X86::BI__builtin_ia32_roundps: 2620 case X86::BI__builtin_ia32_roundpd: 2621 case X86::BI__builtin_ia32_roundps256: 2622 case X86::BI__builtin_ia32_roundpd256: 2623 i = 1; l = 0; u = 15; 2624 break; 2625 case X86::BI__builtin_ia32_roundss: 2626 case X86::BI__builtin_ia32_roundsd: 2627 case X86::BI__builtin_ia32_rangepd128_mask: 2628 case X86::BI__builtin_ia32_rangepd256_mask: 2629 case X86::BI__builtin_ia32_rangepd512_mask: 2630 case X86::BI__builtin_ia32_rangeps128_mask: 2631 case X86::BI__builtin_ia32_rangeps256_mask: 2632 case X86::BI__builtin_ia32_rangeps512_mask: 2633 case X86::BI__builtin_ia32_getmantsd_round_mask: 2634 case X86::BI__builtin_ia32_getmantss_round_mask: 2635 i = 2; l = 0; u = 15; 2636 break; 2637 case X86::BI__builtin_ia32_cmpps: 2638 case X86::BI__builtin_ia32_cmpss: 2639 case X86::BI__builtin_ia32_cmppd: 2640 case X86::BI__builtin_ia32_cmpsd: 2641 case X86::BI__builtin_ia32_cmpps256: 2642 case X86::BI__builtin_ia32_cmppd256: 2643 case X86::BI__builtin_ia32_cmpps128_mask: 2644 case X86::BI__builtin_ia32_cmppd128_mask: 2645 case X86::BI__builtin_ia32_cmpps256_mask: 2646 case X86::BI__builtin_ia32_cmppd256_mask: 2647 case X86::BI__builtin_ia32_cmpps512_mask: 2648 case X86::BI__builtin_ia32_cmppd512_mask: 2649 case X86::BI__builtin_ia32_cmpsd_mask: 2650 case X86::BI__builtin_ia32_cmpss_mask: 2651 i = 2; l = 0; u = 31; 2652 break; 2653 case X86::BI__builtin_ia32_vcvtps2ph: 2654 case X86::BI__builtin_ia32_vcvtps2ph_mask: 2655 case X86::BI__builtin_ia32_vcvtps2ph256: 2656 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 2657 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 2658 case X86::BI__builtin_ia32_rndscaleps_128_mask: 2659 case X86::BI__builtin_ia32_rndscalepd_128_mask: 2660 case X86::BI__builtin_ia32_rndscaleps_256_mask: 2661 case X86::BI__builtin_ia32_rndscalepd_256_mask: 2662 case X86::BI__builtin_ia32_rndscaleps_mask: 2663 case X86::BI__builtin_ia32_rndscalepd_mask: 2664 case X86::BI__builtin_ia32_reducepd128_mask: 2665 case X86::BI__builtin_ia32_reducepd256_mask: 2666 case X86::BI__builtin_ia32_reducepd512_mask: 2667 case X86::BI__builtin_ia32_reduceps128_mask: 2668 case X86::BI__builtin_ia32_reduceps256_mask: 2669 case X86::BI__builtin_ia32_reduceps512_mask: 2670 case X86::BI__builtin_ia32_prold512_mask: 2671 case X86::BI__builtin_ia32_prolq512_mask: 2672 case X86::BI__builtin_ia32_prold128_mask: 2673 case X86::BI__builtin_ia32_prold256_mask: 2674 case X86::BI__builtin_ia32_prolq128_mask: 2675 case X86::BI__builtin_ia32_prolq256_mask: 2676 case X86::BI__builtin_ia32_prord128_mask: 2677 case X86::BI__builtin_ia32_prord256_mask: 2678 case X86::BI__builtin_ia32_prorq128_mask: 2679 case X86::BI__builtin_ia32_prorq256_mask: 2680 case X86::BI__builtin_ia32_fpclasspd128_mask: 2681 case X86::BI__builtin_ia32_fpclasspd256_mask: 2682 case X86::BI__builtin_ia32_fpclassps128_mask: 2683 case X86::BI__builtin_ia32_fpclassps256_mask: 2684 case X86::BI__builtin_ia32_fpclassps512_mask: 2685 case X86::BI__builtin_ia32_fpclasspd512_mask: 2686 case X86::BI__builtin_ia32_fpclasssd_mask: 2687 case X86::BI__builtin_ia32_fpclassss_mask: 2688 i = 1; l = 0; u = 255; 2689 break; 2690 case X86::BI__builtin_ia32_palignr128: 2691 case X86::BI__builtin_ia32_palignr256: 2692 case X86::BI__builtin_ia32_palignr512: 2693 case X86::BI__builtin_ia32_vcomisd: 2694 case X86::BI__builtin_ia32_vcomiss: 2695 case X86::BI__builtin_ia32_dbpsadbw128_mask: 2696 case X86::BI__builtin_ia32_dbpsadbw256_mask: 2697 case X86::BI__builtin_ia32_dbpsadbw512_mask: 2698 case X86::BI__builtin_ia32_vpshldd128_mask: 2699 case X86::BI__builtin_ia32_vpshldd256_mask: 2700 case X86::BI__builtin_ia32_vpshldd512_mask: 2701 case X86::BI__builtin_ia32_vpshldq128_mask: 2702 case X86::BI__builtin_ia32_vpshldq256_mask: 2703 case X86::BI__builtin_ia32_vpshldq512_mask: 2704 case X86::BI__builtin_ia32_vpshldw128_mask: 2705 case X86::BI__builtin_ia32_vpshldw256_mask: 2706 case X86::BI__builtin_ia32_vpshldw512_mask: 2707 case X86::BI__builtin_ia32_vpshrdd128_mask: 2708 case X86::BI__builtin_ia32_vpshrdd256_mask: 2709 case X86::BI__builtin_ia32_vpshrdd512_mask: 2710 case X86::BI__builtin_ia32_vpshrdq128_mask: 2711 case X86::BI__builtin_ia32_vpshrdq256_mask: 2712 case X86::BI__builtin_ia32_vpshrdq512_mask: 2713 case X86::BI__builtin_ia32_vpshrdw128_mask: 2714 case X86::BI__builtin_ia32_vpshrdw256_mask: 2715 case X86::BI__builtin_ia32_vpshrdw512_mask: 2716 i = 2; l = 0; u = 255; 2717 break; 2718 case X86::BI__builtin_ia32_fixupimmpd512_mask: 2719 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 2720 case X86::BI__builtin_ia32_fixupimmps512_mask: 2721 case X86::BI__builtin_ia32_fixupimmps512_maskz: 2722 case X86::BI__builtin_ia32_fixupimmsd_mask: 2723 case X86::BI__builtin_ia32_fixupimmsd_maskz: 2724 case X86::BI__builtin_ia32_fixupimmss_mask: 2725 case X86::BI__builtin_ia32_fixupimmss_maskz: 2726 case X86::BI__builtin_ia32_fixupimmpd128_mask: 2727 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 2728 case X86::BI__builtin_ia32_fixupimmpd256_mask: 2729 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 2730 case X86::BI__builtin_ia32_fixupimmps128_mask: 2731 case X86::BI__builtin_ia32_fixupimmps128_maskz: 2732 case X86::BI__builtin_ia32_fixupimmps256_mask: 2733 case X86::BI__builtin_ia32_fixupimmps256_maskz: 2734 case X86::BI__builtin_ia32_pternlogd512_mask: 2735 case X86::BI__builtin_ia32_pternlogd512_maskz: 2736 case X86::BI__builtin_ia32_pternlogq512_mask: 2737 case X86::BI__builtin_ia32_pternlogq512_maskz: 2738 case X86::BI__builtin_ia32_pternlogd128_mask: 2739 case X86::BI__builtin_ia32_pternlogd128_maskz: 2740 case X86::BI__builtin_ia32_pternlogd256_mask: 2741 case X86::BI__builtin_ia32_pternlogd256_maskz: 2742 case X86::BI__builtin_ia32_pternlogq128_mask: 2743 case X86::BI__builtin_ia32_pternlogq128_maskz: 2744 case X86::BI__builtin_ia32_pternlogq256_mask: 2745 case X86::BI__builtin_ia32_pternlogq256_maskz: 2746 i = 3; l = 0; u = 255; 2747 break; 2748 case X86::BI__builtin_ia32_gatherpfdpd: 2749 case X86::BI__builtin_ia32_gatherpfdps: 2750 case X86::BI__builtin_ia32_gatherpfqpd: 2751 case X86::BI__builtin_ia32_gatherpfqps: 2752 case X86::BI__builtin_ia32_scatterpfdpd: 2753 case X86::BI__builtin_ia32_scatterpfdps: 2754 case X86::BI__builtin_ia32_scatterpfqpd: 2755 case X86::BI__builtin_ia32_scatterpfqps: 2756 i = 4; l = 2; u = 3; 2757 break; 2758 case X86::BI__builtin_ia32_rndscalesd_round_mask: 2759 case X86::BI__builtin_ia32_rndscaless_round_mask: 2760 i = 4; l = 0; u = 255; 2761 break; 2762 } 2763 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 2764 } 2765 2766 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 2767 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 2768 /// Returns true when the format fits the function and the FormatStringInfo has 2769 /// been populated. 2770 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 2771 FormatStringInfo *FSI) { 2772 FSI->HasVAListArg = Format->getFirstArg() == 0; 2773 FSI->FormatIdx = Format->getFormatIdx() - 1; 2774 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 2775 2776 // The way the format attribute works in GCC, the implicit this argument 2777 // of member functions is counted. However, it doesn't appear in our own 2778 // lists, so decrement format_idx in that case. 2779 if (IsCXXMember) { 2780 if(FSI->FormatIdx == 0) 2781 return false; 2782 --FSI->FormatIdx; 2783 if (FSI->FirstDataArg != 0) 2784 --FSI->FirstDataArg; 2785 } 2786 return true; 2787 } 2788 2789 /// Checks if a the given expression evaluates to null. 2790 /// 2791 /// Returns true if the value evaluates to null. 2792 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 2793 // If the expression has non-null type, it doesn't evaluate to null. 2794 if (auto nullability 2795 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 2796 if (*nullability == NullabilityKind::NonNull) 2797 return false; 2798 } 2799 2800 // As a special case, transparent unions initialized with zero are 2801 // considered null for the purposes of the nonnull attribute. 2802 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 2803 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 2804 if (const CompoundLiteralExpr *CLE = 2805 dyn_cast<CompoundLiteralExpr>(Expr)) 2806 if (const InitListExpr *ILE = 2807 dyn_cast<InitListExpr>(CLE->getInitializer())) 2808 Expr = ILE->getInit(0); 2809 } 2810 2811 bool Result; 2812 return (!Expr->isValueDependent() && 2813 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 2814 !Result); 2815 } 2816 2817 static void CheckNonNullArgument(Sema &S, 2818 const Expr *ArgExpr, 2819 SourceLocation CallSiteLoc) { 2820 if (CheckNonNullExpr(S, ArgExpr)) 2821 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 2822 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange()); 2823 } 2824 2825 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 2826 FormatStringInfo FSI; 2827 if ((GetFormatStringType(Format) == FST_NSString) && 2828 getFormatStringInfo(Format, false, &FSI)) { 2829 Idx = FSI.FormatIdx; 2830 return true; 2831 } 2832 return false; 2833 } 2834 2835 /// Diagnose use of %s directive in an NSString which is being passed 2836 /// as formatting string to formatting method. 2837 static void 2838 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 2839 const NamedDecl *FDecl, 2840 Expr **Args, 2841 unsigned NumArgs) { 2842 unsigned Idx = 0; 2843 bool Format = false; 2844 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 2845 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 2846 Idx = 2; 2847 Format = true; 2848 } 2849 else 2850 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 2851 if (S.GetFormatNSStringIdx(I, Idx)) { 2852 Format = true; 2853 break; 2854 } 2855 } 2856 if (!Format || NumArgs <= Idx) 2857 return; 2858 const Expr *FormatExpr = Args[Idx]; 2859 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 2860 FormatExpr = CSCE->getSubExpr(); 2861 const StringLiteral *FormatString; 2862 if (const ObjCStringLiteral *OSL = 2863 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 2864 FormatString = OSL->getString(); 2865 else 2866 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 2867 if (!FormatString) 2868 return; 2869 if (S.FormatStringHasSArg(FormatString)) { 2870 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 2871 << "%s" << 1 << 1; 2872 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 2873 << FDecl->getDeclName(); 2874 } 2875 } 2876 2877 /// Determine whether the given type has a non-null nullability annotation. 2878 static bool isNonNullType(ASTContext &ctx, QualType type) { 2879 if (auto nullability = type->getNullability(ctx)) 2880 return *nullability == NullabilityKind::NonNull; 2881 2882 return false; 2883 } 2884 2885 static void CheckNonNullArguments(Sema &S, 2886 const NamedDecl *FDecl, 2887 const FunctionProtoType *Proto, 2888 ArrayRef<const Expr *> Args, 2889 SourceLocation CallSiteLoc) { 2890 assert((FDecl || Proto) && "Need a function declaration or prototype"); 2891 2892 // Check the attributes attached to the method/function itself. 2893 llvm::SmallBitVector NonNullArgs; 2894 if (FDecl) { 2895 // Handle the nonnull attribute on the function/method declaration itself. 2896 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 2897 if (!NonNull->args_size()) { 2898 // Easy case: all pointer arguments are nonnull. 2899 for (const auto *Arg : Args) 2900 if (S.isValidPointerAttrType(Arg->getType())) 2901 CheckNonNullArgument(S, Arg, CallSiteLoc); 2902 return; 2903 } 2904 2905 for (const ParamIdx &Idx : NonNull->args()) { 2906 unsigned IdxAST = Idx.getASTIndex(); 2907 if (IdxAST >= Args.size()) 2908 continue; 2909 if (NonNullArgs.empty()) 2910 NonNullArgs.resize(Args.size()); 2911 NonNullArgs.set(IdxAST); 2912 } 2913 } 2914 } 2915 2916 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 2917 // Handle the nonnull attribute on the parameters of the 2918 // function/method. 2919 ArrayRef<ParmVarDecl*> parms; 2920 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 2921 parms = FD->parameters(); 2922 else 2923 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 2924 2925 unsigned ParamIndex = 0; 2926 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 2927 I != E; ++I, ++ParamIndex) { 2928 const ParmVarDecl *PVD = *I; 2929 if (PVD->hasAttr<NonNullAttr>() || 2930 isNonNullType(S.Context, PVD->getType())) { 2931 if (NonNullArgs.empty()) 2932 NonNullArgs.resize(Args.size()); 2933 2934 NonNullArgs.set(ParamIndex); 2935 } 2936 } 2937 } else { 2938 // If we have a non-function, non-method declaration but no 2939 // function prototype, try to dig out the function prototype. 2940 if (!Proto) { 2941 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 2942 QualType type = VD->getType().getNonReferenceType(); 2943 if (auto pointerType = type->getAs<PointerType>()) 2944 type = pointerType->getPointeeType(); 2945 else if (auto blockType = type->getAs<BlockPointerType>()) 2946 type = blockType->getPointeeType(); 2947 // FIXME: data member pointers? 2948 2949 // Dig out the function prototype, if there is one. 2950 Proto = type->getAs<FunctionProtoType>(); 2951 } 2952 } 2953 2954 // Fill in non-null argument information from the nullability 2955 // information on the parameter types (if we have them). 2956 if (Proto) { 2957 unsigned Index = 0; 2958 for (auto paramType : Proto->getParamTypes()) { 2959 if (isNonNullType(S.Context, paramType)) { 2960 if (NonNullArgs.empty()) 2961 NonNullArgs.resize(Args.size()); 2962 2963 NonNullArgs.set(Index); 2964 } 2965 2966 ++Index; 2967 } 2968 } 2969 } 2970 2971 // Check for non-null arguments. 2972 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 2973 ArgIndex != ArgIndexEnd; ++ArgIndex) { 2974 if (NonNullArgs[ArgIndex]) 2975 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 2976 } 2977 } 2978 2979 /// Handles the checks for format strings, non-POD arguments to vararg 2980 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 2981 /// attributes. 2982 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 2983 const Expr *ThisArg, ArrayRef<const Expr *> Args, 2984 bool IsMemberFunction, SourceLocation Loc, 2985 SourceRange Range, VariadicCallType CallType) { 2986 // FIXME: We should check as much as we can in the template definition. 2987 if (CurContext->isDependentContext()) 2988 return; 2989 2990 // Printf and scanf checking. 2991 llvm::SmallBitVector CheckedVarArgs; 2992 if (FDecl) { 2993 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 2994 // Only create vector if there are format attributes. 2995 CheckedVarArgs.resize(Args.size()); 2996 2997 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 2998 CheckedVarArgs); 2999 } 3000 } 3001 3002 // Refuse POD arguments that weren't caught by the format string 3003 // checks above. 3004 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 3005 if (CallType != VariadicDoesNotApply && 3006 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 3007 unsigned NumParams = Proto ? Proto->getNumParams() 3008 : FDecl && isa<FunctionDecl>(FDecl) 3009 ? cast<FunctionDecl>(FDecl)->getNumParams() 3010 : FDecl && isa<ObjCMethodDecl>(FDecl) 3011 ? cast<ObjCMethodDecl>(FDecl)->param_size() 3012 : 0; 3013 3014 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 3015 // Args[ArgIdx] can be null in malformed code. 3016 if (const Expr *Arg = Args[ArgIdx]) { 3017 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 3018 checkVariadicArgument(Arg, CallType); 3019 } 3020 } 3021 } 3022 3023 if (FDecl || Proto) { 3024 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 3025 3026 // Type safety checking. 3027 if (FDecl) { 3028 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 3029 CheckArgumentWithTypeTag(I, Args, Loc); 3030 } 3031 } 3032 3033 if (FD) 3034 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 3035 } 3036 3037 /// CheckConstructorCall - Check a constructor call for correctness and safety 3038 /// properties not enforced by the C type system. 3039 void Sema::CheckConstructorCall(FunctionDecl *FDecl, 3040 ArrayRef<const Expr *> Args, 3041 const FunctionProtoType *Proto, 3042 SourceLocation Loc) { 3043 VariadicCallType CallType = 3044 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 3045 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 3046 Loc, SourceRange(), CallType); 3047 } 3048 3049 /// CheckFunctionCall - Check a direct function call for various correctness 3050 /// and safety properties not strictly enforced by the C type system. 3051 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 3052 const FunctionProtoType *Proto) { 3053 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 3054 isa<CXXMethodDecl>(FDecl); 3055 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 3056 IsMemberOperatorCall; 3057 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 3058 TheCall->getCallee()); 3059 Expr** Args = TheCall->getArgs(); 3060 unsigned NumArgs = TheCall->getNumArgs(); 3061 3062 Expr *ImplicitThis = nullptr; 3063 if (IsMemberOperatorCall) { 3064 // If this is a call to a member operator, hide the first argument 3065 // from checkCall. 3066 // FIXME: Our choice of AST representation here is less than ideal. 3067 ImplicitThis = Args[0]; 3068 ++Args; 3069 --NumArgs; 3070 } else if (IsMemberFunction) 3071 ImplicitThis = 3072 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 3073 3074 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 3075 IsMemberFunction, TheCall->getRParenLoc(), 3076 TheCall->getCallee()->getSourceRange(), CallType); 3077 3078 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 3079 // None of the checks below are needed for functions that don't have 3080 // simple names (e.g., C++ conversion functions). 3081 if (!FnInfo) 3082 return false; 3083 3084 CheckAbsoluteValueFunction(TheCall, FDecl); 3085 CheckMaxUnsignedZero(TheCall, FDecl); 3086 3087 if (getLangOpts().ObjC1) 3088 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 3089 3090 unsigned CMId = FDecl->getMemoryFunctionKind(); 3091 if (CMId == 0) 3092 return false; 3093 3094 // Handle memory setting and copying functions. 3095 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 3096 CheckStrlcpycatArguments(TheCall, FnInfo); 3097 else if (CMId == Builtin::BIstrncat) 3098 CheckStrncatArguments(TheCall, FnInfo); 3099 else 3100 CheckMemaccessArguments(TheCall, CMId, FnInfo); 3101 3102 return false; 3103 } 3104 3105 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 3106 ArrayRef<const Expr *> Args) { 3107 VariadicCallType CallType = 3108 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 3109 3110 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 3111 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 3112 CallType); 3113 3114 return false; 3115 } 3116 3117 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 3118 const FunctionProtoType *Proto) { 3119 QualType Ty; 3120 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 3121 Ty = V->getType().getNonReferenceType(); 3122 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 3123 Ty = F->getType().getNonReferenceType(); 3124 else 3125 return false; 3126 3127 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 3128 !Ty->isFunctionProtoType()) 3129 return false; 3130 3131 VariadicCallType CallType; 3132 if (!Proto || !Proto->isVariadic()) { 3133 CallType = VariadicDoesNotApply; 3134 } else if (Ty->isBlockPointerType()) { 3135 CallType = VariadicBlock; 3136 } else { // Ty->isFunctionPointerType() 3137 CallType = VariadicFunction; 3138 } 3139 3140 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 3141 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 3142 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 3143 TheCall->getCallee()->getSourceRange(), CallType); 3144 3145 return false; 3146 } 3147 3148 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 3149 /// such as function pointers returned from functions. 3150 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 3151 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 3152 TheCall->getCallee()); 3153 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 3154 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 3155 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 3156 TheCall->getCallee()->getSourceRange(), CallType); 3157 3158 return false; 3159 } 3160 3161 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 3162 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 3163 return false; 3164 3165 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 3166 switch (Op) { 3167 case AtomicExpr::AO__c11_atomic_init: 3168 case AtomicExpr::AO__opencl_atomic_init: 3169 llvm_unreachable("There is no ordering argument for an init"); 3170 3171 case AtomicExpr::AO__c11_atomic_load: 3172 case AtomicExpr::AO__opencl_atomic_load: 3173 case AtomicExpr::AO__atomic_load_n: 3174 case AtomicExpr::AO__atomic_load: 3175 return OrderingCABI != llvm::AtomicOrderingCABI::release && 3176 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 3177 3178 case AtomicExpr::AO__c11_atomic_store: 3179 case AtomicExpr::AO__opencl_atomic_store: 3180 case AtomicExpr::AO__atomic_store: 3181 case AtomicExpr::AO__atomic_store_n: 3182 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 3183 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 3184 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 3185 3186 default: 3187 return true; 3188 } 3189 } 3190 3191 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 3192 AtomicExpr::AtomicOp Op) { 3193 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 3194 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 3195 3196 // All the non-OpenCL operations take one of the following forms. 3197 // The OpenCL operations take the __c11 forms with one extra argument for 3198 // synchronization scope. 3199 enum { 3200 // C __c11_atomic_init(A *, C) 3201 Init, 3202 3203 // C __c11_atomic_load(A *, int) 3204 Load, 3205 3206 // void __atomic_load(A *, CP, int) 3207 LoadCopy, 3208 3209 // void __atomic_store(A *, CP, int) 3210 Copy, 3211 3212 // C __c11_atomic_add(A *, M, int) 3213 Arithmetic, 3214 3215 // C __atomic_exchange_n(A *, CP, int) 3216 Xchg, 3217 3218 // void __atomic_exchange(A *, C *, CP, int) 3219 GNUXchg, 3220 3221 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 3222 C11CmpXchg, 3223 3224 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 3225 GNUCmpXchg 3226 } Form = Init; 3227 3228 const unsigned NumForm = GNUCmpXchg + 1; 3229 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 3230 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 3231 // where: 3232 // C is an appropriate type, 3233 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 3234 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 3235 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 3236 // the int parameters are for orderings. 3237 3238 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 3239 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 3240 "need to update code for modified forms"); 3241 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 3242 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == 3243 AtomicExpr::AO__atomic_load, 3244 "need to update code for modified C11 atomics"); 3245 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 3246 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 3247 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 3248 Op <= AtomicExpr::AO__c11_atomic_fetch_xor) || 3249 IsOpenCL; 3250 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 3251 Op == AtomicExpr::AO__atomic_store_n || 3252 Op == AtomicExpr::AO__atomic_exchange_n || 3253 Op == AtomicExpr::AO__atomic_compare_exchange_n; 3254 bool IsAddSub = false; 3255 bool IsMinMax = false; 3256 3257 switch (Op) { 3258 case AtomicExpr::AO__c11_atomic_init: 3259 case AtomicExpr::AO__opencl_atomic_init: 3260 Form = Init; 3261 break; 3262 3263 case AtomicExpr::AO__c11_atomic_load: 3264 case AtomicExpr::AO__opencl_atomic_load: 3265 case AtomicExpr::AO__atomic_load_n: 3266 Form = Load; 3267 break; 3268 3269 case AtomicExpr::AO__atomic_load: 3270 Form = LoadCopy; 3271 break; 3272 3273 case AtomicExpr::AO__c11_atomic_store: 3274 case AtomicExpr::AO__opencl_atomic_store: 3275 case AtomicExpr::AO__atomic_store: 3276 case AtomicExpr::AO__atomic_store_n: 3277 Form = Copy; 3278 break; 3279 3280 case AtomicExpr::AO__c11_atomic_fetch_add: 3281 case AtomicExpr::AO__c11_atomic_fetch_sub: 3282 case AtomicExpr::AO__opencl_atomic_fetch_add: 3283 case AtomicExpr::AO__opencl_atomic_fetch_sub: 3284 case AtomicExpr::AO__opencl_atomic_fetch_min: 3285 case AtomicExpr::AO__opencl_atomic_fetch_max: 3286 case AtomicExpr::AO__atomic_fetch_add: 3287 case AtomicExpr::AO__atomic_fetch_sub: 3288 case AtomicExpr::AO__atomic_add_fetch: 3289 case AtomicExpr::AO__atomic_sub_fetch: 3290 IsAddSub = true; 3291 LLVM_FALLTHROUGH; 3292 case AtomicExpr::AO__c11_atomic_fetch_and: 3293 case AtomicExpr::AO__c11_atomic_fetch_or: 3294 case AtomicExpr::AO__c11_atomic_fetch_xor: 3295 case AtomicExpr::AO__opencl_atomic_fetch_and: 3296 case AtomicExpr::AO__opencl_atomic_fetch_or: 3297 case AtomicExpr::AO__opencl_atomic_fetch_xor: 3298 case AtomicExpr::AO__atomic_fetch_and: 3299 case AtomicExpr::AO__atomic_fetch_or: 3300 case AtomicExpr::AO__atomic_fetch_xor: 3301 case AtomicExpr::AO__atomic_fetch_nand: 3302 case AtomicExpr::AO__atomic_and_fetch: 3303 case AtomicExpr::AO__atomic_or_fetch: 3304 case AtomicExpr::AO__atomic_xor_fetch: 3305 case AtomicExpr::AO__atomic_nand_fetch: 3306 Form = Arithmetic; 3307 break; 3308 3309 case AtomicExpr::AO__atomic_fetch_min: 3310 case AtomicExpr::AO__atomic_fetch_max: 3311 IsMinMax = true; 3312 Form = Arithmetic; 3313 break; 3314 3315 case AtomicExpr::AO__c11_atomic_exchange: 3316 case AtomicExpr::AO__opencl_atomic_exchange: 3317 case AtomicExpr::AO__atomic_exchange_n: 3318 Form = Xchg; 3319 break; 3320 3321 case AtomicExpr::AO__atomic_exchange: 3322 Form = GNUXchg; 3323 break; 3324 3325 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 3326 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 3327 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 3328 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 3329 Form = C11CmpXchg; 3330 break; 3331 3332 case AtomicExpr::AO__atomic_compare_exchange: 3333 case AtomicExpr::AO__atomic_compare_exchange_n: 3334 Form = GNUCmpXchg; 3335 break; 3336 } 3337 3338 unsigned AdjustedNumArgs = NumArgs[Form]; 3339 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 3340 ++AdjustedNumArgs; 3341 // Check we have the right number of arguments. 3342 if (TheCall->getNumArgs() < AdjustedNumArgs) { 3343 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 3344 << 0 << AdjustedNumArgs << TheCall->getNumArgs() 3345 << TheCall->getCallee()->getSourceRange(); 3346 return ExprError(); 3347 } else if (TheCall->getNumArgs() > AdjustedNumArgs) { 3348 Diag(TheCall->getArg(AdjustedNumArgs)->getLocStart(), 3349 diag::err_typecheck_call_too_many_args) 3350 << 0 << AdjustedNumArgs << TheCall->getNumArgs() 3351 << TheCall->getCallee()->getSourceRange(); 3352 return ExprError(); 3353 } 3354 3355 // Inspect the first argument of the atomic operation. 3356 Expr *Ptr = TheCall->getArg(0); 3357 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 3358 if (ConvertedPtr.isInvalid()) 3359 return ExprError(); 3360 3361 Ptr = ConvertedPtr.get(); 3362 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 3363 if (!pointerType) { 3364 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 3365 << Ptr->getType() << Ptr->getSourceRange(); 3366 return ExprError(); 3367 } 3368 3369 // For a __c11 builtin, this should be a pointer to an _Atomic type. 3370 QualType AtomTy = pointerType->getPointeeType(); // 'A' 3371 QualType ValType = AtomTy; // 'C' 3372 if (IsC11) { 3373 if (!AtomTy->isAtomicType()) { 3374 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic) 3375 << Ptr->getType() << Ptr->getSourceRange(); 3376 return ExprError(); 3377 } 3378 if (AtomTy.isConstQualified() || 3379 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 3380 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic) 3381 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 3382 << Ptr->getSourceRange(); 3383 return ExprError(); 3384 } 3385 ValType = AtomTy->getAs<AtomicType>()->getValueType(); 3386 } else if (Form != Load && Form != LoadCopy) { 3387 if (ValType.isConstQualified()) { 3388 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer) 3389 << Ptr->getType() << Ptr->getSourceRange(); 3390 return ExprError(); 3391 } 3392 } 3393 3394 // For an arithmetic operation, the implied arithmetic must be well-formed. 3395 if (Form == Arithmetic) { 3396 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 3397 if (IsAddSub && !ValType->isIntegerType() 3398 && !ValType->isPointerType()) { 3399 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 3400 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 3401 return ExprError(); 3402 } 3403 if (IsMinMax) { 3404 const BuiltinType *BT = ValType->getAs<BuiltinType>(); 3405 if (!BT || (BT->getKind() != BuiltinType::Int && 3406 BT->getKind() != BuiltinType::UInt)) { 3407 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_int32_or_ptr); 3408 return ExprError(); 3409 } 3410 } 3411 if (!IsAddSub && !IsMinMax && !ValType->isIntegerType()) { 3412 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int) 3413 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 3414 return ExprError(); 3415 } 3416 if (IsC11 && ValType->isPointerType() && 3417 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(), 3418 diag::err_incomplete_type)) { 3419 return ExprError(); 3420 } 3421 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 3422 // For __atomic_*_n operations, the value type must be a scalar integral or 3423 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 3424 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 3425 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 3426 return ExprError(); 3427 } 3428 3429 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 3430 !AtomTy->isScalarType()) { 3431 // For GNU atomics, require a trivially-copyable type. This is not part of 3432 // the GNU atomics specification, but we enforce it for sanity. 3433 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy) 3434 << Ptr->getType() << Ptr->getSourceRange(); 3435 return ExprError(); 3436 } 3437 3438 switch (ValType.getObjCLifetime()) { 3439 case Qualifiers::OCL_None: 3440 case Qualifiers::OCL_ExplicitNone: 3441 // okay 3442 break; 3443 3444 case Qualifiers::OCL_Weak: 3445 case Qualifiers::OCL_Strong: 3446 case Qualifiers::OCL_Autoreleasing: 3447 // FIXME: Can this happen? By this point, ValType should be known 3448 // to be trivially copyable. 3449 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 3450 << ValType << Ptr->getSourceRange(); 3451 return ExprError(); 3452 } 3453 3454 // All atomic operations have an overload which takes a pointer to a volatile 3455 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself 3456 // into the result or the other operands. Similarly atomic_load takes a 3457 // pointer to a const 'A'. 3458 ValType.removeLocalVolatile(); 3459 ValType.removeLocalConst(); 3460 QualType ResultType = ValType; 3461 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 3462 Form == Init) 3463 ResultType = Context.VoidTy; 3464 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 3465 ResultType = Context.BoolTy; 3466 3467 // The type of a parameter passed 'by value'. In the GNU atomics, such 3468 // arguments are actually passed as pointers. 3469 QualType ByValType = ValType; // 'CP' 3470 bool IsPassedByAddress = false; 3471 if (!IsC11 && !IsN) { 3472 ByValType = Ptr->getType(); 3473 IsPassedByAddress = true; 3474 } 3475 3476 // The first argument's non-CV pointer type is used to deduce the type of 3477 // subsequent arguments, except for: 3478 // - weak flag (always converted to bool) 3479 // - memory order (always converted to int) 3480 // - scope (always converted to int) 3481 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) { 3482 QualType Ty; 3483 if (i < NumVals[Form] + 1) { 3484 switch (i) { 3485 case 0: 3486 // The first argument is always a pointer. It has a fixed type. 3487 // It is always dereferenced, a nullptr is undefined. 3488 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getLocStart()); 3489 // Nothing else to do: we already know all we want about this pointer. 3490 continue; 3491 case 1: 3492 // The second argument is the non-atomic operand. For arithmetic, this 3493 // is always passed by value, and for a compare_exchange it is always 3494 // passed by address. For the rest, GNU uses by-address and C11 uses 3495 // by-value. 3496 assert(Form != Load); 3497 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 3498 Ty = ValType; 3499 else if (Form == Copy || Form == Xchg) { 3500 if (IsPassedByAddress) 3501 // The value pointer is always dereferenced, a nullptr is undefined. 3502 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getLocStart()); 3503 Ty = ByValType; 3504 } else if (Form == Arithmetic) 3505 Ty = Context.getPointerDiffType(); 3506 else { 3507 Expr *ValArg = TheCall->getArg(i); 3508 // The value pointer is always dereferenced, a nullptr is undefined. 3509 CheckNonNullArgument(*this, ValArg, DRE->getLocStart()); 3510 LangAS AS = LangAS::Default; 3511 // Keep address space of non-atomic pointer type. 3512 if (const PointerType *PtrTy = 3513 ValArg->getType()->getAs<PointerType>()) { 3514 AS = PtrTy->getPointeeType().getAddressSpace(); 3515 } 3516 Ty = Context.getPointerType( 3517 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 3518 } 3519 break; 3520 case 2: 3521 // The third argument to compare_exchange / GNU exchange is the desired 3522 // value, either by-value (for the C11 and *_n variant) or as a pointer. 3523 if (IsPassedByAddress) 3524 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getLocStart()); 3525 Ty = ByValType; 3526 break; 3527 case 3: 3528 // The fourth argument to GNU compare_exchange is a 'weak' flag. 3529 Ty = Context.BoolTy; 3530 break; 3531 } 3532 } else { 3533 // The order(s) and scope are always converted to int. 3534 Ty = Context.IntTy; 3535 } 3536 3537 InitializedEntity Entity = 3538 InitializedEntity::InitializeParameter(Context, Ty, false); 3539 ExprResult Arg = TheCall->getArg(i); 3540 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 3541 if (Arg.isInvalid()) 3542 return true; 3543 TheCall->setArg(i, Arg.get()); 3544 } 3545 3546 // Permute the arguments into a 'consistent' order. 3547 SmallVector<Expr*, 5> SubExprs; 3548 SubExprs.push_back(Ptr); 3549 switch (Form) { 3550 case Init: 3551 // Note, AtomicExpr::getVal1() has a special case for this atomic. 3552 SubExprs.push_back(TheCall->getArg(1)); // Val1 3553 break; 3554 case Load: 3555 SubExprs.push_back(TheCall->getArg(1)); // Order 3556 break; 3557 case LoadCopy: 3558 case Copy: 3559 case Arithmetic: 3560 case Xchg: 3561 SubExprs.push_back(TheCall->getArg(2)); // Order 3562 SubExprs.push_back(TheCall->getArg(1)); // Val1 3563 break; 3564 case GNUXchg: 3565 // Note, AtomicExpr::getVal2() has a special case for this atomic. 3566 SubExprs.push_back(TheCall->getArg(3)); // Order 3567 SubExprs.push_back(TheCall->getArg(1)); // Val1 3568 SubExprs.push_back(TheCall->getArg(2)); // Val2 3569 break; 3570 case C11CmpXchg: 3571 SubExprs.push_back(TheCall->getArg(3)); // Order 3572 SubExprs.push_back(TheCall->getArg(1)); // Val1 3573 SubExprs.push_back(TheCall->getArg(4)); // OrderFail 3574 SubExprs.push_back(TheCall->getArg(2)); // Val2 3575 break; 3576 case GNUCmpXchg: 3577 SubExprs.push_back(TheCall->getArg(4)); // Order 3578 SubExprs.push_back(TheCall->getArg(1)); // Val1 3579 SubExprs.push_back(TheCall->getArg(5)); // OrderFail 3580 SubExprs.push_back(TheCall->getArg(2)); // Val2 3581 SubExprs.push_back(TheCall->getArg(3)); // Weak 3582 break; 3583 } 3584 3585 if (SubExprs.size() >= 2 && Form != Init) { 3586 llvm::APSInt Result(32); 3587 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) && 3588 !isValidOrderingForOp(Result.getSExtValue(), Op)) 3589 Diag(SubExprs[1]->getLocStart(), 3590 diag::warn_atomic_op_has_invalid_memory_order) 3591 << SubExprs[1]->getSourceRange(); 3592 } 3593 3594 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 3595 auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1); 3596 llvm::APSInt Result(32); 3597 if (Scope->isIntegerConstantExpr(Result, Context) && 3598 !ScopeModel->isValid(Result.getZExtValue())) { 3599 Diag(Scope->getLocStart(), diag::err_atomic_op_has_invalid_synch_scope) 3600 << Scope->getSourceRange(); 3601 } 3602 SubExprs.push_back(Scope); 3603 } 3604 3605 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(), 3606 SubExprs, ResultType, Op, 3607 TheCall->getRParenLoc()); 3608 3609 if ((Op == AtomicExpr::AO__c11_atomic_load || 3610 Op == AtomicExpr::AO__c11_atomic_store || 3611 Op == AtomicExpr::AO__opencl_atomic_load || 3612 Op == AtomicExpr::AO__opencl_atomic_store ) && 3613 Context.AtomicUsesUnsupportedLibcall(AE)) 3614 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) 3615 << ((Op == AtomicExpr::AO__c11_atomic_load || 3616 Op == AtomicExpr::AO__opencl_atomic_load) 3617 ? 0 : 1); 3618 3619 return AE; 3620 } 3621 3622 /// checkBuiltinArgument - Given a call to a builtin function, perform 3623 /// normal type-checking on the given argument, updating the call in 3624 /// place. This is useful when a builtin function requires custom 3625 /// type-checking for some of its arguments but not necessarily all of 3626 /// them. 3627 /// 3628 /// Returns true on error. 3629 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 3630 FunctionDecl *Fn = E->getDirectCallee(); 3631 assert(Fn && "builtin call without direct callee!"); 3632 3633 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 3634 InitializedEntity Entity = 3635 InitializedEntity::InitializeParameter(S.Context, Param); 3636 3637 ExprResult Arg = E->getArg(0); 3638 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 3639 if (Arg.isInvalid()) 3640 return true; 3641 3642 E->setArg(ArgIndex, Arg.get()); 3643 return false; 3644 } 3645 3646 /// SemaBuiltinAtomicOverloaded - We have a call to a function like 3647 /// __sync_fetch_and_add, which is an overloaded function based on the pointer 3648 /// type of its first argument. The main ActOnCallExpr routines have already 3649 /// promoted the types of arguments because all of these calls are prototyped as 3650 /// void(...). 3651 /// 3652 /// This function goes through and does final semantic checking for these 3653 /// builtins, 3654 ExprResult 3655 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 3656 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 3657 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 3658 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 3659 3660 // Ensure that we have at least one argument to do type inference from. 3661 if (TheCall->getNumArgs() < 1) { 3662 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 3663 << 0 << 1 << TheCall->getNumArgs() 3664 << TheCall->getCallee()->getSourceRange(); 3665 return ExprError(); 3666 } 3667 3668 // Inspect the first argument of the atomic builtin. This should always be 3669 // a pointer type, whose element is an integral scalar or pointer type. 3670 // Because it is a pointer type, we don't have to worry about any implicit 3671 // casts here. 3672 // FIXME: We don't allow floating point scalars as input. 3673 Expr *FirstArg = TheCall->getArg(0); 3674 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 3675 if (FirstArgResult.isInvalid()) 3676 return ExprError(); 3677 FirstArg = FirstArgResult.get(); 3678 TheCall->setArg(0, FirstArg); 3679 3680 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 3681 if (!pointerType) { 3682 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 3683 << FirstArg->getType() << FirstArg->getSourceRange(); 3684 return ExprError(); 3685 } 3686 3687 QualType ValType = pointerType->getPointeeType(); 3688 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 3689 !ValType->isBlockPointerType()) { 3690 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr) 3691 << FirstArg->getType() << FirstArg->getSourceRange(); 3692 return ExprError(); 3693 } 3694 3695 if (ValType.isConstQualified()) { 3696 Diag(DRE->getLocStart(), diag::err_atomic_builtin_cannot_be_const) 3697 << FirstArg->getType() << FirstArg->getSourceRange(); 3698 return ExprError(); 3699 } 3700 3701 switch (ValType.getObjCLifetime()) { 3702 case Qualifiers::OCL_None: 3703 case Qualifiers::OCL_ExplicitNone: 3704 // okay 3705 break; 3706 3707 case Qualifiers::OCL_Weak: 3708 case Qualifiers::OCL_Strong: 3709 case Qualifiers::OCL_Autoreleasing: 3710 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 3711 << ValType << FirstArg->getSourceRange(); 3712 return ExprError(); 3713 } 3714 3715 // Strip any qualifiers off ValType. 3716 ValType = ValType.getUnqualifiedType(); 3717 3718 // The majority of builtins return a value, but a few have special return 3719 // types, so allow them to override appropriately below. 3720 QualType ResultType = ValType; 3721 3722 // We need to figure out which concrete builtin this maps onto. For example, 3723 // __sync_fetch_and_add with a 2 byte object turns into 3724 // __sync_fetch_and_add_2. 3725 #define BUILTIN_ROW(x) \ 3726 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 3727 Builtin::BI##x##_8, Builtin::BI##x##_16 } 3728 3729 static const unsigned BuiltinIndices[][5] = { 3730 BUILTIN_ROW(__sync_fetch_and_add), 3731 BUILTIN_ROW(__sync_fetch_and_sub), 3732 BUILTIN_ROW(__sync_fetch_and_or), 3733 BUILTIN_ROW(__sync_fetch_and_and), 3734 BUILTIN_ROW(__sync_fetch_and_xor), 3735 BUILTIN_ROW(__sync_fetch_and_nand), 3736 3737 BUILTIN_ROW(__sync_add_and_fetch), 3738 BUILTIN_ROW(__sync_sub_and_fetch), 3739 BUILTIN_ROW(__sync_and_and_fetch), 3740 BUILTIN_ROW(__sync_or_and_fetch), 3741 BUILTIN_ROW(__sync_xor_and_fetch), 3742 BUILTIN_ROW(__sync_nand_and_fetch), 3743 3744 BUILTIN_ROW(__sync_val_compare_and_swap), 3745 BUILTIN_ROW(__sync_bool_compare_and_swap), 3746 BUILTIN_ROW(__sync_lock_test_and_set), 3747 BUILTIN_ROW(__sync_lock_release), 3748 BUILTIN_ROW(__sync_swap) 3749 }; 3750 #undef BUILTIN_ROW 3751 3752 // Determine the index of the size. 3753 unsigned SizeIndex; 3754 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 3755 case 1: SizeIndex = 0; break; 3756 case 2: SizeIndex = 1; break; 3757 case 4: SizeIndex = 2; break; 3758 case 8: SizeIndex = 3; break; 3759 case 16: SizeIndex = 4; break; 3760 default: 3761 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size) 3762 << FirstArg->getType() << FirstArg->getSourceRange(); 3763 return ExprError(); 3764 } 3765 3766 // Each of these builtins has one pointer argument, followed by some number of 3767 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 3768 // that we ignore. Find out which row of BuiltinIndices to read from as well 3769 // as the number of fixed args. 3770 unsigned BuiltinID = FDecl->getBuiltinID(); 3771 unsigned BuiltinIndex, NumFixed = 1; 3772 bool WarnAboutSemanticsChange = false; 3773 switch (BuiltinID) { 3774 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 3775 case Builtin::BI__sync_fetch_and_add: 3776 case Builtin::BI__sync_fetch_and_add_1: 3777 case Builtin::BI__sync_fetch_and_add_2: 3778 case Builtin::BI__sync_fetch_and_add_4: 3779 case Builtin::BI__sync_fetch_and_add_8: 3780 case Builtin::BI__sync_fetch_and_add_16: 3781 BuiltinIndex = 0; 3782 break; 3783 3784 case Builtin::BI__sync_fetch_and_sub: 3785 case Builtin::BI__sync_fetch_and_sub_1: 3786 case Builtin::BI__sync_fetch_and_sub_2: 3787 case Builtin::BI__sync_fetch_and_sub_4: 3788 case Builtin::BI__sync_fetch_and_sub_8: 3789 case Builtin::BI__sync_fetch_and_sub_16: 3790 BuiltinIndex = 1; 3791 break; 3792 3793 case Builtin::BI__sync_fetch_and_or: 3794 case Builtin::BI__sync_fetch_and_or_1: 3795 case Builtin::BI__sync_fetch_and_or_2: 3796 case Builtin::BI__sync_fetch_and_or_4: 3797 case Builtin::BI__sync_fetch_and_or_8: 3798 case Builtin::BI__sync_fetch_and_or_16: 3799 BuiltinIndex = 2; 3800 break; 3801 3802 case Builtin::BI__sync_fetch_and_and: 3803 case Builtin::BI__sync_fetch_and_and_1: 3804 case Builtin::BI__sync_fetch_and_and_2: 3805 case Builtin::BI__sync_fetch_and_and_4: 3806 case Builtin::BI__sync_fetch_and_and_8: 3807 case Builtin::BI__sync_fetch_and_and_16: 3808 BuiltinIndex = 3; 3809 break; 3810 3811 case Builtin::BI__sync_fetch_and_xor: 3812 case Builtin::BI__sync_fetch_and_xor_1: 3813 case Builtin::BI__sync_fetch_and_xor_2: 3814 case Builtin::BI__sync_fetch_and_xor_4: 3815 case Builtin::BI__sync_fetch_and_xor_8: 3816 case Builtin::BI__sync_fetch_and_xor_16: 3817 BuiltinIndex = 4; 3818 break; 3819 3820 case Builtin::BI__sync_fetch_and_nand: 3821 case Builtin::BI__sync_fetch_and_nand_1: 3822 case Builtin::BI__sync_fetch_and_nand_2: 3823 case Builtin::BI__sync_fetch_and_nand_4: 3824 case Builtin::BI__sync_fetch_and_nand_8: 3825 case Builtin::BI__sync_fetch_and_nand_16: 3826 BuiltinIndex = 5; 3827 WarnAboutSemanticsChange = true; 3828 break; 3829 3830 case Builtin::BI__sync_add_and_fetch: 3831 case Builtin::BI__sync_add_and_fetch_1: 3832 case Builtin::BI__sync_add_and_fetch_2: 3833 case Builtin::BI__sync_add_and_fetch_4: 3834 case Builtin::BI__sync_add_and_fetch_8: 3835 case Builtin::BI__sync_add_and_fetch_16: 3836 BuiltinIndex = 6; 3837 break; 3838 3839 case Builtin::BI__sync_sub_and_fetch: 3840 case Builtin::BI__sync_sub_and_fetch_1: 3841 case Builtin::BI__sync_sub_and_fetch_2: 3842 case Builtin::BI__sync_sub_and_fetch_4: 3843 case Builtin::BI__sync_sub_and_fetch_8: 3844 case Builtin::BI__sync_sub_and_fetch_16: 3845 BuiltinIndex = 7; 3846 break; 3847 3848 case Builtin::BI__sync_and_and_fetch: 3849 case Builtin::BI__sync_and_and_fetch_1: 3850 case Builtin::BI__sync_and_and_fetch_2: 3851 case Builtin::BI__sync_and_and_fetch_4: 3852 case Builtin::BI__sync_and_and_fetch_8: 3853 case Builtin::BI__sync_and_and_fetch_16: 3854 BuiltinIndex = 8; 3855 break; 3856 3857 case Builtin::BI__sync_or_and_fetch: 3858 case Builtin::BI__sync_or_and_fetch_1: 3859 case Builtin::BI__sync_or_and_fetch_2: 3860 case Builtin::BI__sync_or_and_fetch_4: 3861 case Builtin::BI__sync_or_and_fetch_8: 3862 case Builtin::BI__sync_or_and_fetch_16: 3863 BuiltinIndex = 9; 3864 break; 3865 3866 case Builtin::BI__sync_xor_and_fetch: 3867 case Builtin::BI__sync_xor_and_fetch_1: 3868 case Builtin::BI__sync_xor_and_fetch_2: 3869 case Builtin::BI__sync_xor_and_fetch_4: 3870 case Builtin::BI__sync_xor_and_fetch_8: 3871 case Builtin::BI__sync_xor_and_fetch_16: 3872 BuiltinIndex = 10; 3873 break; 3874 3875 case Builtin::BI__sync_nand_and_fetch: 3876 case Builtin::BI__sync_nand_and_fetch_1: 3877 case Builtin::BI__sync_nand_and_fetch_2: 3878 case Builtin::BI__sync_nand_and_fetch_4: 3879 case Builtin::BI__sync_nand_and_fetch_8: 3880 case Builtin::BI__sync_nand_and_fetch_16: 3881 BuiltinIndex = 11; 3882 WarnAboutSemanticsChange = true; 3883 break; 3884 3885 case Builtin::BI__sync_val_compare_and_swap: 3886 case Builtin::BI__sync_val_compare_and_swap_1: 3887 case Builtin::BI__sync_val_compare_and_swap_2: 3888 case Builtin::BI__sync_val_compare_and_swap_4: 3889 case Builtin::BI__sync_val_compare_and_swap_8: 3890 case Builtin::BI__sync_val_compare_and_swap_16: 3891 BuiltinIndex = 12; 3892 NumFixed = 2; 3893 break; 3894 3895 case Builtin::BI__sync_bool_compare_and_swap: 3896 case Builtin::BI__sync_bool_compare_and_swap_1: 3897 case Builtin::BI__sync_bool_compare_and_swap_2: 3898 case Builtin::BI__sync_bool_compare_and_swap_4: 3899 case Builtin::BI__sync_bool_compare_and_swap_8: 3900 case Builtin::BI__sync_bool_compare_and_swap_16: 3901 BuiltinIndex = 13; 3902 NumFixed = 2; 3903 ResultType = Context.BoolTy; 3904 break; 3905 3906 case Builtin::BI__sync_lock_test_and_set: 3907 case Builtin::BI__sync_lock_test_and_set_1: 3908 case Builtin::BI__sync_lock_test_and_set_2: 3909 case Builtin::BI__sync_lock_test_and_set_4: 3910 case Builtin::BI__sync_lock_test_and_set_8: 3911 case Builtin::BI__sync_lock_test_and_set_16: 3912 BuiltinIndex = 14; 3913 break; 3914 3915 case Builtin::BI__sync_lock_release: 3916 case Builtin::BI__sync_lock_release_1: 3917 case Builtin::BI__sync_lock_release_2: 3918 case Builtin::BI__sync_lock_release_4: 3919 case Builtin::BI__sync_lock_release_8: 3920 case Builtin::BI__sync_lock_release_16: 3921 BuiltinIndex = 15; 3922 NumFixed = 0; 3923 ResultType = Context.VoidTy; 3924 break; 3925 3926 case Builtin::BI__sync_swap: 3927 case Builtin::BI__sync_swap_1: 3928 case Builtin::BI__sync_swap_2: 3929 case Builtin::BI__sync_swap_4: 3930 case Builtin::BI__sync_swap_8: 3931 case Builtin::BI__sync_swap_16: 3932 BuiltinIndex = 16; 3933 break; 3934 } 3935 3936 // Now that we know how many fixed arguments we expect, first check that we 3937 // have at least that many. 3938 if (TheCall->getNumArgs() < 1+NumFixed) { 3939 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 3940 << 0 << 1+NumFixed << TheCall->getNumArgs() 3941 << TheCall->getCallee()->getSourceRange(); 3942 return ExprError(); 3943 } 3944 3945 if (WarnAboutSemanticsChange) { 3946 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change) 3947 << TheCall->getCallee()->getSourceRange(); 3948 } 3949 3950 // Get the decl for the concrete builtin from this, we can tell what the 3951 // concrete integer type we should convert to is. 3952 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 3953 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 3954 FunctionDecl *NewBuiltinDecl; 3955 if (NewBuiltinID == BuiltinID) 3956 NewBuiltinDecl = FDecl; 3957 else { 3958 // Perform builtin lookup to avoid redeclaring it. 3959 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 3960 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName); 3961 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 3962 assert(Res.getFoundDecl()); 3963 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 3964 if (!NewBuiltinDecl) 3965 return ExprError(); 3966 } 3967 3968 // The first argument --- the pointer --- has a fixed type; we 3969 // deduce the types of the rest of the arguments accordingly. Walk 3970 // the remaining arguments, converting them to the deduced value type. 3971 for (unsigned i = 0; i != NumFixed; ++i) { 3972 ExprResult Arg = TheCall->getArg(i+1); 3973 3974 // GCC does an implicit conversion to the pointer or integer ValType. This 3975 // can fail in some cases (1i -> int**), check for this error case now. 3976 // Initialize the argument. 3977 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 3978 ValType, /*consume*/ false); 3979 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 3980 if (Arg.isInvalid()) 3981 return ExprError(); 3982 3983 // Okay, we have something that *can* be converted to the right type. Check 3984 // to see if there is a potentially weird extension going on here. This can 3985 // happen when you do an atomic operation on something like an char* and 3986 // pass in 42. The 42 gets converted to char. This is even more strange 3987 // for things like 45.123 -> char, etc. 3988 // FIXME: Do this check. 3989 TheCall->setArg(i+1, Arg.get()); 3990 } 3991 3992 ASTContext& Context = this->getASTContext(); 3993 3994 // Create a new DeclRefExpr to refer to the new decl. 3995 DeclRefExpr* NewDRE = DeclRefExpr::Create( 3996 Context, 3997 DRE->getQualifierLoc(), 3998 SourceLocation(), 3999 NewBuiltinDecl, 4000 /*enclosing*/ false, 4001 DRE->getLocation(), 4002 Context.BuiltinFnTy, 4003 DRE->getValueKind()); 4004 4005 // Set the callee in the CallExpr. 4006 // FIXME: This loses syntactic information. 4007 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 4008 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 4009 CK_BuiltinFnToFnPtr); 4010 TheCall->setCallee(PromotedCall.get()); 4011 4012 // Change the result type of the call to match the original value type. This 4013 // is arbitrary, but the codegen for these builtins ins design to handle it 4014 // gracefully. 4015 TheCall->setType(ResultType); 4016 4017 return TheCallResult; 4018 } 4019 4020 /// SemaBuiltinNontemporalOverloaded - We have a call to 4021 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 4022 /// overloaded function based on the pointer type of its last argument. 4023 /// 4024 /// This function goes through and does final semantic checking for these 4025 /// builtins. 4026 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 4027 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 4028 DeclRefExpr *DRE = 4029 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4030 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 4031 unsigned BuiltinID = FDecl->getBuiltinID(); 4032 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 4033 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 4034 "Unexpected nontemporal load/store builtin!"); 4035 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 4036 unsigned numArgs = isStore ? 2 : 1; 4037 4038 // Ensure that we have the proper number of arguments. 4039 if (checkArgCount(*this, TheCall, numArgs)) 4040 return ExprError(); 4041 4042 // Inspect the last argument of the nontemporal builtin. This should always 4043 // be a pointer type, from which we imply the type of the memory access. 4044 // Because it is a pointer type, we don't have to worry about any implicit 4045 // casts here. 4046 Expr *PointerArg = TheCall->getArg(numArgs - 1); 4047 ExprResult PointerArgResult = 4048 DefaultFunctionArrayLvalueConversion(PointerArg); 4049 4050 if (PointerArgResult.isInvalid()) 4051 return ExprError(); 4052 PointerArg = PointerArgResult.get(); 4053 TheCall->setArg(numArgs - 1, PointerArg); 4054 4055 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 4056 if (!pointerType) { 4057 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer) 4058 << PointerArg->getType() << PointerArg->getSourceRange(); 4059 return ExprError(); 4060 } 4061 4062 QualType ValType = pointerType->getPointeeType(); 4063 4064 // Strip any qualifiers off ValType. 4065 ValType = ValType.getUnqualifiedType(); 4066 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 4067 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 4068 !ValType->isVectorType()) { 4069 Diag(DRE->getLocStart(), 4070 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 4071 << PointerArg->getType() << PointerArg->getSourceRange(); 4072 return ExprError(); 4073 } 4074 4075 if (!isStore) { 4076 TheCall->setType(ValType); 4077 return TheCallResult; 4078 } 4079 4080 ExprResult ValArg = TheCall->getArg(0); 4081 InitializedEntity Entity = InitializedEntity::InitializeParameter( 4082 Context, ValType, /*consume*/ false); 4083 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 4084 if (ValArg.isInvalid()) 4085 return ExprError(); 4086 4087 TheCall->setArg(0, ValArg.get()); 4088 TheCall->setType(Context.VoidTy); 4089 return TheCallResult; 4090 } 4091 4092 /// CheckObjCString - Checks that the argument to the builtin 4093 /// CFString constructor is correct 4094 /// Note: It might also make sense to do the UTF-16 conversion here (would 4095 /// simplify the backend). 4096 bool Sema::CheckObjCString(Expr *Arg) { 4097 Arg = Arg->IgnoreParenCasts(); 4098 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 4099 4100 if (!Literal || !Literal->isAscii()) { 4101 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant) 4102 << Arg->getSourceRange(); 4103 return true; 4104 } 4105 4106 if (Literal->containsNonAsciiOrNull()) { 4107 StringRef String = Literal->getString(); 4108 unsigned NumBytes = String.size(); 4109 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 4110 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 4111 llvm::UTF16 *ToPtr = &ToBuf[0]; 4112 4113 llvm::ConversionResult Result = 4114 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 4115 ToPtr + NumBytes, llvm::strictConversion); 4116 // Check for conversion failure. 4117 if (Result != llvm::conversionOK) 4118 Diag(Arg->getLocStart(), 4119 diag::warn_cfstring_truncated) << Arg->getSourceRange(); 4120 } 4121 return false; 4122 } 4123 4124 /// CheckObjCString - Checks that the format string argument to the os_log() 4125 /// and os_trace() functions is correct, and converts it to const char *. 4126 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 4127 Arg = Arg->IgnoreParenCasts(); 4128 auto *Literal = dyn_cast<StringLiteral>(Arg); 4129 if (!Literal) { 4130 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 4131 Literal = ObjcLiteral->getString(); 4132 } 4133 } 4134 4135 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 4136 return ExprError( 4137 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant) 4138 << Arg->getSourceRange()); 4139 } 4140 4141 ExprResult Result(Literal); 4142 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 4143 InitializedEntity Entity = 4144 InitializedEntity::InitializeParameter(Context, ResultTy, false); 4145 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 4146 return Result; 4147 } 4148 4149 /// Check that the user is calling the appropriate va_start builtin for the 4150 /// target and calling convention. 4151 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 4152 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 4153 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 4154 bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64; 4155 bool IsWindows = TT.isOSWindows(); 4156 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 4157 if (IsX64 || IsAArch64) { 4158 CallingConv CC = CC_C; 4159 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 4160 CC = FD->getType()->getAs<FunctionType>()->getCallConv(); 4161 if (IsMSVAStart) { 4162 // Don't allow this in System V ABI functions. 4163 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 4164 return S.Diag(Fn->getLocStart(), 4165 diag::err_ms_va_start_used_in_sysv_function); 4166 } else { 4167 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 4168 // On x64 Windows, don't allow this in System V ABI functions. 4169 // (Yes, that means there's no corresponding way to support variadic 4170 // System V ABI functions on Windows.) 4171 if ((IsWindows && CC == CC_X86_64SysV) || 4172 (!IsWindows && CC == CC_Win64)) 4173 return S.Diag(Fn->getLocStart(), 4174 diag::err_va_start_used_in_wrong_abi_function) 4175 << !IsWindows; 4176 } 4177 return false; 4178 } 4179 4180 if (IsMSVAStart) 4181 return S.Diag(Fn->getLocStart(), diag::err_builtin_x64_aarch64_only); 4182 return false; 4183 } 4184 4185 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 4186 ParmVarDecl **LastParam = nullptr) { 4187 // Determine whether the current function, block, or obj-c method is variadic 4188 // and get its parameter list. 4189 bool IsVariadic = false; 4190 ArrayRef<ParmVarDecl *> Params; 4191 DeclContext *Caller = S.CurContext; 4192 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 4193 IsVariadic = Block->isVariadic(); 4194 Params = Block->parameters(); 4195 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 4196 IsVariadic = FD->isVariadic(); 4197 Params = FD->parameters(); 4198 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 4199 IsVariadic = MD->isVariadic(); 4200 // FIXME: This isn't correct for methods (results in bogus warning). 4201 Params = MD->parameters(); 4202 } else if (isa<CapturedDecl>(Caller)) { 4203 // We don't support va_start in a CapturedDecl. 4204 S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt); 4205 return true; 4206 } else { 4207 // This must be some other declcontext that parses exprs. 4208 S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function); 4209 return true; 4210 } 4211 4212 if (!IsVariadic) { 4213 S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function); 4214 return true; 4215 } 4216 4217 if (LastParam) 4218 *LastParam = Params.empty() ? nullptr : Params.back(); 4219 4220 return false; 4221 } 4222 4223 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 4224 /// for validity. Emit an error and return true on failure; return false 4225 /// on success. 4226 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 4227 Expr *Fn = TheCall->getCallee(); 4228 4229 if (checkVAStartABI(*this, BuiltinID, Fn)) 4230 return true; 4231 4232 if (TheCall->getNumArgs() > 2) { 4233 Diag(TheCall->getArg(2)->getLocStart(), 4234 diag::err_typecheck_call_too_many_args) 4235 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 4236 << Fn->getSourceRange() 4237 << SourceRange(TheCall->getArg(2)->getLocStart(), 4238 (*(TheCall->arg_end()-1))->getLocEnd()); 4239 return true; 4240 } 4241 4242 if (TheCall->getNumArgs() < 2) { 4243 return Diag(TheCall->getLocEnd(), 4244 diag::err_typecheck_call_too_few_args_at_least) 4245 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 4246 } 4247 4248 // Type-check the first argument normally. 4249 if (checkBuiltinArgument(*this, TheCall, 0)) 4250 return true; 4251 4252 // Check that the current function is variadic, and get its last parameter. 4253 ParmVarDecl *LastParam; 4254 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 4255 return true; 4256 4257 // Verify that the second argument to the builtin is the last argument of the 4258 // current function or method. 4259 bool SecondArgIsLastNamedArgument = false; 4260 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 4261 4262 // These are valid if SecondArgIsLastNamedArgument is false after the next 4263 // block. 4264 QualType Type; 4265 SourceLocation ParamLoc; 4266 bool IsCRegister = false; 4267 4268 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 4269 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 4270 SecondArgIsLastNamedArgument = PV == LastParam; 4271 4272 Type = PV->getType(); 4273 ParamLoc = PV->getLocation(); 4274 IsCRegister = 4275 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 4276 } 4277 } 4278 4279 if (!SecondArgIsLastNamedArgument) 4280 Diag(TheCall->getArg(1)->getLocStart(), 4281 diag::warn_second_arg_of_va_start_not_last_named_param); 4282 else if (IsCRegister || Type->isReferenceType() || 4283 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 4284 // Promotable integers are UB, but enumerations need a bit of 4285 // extra checking to see what their promotable type actually is. 4286 if (!Type->isPromotableIntegerType()) 4287 return false; 4288 if (!Type->isEnumeralType()) 4289 return true; 4290 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl(); 4291 return !(ED && 4292 Context.typesAreCompatible(ED->getPromotionType(), Type)); 4293 }()) { 4294 unsigned Reason = 0; 4295 if (Type->isReferenceType()) Reason = 1; 4296 else if (IsCRegister) Reason = 2; 4297 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason; 4298 Diag(ParamLoc, diag::note_parameter_type) << Type; 4299 } 4300 4301 TheCall->setType(Context.VoidTy); 4302 return false; 4303 } 4304 4305 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 4306 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 4307 // const char *named_addr); 4308 4309 Expr *Func = Call->getCallee(); 4310 4311 if (Call->getNumArgs() < 3) 4312 return Diag(Call->getLocEnd(), 4313 diag::err_typecheck_call_too_few_args_at_least) 4314 << 0 /*function call*/ << 3 << Call->getNumArgs(); 4315 4316 // Type-check the first argument normally. 4317 if (checkBuiltinArgument(*this, Call, 0)) 4318 return true; 4319 4320 // Check that the current function is variadic. 4321 if (checkVAStartIsInVariadicFunction(*this, Func)) 4322 return true; 4323 4324 // __va_start on Windows does not validate the parameter qualifiers 4325 4326 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 4327 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 4328 4329 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 4330 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 4331 4332 const QualType &ConstCharPtrTy = 4333 Context.getPointerType(Context.CharTy.withConst()); 4334 if (!Arg1Ty->isPointerType() || 4335 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy) 4336 Diag(Arg1->getLocStart(), diag::err_typecheck_convert_incompatible) 4337 << Arg1->getType() << ConstCharPtrTy 4338 << 1 /* different class */ 4339 << 0 /* qualifier difference */ 4340 << 3 /* parameter mismatch */ 4341 << 2 << Arg1->getType() << ConstCharPtrTy; 4342 4343 const QualType SizeTy = Context.getSizeType(); 4344 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 4345 Diag(Arg2->getLocStart(), diag::err_typecheck_convert_incompatible) 4346 << Arg2->getType() << SizeTy 4347 << 1 /* different class */ 4348 << 0 /* qualifier difference */ 4349 << 3 /* parameter mismatch */ 4350 << 3 << Arg2->getType() << SizeTy; 4351 4352 return false; 4353 } 4354 4355 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 4356 /// friends. This is declared to take (...), so we have to check everything. 4357 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 4358 if (TheCall->getNumArgs() < 2) 4359 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 4360 << 0 << 2 << TheCall->getNumArgs()/*function call*/; 4361 if (TheCall->getNumArgs() > 2) 4362 return Diag(TheCall->getArg(2)->getLocStart(), 4363 diag::err_typecheck_call_too_many_args) 4364 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 4365 << SourceRange(TheCall->getArg(2)->getLocStart(), 4366 (*(TheCall->arg_end()-1))->getLocEnd()); 4367 4368 ExprResult OrigArg0 = TheCall->getArg(0); 4369 ExprResult OrigArg1 = TheCall->getArg(1); 4370 4371 // Do standard promotions between the two arguments, returning their common 4372 // type. 4373 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false); 4374 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 4375 return true; 4376 4377 // Make sure any conversions are pushed back into the call; this is 4378 // type safe since unordered compare builtins are declared as "_Bool 4379 // foo(...)". 4380 TheCall->setArg(0, OrigArg0.get()); 4381 TheCall->setArg(1, OrigArg1.get()); 4382 4383 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 4384 return false; 4385 4386 // If the common type isn't a real floating type, then the arguments were 4387 // invalid for this operation. 4388 if (Res.isNull() || !Res->isRealFloatingType()) 4389 return Diag(OrigArg0.get()->getLocStart(), 4390 diag::err_typecheck_call_invalid_ordered_compare) 4391 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 4392 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd()); 4393 4394 return false; 4395 } 4396 4397 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 4398 /// __builtin_isnan and friends. This is declared to take (...), so we have 4399 /// to check everything. We expect the last argument to be a floating point 4400 /// value. 4401 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 4402 if (TheCall->getNumArgs() < NumArgs) 4403 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 4404 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/; 4405 if (TheCall->getNumArgs() > NumArgs) 4406 return Diag(TheCall->getArg(NumArgs)->getLocStart(), 4407 diag::err_typecheck_call_too_many_args) 4408 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 4409 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(), 4410 (*(TheCall->arg_end()-1))->getLocEnd()); 4411 4412 Expr *OrigArg = TheCall->getArg(NumArgs-1); 4413 4414 if (OrigArg->isTypeDependent()) 4415 return false; 4416 4417 // This operation requires a non-_Complex floating-point number. 4418 if (!OrigArg->getType()->isRealFloatingType()) 4419 return Diag(OrigArg->getLocStart(), 4420 diag::err_typecheck_call_invalid_unary_fp) 4421 << OrigArg->getType() << OrigArg->getSourceRange(); 4422 4423 // If this is an implicit conversion from float -> float or double, remove it. 4424 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) { 4425 // Only remove standard FloatCasts, leaving other casts inplace 4426 if (Cast->getCastKind() == CK_FloatingCast) { 4427 Expr *CastArg = Cast->getSubExpr(); 4428 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) { 4429 assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) || 4430 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) && 4431 "promotion from float to either float or double is the only expected cast here"); 4432 Cast->setSubExpr(nullptr); 4433 TheCall->setArg(NumArgs-1, CastArg); 4434 } 4435 } 4436 } 4437 4438 return false; 4439 } 4440 4441 // Customized Sema Checking for VSX builtins that have the following signature: 4442 // vector [...] builtinName(vector [...], vector [...], const int); 4443 // Which takes the same type of vectors (any legal vector type) for the first 4444 // two arguments and takes compile time constant for the third argument. 4445 // Example builtins are : 4446 // vector double vec_xxpermdi(vector double, vector double, int); 4447 // vector short vec_xxsldwi(vector short, vector short, int); 4448 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 4449 unsigned ExpectedNumArgs = 3; 4450 if (TheCall->getNumArgs() < ExpectedNumArgs) 4451 return Diag(TheCall->getLocEnd(), 4452 diag::err_typecheck_call_too_few_args_at_least) 4453 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 4454 << TheCall->getSourceRange(); 4455 4456 if (TheCall->getNumArgs() > ExpectedNumArgs) 4457 return Diag(TheCall->getLocEnd(), 4458 diag::err_typecheck_call_too_many_args_at_most) 4459 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 4460 << TheCall->getSourceRange(); 4461 4462 // Check the third argument is a compile time constant 4463 llvm::APSInt Value; 4464 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context)) 4465 return Diag(TheCall->getLocStart(), 4466 diag::err_vsx_builtin_nonconstant_argument) 4467 << 3 /* argument index */ << TheCall->getDirectCallee() 4468 << SourceRange(TheCall->getArg(2)->getLocStart(), 4469 TheCall->getArg(2)->getLocEnd()); 4470 4471 QualType Arg1Ty = TheCall->getArg(0)->getType(); 4472 QualType Arg2Ty = TheCall->getArg(1)->getType(); 4473 4474 // Check the type of argument 1 and argument 2 are vectors. 4475 SourceLocation BuiltinLoc = TheCall->getLocStart(); 4476 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 4477 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 4478 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 4479 << TheCall->getDirectCallee() 4480 << SourceRange(TheCall->getArg(0)->getLocStart(), 4481 TheCall->getArg(1)->getLocEnd()); 4482 } 4483 4484 // Check the first two arguments are the same type. 4485 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 4486 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 4487 << TheCall->getDirectCallee() 4488 << SourceRange(TheCall->getArg(0)->getLocStart(), 4489 TheCall->getArg(1)->getLocEnd()); 4490 } 4491 4492 // When default clang type checking is turned off and the customized type 4493 // checking is used, the returning type of the function must be explicitly 4494 // set. Otherwise it is _Bool by default. 4495 TheCall->setType(Arg1Ty); 4496 4497 return false; 4498 } 4499 4500 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 4501 // This is declared to take (...), so we have to check everything. 4502 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 4503 if (TheCall->getNumArgs() < 2) 4504 return ExprError(Diag(TheCall->getLocEnd(), 4505 diag::err_typecheck_call_too_few_args_at_least) 4506 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 4507 << TheCall->getSourceRange()); 4508 4509 // Determine which of the following types of shufflevector we're checking: 4510 // 1) unary, vector mask: (lhs, mask) 4511 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 4512 QualType resType = TheCall->getArg(0)->getType(); 4513 unsigned numElements = 0; 4514 4515 if (!TheCall->getArg(0)->isTypeDependent() && 4516 !TheCall->getArg(1)->isTypeDependent()) { 4517 QualType LHSType = TheCall->getArg(0)->getType(); 4518 QualType RHSType = TheCall->getArg(1)->getType(); 4519 4520 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 4521 return ExprError(Diag(TheCall->getLocStart(), 4522 diag::err_vec_builtin_non_vector) 4523 << TheCall->getDirectCallee() 4524 << SourceRange(TheCall->getArg(0)->getLocStart(), 4525 TheCall->getArg(1)->getLocEnd())); 4526 4527 numElements = LHSType->getAs<VectorType>()->getNumElements(); 4528 unsigned numResElements = TheCall->getNumArgs() - 2; 4529 4530 // Check to see if we have a call with 2 vector arguments, the unary shuffle 4531 // with mask. If so, verify that RHS is an integer vector type with the 4532 // same number of elts as lhs. 4533 if (TheCall->getNumArgs() == 2) { 4534 if (!RHSType->hasIntegerRepresentation() || 4535 RHSType->getAs<VectorType>()->getNumElements() != numElements) 4536 return ExprError(Diag(TheCall->getLocStart(), 4537 diag::err_vec_builtin_incompatible_vector) 4538 << TheCall->getDirectCallee() 4539 << SourceRange(TheCall->getArg(1)->getLocStart(), 4540 TheCall->getArg(1)->getLocEnd())); 4541 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 4542 return ExprError(Diag(TheCall->getLocStart(), 4543 diag::err_vec_builtin_incompatible_vector) 4544 << TheCall->getDirectCallee() 4545 << SourceRange(TheCall->getArg(0)->getLocStart(), 4546 TheCall->getArg(1)->getLocEnd())); 4547 } else if (numElements != numResElements) { 4548 QualType eltType = LHSType->getAs<VectorType>()->getElementType(); 4549 resType = Context.getVectorType(eltType, numResElements, 4550 VectorType::GenericVector); 4551 } 4552 } 4553 4554 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 4555 if (TheCall->getArg(i)->isTypeDependent() || 4556 TheCall->getArg(i)->isValueDependent()) 4557 continue; 4558 4559 llvm::APSInt Result(32); 4560 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 4561 return ExprError(Diag(TheCall->getLocStart(), 4562 diag::err_shufflevector_nonconstant_argument) 4563 << TheCall->getArg(i)->getSourceRange()); 4564 4565 // Allow -1 which will be translated to undef in the IR. 4566 if (Result.isSigned() && Result.isAllOnesValue()) 4567 continue; 4568 4569 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 4570 return ExprError(Diag(TheCall->getLocStart(), 4571 diag::err_shufflevector_argument_too_large) 4572 << TheCall->getArg(i)->getSourceRange()); 4573 } 4574 4575 SmallVector<Expr*, 32> exprs; 4576 4577 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 4578 exprs.push_back(TheCall->getArg(i)); 4579 TheCall->setArg(i, nullptr); 4580 } 4581 4582 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 4583 TheCall->getCallee()->getLocStart(), 4584 TheCall->getRParenLoc()); 4585 } 4586 4587 /// SemaConvertVectorExpr - Handle __builtin_convertvector 4588 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 4589 SourceLocation BuiltinLoc, 4590 SourceLocation RParenLoc) { 4591 ExprValueKind VK = VK_RValue; 4592 ExprObjectKind OK = OK_Ordinary; 4593 QualType DstTy = TInfo->getType(); 4594 QualType SrcTy = E->getType(); 4595 4596 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 4597 return ExprError(Diag(BuiltinLoc, 4598 diag::err_convertvector_non_vector) 4599 << E->getSourceRange()); 4600 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 4601 return ExprError(Diag(BuiltinLoc, 4602 diag::err_convertvector_non_vector_type)); 4603 4604 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 4605 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements(); 4606 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements(); 4607 if (SrcElts != DstElts) 4608 return ExprError(Diag(BuiltinLoc, 4609 diag::err_convertvector_incompatible_vector) 4610 << E->getSourceRange()); 4611 } 4612 4613 return new (Context) 4614 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 4615 } 4616 4617 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 4618 // This is declared to take (const void*, ...) and can take two 4619 // optional constant int args. 4620 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 4621 unsigned NumArgs = TheCall->getNumArgs(); 4622 4623 if (NumArgs > 3) 4624 return Diag(TheCall->getLocEnd(), 4625 diag::err_typecheck_call_too_many_args_at_most) 4626 << 0 /*function call*/ << 3 << NumArgs 4627 << TheCall->getSourceRange(); 4628 4629 // Argument 0 is checked for us and the remaining arguments must be 4630 // constant integers. 4631 for (unsigned i = 1; i != NumArgs; ++i) 4632 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 4633 return true; 4634 4635 return false; 4636 } 4637 4638 /// SemaBuiltinAssume - Handle __assume (MS Extension). 4639 // __assume does not evaluate its arguments, and should warn if its argument 4640 // has side effects. 4641 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 4642 Expr *Arg = TheCall->getArg(0); 4643 if (Arg->isInstantiationDependent()) return false; 4644 4645 if (Arg->HasSideEffects(Context)) 4646 Diag(Arg->getLocStart(), diag::warn_assume_side_effects) 4647 << Arg->getSourceRange() 4648 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 4649 4650 return false; 4651 } 4652 4653 /// Handle __builtin_alloca_with_align. This is declared 4654 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 4655 /// than 8. 4656 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 4657 // The alignment must be a constant integer. 4658 Expr *Arg = TheCall->getArg(1); 4659 4660 // We can't check the value of a dependent argument. 4661 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 4662 if (const auto *UE = 4663 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 4664 if (UE->getKind() == UETT_AlignOf) 4665 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof) 4666 << Arg->getSourceRange(); 4667 4668 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 4669 4670 if (!Result.isPowerOf2()) 4671 return Diag(TheCall->getLocStart(), 4672 diag::err_alignment_not_power_of_two) 4673 << Arg->getSourceRange(); 4674 4675 if (Result < Context.getCharWidth()) 4676 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small) 4677 << (unsigned)Context.getCharWidth() 4678 << Arg->getSourceRange(); 4679 4680 if (Result > std::numeric_limits<int32_t>::max()) 4681 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big) 4682 << std::numeric_limits<int32_t>::max() 4683 << Arg->getSourceRange(); 4684 } 4685 4686 return false; 4687 } 4688 4689 /// Handle __builtin_assume_aligned. This is declared 4690 /// as (const void*, size_t, ...) and can take one optional constant int arg. 4691 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 4692 unsigned NumArgs = TheCall->getNumArgs(); 4693 4694 if (NumArgs > 3) 4695 return Diag(TheCall->getLocEnd(), 4696 diag::err_typecheck_call_too_many_args_at_most) 4697 << 0 /*function call*/ << 3 << NumArgs 4698 << TheCall->getSourceRange(); 4699 4700 // The alignment must be a constant integer. 4701 Expr *Arg = TheCall->getArg(1); 4702 4703 // We can't check the value of a dependent argument. 4704 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 4705 llvm::APSInt Result; 4706 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 4707 return true; 4708 4709 if (!Result.isPowerOf2()) 4710 return Diag(TheCall->getLocStart(), 4711 diag::err_alignment_not_power_of_two) 4712 << Arg->getSourceRange(); 4713 } 4714 4715 if (NumArgs > 2) { 4716 ExprResult Arg(TheCall->getArg(2)); 4717 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 4718 Context.getSizeType(), false); 4719 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4720 if (Arg.isInvalid()) return true; 4721 TheCall->setArg(2, Arg.get()); 4722 } 4723 4724 return false; 4725 } 4726 4727 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 4728 unsigned BuiltinID = 4729 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 4730 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 4731 4732 unsigned NumArgs = TheCall->getNumArgs(); 4733 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 4734 if (NumArgs < NumRequiredArgs) { 4735 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 4736 << 0 /* function call */ << NumRequiredArgs << NumArgs 4737 << TheCall->getSourceRange(); 4738 } 4739 if (NumArgs >= NumRequiredArgs + 0x100) { 4740 return Diag(TheCall->getLocEnd(), 4741 diag::err_typecheck_call_too_many_args_at_most) 4742 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 4743 << TheCall->getSourceRange(); 4744 } 4745 unsigned i = 0; 4746 4747 // For formatting call, check buffer arg. 4748 if (!IsSizeCall) { 4749 ExprResult Arg(TheCall->getArg(i)); 4750 InitializedEntity Entity = InitializedEntity::InitializeParameter( 4751 Context, Context.VoidPtrTy, false); 4752 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4753 if (Arg.isInvalid()) 4754 return true; 4755 TheCall->setArg(i, Arg.get()); 4756 i++; 4757 } 4758 4759 // Check string literal arg. 4760 unsigned FormatIdx = i; 4761 { 4762 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 4763 if (Arg.isInvalid()) 4764 return true; 4765 TheCall->setArg(i, Arg.get()); 4766 i++; 4767 } 4768 4769 // Make sure variadic args are scalar. 4770 unsigned FirstDataArg = i; 4771 while (i < NumArgs) { 4772 ExprResult Arg = DefaultVariadicArgumentPromotion( 4773 TheCall->getArg(i), VariadicFunction, nullptr); 4774 if (Arg.isInvalid()) 4775 return true; 4776 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 4777 if (ArgSize.getQuantity() >= 0x100) { 4778 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big) 4779 << i << (int)ArgSize.getQuantity() << 0xff 4780 << TheCall->getSourceRange(); 4781 } 4782 TheCall->setArg(i, Arg.get()); 4783 i++; 4784 } 4785 4786 // Check formatting specifiers. NOTE: We're only doing this for the non-size 4787 // call to avoid duplicate diagnostics. 4788 if (!IsSizeCall) { 4789 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 4790 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 4791 bool Success = CheckFormatArguments( 4792 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 4793 VariadicFunction, TheCall->getLocStart(), SourceRange(), 4794 CheckedVarArgs); 4795 if (!Success) 4796 return true; 4797 } 4798 4799 if (IsSizeCall) { 4800 TheCall->setType(Context.getSizeType()); 4801 } else { 4802 TheCall->setType(Context.VoidPtrTy); 4803 } 4804 return false; 4805 } 4806 4807 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 4808 /// TheCall is a constant expression. 4809 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 4810 llvm::APSInt &Result) { 4811 Expr *Arg = TheCall->getArg(ArgNum); 4812 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4813 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 4814 4815 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 4816 4817 if (!Arg->isIntegerConstantExpr(Result, Context)) 4818 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type) 4819 << FDecl->getDeclName() << Arg->getSourceRange(); 4820 4821 return false; 4822 } 4823 4824 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 4825 /// TheCall is a constant expression in the range [Low, High]. 4826 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 4827 int Low, int High) { 4828 llvm::APSInt Result; 4829 4830 // We can't check the value of a dependent argument. 4831 Expr *Arg = TheCall->getArg(ArgNum); 4832 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4833 return false; 4834 4835 // Check constant-ness first. 4836 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4837 return true; 4838 4839 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) 4840 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 4841 << Low << High << Arg->getSourceRange(); 4842 4843 return false; 4844 } 4845 4846 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 4847 /// TheCall is a constant expression is a multiple of Num.. 4848 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 4849 unsigned Num) { 4850 llvm::APSInt Result; 4851 4852 // We can't check the value of a dependent argument. 4853 Expr *Arg = TheCall->getArg(ArgNum); 4854 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4855 return false; 4856 4857 // Check constant-ness first. 4858 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4859 return true; 4860 4861 if (Result.getSExtValue() % Num != 0) 4862 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple) 4863 << Num << Arg->getSourceRange(); 4864 4865 return false; 4866 } 4867 4868 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 4869 /// TheCall is an ARM/AArch64 special register string literal. 4870 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 4871 int ArgNum, unsigned ExpectedFieldNum, 4872 bool AllowName) { 4873 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 4874 BuiltinID == ARM::BI__builtin_arm_wsr64 || 4875 BuiltinID == ARM::BI__builtin_arm_rsr || 4876 BuiltinID == ARM::BI__builtin_arm_rsrp || 4877 BuiltinID == ARM::BI__builtin_arm_wsr || 4878 BuiltinID == ARM::BI__builtin_arm_wsrp; 4879 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 4880 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 4881 BuiltinID == AArch64::BI__builtin_arm_rsr || 4882 BuiltinID == AArch64::BI__builtin_arm_rsrp || 4883 BuiltinID == AArch64::BI__builtin_arm_wsr || 4884 BuiltinID == AArch64::BI__builtin_arm_wsrp; 4885 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 4886 4887 // We can't check the value of a dependent argument. 4888 Expr *Arg = TheCall->getArg(ArgNum); 4889 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4890 return false; 4891 4892 // Check if the argument is a string literal. 4893 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 4894 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal) 4895 << Arg->getSourceRange(); 4896 4897 // Check the type of special register given. 4898 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 4899 SmallVector<StringRef, 6> Fields; 4900 Reg.split(Fields, ":"); 4901 4902 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 4903 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg) 4904 << Arg->getSourceRange(); 4905 4906 // If the string is the name of a register then we cannot check that it is 4907 // valid here but if the string is of one the forms described in ACLE then we 4908 // can check that the supplied fields are integers and within the valid 4909 // ranges. 4910 if (Fields.size() > 1) { 4911 bool FiveFields = Fields.size() == 5; 4912 4913 bool ValidString = true; 4914 if (IsARMBuiltin) { 4915 ValidString &= Fields[0].startswith_lower("cp") || 4916 Fields[0].startswith_lower("p"); 4917 if (ValidString) 4918 Fields[0] = 4919 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 4920 4921 ValidString &= Fields[2].startswith_lower("c"); 4922 if (ValidString) 4923 Fields[2] = Fields[2].drop_front(1); 4924 4925 if (FiveFields) { 4926 ValidString &= Fields[3].startswith_lower("c"); 4927 if (ValidString) 4928 Fields[3] = Fields[3].drop_front(1); 4929 } 4930 } 4931 4932 SmallVector<int, 5> Ranges; 4933 if (FiveFields) 4934 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 4935 else 4936 Ranges.append({15, 7, 15}); 4937 4938 for (unsigned i=0; i<Fields.size(); ++i) { 4939 int IntField; 4940 ValidString &= !Fields[i].getAsInteger(10, IntField); 4941 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 4942 } 4943 4944 if (!ValidString) 4945 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg) 4946 << Arg->getSourceRange(); 4947 } else if (IsAArch64Builtin && Fields.size() == 1) { 4948 // If the register name is one of those that appear in the condition below 4949 // and the special register builtin being used is one of the write builtins, 4950 // then we require that the argument provided for writing to the register 4951 // is an integer constant expression. This is because it will be lowered to 4952 // an MSR (immediate) instruction, so we need to know the immediate at 4953 // compile time. 4954 if (TheCall->getNumArgs() != 2) 4955 return false; 4956 4957 std::string RegLower = Reg.lower(); 4958 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 4959 RegLower != "pan" && RegLower != "uao") 4960 return false; 4961 4962 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 4963 } 4964 4965 return false; 4966 } 4967 4968 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 4969 /// This checks that the target supports __builtin_longjmp and 4970 /// that val is a constant 1. 4971 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 4972 if (!Context.getTargetInfo().hasSjLjLowering()) 4973 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported) 4974 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd()); 4975 4976 Expr *Arg = TheCall->getArg(1); 4977 llvm::APSInt Result; 4978 4979 // TODO: This is less than ideal. Overload this to take a value. 4980 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 4981 return true; 4982 4983 if (Result != 1) 4984 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val) 4985 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 4986 4987 return false; 4988 } 4989 4990 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 4991 /// This checks that the target supports __builtin_setjmp. 4992 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 4993 if (!Context.getTargetInfo().hasSjLjLowering()) 4994 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported) 4995 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd()); 4996 return false; 4997 } 4998 4999 namespace { 5000 5001 class UncoveredArgHandler { 5002 enum { Unknown = -1, AllCovered = -2 }; 5003 5004 signed FirstUncoveredArg = Unknown; 5005 SmallVector<const Expr *, 4> DiagnosticExprs; 5006 5007 public: 5008 UncoveredArgHandler() = default; 5009 5010 bool hasUncoveredArg() const { 5011 return (FirstUncoveredArg >= 0); 5012 } 5013 5014 unsigned getUncoveredArg() const { 5015 assert(hasUncoveredArg() && "no uncovered argument"); 5016 return FirstUncoveredArg; 5017 } 5018 5019 void setAllCovered() { 5020 // A string has been found with all arguments covered, so clear out 5021 // the diagnostics. 5022 DiagnosticExprs.clear(); 5023 FirstUncoveredArg = AllCovered; 5024 } 5025 5026 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 5027 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 5028 5029 // Don't update if a previous string covers all arguments. 5030 if (FirstUncoveredArg == AllCovered) 5031 return; 5032 5033 // UncoveredArgHandler tracks the highest uncovered argument index 5034 // and with it all the strings that match this index. 5035 if (NewFirstUncoveredArg == FirstUncoveredArg) 5036 DiagnosticExprs.push_back(StrExpr); 5037 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 5038 DiagnosticExprs.clear(); 5039 DiagnosticExprs.push_back(StrExpr); 5040 FirstUncoveredArg = NewFirstUncoveredArg; 5041 } 5042 } 5043 5044 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 5045 }; 5046 5047 enum StringLiteralCheckType { 5048 SLCT_NotALiteral, 5049 SLCT_UncheckedLiteral, 5050 SLCT_CheckedLiteral 5051 }; 5052 5053 } // namespace 5054 5055 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 5056 BinaryOperatorKind BinOpKind, 5057 bool AddendIsRight) { 5058 unsigned BitWidth = Offset.getBitWidth(); 5059 unsigned AddendBitWidth = Addend.getBitWidth(); 5060 // There might be negative interim results. 5061 if (Addend.isUnsigned()) { 5062 Addend = Addend.zext(++AddendBitWidth); 5063 Addend.setIsSigned(true); 5064 } 5065 // Adjust the bit width of the APSInts. 5066 if (AddendBitWidth > BitWidth) { 5067 Offset = Offset.sext(AddendBitWidth); 5068 BitWidth = AddendBitWidth; 5069 } else if (BitWidth > AddendBitWidth) { 5070 Addend = Addend.sext(BitWidth); 5071 } 5072 5073 bool Ov = false; 5074 llvm::APSInt ResOffset = Offset; 5075 if (BinOpKind == BO_Add) 5076 ResOffset = Offset.sadd_ov(Addend, Ov); 5077 else { 5078 assert(AddendIsRight && BinOpKind == BO_Sub && 5079 "operator must be add or sub with addend on the right"); 5080 ResOffset = Offset.ssub_ov(Addend, Ov); 5081 } 5082 5083 // We add an offset to a pointer here so we should support an offset as big as 5084 // possible. 5085 if (Ov) { 5086 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 5087 "index (intermediate) result too big"); 5088 Offset = Offset.sext(2 * BitWidth); 5089 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 5090 return; 5091 } 5092 5093 Offset = ResOffset; 5094 } 5095 5096 namespace { 5097 5098 // This is a wrapper class around StringLiteral to support offsetted string 5099 // literals as format strings. It takes the offset into account when returning 5100 // the string and its length or the source locations to display notes correctly. 5101 class FormatStringLiteral { 5102 const StringLiteral *FExpr; 5103 int64_t Offset; 5104 5105 public: 5106 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 5107 : FExpr(fexpr), Offset(Offset) {} 5108 5109 StringRef getString() const { 5110 return FExpr->getString().drop_front(Offset); 5111 } 5112 5113 unsigned getByteLength() const { 5114 return FExpr->getByteLength() - getCharByteWidth() * Offset; 5115 } 5116 5117 unsigned getLength() const { return FExpr->getLength() - Offset; } 5118 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 5119 5120 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 5121 5122 QualType getType() const { return FExpr->getType(); } 5123 5124 bool isAscii() const { return FExpr->isAscii(); } 5125 bool isWide() const { return FExpr->isWide(); } 5126 bool isUTF8() const { return FExpr->isUTF8(); } 5127 bool isUTF16() const { return FExpr->isUTF16(); } 5128 bool isUTF32() const { return FExpr->isUTF32(); } 5129 bool isPascal() const { return FExpr->isPascal(); } 5130 5131 SourceLocation getLocationOfByte( 5132 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 5133 const TargetInfo &Target, unsigned *StartToken = nullptr, 5134 unsigned *StartTokenByteOffset = nullptr) const { 5135 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 5136 StartToken, StartTokenByteOffset); 5137 } 5138 5139 SourceLocation getLocStart() const LLVM_READONLY { 5140 return FExpr->getLocStart().getLocWithOffset(Offset); 5141 } 5142 5143 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); } 5144 }; 5145 5146 } // namespace 5147 5148 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 5149 const Expr *OrigFormatExpr, 5150 ArrayRef<const Expr *> Args, 5151 bool HasVAListArg, unsigned format_idx, 5152 unsigned firstDataArg, 5153 Sema::FormatStringType Type, 5154 bool inFunctionCall, 5155 Sema::VariadicCallType CallType, 5156 llvm::SmallBitVector &CheckedVarArgs, 5157 UncoveredArgHandler &UncoveredArg); 5158 5159 // Determine if an expression is a string literal or constant string. 5160 // If this function returns false on the arguments to a function expecting a 5161 // format string, we will usually need to emit a warning. 5162 // True string literals are then checked by CheckFormatString. 5163 static StringLiteralCheckType 5164 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 5165 bool HasVAListArg, unsigned format_idx, 5166 unsigned firstDataArg, Sema::FormatStringType Type, 5167 Sema::VariadicCallType CallType, bool InFunctionCall, 5168 llvm::SmallBitVector &CheckedVarArgs, 5169 UncoveredArgHandler &UncoveredArg, 5170 llvm::APSInt Offset) { 5171 tryAgain: 5172 assert(Offset.isSigned() && "invalid offset"); 5173 5174 if (E->isTypeDependent() || E->isValueDependent()) 5175 return SLCT_NotALiteral; 5176 5177 E = E->IgnoreParenCasts(); 5178 5179 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 5180 // Technically -Wformat-nonliteral does not warn about this case. 5181 // The behavior of printf and friends in this case is implementation 5182 // dependent. Ideally if the format string cannot be null then 5183 // it should have a 'nonnull' attribute in the function prototype. 5184 return SLCT_UncheckedLiteral; 5185 5186 switch (E->getStmtClass()) { 5187 case Stmt::BinaryConditionalOperatorClass: 5188 case Stmt::ConditionalOperatorClass: { 5189 // The expression is a literal if both sub-expressions were, and it was 5190 // completely checked only if both sub-expressions were checked. 5191 const AbstractConditionalOperator *C = 5192 cast<AbstractConditionalOperator>(E); 5193 5194 // Determine whether it is necessary to check both sub-expressions, for 5195 // example, because the condition expression is a constant that can be 5196 // evaluated at compile time. 5197 bool CheckLeft = true, CheckRight = true; 5198 5199 bool Cond; 5200 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) { 5201 if (Cond) 5202 CheckRight = false; 5203 else 5204 CheckLeft = false; 5205 } 5206 5207 // We need to maintain the offsets for the right and the left hand side 5208 // separately to check if every possible indexed expression is a valid 5209 // string literal. They might have different offsets for different string 5210 // literals in the end. 5211 StringLiteralCheckType Left; 5212 if (!CheckLeft) 5213 Left = SLCT_UncheckedLiteral; 5214 else { 5215 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 5216 HasVAListArg, format_idx, firstDataArg, 5217 Type, CallType, InFunctionCall, 5218 CheckedVarArgs, UncoveredArg, Offset); 5219 if (Left == SLCT_NotALiteral || !CheckRight) { 5220 return Left; 5221 } 5222 } 5223 5224 StringLiteralCheckType Right = 5225 checkFormatStringExpr(S, C->getFalseExpr(), Args, 5226 HasVAListArg, format_idx, firstDataArg, 5227 Type, CallType, InFunctionCall, CheckedVarArgs, 5228 UncoveredArg, Offset); 5229 5230 return (CheckLeft && Left < Right) ? Left : Right; 5231 } 5232 5233 case Stmt::ImplicitCastExprClass: 5234 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 5235 goto tryAgain; 5236 5237 case Stmt::OpaqueValueExprClass: 5238 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 5239 E = src; 5240 goto tryAgain; 5241 } 5242 return SLCT_NotALiteral; 5243 5244 case Stmt::PredefinedExprClass: 5245 // While __func__, etc., are technically not string literals, they 5246 // cannot contain format specifiers and thus are not a security 5247 // liability. 5248 return SLCT_UncheckedLiteral; 5249 5250 case Stmt::DeclRefExprClass: { 5251 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 5252 5253 // As an exception, do not flag errors for variables binding to 5254 // const string literals. 5255 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 5256 bool isConstant = false; 5257 QualType T = DR->getType(); 5258 5259 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 5260 isConstant = AT->getElementType().isConstant(S.Context); 5261 } else if (const PointerType *PT = T->getAs<PointerType>()) { 5262 isConstant = T.isConstant(S.Context) && 5263 PT->getPointeeType().isConstant(S.Context); 5264 } else if (T->isObjCObjectPointerType()) { 5265 // In ObjC, there is usually no "const ObjectPointer" type, 5266 // so don't check if the pointee type is constant. 5267 isConstant = T.isConstant(S.Context); 5268 } 5269 5270 if (isConstant) { 5271 if (const Expr *Init = VD->getAnyInitializer()) { 5272 // Look through initializers like const char c[] = { "foo" } 5273 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 5274 if (InitList->isStringLiteralInit()) 5275 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 5276 } 5277 return checkFormatStringExpr(S, Init, Args, 5278 HasVAListArg, format_idx, 5279 firstDataArg, Type, CallType, 5280 /*InFunctionCall*/ false, CheckedVarArgs, 5281 UncoveredArg, Offset); 5282 } 5283 } 5284 5285 // For vprintf* functions (i.e., HasVAListArg==true), we add a 5286 // special check to see if the format string is a function parameter 5287 // of the function calling the printf function. If the function 5288 // has an attribute indicating it is a printf-like function, then we 5289 // should suppress warnings concerning non-literals being used in a call 5290 // to a vprintf function. For example: 5291 // 5292 // void 5293 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 5294 // va_list ap; 5295 // va_start(ap, fmt); 5296 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 5297 // ... 5298 // } 5299 if (HasVAListArg) { 5300 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 5301 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 5302 int PVIndex = PV->getFunctionScopeIndex() + 1; 5303 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 5304 // adjust for implicit parameter 5305 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 5306 if (MD->isInstance()) 5307 ++PVIndex; 5308 // We also check if the formats are compatible. 5309 // We can't pass a 'scanf' string to a 'printf' function. 5310 if (PVIndex == PVFormat->getFormatIdx() && 5311 Type == S.GetFormatStringType(PVFormat)) 5312 return SLCT_UncheckedLiteral; 5313 } 5314 } 5315 } 5316 } 5317 } 5318 5319 return SLCT_NotALiteral; 5320 } 5321 5322 case Stmt::CallExprClass: 5323 case Stmt::CXXMemberCallExprClass: { 5324 const CallExpr *CE = cast<CallExpr>(E); 5325 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 5326 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) { 5327 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 5328 return checkFormatStringExpr(S, Arg, Args, 5329 HasVAListArg, format_idx, firstDataArg, 5330 Type, CallType, InFunctionCall, 5331 CheckedVarArgs, UncoveredArg, Offset); 5332 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) { 5333 unsigned BuiltinID = FD->getBuiltinID(); 5334 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 5335 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 5336 const Expr *Arg = CE->getArg(0); 5337 return checkFormatStringExpr(S, Arg, Args, 5338 HasVAListArg, format_idx, 5339 firstDataArg, Type, CallType, 5340 InFunctionCall, CheckedVarArgs, 5341 UncoveredArg, Offset); 5342 } 5343 } 5344 } 5345 5346 return SLCT_NotALiteral; 5347 } 5348 case Stmt::ObjCMessageExprClass: { 5349 const auto *ME = cast<ObjCMessageExpr>(E); 5350 if (const auto *ND = ME->getMethodDecl()) { 5351 if (const auto *FA = ND->getAttr<FormatArgAttr>()) { 5352 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 5353 return checkFormatStringExpr( 5354 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 5355 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset); 5356 } 5357 } 5358 5359 return SLCT_NotALiteral; 5360 } 5361 case Stmt::ObjCStringLiteralClass: 5362 case Stmt::StringLiteralClass: { 5363 const StringLiteral *StrE = nullptr; 5364 5365 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 5366 StrE = ObjCFExpr->getString(); 5367 else 5368 StrE = cast<StringLiteral>(E); 5369 5370 if (StrE) { 5371 if (Offset.isNegative() || Offset > StrE->getLength()) { 5372 // TODO: It would be better to have an explicit warning for out of 5373 // bounds literals. 5374 return SLCT_NotALiteral; 5375 } 5376 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 5377 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 5378 firstDataArg, Type, InFunctionCall, CallType, 5379 CheckedVarArgs, UncoveredArg); 5380 return SLCT_CheckedLiteral; 5381 } 5382 5383 return SLCT_NotALiteral; 5384 } 5385 case Stmt::BinaryOperatorClass: { 5386 llvm::APSInt LResult; 5387 llvm::APSInt RResult; 5388 5389 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 5390 5391 // A string literal + an int offset is still a string literal. 5392 if (BinOp->isAdditiveOp()) { 5393 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context); 5394 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context); 5395 5396 if (LIsInt != RIsInt) { 5397 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 5398 5399 if (LIsInt) { 5400 if (BinOpKind == BO_Add) { 5401 sumOffsets(Offset, LResult, BinOpKind, RIsInt); 5402 E = BinOp->getRHS(); 5403 goto tryAgain; 5404 } 5405 } else { 5406 sumOffsets(Offset, RResult, BinOpKind, RIsInt); 5407 E = BinOp->getLHS(); 5408 goto tryAgain; 5409 } 5410 } 5411 } 5412 5413 return SLCT_NotALiteral; 5414 } 5415 case Stmt::UnaryOperatorClass: { 5416 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 5417 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 5418 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 5419 llvm::APSInt IndexResult; 5420 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) { 5421 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true); 5422 E = ASE->getBase(); 5423 goto tryAgain; 5424 } 5425 } 5426 5427 return SLCT_NotALiteral; 5428 } 5429 5430 default: 5431 return SLCT_NotALiteral; 5432 } 5433 } 5434 5435 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 5436 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 5437 .Case("scanf", FST_Scanf) 5438 .Cases("printf", "printf0", FST_Printf) 5439 .Cases("NSString", "CFString", FST_NSString) 5440 .Case("strftime", FST_Strftime) 5441 .Case("strfmon", FST_Strfmon) 5442 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 5443 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 5444 .Case("os_trace", FST_OSLog) 5445 .Case("os_log", FST_OSLog) 5446 .Default(FST_Unknown); 5447 } 5448 5449 /// CheckFormatArguments - Check calls to printf and scanf (and similar 5450 /// functions) for correct use of format strings. 5451 /// Returns true if a format string has been fully checked. 5452 bool Sema::CheckFormatArguments(const FormatAttr *Format, 5453 ArrayRef<const Expr *> Args, 5454 bool IsCXXMember, 5455 VariadicCallType CallType, 5456 SourceLocation Loc, SourceRange Range, 5457 llvm::SmallBitVector &CheckedVarArgs) { 5458 FormatStringInfo FSI; 5459 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 5460 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 5461 FSI.FirstDataArg, GetFormatStringType(Format), 5462 CallType, Loc, Range, CheckedVarArgs); 5463 return false; 5464 } 5465 5466 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 5467 bool HasVAListArg, unsigned format_idx, 5468 unsigned firstDataArg, FormatStringType Type, 5469 VariadicCallType CallType, 5470 SourceLocation Loc, SourceRange Range, 5471 llvm::SmallBitVector &CheckedVarArgs) { 5472 // CHECK: printf/scanf-like function is called with no format string. 5473 if (format_idx >= Args.size()) { 5474 Diag(Loc, diag::warn_missing_format_string) << Range; 5475 return false; 5476 } 5477 5478 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 5479 5480 // CHECK: format string is not a string literal. 5481 // 5482 // Dynamically generated format strings are difficult to 5483 // automatically vet at compile time. Requiring that format strings 5484 // are string literals: (1) permits the checking of format strings by 5485 // the compiler and thereby (2) can practically remove the source of 5486 // many format string exploits. 5487 5488 // Format string can be either ObjC string (e.g. @"%d") or 5489 // C string (e.g. "%d") 5490 // ObjC string uses the same format specifiers as C string, so we can use 5491 // the same format string checking logic for both ObjC and C strings. 5492 UncoveredArgHandler UncoveredArg; 5493 StringLiteralCheckType CT = 5494 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 5495 format_idx, firstDataArg, Type, CallType, 5496 /*IsFunctionCall*/ true, CheckedVarArgs, 5497 UncoveredArg, 5498 /*no string offset*/ llvm::APSInt(64, false) = 0); 5499 5500 // Generate a diagnostic where an uncovered argument is detected. 5501 if (UncoveredArg.hasUncoveredArg()) { 5502 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 5503 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 5504 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 5505 } 5506 5507 if (CT != SLCT_NotALiteral) 5508 // Literal format string found, check done! 5509 return CT == SLCT_CheckedLiteral; 5510 5511 // Strftime is particular as it always uses a single 'time' argument, 5512 // so it is safe to pass a non-literal string. 5513 if (Type == FST_Strftime) 5514 return false; 5515 5516 // Do not emit diag when the string param is a macro expansion and the 5517 // format is either NSString or CFString. This is a hack to prevent 5518 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 5519 // which are usually used in place of NS and CF string literals. 5520 SourceLocation FormatLoc = Args[format_idx]->getLocStart(); 5521 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 5522 return false; 5523 5524 // If there are no arguments specified, warn with -Wformat-security, otherwise 5525 // warn only with -Wformat-nonliteral. 5526 if (Args.size() == firstDataArg) { 5527 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 5528 << OrigFormatExpr->getSourceRange(); 5529 switch (Type) { 5530 default: 5531 break; 5532 case FST_Kprintf: 5533 case FST_FreeBSDKPrintf: 5534 case FST_Printf: 5535 Diag(FormatLoc, diag::note_format_security_fixit) 5536 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 5537 break; 5538 case FST_NSString: 5539 Diag(FormatLoc, diag::note_format_security_fixit) 5540 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 5541 break; 5542 } 5543 } else { 5544 Diag(FormatLoc, diag::warn_format_nonliteral) 5545 << OrigFormatExpr->getSourceRange(); 5546 } 5547 return false; 5548 } 5549 5550 namespace { 5551 5552 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 5553 protected: 5554 Sema &S; 5555 const FormatStringLiteral *FExpr; 5556 const Expr *OrigFormatExpr; 5557 const Sema::FormatStringType FSType; 5558 const unsigned FirstDataArg; 5559 const unsigned NumDataArgs; 5560 const char *Beg; // Start of format string. 5561 const bool HasVAListArg; 5562 ArrayRef<const Expr *> Args; 5563 unsigned FormatIdx; 5564 llvm::SmallBitVector CoveredArgs; 5565 bool usesPositionalArgs = false; 5566 bool atFirstArg = true; 5567 bool inFunctionCall; 5568 Sema::VariadicCallType CallType; 5569 llvm::SmallBitVector &CheckedVarArgs; 5570 UncoveredArgHandler &UncoveredArg; 5571 5572 public: 5573 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 5574 const Expr *origFormatExpr, 5575 const Sema::FormatStringType type, unsigned firstDataArg, 5576 unsigned numDataArgs, const char *beg, bool hasVAListArg, 5577 ArrayRef<const Expr *> Args, unsigned formatIdx, 5578 bool inFunctionCall, Sema::VariadicCallType callType, 5579 llvm::SmallBitVector &CheckedVarArgs, 5580 UncoveredArgHandler &UncoveredArg) 5581 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 5582 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 5583 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 5584 inFunctionCall(inFunctionCall), CallType(callType), 5585 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 5586 CoveredArgs.resize(numDataArgs); 5587 CoveredArgs.reset(); 5588 } 5589 5590 void DoneProcessing(); 5591 5592 void HandleIncompleteSpecifier(const char *startSpecifier, 5593 unsigned specifierLen) override; 5594 5595 void HandleInvalidLengthModifier( 5596 const analyze_format_string::FormatSpecifier &FS, 5597 const analyze_format_string::ConversionSpecifier &CS, 5598 const char *startSpecifier, unsigned specifierLen, 5599 unsigned DiagID); 5600 5601 void HandleNonStandardLengthModifier( 5602 const analyze_format_string::FormatSpecifier &FS, 5603 const char *startSpecifier, unsigned specifierLen); 5604 5605 void HandleNonStandardConversionSpecifier( 5606 const analyze_format_string::ConversionSpecifier &CS, 5607 const char *startSpecifier, unsigned specifierLen); 5608 5609 void HandlePosition(const char *startPos, unsigned posLen) override; 5610 5611 void HandleInvalidPosition(const char *startSpecifier, 5612 unsigned specifierLen, 5613 analyze_format_string::PositionContext p) override; 5614 5615 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 5616 5617 void HandleNullChar(const char *nullCharacter) override; 5618 5619 template <typename Range> 5620 static void 5621 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 5622 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 5623 bool IsStringLocation, Range StringRange, 5624 ArrayRef<FixItHint> Fixit = None); 5625 5626 protected: 5627 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 5628 const char *startSpec, 5629 unsigned specifierLen, 5630 const char *csStart, unsigned csLen); 5631 5632 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 5633 const char *startSpec, 5634 unsigned specifierLen); 5635 5636 SourceRange getFormatStringRange(); 5637 CharSourceRange getSpecifierRange(const char *startSpecifier, 5638 unsigned specifierLen); 5639 SourceLocation getLocationOfByte(const char *x); 5640 5641 const Expr *getDataArg(unsigned i) const; 5642 5643 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 5644 const analyze_format_string::ConversionSpecifier &CS, 5645 const char *startSpecifier, unsigned specifierLen, 5646 unsigned argIndex); 5647 5648 template <typename Range> 5649 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 5650 bool IsStringLocation, Range StringRange, 5651 ArrayRef<FixItHint> Fixit = None); 5652 }; 5653 5654 } // namespace 5655 5656 SourceRange CheckFormatHandler::getFormatStringRange() { 5657 return OrigFormatExpr->getSourceRange(); 5658 } 5659 5660 CharSourceRange CheckFormatHandler:: 5661 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 5662 SourceLocation Start = getLocationOfByte(startSpecifier); 5663 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 5664 5665 // Advance the end SourceLocation by one due to half-open ranges. 5666 End = End.getLocWithOffset(1); 5667 5668 return CharSourceRange::getCharRange(Start, End); 5669 } 5670 5671 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 5672 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 5673 S.getLangOpts(), S.Context.getTargetInfo()); 5674 } 5675 5676 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 5677 unsigned specifierLen){ 5678 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 5679 getLocationOfByte(startSpecifier), 5680 /*IsStringLocation*/true, 5681 getSpecifierRange(startSpecifier, specifierLen)); 5682 } 5683 5684 void CheckFormatHandler::HandleInvalidLengthModifier( 5685 const analyze_format_string::FormatSpecifier &FS, 5686 const analyze_format_string::ConversionSpecifier &CS, 5687 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 5688 using namespace analyze_format_string; 5689 5690 const LengthModifier &LM = FS.getLengthModifier(); 5691 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 5692 5693 // See if we know how to fix this length modifier. 5694 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 5695 if (FixedLM) { 5696 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 5697 getLocationOfByte(LM.getStart()), 5698 /*IsStringLocation*/true, 5699 getSpecifierRange(startSpecifier, specifierLen)); 5700 5701 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 5702 << FixedLM->toString() 5703 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 5704 5705 } else { 5706 FixItHint Hint; 5707 if (DiagID == diag::warn_format_nonsensical_length) 5708 Hint = FixItHint::CreateRemoval(LMRange); 5709 5710 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 5711 getLocationOfByte(LM.getStart()), 5712 /*IsStringLocation*/true, 5713 getSpecifierRange(startSpecifier, specifierLen), 5714 Hint); 5715 } 5716 } 5717 5718 void CheckFormatHandler::HandleNonStandardLengthModifier( 5719 const analyze_format_string::FormatSpecifier &FS, 5720 const char *startSpecifier, unsigned specifierLen) { 5721 using namespace analyze_format_string; 5722 5723 const LengthModifier &LM = FS.getLengthModifier(); 5724 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 5725 5726 // See if we know how to fix this length modifier. 5727 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 5728 if (FixedLM) { 5729 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5730 << LM.toString() << 0, 5731 getLocationOfByte(LM.getStart()), 5732 /*IsStringLocation*/true, 5733 getSpecifierRange(startSpecifier, specifierLen)); 5734 5735 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 5736 << FixedLM->toString() 5737 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 5738 5739 } else { 5740 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5741 << LM.toString() << 0, 5742 getLocationOfByte(LM.getStart()), 5743 /*IsStringLocation*/true, 5744 getSpecifierRange(startSpecifier, specifierLen)); 5745 } 5746 } 5747 5748 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 5749 const analyze_format_string::ConversionSpecifier &CS, 5750 const char *startSpecifier, unsigned specifierLen) { 5751 using namespace analyze_format_string; 5752 5753 // See if we know how to fix this conversion specifier. 5754 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 5755 if (FixedCS) { 5756 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5757 << CS.toString() << /*conversion specifier*/1, 5758 getLocationOfByte(CS.getStart()), 5759 /*IsStringLocation*/true, 5760 getSpecifierRange(startSpecifier, specifierLen)); 5761 5762 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 5763 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 5764 << FixedCS->toString() 5765 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 5766 } else { 5767 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5768 << CS.toString() << /*conversion specifier*/1, 5769 getLocationOfByte(CS.getStart()), 5770 /*IsStringLocation*/true, 5771 getSpecifierRange(startSpecifier, specifierLen)); 5772 } 5773 } 5774 5775 void CheckFormatHandler::HandlePosition(const char *startPos, 5776 unsigned posLen) { 5777 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 5778 getLocationOfByte(startPos), 5779 /*IsStringLocation*/true, 5780 getSpecifierRange(startPos, posLen)); 5781 } 5782 5783 void 5784 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 5785 analyze_format_string::PositionContext p) { 5786 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 5787 << (unsigned) p, 5788 getLocationOfByte(startPos), /*IsStringLocation*/true, 5789 getSpecifierRange(startPos, posLen)); 5790 } 5791 5792 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 5793 unsigned posLen) { 5794 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 5795 getLocationOfByte(startPos), 5796 /*IsStringLocation*/true, 5797 getSpecifierRange(startPos, posLen)); 5798 } 5799 5800 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 5801 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 5802 // The presence of a null character is likely an error. 5803 EmitFormatDiagnostic( 5804 S.PDiag(diag::warn_printf_format_string_contains_null_char), 5805 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 5806 getFormatStringRange()); 5807 } 5808 } 5809 5810 // Note that this may return NULL if there was an error parsing or building 5811 // one of the argument expressions. 5812 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 5813 return Args[FirstDataArg + i]; 5814 } 5815 5816 void CheckFormatHandler::DoneProcessing() { 5817 // Does the number of data arguments exceed the number of 5818 // format conversions in the format string? 5819 if (!HasVAListArg) { 5820 // Find any arguments that weren't covered. 5821 CoveredArgs.flip(); 5822 signed notCoveredArg = CoveredArgs.find_first(); 5823 if (notCoveredArg >= 0) { 5824 assert((unsigned)notCoveredArg < NumDataArgs); 5825 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 5826 } else { 5827 UncoveredArg.setAllCovered(); 5828 } 5829 } 5830 } 5831 5832 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 5833 const Expr *ArgExpr) { 5834 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 5835 "Invalid state"); 5836 5837 if (!ArgExpr) 5838 return; 5839 5840 SourceLocation Loc = ArgExpr->getLocStart(); 5841 5842 if (S.getSourceManager().isInSystemMacro(Loc)) 5843 return; 5844 5845 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 5846 for (auto E : DiagnosticExprs) 5847 PDiag << E->getSourceRange(); 5848 5849 CheckFormatHandler::EmitFormatDiagnostic( 5850 S, IsFunctionCall, DiagnosticExprs[0], 5851 PDiag, Loc, /*IsStringLocation*/false, 5852 DiagnosticExprs[0]->getSourceRange()); 5853 } 5854 5855 bool 5856 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 5857 SourceLocation Loc, 5858 const char *startSpec, 5859 unsigned specifierLen, 5860 const char *csStart, 5861 unsigned csLen) { 5862 bool keepGoing = true; 5863 if (argIndex < NumDataArgs) { 5864 // Consider the argument coverered, even though the specifier doesn't 5865 // make sense. 5866 CoveredArgs.set(argIndex); 5867 } 5868 else { 5869 // If argIndex exceeds the number of data arguments we 5870 // don't issue a warning because that is just a cascade of warnings (and 5871 // they may have intended '%%' anyway). We don't want to continue processing 5872 // the format string after this point, however, as we will like just get 5873 // gibberish when trying to match arguments. 5874 keepGoing = false; 5875 } 5876 5877 StringRef Specifier(csStart, csLen); 5878 5879 // If the specifier in non-printable, it could be the first byte of a UTF-8 5880 // sequence. In that case, print the UTF-8 code point. If not, print the byte 5881 // hex value. 5882 std::string CodePointStr; 5883 if (!llvm::sys::locale::isPrint(*csStart)) { 5884 llvm::UTF32 CodePoint; 5885 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 5886 const llvm::UTF8 *E = 5887 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 5888 llvm::ConversionResult Result = 5889 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 5890 5891 if (Result != llvm::conversionOK) { 5892 unsigned char FirstChar = *csStart; 5893 CodePoint = (llvm::UTF32)FirstChar; 5894 } 5895 5896 llvm::raw_string_ostream OS(CodePointStr); 5897 if (CodePoint < 256) 5898 OS << "\\x" << llvm::format("%02x", CodePoint); 5899 else if (CodePoint <= 0xFFFF) 5900 OS << "\\u" << llvm::format("%04x", CodePoint); 5901 else 5902 OS << "\\U" << llvm::format("%08x", CodePoint); 5903 OS.flush(); 5904 Specifier = CodePointStr; 5905 } 5906 5907 EmitFormatDiagnostic( 5908 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 5909 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 5910 5911 return keepGoing; 5912 } 5913 5914 void 5915 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 5916 const char *startSpec, 5917 unsigned specifierLen) { 5918 EmitFormatDiagnostic( 5919 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 5920 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 5921 } 5922 5923 bool 5924 CheckFormatHandler::CheckNumArgs( 5925 const analyze_format_string::FormatSpecifier &FS, 5926 const analyze_format_string::ConversionSpecifier &CS, 5927 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 5928 5929 if (argIndex >= NumDataArgs) { 5930 PartialDiagnostic PDiag = FS.usesPositionalArg() 5931 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 5932 << (argIndex+1) << NumDataArgs) 5933 : S.PDiag(diag::warn_printf_insufficient_data_args); 5934 EmitFormatDiagnostic( 5935 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 5936 getSpecifierRange(startSpecifier, specifierLen)); 5937 5938 // Since more arguments than conversion tokens are given, by extension 5939 // all arguments are covered, so mark this as so. 5940 UncoveredArg.setAllCovered(); 5941 return false; 5942 } 5943 return true; 5944 } 5945 5946 template<typename Range> 5947 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 5948 SourceLocation Loc, 5949 bool IsStringLocation, 5950 Range StringRange, 5951 ArrayRef<FixItHint> FixIt) { 5952 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 5953 Loc, IsStringLocation, StringRange, FixIt); 5954 } 5955 5956 /// If the format string is not within the function call, emit a note 5957 /// so that the function call and string are in diagnostic messages. 5958 /// 5959 /// \param InFunctionCall if true, the format string is within the function 5960 /// call and only one diagnostic message will be produced. Otherwise, an 5961 /// extra note will be emitted pointing to location of the format string. 5962 /// 5963 /// \param ArgumentExpr the expression that is passed as the format string 5964 /// argument in the function call. Used for getting locations when two 5965 /// diagnostics are emitted. 5966 /// 5967 /// \param PDiag the callee should already have provided any strings for the 5968 /// diagnostic message. This function only adds locations and fixits 5969 /// to diagnostics. 5970 /// 5971 /// \param Loc primary location for diagnostic. If two diagnostics are 5972 /// required, one will be at Loc and a new SourceLocation will be created for 5973 /// the other one. 5974 /// 5975 /// \param IsStringLocation if true, Loc points to the format string should be 5976 /// used for the note. Otherwise, Loc points to the argument list and will 5977 /// be used with PDiag. 5978 /// 5979 /// \param StringRange some or all of the string to highlight. This is 5980 /// templated so it can accept either a CharSourceRange or a SourceRange. 5981 /// 5982 /// \param FixIt optional fix it hint for the format string. 5983 template <typename Range> 5984 void CheckFormatHandler::EmitFormatDiagnostic( 5985 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 5986 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 5987 Range StringRange, ArrayRef<FixItHint> FixIt) { 5988 if (InFunctionCall) { 5989 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 5990 D << StringRange; 5991 D << FixIt; 5992 } else { 5993 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 5994 << ArgumentExpr->getSourceRange(); 5995 5996 const Sema::SemaDiagnosticBuilder &Note = 5997 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 5998 diag::note_format_string_defined); 5999 6000 Note << StringRange; 6001 Note << FixIt; 6002 } 6003 } 6004 6005 //===--- CHECK: Printf format string checking ------------------------------===// 6006 6007 namespace { 6008 6009 class CheckPrintfHandler : public CheckFormatHandler { 6010 public: 6011 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 6012 const Expr *origFormatExpr, 6013 const Sema::FormatStringType type, unsigned firstDataArg, 6014 unsigned numDataArgs, bool isObjC, const char *beg, 6015 bool hasVAListArg, ArrayRef<const Expr *> Args, 6016 unsigned formatIdx, bool inFunctionCall, 6017 Sema::VariadicCallType CallType, 6018 llvm::SmallBitVector &CheckedVarArgs, 6019 UncoveredArgHandler &UncoveredArg) 6020 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 6021 numDataArgs, beg, hasVAListArg, Args, formatIdx, 6022 inFunctionCall, CallType, CheckedVarArgs, 6023 UncoveredArg) {} 6024 6025 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 6026 6027 /// Returns true if '%@' specifiers are allowed in the format string. 6028 bool allowsObjCArg() const { 6029 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 6030 FSType == Sema::FST_OSTrace; 6031 } 6032 6033 bool HandleInvalidPrintfConversionSpecifier( 6034 const analyze_printf::PrintfSpecifier &FS, 6035 const char *startSpecifier, 6036 unsigned specifierLen) override; 6037 6038 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 6039 const char *startSpecifier, 6040 unsigned specifierLen) override; 6041 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 6042 const char *StartSpecifier, 6043 unsigned SpecifierLen, 6044 const Expr *E); 6045 6046 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 6047 const char *startSpecifier, unsigned specifierLen); 6048 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 6049 const analyze_printf::OptionalAmount &Amt, 6050 unsigned type, 6051 const char *startSpecifier, unsigned specifierLen); 6052 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 6053 const analyze_printf::OptionalFlag &flag, 6054 const char *startSpecifier, unsigned specifierLen); 6055 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 6056 const analyze_printf::OptionalFlag &ignoredFlag, 6057 const analyze_printf::OptionalFlag &flag, 6058 const char *startSpecifier, unsigned specifierLen); 6059 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 6060 const Expr *E); 6061 6062 void HandleEmptyObjCModifierFlag(const char *startFlag, 6063 unsigned flagLen) override; 6064 6065 void HandleInvalidObjCModifierFlag(const char *startFlag, 6066 unsigned flagLen) override; 6067 6068 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 6069 const char *flagsEnd, 6070 const char *conversionPosition) 6071 override; 6072 }; 6073 6074 } // namespace 6075 6076 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 6077 const analyze_printf::PrintfSpecifier &FS, 6078 const char *startSpecifier, 6079 unsigned specifierLen) { 6080 const analyze_printf::PrintfConversionSpecifier &CS = 6081 FS.getConversionSpecifier(); 6082 6083 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 6084 getLocationOfByte(CS.getStart()), 6085 startSpecifier, specifierLen, 6086 CS.getStart(), CS.getLength()); 6087 } 6088 6089 bool CheckPrintfHandler::HandleAmount( 6090 const analyze_format_string::OptionalAmount &Amt, 6091 unsigned k, const char *startSpecifier, 6092 unsigned specifierLen) { 6093 if (Amt.hasDataArgument()) { 6094 if (!HasVAListArg) { 6095 unsigned argIndex = Amt.getArgIndex(); 6096 if (argIndex >= NumDataArgs) { 6097 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 6098 << k, 6099 getLocationOfByte(Amt.getStart()), 6100 /*IsStringLocation*/true, 6101 getSpecifierRange(startSpecifier, specifierLen)); 6102 // Don't do any more checking. We will just emit 6103 // spurious errors. 6104 return false; 6105 } 6106 6107 // Type check the data argument. It should be an 'int'. 6108 // Although not in conformance with C99, we also allow the argument to be 6109 // an 'unsigned int' as that is a reasonably safe case. GCC also 6110 // doesn't emit a warning for that case. 6111 CoveredArgs.set(argIndex); 6112 const Expr *Arg = getDataArg(argIndex); 6113 if (!Arg) 6114 return false; 6115 6116 QualType T = Arg->getType(); 6117 6118 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 6119 assert(AT.isValid()); 6120 6121 if (!AT.matchesType(S.Context, T)) { 6122 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 6123 << k << AT.getRepresentativeTypeName(S.Context) 6124 << T << Arg->getSourceRange(), 6125 getLocationOfByte(Amt.getStart()), 6126 /*IsStringLocation*/true, 6127 getSpecifierRange(startSpecifier, specifierLen)); 6128 // Don't do any more checking. We will just emit 6129 // spurious errors. 6130 return false; 6131 } 6132 } 6133 } 6134 return true; 6135 } 6136 6137 void CheckPrintfHandler::HandleInvalidAmount( 6138 const analyze_printf::PrintfSpecifier &FS, 6139 const analyze_printf::OptionalAmount &Amt, 6140 unsigned type, 6141 const char *startSpecifier, 6142 unsigned specifierLen) { 6143 const analyze_printf::PrintfConversionSpecifier &CS = 6144 FS.getConversionSpecifier(); 6145 6146 FixItHint fixit = 6147 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 6148 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 6149 Amt.getConstantLength())) 6150 : FixItHint(); 6151 6152 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 6153 << type << CS.toString(), 6154 getLocationOfByte(Amt.getStart()), 6155 /*IsStringLocation*/true, 6156 getSpecifierRange(startSpecifier, specifierLen), 6157 fixit); 6158 } 6159 6160 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 6161 const analyze_printf::OptionalFlag &flag, 6162 const char *startSpecifier, 6163 unsigned specifierLen) { 6164 // Warn about pointless flag with a fixit removal. 6165 const analyze_printf::PrintfConversionSpecifier &CS = 6166 FS.getConversionSpecifier(); 6167 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 6168 << flag.toString() << CS.toString(), 6169 getLocationOfByte(flag.getPosition()), 6170 /*IsStringLocation*/true, 6171 getSpecifierRange(startSpecifier, specifierLen), 6172 FixItHint::CreateRemoval( 6173 getSpecifierRange(flag.getPosition(), 1))); 6174 } 6175 6176 void CheckPrintfHandler::HandleIgnoredFlag( 6177 const analyze_printf::PrintfSpecifier &FS, 6178 const analyze_printf::OptionalFlag &ignoredFlag, 6179 const analyze_printf::OptionalFlag &flag, 6180 const char *startSpecifier, 6181 unsigned specifierLen) { 6182 // Warn about ignored flag with a fixit removal. 6183 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 6184 << ignoredFlag.toString() << flag.toString(), 6185 getLocationOfByte(ignoredFlag.getPosition()), 6186 /*IsStringLocation*/true, 6187 getSpecifierRange(startSpecifier, specifierLen), 6188 FixItHint::CreateRemoval( 6189 getSpecifierRange(ignoredFlag.getPosition(), 1))); 6190 } 6191 6192 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 6193 unsigned flagLen) { 6194 // Warn about an empty flag. 6195 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 6196 getLocationOfByte(startFlag), 6197 /*IsStringLocation*/true, 6198 getSpecifierRange(startFlag, flagLen)); 6199 } 6200 6201 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 6202 unsigned flagLen) { 6203 // Warn about an invalid flag. 6204 auto Range = getSpecifierRange(startFlag, flagLen); 6205 StringRef flag(startFlag, flagLen); 6206 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 6207 getLocationOfByte(startFlag), 6208 /*IsStringLocation*/true, 6209 Range, FixItHint::CreateRemoval(Range)); 6210 } 6211 6212 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 6213 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 6214 // Warn about using '[...]' without a '@' conversion. 6215 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 6216 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 6217 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 6218 getLocationOfByte(conversionPosition), 6219 /*IsStringLocation*/true, 6220 Range, FixItHint::CreateRemoval(Range)); 6221 } 6222 6223 // Determines if the specified is a C++ class or struct containing 6224 // a member with the specified name and kind (e.g. a CXXMethodDecl named 6225 // "c_str()"). 6226 template<typename MemberKind> 6227 static llvm::SmallPtrSet<MemberKind*, 1> 6228 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 6229 const RecordType *RT = Ty->getAs<RecordType>(); 6230 llvm::SmallPtrSet<MemberKind*, 1> Results; 6231 6232 if (!RT) 6233 return Results; 6234 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 6235 if (!RD || !RD->getDefinition()) 6236 return Results; 6237 6238 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 6239 Sema::LookupMemberName); 6240 R.suppressDiagnostics(); 6241 6242 // We just need to include all members of the right kind turned up by the 6243 // filter, at this point. 6244 if (S.LookupQualifiedName(R, RT->getDecl())) 6245 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 6246 NamedDecl *decl = (*I)->getUnderlyingDecl(); 6247 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 6248 Results.insert(FK); 6249 } 6250 return Results; 6251 } 6252 6253 /// Check if we could call '.c_str()' on an object. 6254 /// 6255 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 6256 /// allow the call, or if it would be ambiguous). 6257 bool Sema::hasCStrMethod(const Expr *E) { 6258 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 6259 6260 MethodSet Results = 6261 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 6262 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 6263 MI != ME; ++MI) 6264 if ((*MI)->getMinRequiredArguments() == 0) 6265 return true; 6266 return false; 6267 } 6268 6269 // Check if a (w)string was passed when a (w)char* was needed, and offer a 6270 // better diagnostic if so. AT is assumed to be valid. 6271 // Returns true when a c_str() conversion method is found. 6272 bool CheckPrintfHandler::checkForCStrMembers( 6273 const analyze_printf::ArgType &AT, const Expr *E) { 6274 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 6275 6276 MethodSet Results = 6277 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 6278 6279 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 6280 MI != ME; ++MI) { 6281 const CXXMethodDecl *Method = *MI; 6282 if (Method->getMinRequiredArguments() == 0 && 6283 AT.matchesType(S.Context, Method->getReturnType())) { 6284 // FIXME: Suggest parens if the expression needs them. 6285 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd()); 6286 S.Diag(E->getLocStart(), diag::note_printf_c_str) 6287 << "c_str()" 6288 << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 6289 return true; 6290 } 6291 } 6292 6293 return false; 6294 } 6295 6296 bool 6297 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 6298 &FS, 6299 const char *startSpecifier, 6300 unsigned specifierLen) { 6301 using namespace analyze_format_string; 6302 using namespace analyze_printf; 6303 6304 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 6305 6306 if (FS.consumesDataArgument()) { 6307 if (atFirstArg) { 6308 atFirstArg = false; 6309 usesPositionalArgs = FS.usesPositionalArg(); 6310 } 6311 else if (usesPositionalArgs != FS.usesPositionalArg()) { 6312 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 6313 startSpecifier, specifierLen); 6314 return false; 6315 } 6316 } 6317 6318 // First check if the field width, precision, and conversion specifier 6319 // have matching data arguments. 6320 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 6321 startSpecifier, specifierLen)) { 6322 return false; 6323 } 6324 6325 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 6326 startSpecifier, specifierLen)) { 6327 return false; 6328 } 6329 6330 if (!CS.consumesDataArgument()) { 6331 // FIXME: Technically specifying a precision or field width here 6332 // makes no sense. Worth issuing a warning at some point. 6333 return true; 6334 } 6335 6336 // Consume the argument. 6337 unsigned argIndex = FS.getArgIndex(); 6338 if (argIndex < NumDataArgs) { 6339 // The check to see if the argIndex is valid will come later. 6340 // We set the bit here because we may exit early from this 6341 // function if we encounter some other error. 6342 CoveredArgs.set(argIndex); 6343 } 6344 6345 // FreeBSD kernel extensions. 6346 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 6347 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 6348 // We need at least two arguments. 6349 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 6350 return false; 6351 6352 // Claim the second argument. 6353 CoveredArgs.set(argIndex + 1); 6354 6355 // Type check the first argument (int for %b, pointer for %D) 6356 const Expr *Ex = getDataArg(argIndex); 6357 const analyze_printf::ArgType &AT = 6358 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 6359 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 6360 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 6361 EmitFormatDiagnostic( 6362 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 6363 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 6364 << false << Ex->getSourceRange(), 6365 Ex->getLocStart(), /*IsStringLocation*/false, 6366 getSpecifierRange(startSpecifier, specifierLen)); 6367 6368 // Type check the second argument (char * for both %b and %D) 6369 Ex = getDataArg(argIndex + 1); 6370 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 6371 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 6372 EmitFormatDiagnostic( 6373 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 6374 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 6375 << false << Ex->getSourceRange(), 6376 Ex->getLocStart(), /*IsStringLocation*/false, 6377 getSpecifierRange(startSpecifier, specifierLen)); 6378 6379 return true; 6380 } 6381 6382 // Check for using an Objective-C specific conversion specifier 6383 // in a non-ObjC literal. 6384 if (!allowsObjCArg() && CS.isObjCArg()) { 6385 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 6386 specifierLen); 6387 } 6388 6389 // %P can only be used with os_log. 6390 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 6391 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 6392 specifierLen); 6393 } 6394 6395 // %n is not allowed with os_log. 6396 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 6397 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 6398 getLocationOfByte(CS.getStart()), 6399 /*IsStringLocation*/ false, 6400 getSpecifierRange(startSpecifier, specifierLen)); 6401 6402 return true; 6403 } 6404 6405 // Only scalars are allowed for os_trace. 6406 if (FSType == Sema::FST_OSTrace && 6407 (CS.getKind() == ConversionSpecifier::PArg || 6408 CS.getKind() == ConversionSpecifier::sArg || 6409 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 6410 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 6411 specifierLen); 6412 } 6413 6414 // Check for use of public/private annotation outside of os_log(). 6415 if (FSType != Sema::FST_OSLog) { 6416 if (FS.isPublic().isSet()) { 6417 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 6418 << "public", 6419 getLocationOfByte(FS.isPublic().getPosition()), 6420 /*IsStringLocation*/ false, 6421 getSpecifierRange(startSpecifier, specifierLen)); 6422 } 6423 if (FS.isPrivate().isSet()) { 6424 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 6425 << "private", 6426 getLocationOfByte(FS.isPrivate().getPosition()), 6427 /*IsStringLocation*/ false, 6428 getSpecifierRange(startSpecifier, specifierLen)); 6429 } 6430 } 6431 6432 // Check for invalid use of field width 6433 if (!FS.hasValidFieldWidth()) { 6434 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 6435 startSpecifier, specifierLen); 6436 } 6437 6438 // Check for invalid use of precision 6439 if (!FS.hasValidPrecision()) { 6440 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 6441 startSpecifier, specifierLen); 6442 } 6443 6444 // Precision is mandatory for %P specifier. 6445 if (CS.getKind() == ConversionSpecifier::PArg && 6446 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 6447 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 6448 getLocationOfByte(startSpecifier), 6449 /*IsStringLocation*/ false, 6450 getSpecifierRange(startSpecifier, specifierLen)); 6451 } 6452 6453 // Check each flag does not conflict with any other component. 6454 if (!FS.hasValidThousandsGroupingPrefix()) 6455 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 6456 if (!FS.hasValidLeadingZeros()) 6457 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 6458 if (!FS.hasValidPlusPrefix()) 6459 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 6460 if (!FS.hasValidSpacePrefix()) 6461 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 6462 if (!FS.hasValidAlternativeForm()) 6463 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 6464 if (!FS.hasValidLeftJustified()) 6465 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 6466 6467 // Check that flags are not ignored by another flag 6468 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 6469 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 6470 startSpecifier, specifierLen); 6471 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 6472 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 6473 startSpecifier, specifierLen); 6474 6475 // Check the length modifier is valid with the given conversion specifier. 6476 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 6477 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6478 diag::warn_format_nonsensical_length); 6479 else if (!FS.hasStandardLengthModifier()) 6480 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 6481 else if (!FS.hasStandardLengthConversionCombination()) 6482 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6483 diag::warn_format_non_standard_conversion_spec); 6484 6485 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 6486 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 6487 6488 // The remaining checks depend on the data arguments. 6489 if (HasVAListArg) 6490 return true; 6491 6492 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 6493 return false; 6494 6495 const Expr *Arg = getDataArg(argIndex); 6496 if (!Arg) 6497 return true; 6498 6499 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 6500 } 6501 6502 static bool requiresParensToAddCast(const Expr *E) { 6503 // FIXME: We should have a general way to reason about operator 6504 // precedence and whether parens are actually needed here. 6505 // Take care of a few common cases where they aren't. 6506 const Expr *Inside = E->IgnoreImpCasts(); 6507 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 6508 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 6509 6510 switch (Inside->getStmtClass()) { 6511 case Stmt::ArraySubscriptExprClass: 6512 case Stmt::CallExprClass: 6513 case Stmt::CharacterLiteralClass: 6514 case Stmt::CXXBoolLiteralExprClass: 6515 case Stmt::DeclRefExprClass: 6516 case Stmt::FloatingLiteralClass: 6517 case Stmt::IntegerLiteralClass: 6518 case Stmt::MemberExprClass: 6519 case Stmt::ObjCArrayLiteralClass: 6520 case Stmt::ObjCBoolLiteralExprClass: 6521 case Stmt::ObjCBoxedExprClass: 6522 case Stmt::ObjCDictionaryLiteralClass: 6523 case Stmt::ObjCEncodeExprClass: 6524 case Stmt::ObjCIvarRefExprClass: 6525 case Stmt::ObjCMessageExprClass: 6526 case Stmt::ObjCPropertyRefExprClass: 6527 case Stmt::ObjCStringLiteralClass: 6528 case Stmt::ObjCSubscriptRefExprClass: 6529 case Stmt::ParenExprClass: 6530 case Stmt::StringLiteralClass: 6531 case Stmt::UnaryOperatorClass: 6532 return false; 6533 default: 6534 return true; 6535 } 6536 } 6537 6538 static std::pair<QualType, StringRef> 6539 shouldNotPrintDirectly(const ASTContext &Context, 6540 QualType IntendedTy, 6541 const Expr *E) { 6542 // Use a 'while' to peel off layers of typedefs. 6543 QualType TyTy = IntendedTy; 6544 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 6545 StringRef Name = UserTy->getDecl()->getName(); 6546 QualType CastTy = llvm::StringSwitch<QualType>(Name) 6547 .Case("CFIndex", Context.getNSIntegerType()) 6548 .Case("NSInteger", Context.getNSIntegerType()) 6549 .Case("NSUInteger", Context.getNSUIntegerType()) 6550 .Case("SInt32", Context.IntTy) 6551 .Case("UInt32", Context.UnsignedIntTy) 6552 .Default(QualType()); 6553 6554 if (!CastTy.isNull()) 6555 return std::make_pair(CastTy, Name); 6556 6557 TyTy = UserTy->desugar(); 6558 } 6559 6560 // Strip parens if necessary. 6561 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 6562 return shouldNotPrintDirectly(Context, 6563 PE->getSubExpr()->getType(), 6564 PE->getSubExpr()); 6565 6566 // If this is a conditional expression, then its result type is constructed 6567 // via usual arithmetic conversions and thus there might be no necessary 6568 // typedef sugar there. Recurse to operands to check for NSInteger & 6569 // Co. usage condition. 6570 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 6571 QualType TrueTy, FalseTy; 6572 StringRef TrueName, FalseName; 6573 6574 std::tie(TrueTy, TrueName) = 6575 shouldNotPrintDirectly(Context, 6576 CO->getTrueExpr()->getType(), 6577 CO->getTrueExpr()); 6578 std::tie(FalseTy, FalseName) = 6579 shouldNotPrintDirectly(Context, 6580 CO->getFalseExpr()->getType(), 6581 CO->getFalseExpr()); 6582 6583 if (TrueTy == FalseTy) 6584 return std::make_pair(TrueTy, TrueName); 6585 else if (TrueTy.isNull()) 6586 return std::make_pair(FalseTy, FalseName); 6587 else if (FalseTy.isNull()) 6588 return std::make_pair(TrueTy, TrueName); 6589 } 6590 6591 return std::make_pair(QualType(), StringRef()); 6592 } 6593 6594 bool 6595 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 6596 const char *StartSpecifier, 6597 unsigned SpecifierLen, 6598 const Expr *E) { 6599 using namespace analyze_format_string; 6600 using namespace analyze_printf; 6601 6602 // Now type check the data expression that matches the 6603 // format specifier. 6604 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 6605 if (!AT.isValid()) 6606 return true; 6607 6608 QualType ExprTy = E->getType(); 6609 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 6610 ExprTy = TET->getUnderlyingExpr()->getType(); 6611 } 6612 6613 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy); 6614 6615 if (match == analyze_printf::ArgType::Match) { 6616 return true; 6617 } 6618 6619 // Look through argument promotions for our error message's reported type. 6620 // This includes the integral and floating promotions, but excludes array 6621 // and function pointer decay; seeing that an argument intended to be a 6622 // string has type 'char [6]' is probably more confusing than 'char *'. 6623 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 6624 if (ICE->getCastKind() == CK_IntegralCast || 6625 ICE->getCastKind() == CK_FloatingCast) { 6626 E = ICE->getSubExpr(); 6627 ExprTy = E->getType(); 6628 6629 // Check if we didn't match because of an implicit cast from a 'char' 6630 // or 'short' to an 'int'. This is done because printf is a varargs 6631 // function. 6632 if (ICE->getType() == S.Context.IntTy || 6633 ICE->getType() == S.Context.UnsignedIntTy) { 6634 // All further checking is done on the subexpression. 6635 if (AT.matchesType(S.Context, ExprTy)) 6636 return true; 6637 } 6638 } 6639 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 6640 // Special case for 'a', which has type 'int' in C. 6641 // Note, however, that we do /not/ want to treat multibyte constants like 6642 // 'MooV' as characters! This form is deprecated but still exists. 6643 if (ExprTy == S.Context.IntTy) 6644 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 6645 ExprTy = S.Context.CharTy; 6646 } 6647 6648 // Look through enums to their underlying type. 6649 bool IsEnum = false; 6650 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 6651 ExprTy = EnumTy->getDecl()->getIntegerType(); 6652 IsEnum = true; 6653 } 6654 6655 // %C in an Objective-C context prints a unichar, not a wchar_t. 6656 // If the argument is an integer of some kind, believe the %C and suggest 6657 // a cast instead of changing the conversion specifier. 6658 QualType IntendedTy = ExprTy; 6659 if (isObjCContext() && 6660 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 6661 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 6662 !ExprTy->isCharType()) { 6663 // 'unichar' is defined as a typedef of unsigned short, but we should 6664 // prefer using the typedef if it is visible. 6665 IntendedTy = S.Context.UnsignedShortTy; 6666 6667 // While we are here, check if the value is an IntegerLiteral that happens 6668 // to be within the valid range. 6669 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 6670 const llvm::APInt &V = IL->getValue(); 6671 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 6672 return true; 6673 } 6674 6675 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(), 6676 Sema::LookupOrdinaryName); 6677 if (S.LookupName(Result, S.getCurScope())) { 6678 NamedDecl *ND = Result.getFoundDecl(); 6679 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 6680 if (TD->getUnderlyingType() == IntendedTy) 6681 IntendedTy = S.Context.getTypedefType(TD); 6682 } 6683 } 6684 } 6685 6686 // Special-case some of Darwin's platform-independence types by suggesting 6687 // casts to primitive types that are known to be large enough. 6688 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 6689 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 6690 QualType CastTy; 6691 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 6692 if (!CastTy.isNull()) { 6693 IntendedTy = CastTy; 6694 ShouldNotPrintDirectly = true; 6695 } 6696 } 6697 6698 // We may be able to offer a FixItHint if it is a supported type. 6699 PrintfSpecifier fixedFS = FS; 6700 bool success = 6701 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 6702 6703 if (success) { 6704 // Get the fix string from the fixed format specifier 6705 SmallString<16> buf; 6706 llvm::raw_svector_ostream os(buf); 6707 fixedFS.toString(os); 6708 6709 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 6710 6711 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 6712 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 6713 if (match == analyze_format_string::ArgType::NoMatchPedantic) { 6714 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 6715 } 6716 // In this case, the specifier is wrong and should be changed to match 6717 // the argument. 6718 EmitFormatDiagnostic(S.PDiag(diag) 6719 << AT.getRepresentativeTypeName(S.Context) 6720 << IntendedTy << IsEnum << E->getSourceRange(), 6721 E->getLocStart(), 6722 /*IsStringLocation*/ false, SpecRange, 6723 FixItHint::CreateReplacement(SpecRange, os.str())); 6724 } else { 6725 // The canonical type for formatting this value is different from the 6726 // actual type of the expression. (This occurs, for example, with Darwin's 6727 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 6728 // should be printed as 'long' for 64-bit compatibility.) 6729 // Rather than emitting a normal format/argument mismatch, we want to 6730 // add a cast to the recommended type (and correct the format string 6731 // if necessary). 6732 SmallString<16> CastBuf; 6733 llvm::raw_svector_ostream CastFix(CastBuf); 6734 CastFix << "("; 6735 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 6736 CastFix << ")"; 6737 6738 SmallVector<FixItHint,4> Hints; 6739 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 6740 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 6741 6742 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 6743 // If there's already a cast present, just replace it. 6744 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 6745 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 6746 6747 } else if (!requiresParensToAddCast(E)) { 6748 // If the expression has high enough precedence, 6749 // just write the C-style cast. 6750 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(), 6751 CastFix.str())); 6752 } else { 6753 // Otherwise, add parens around the expression as well as the cast. 6754 CastFix << "("; 6755 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(), 6756 CastFix.str())); 6757 6758 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd()); 6759 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 6760 } 6761 6762 if (ShouldNotPrintDirectly) { 6763 // The expression has a type that should not be printed directly. 6764 // We extract the name from the typedef because we don't want to show 6765 // the underlying type in the diagnostic. 6766 StringRef Name; 6767 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 6768 Name = TypedefTy->getDecl()->getName(); 6769 else 6770 Name = CastTyName; 6771 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast) 6772 << Name << IntendedTy << IsEnum 6773 << E->getSourceRange(), 6774 E->getLocStart(), /*IsStringLocation=*/false, 6775 SpecRange, Hints); 6776 } else { 6777 // In this case, the expression could be printed using a different 6778 // specifier, but we've decided that the specifier is probably correct 6779 // and we should cast instead. Just use the normal warning message. 6780 EmitFormatDiagnostic( 6781 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 6782 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 6783 << E->getSourceRange(), 6784 E->getLocStart(), /*IsStringLocation*/false, 6785 SpecRange, Hints); 6786 } 6787 } 6788 } else { 6789 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 6790 SpecifierLen); 6791 // Since the warning for passing non-POD types to variadic functions 6792 // was deferred until now, we emit a warning for non-POD 6793 // arguments here. 6794 switch (S.isValidVarArgType(ExprTy)) { 6795 case Sema::VAK_Valid: 6796 case Sema::VAK_ValidInCXX11: { 6797 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 6798 if (match == analyze_printf::ArgType::NoMatchPedantic) { 6799 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 6800 } 6801 6802 EmitFormatDiagnostic( 6803 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 6804 << IsEnum << CSR << E->getSourceRange(), 6805 E->getLocStart(), /*IsStringLocation*/ false, CSR); 6806 break; 6807 } 6808 case Sema::VAK_Undefined: 6809 case Sema::VAK_MSVCUndefined: 6810 EmitFormatDiagnostic( 6811 S.PDiag(diag::warn_non_pod_vararg_with_format_string) 6812 << S.getLangOpts().CPlusPlus11 6813 << ExprTy 6814 << CallType 6815 << AT.getRepresentativeTypeName(S.Context) 6816 << CSR 6817 << E->getSourceRange(), 6818 E->getLocStart(), /*IsStringLocation*/false, CSR); 6819 checkForCStrMembers(AT, E); 6820 break; 6821 6822 case Sema::VAK_Invalid: 6823 if (ExprTy->isObjCObjectType()) 6824 EmitFormatDiagnostic( 6825 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 6826 << S.getLangOpts().CPlusPlus11 6827 << ExprTy 6828 << CallType 6829 << AT.getRepresentativeTypeName(S.Context) 6830 << CSR 6831 << E->getSourceRange(), 6832 E->getLocStart(), /*IsStringLocation*/false, CSR); 6833 else 6834 // FIXME: If this is an initializer list, suggest removing the braces 6835 // or inserting a cast to the target type. 6836 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format) 6837 << isa<InitListExpr>(E) << ExprTy << CallType 6838 << AT.getRepresentativeTypeName(S.Context) 6839 << E->getSourceRange(); 6840 break; 6841 } 6842 6843 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 6844 "format string specifier index out of range"); 6845 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 6846 } 6847 6848 return true; 6849 } 6850 6851 //===--- CHECK: Scanf format string checking ------------------------------===// 6852 6853 namespace { 6854 6855 class CheckScanfHandler : public CheckFormatHandler { 6856 public: 6857 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 6858 const Expr *origFormatExpr, Sema::FormatStringType type, 6859 unsigned firstDataArg, unsigned numDataArgs, 6860 const char *beg, bool hasVAListArg, 6861 ArrayRef<const Expr *> Args, unsigned formatIdx, 6862 bool inFunctionCall, Sema::VariadicCallType CallType, 6863 llvm::SmallBitVector &CheckedVarArgs, 6864 UncoveredArgHandler &UncoveredArg) 6865 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 6866 numDataArgs, beg, hasVAListArg, Args, formatIdx, 6867 inFunctionCall, CallType, CheckedVarArgs, 6868 UncoveredArg) {} 6869 6870 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 6871 const char *startSpecifier, 6872 unsigned specifierLen) override; 6873 6874 bool HandleInvalidScanfConversionSpecifier( 6875 const analyze_scanf::ScanfSpecifier &FS, 6876 const char *startSpecifier, 6877 unsigned specifierLen) override; 6878 6879 void HandleIncompleteScanList(const char *start, const char *end) override; 6880 }; 6881 6882 } // namespace 6883 6884 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 6885 const char *end) { 6886 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 6887 getLocationOfByte(end), /*IsStringLocation*/true, 6888 getSpecifierRange(start, end - start)); 6889 } 6890 6891 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 6892 const analyze_scanf::ScanfSpecifier &FS, 6893 const char *startSpecifier, 6894 unsigned specifierLen) { 6895 const analyze_scanf::ScanfConversionSpecifier &CS = 6896 FS.getConversionSpecifier(); 6897 6898 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 6899 getLocationOfByte(CS.getStart()), 6900 startSpecifier, specifierLen, 6901 CS.getStart(), CS.getLength()); 6902 } 6903 6904 bool CheckScanfHandler::HandleScanfSpecifier( 6905 const analyze_scanf::ScanfSpecifier &FS, 6906 const char *startSpecifier, 6907 unsigned specifierLen) { 6908 using namespace analyze_scanf; 6909 using namespace analyze_format_string; 6910 6911 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 6912 6913 // Handle case where '%' and '*' don't consume an argument. These shouldn't 6914 // be used to decide if we are using positional arguments consistently. 6915 if (FS.consumesDataArgument()) { 6916 if (atFirstArg) { 6917 atFirstArg = false; 6918 usesPositionalArgs = FS.usesPositionalArg(); 6919 } 6920 else if (usesPositionalArgs != FS.usesPositionalArg()) { 6921 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 6922 startSpecifier, specifierLen); 6923 return false; 6924 } 6925 } 6926 6927 // Check if the field with is non-zero. 6928 const OptionalAmount &Amt = FS.getFieldWidth(); 6929 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 6930 if (Amt.getConstantAmount() == 0) { 6931 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 6932 Amt.getConstantLength()); 6933 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 6934 getLocationOfByte(Amt.getStart()), 6935 /*IsStringLocation*/true, R, 6936 FixItHint::CreateRemoval(R)); 6937 } 6938 } 6939 6940 if (!FS.consumesDataArgument()) { 6941 // FIXME: Technically specifying a precision or field width here 6942 // makes no sense. Worth issuing a warning at some point. 6943 return true; 6944 } 6945 6946 // Consume the argument. 6947 unsigned argIndex = FS.getArgIndex(); 6948 if (argIndex < NumDataArgs) { 6949 // The check to see if the argIndex is valid will come later. 6950 // We set the bit here because we may exit early from this 6951 // function if we encounter some other error. 6952 CoveredArgs.set(argIndex); 6953 } 6954 6955 // Check the length modifier is valid with the given conversion specifier. 6956 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 6957 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6958 diag::warn_format_nonsensical_length); 6959 else if (!FS.hasStandardLengthModifier()) 6960 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 6961 else if (!FS.hasStandardLengthConversionCombination()) 6962 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6963 diag::warn_format_non_standard_conversion_spec); 6964 6965 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 6966 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 6967 6968 // The remaining checks depend on the data arguments. 6969 if (HasVAListArg) 6970 return true; 6971 6972 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 6973 return false; 6974 6975 // Check that the argument type matches the format specifier. 6976 const Expr *Ex = getDataArg(argIndex); 6977 if (!Ex) 6978 return true; 6979 6980 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 6981 6982 if (!AT.isValid()) { 6983 return true; 6984 } 6985 6986 analyze_format_string::ArgType::MatchKind match = 6987 AT.matchesType(S.Context, Ex->getType()); 6988 if (match == analyze_format_string::ArgType::Match) { 6989 return true; 6990 } 6991 6992 ScanfSpecifier fixedFS = FS; 6993 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 6994 S.getLangOpts(), S.Context); 6995 6996 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 6997 if (match == analyze_format_string::ArgType::NoMatchPedantic) { 6998 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 6999 } 7000 7001 if (success) { 7002 // Get the fix string from the fixed format specifier. 7003 SmallString<128> buf; 7004 llvm::raw_svector_ostream os(buf); 7005 fixedFS.toString(os); 7006 7007 EmitFormatDiagnostic( 7008 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) 7009 << Ex->getType() << false << Ex->getSourceRange(), 7010 Ex->getLocStart(), 7011 /*IsStringLocation*/ false, 7012 getSpecifierRange(startSpecifier, specifierLen), 7013 FixItHint::CreateReplacement( 7014 getSpecifierRange(startSpecifier, specifierLen), os.str())); 7015 } else { 7016 EmitFormatDiagnostic(S.PDiag(diag) 7017 << AT.getRepresentativeTypeName(S.Context) 7018 << Ex->getType() << false << Ex->getSourceRange(), 7019 Ex->getLocStart(), 7020 /*IsStringLocation*/ false, 7021 getSpecifierRange(startSpecifier, specifierLen)); 7022 } 7023 7024 return true; 7025 } 7026 7027 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 7028 const Expr *OrigFormatExpr, 7029 ArrayRef<const Expr *> Args, 7030 bool HasVAListArg, unsigned format_idx, 7031 unsigned firstDataArg, 7032 Sema::FormatStringType Type, 7033 bool inFunctionCall, 7034 Sema::VariadicCallType CallType, 7035 llvm::SmallBitVector &CheckedVarArgs, 7036 UncoveredArgHandler &UncoveredArg) { 7037 // CHECK: is the format string a wide literal? 7038 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 7039 CheckFormatHandler::EmitFormatDiagnostic( 7040 S, inFunctionCall, Args[format_idx], 7041 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(), 7042 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 7043 return; 7044 } 7045 7046 // Str - The format string. NOTE: this is NOT null-terminated! 7047 StringRef StrRef = FExpr->getString(); 7048 const char *Str = StrRef.data(); 7049 // Account for cases where the string literal is truncated in a declaration. 7050 const ConstantArrayType *T = 7051 S.Context.getAsConstantArrayType(FExpr->getType()); 7052 assert(T && "String literal not of constant array type!"); 7053 size_t TypeSize = T->getSize().getZExtValue(); 7054 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 7055 const unsigned numDataArgs = Args.size() - firstDataArg; 7056 7057 // Emit a warning if the string literal is truncated and does not contain an 7058 // embedded null character. 7059 if (TypeSize <= StrRef.size() && 7060 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 7061 CheckFormatHandler::EmitFormatDiagnostic( 7062 S, inFunctionCall, Args[format_idx], 7063 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 7064 FExpr->getLocStart(), 7065 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 7066 return; 7067 } 7068 7069 // CHECK: empty format string? 7070 if (StrLen == 0 && numDataArgs > 0) { 7071 CheckFormatHandler::EmitFormatDiagnostic( 7072 S, inFunctionCall, Args[format_idx], 7073 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(), 7074 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 7075 return; 7076 } 7077 7078 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 7079 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 7080 Type == Sema::FST_OSTrace) { 7081 CheckPrintfHandler H( 7082 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 7083 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 7084 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 7085 CheckedVarArgs, UncoveredArg); 7086 7087 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 7088 S.getLangOpts(), 7089 S.Context.getTargetInfo(), 7090 Type == Sema::FST_FreeBSDKPrintf)) 7091 H.DoneProcessing(); 7092 } else if (Type == Sema::FST_Scanf) { 7093 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 7094 numDataArgs, Str, HasVAListArg, Args, format_idx, 7095 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 7096 7097 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 7098 S.getLangOpts(), 7099 S.Context.getTargetInfo())) 7100 H.DoneProcessing(); 7101 } // TODO: handle other formats 7102 } 7103 7104 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 7105 // Str - The format string. NOTE: this is NOT null-terminated! 7106 StringRef StrRef = FExpr->getString(); 7107 const char *Str = StrRef.data(); 7108 // Account for cases where the string literal is truncated in a declaration. 7109 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 7110 assert(T && "String literal not of constant array type!"); 7111 size_t TypeSize = T->getSize().getZExtValue(); 7112 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 7113 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 7114 getLangOpts(), 7115 Context.getTargetInfo()); 7116 } 7117 7118 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 7119 7120 // Returns the related absolute value function that is larger, of 0 if one 7121 // does not exist. 7122 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 7123 switch (AbsFunction) { 7124 default: 7125 return 0; 7126 7127 case Builtin::BI__builtin_abs: 7128 return Builtin::BI__builtin_labs; 7129 case Builtin::BI__builtin_labs: 7130 return Builtin::BI__builtin_llabs; 7131 case Builtin::BI__builtin_llabs: 7132 return 0; 7133 7134 case Builtin::BI__builtin_fabsf: 7135 return Builtin::BI__builtin_fabs; 7136 case Builtin::BI__builtin_fabs: 7137 return Builtin::BI__builtin_fabsl; 7138 case Builtin::BI__builtin_fabsl: 7139 return 0; 7140 7141 case Builtin::BI__builtin_cabsf: 7142 return Builtin::BI__builtin_cabs; 7143 case Builtin::BI__builtin_cabs: 7144 return Builtin::BI__builtin_cabsl; 7145 case Builtin::BI__builtin_cabsl: 7146 return 0; 7147 7148 case Builtin::BIabs: 7149 return Builtin::BIlabs; 7150 case Builtin::BIlabs: 7151 return Builtin::BIllabs; 7152 case Builtin::BIllabs: 7153 return 0; 7154 7155 case Builtin::BIfabsf: 7156 return Builtin::BIfabs; 7157 case Builtin::BIfabs: 7158 return Builtin::BIfabsl; 7159 case Builtin::BIfabsl: 7160 return 0; 7161 7162 case Builtin::BIcabsf: 7163 return Builtin::BIcabs; 7164 case Builtin::BIcabs: 7165 return Builtin::BIcabsl; 7166 case Builtin::BIcabsl: 7167 return 0; 7168 } 7169 } 7170 7171 // Returns the argument type of the absolute value function. 7172 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 7173 unsigned AbsType) { 7174 if (AbsType == 0) 7175 return QualType(); 7176 7177 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 7178 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 7179 if (Error != ASTContext::GE_None) 7180 return QualType(); 7181 7182 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 7183 if (!FT) 7184 return QualType(); 7185 7186 if (FT->getNumParams() != 1) 7187 return QualType(); 7188 7189 return FT->getParamType(0); 7190 } 7191 7192 // Returns the best absolute value function, or zero, based on type and 7193 // current absolute value function. 7194 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 7195 unsigned AbsFunctionKind) { 7196 unsigned BestKind = 0; 7197 uint64_t ArgSize = Context.getTypeSize(ArgType); 7198 for (unsigned Kind = AbsFunctionKind; Kind != 0; 7199 Kind = getLargerAbsoluteValueFunction(Kind)) { 7200 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 7201 if (Context.getTypeSize(ParamType) >= ArgSize) { 7202 if (BestKind == 0) 7203 BestKind = Kind; 7204 else if (Context.hasSameType(ParamType, ArgType)) { 7205 BestKind = Kind; 7206 break; 7207 } 7208 } 7209 } 7210 return BestKind; 7211 } 7212 7213 enum AbsoluteValueKind { 7214 AVK_Integer, 7215 AVK_Floating, 7216 AVK_Complex 7217 }; 7218 7219 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 7220 if (T->isIntegralOrEnumerationType()) 7221 return AVK_Integer; 7222 if (T->isRealFloatingType()) 7223 return AVK_Floating; 7224 if (T->isAnyComplexType()) 7225 return AVK_Complex; 7226 7227 llvm_unreachable("Type not integer, floating, or complex"); 7228 } 7229 7230 // Changes the absolute value function to a different type. Preserves whether 7231 // the function is a builtin. 7232 static unsigned changeAbsFunction(unsigned AbsKind, 7233 AbsoluteValueKind ValueKind) { 7234 switch (ValueKind) { 7235 case AVK_Integer: 7236 switch (AbsKind) { 7237 default: 7238 return 0; 7239 case Builtin::BI__builtin_fabsf: 7240 case Builtin::BI__builtin_fabs: 7241 case Builtin::BI__builtin_fabsl: 7242 case Builtin::BI__builtin_cabsf: 7243 case Builtin::BI__builtin_cabs: 7244 case Builtin::BI__builtin_cabsl: 7245 return Builtin::BI__builtin_abs; 7246 case Builtin::BIfabsf: 7247 case Builtin::BIfabs: 7248 case Builtin::BIfabsl: 7249 case Builtin::BIcabsf: 7250 case Builtin::BIcabs: 7251 case Builtin::BIcabsl: 7252 return Builtin::BIabs; 7253 } 7254 case AVK_Floating: 7255 switch (AbsKind) { 7256 default: 7257 return 0; 7258 case Builtin::BI__builtin_abs: 7259 case Builtin::BI__builtin_labs: 7260 case Builtin::BI__builtin_llabs: 7261 case Builtin::BI__builtin_cabsf: 7262 case Builtin::BI__builtin_cabs: 7263 case Builtin::BI__builtin_cabsl: 7264 return Builtin::BI__builtin_fabsf; 7265 case Builtin::BIabs: 7266 case Builtin::BIlabs: 7267 case Builtin::BIllabs: 7268 case Builtin::BIcabsf: 7269 case Builtin::BIcabs: 7270 case Builtin::BIcabsl: 7271 return Builtin::BIfabsf; 7272 } 7273 case AVK_Complex: 7274 switch (AbsKind) { 7275 default: 7276 return 0; 7277 case Builtin::BI__builtin_abs: 7278 case Builtin::BI__builtin_labs: 7279 case Builtin::BI__builtin_llabs: 7280 case Builtin::BI__builtin_fabsf: 7281 case Builtin::BI__builtin_fabs: 7282 case Builtin::BI__builtin_fabsl: 7283 return Builtin::BI__builtin_cabsf; 7284 case Builtin::BIabs: 7285 case Builtin::BIlabs: 7286 case Builtin::BIllabs: 7287 case Builtin::BIfabsf: 7288 case Builtin::BIfabs: 7289 case Builtin::BIfabsl: 7290 return Builtin::BIcabsf; 7291 } 7292 } 7293 llvm_unreachable("Unable to convert function"); 7294 } 7295 7296 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 7297 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 7298 if (!FnInfo) 7299 return 0; 7300 7301 switch (FDecl->getBuiltinID()) { 7302 default: 7303 return 0; 7304 case Builtin::BI__builtin_abs: 7305 case Builtin::BI__builtin_fabs: 7306 case Builtin::BI__builtin_fabsf: 7307 case Builtin::BI__builtin_fabsl: 7308 case Builtin::BI__builtin_labs: 7309 case Builtin::BI__builtin_llabs: 7310 case Builtin::BI__builtin_cabs: 7311 case Builtin::BI__builtin_cabsf: 7312 case Builtin::BI__builtin_cabsl: 7313 case Builtin::BIabs: 7314 case Builtin::BIlabs: 7315 case Builtin::BIllabs: 7316 case Builtin::BIfabs: 7317 case Builtin::BIfabsf: 7318 case Builtin::BIfabsl: 7319 case Builtin::BIcabs: 7320 case Builtin::BIcabsf: 7321 case Builtin::BIcabsl: 7322 return FDecl->getBuiltinID(); 7323 } 7324 llvm_unreachable("Unknown Builtin type"); 7325 } 7326 7327 // If the replacement is valid, emit a note with replacement function. 7328 // Additionally, suggest including the proper header if not already included. 7329 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 7330 unsigned AbsKind, QualType ArgType) { 7331 bool EmitHeaderHint = true; 7332 const char *HeaderName = nullptr; 7333 const char *FunctionName = nullptr; 7334 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 7335 FunctionName = "std::abs"; 7336 if (ArgType->isIntegralOrEnumerationType()) { 7337 HeaderName = "cstdlib"; 7338 } else if (ArgType->isRealFloatingType()) { 7339 HeaderName = "cmath"; 7340 } else { 7341 llvm_unreachable("Invalid Type"); 7342 } 7343 7344 // Lookup all std::abs 7345 if (NamespaceDecl *Std = S.getStdNamespace()) { 7346 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 7347 R.suppressDiagnostics(); 7348 S.LookupQualifiedName(R, Std); 7349 7350 for (const auto *I : R) { 7351 const FunctionDecl *FDecl = nullptr; 7352 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 7353 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 7354 } else { 7355 FDecl = dyn_cast<FunctionDecl>(I); 7356 } 7357 if (!FDecl) 7358 continue; 7359 7360 // Found std::abs(), check that they are the right ones. 7361 if (FDecl->getNumParams() != 1) 7362 continue; 7363 7364 // Check that the parameter type can handle the argument. 7365 QualType ParamType = FDecl->getParamDecl(0)->getType(); 7366 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 7367 S.Context.getTypeSize(ArgType) <= 7368 S.Context.getTypeSize(ParamType)) { 7369 // Found a function, don't need the header hint. 7370 EmitHeaderHint = false; 7371 break; 7372 } 7373 } 7374 } 7375 } else { 7376 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 7377 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 7378 7379 if (HeaderName) { 7380 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 7381 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 7382 R.suppressDiagnostics(); 7383 S.LookupName(R, S.getCurScope()); 7384 7385 if (R.isSingleResult()) { 7386 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 7387 if (FD && FD->getBuiltinID() == AbsKind) { 7388 EmitHeaderHint = false; 7389 } else { 7390 return; 7391 } 7392 } else if (!R.empty()) { 7393 return; 7394 } 7395 } 7396 } 7397 7398 S.Diag(Loc, diag::note_replace_abs_function) 7399 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 7400 7401 if (!HeaderName) 7402 return; 7403 7404 if (!EmitHeaderHint) 7405 return; 7406 7407 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 7408 << FunctionName; 7409 } 7410 7411 template <std::size_t StrLen> 7412 static bool IsStdFunction(const FunctionDecl *FDecl, 7413 const char (&Str)[StrLen]) { 7414 if (!FDecl) 7415 return false; 7416 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 7417 return false; 7418 if (!FDecl->isInStdNamespace()) 7419 return false; 7420 7421 return true; 7422 } 7423 7424 // Warn when using the wrong abs() function. 7425 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 7426 const FunctionDecl *FDecl) { 7427 if (Call->getNumArgs() != 1) 7428 return; 7429 7430 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 7431 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 7432 if (AbsKind == 0 && !IsStdAbs) 7433 return; 7434 7435 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 7436 QualType ParamType = Call->getArg(0)->getType(); 7437 7438 // Unsigned types cannot be negative. Suggest removing the absolute value 7439 // function call. 7440 if (ArgType->isUnsignedIntegerType()) { 7441 const char *FunctionName = 7442 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 7443 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 7444 Diag(Call->getExprLoc(), diag::note_remove_abs) 7445 << FunctionName 7446 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 7447 return; 7448 } 7449 7450 // Taking the absolute value of a pointer is very suspicious, they probably 7451 // wanted to index into an array, dereference a pointer, call a function, etc. 7452 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 7453 unsigned DiagType = 0; 7454 if (ArgType->isFunctionType()) 7455 DiagType = 1; 7456 else if (ArgType->isArrayType()) 7457 DiagType = 2; 7458 7459 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 7460 return; 7461 } 7462 7463 // std::abs has overloads which prevent most of the absolute value problems 7464 // from occurring. 7465 if (IsStdAbs) 7466 return; 7467 7468 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 7469 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 7470 7471 // The argument and parameter are the same kind. Check if they are the right 7472 // size. 7473 if (ArgValueKind == ParamValueKind) { 7474 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 7475 return; 7476 7477 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 7478 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 7479 << FDecl << ArgType << ParamType; 7480 7481 if (NewAbsKind == 0) 7482 return; 7483 7484 emitReplacement(*this, Call->getExprLoc(), 7485 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 7486 return; 7487 } 7488 7489 // ArgValueKind != ParamValueKind 7490 // The wrong type of absolute value function was used. Attempt to find the 7491 // proper one. 7492 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 7493 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 7494 if (NewAbsKind == 0) 7495 return; 7496 7497 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 7498 << FDecl << ParamValueKind << ArgValueKind; 7499 7500 emitReplacement(*this, Call->getExprLoc(), 7501 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 7502 } 7503 7504 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 7505 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 7506 const FunctionDecl *FDecl) { 7507 if (!Call || !FDecl) return; 7508 7509 // Ignore template specializations and macros. 7510 if (inTemplateInstantiation()) return; 7511 if (Call->getExprLoc().isMacroID()) return; 7512 7513 // Only care about the one template argument, two function parameter std::max 7514 if (Call->getNumArgs() != 2) return; 7515 if (!IsStdFunction(FDecl, "max")) return; 7516 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 7517 if (!ArgList) return; 7518 if (ArgList->size() != 1) return; 7519 7520 // Check that template type argument is unsigned integer. 7521 const auto& TA = ArgList->get(0); 7522 if (TA.getKind() != TemplateArgument::Type) return; 7523 QualType ArgType = TA.getAsType(); 7524 if (!ArgType->isUnsignedIntegerType()) return; 7525 7526 // See if either argument is a literal zero. 7527 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 7528 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 7529 if (!MTE) return false; 7530 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr()); 7531 if (!Num) return false; 7532 if (Num->getValue() != 0) return false; 7533 return true; 7534 }; 7535 7536 const Expr *FirstArg = Call->getArg(0); 7537 const Expr *SecondArg = Call->getArg(1); 7538 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 7539 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 7540 7541 // Only warn when exactly one argument is zero. 7542 if (IsFirstArgZero == IsSecondArgZero) return; 7543 7544 SourceRange FirstRange = FirstArg->getSourceRange(); 7545 SourceRange SecondRange = SecondArg->getSourceRange(); 7546 7547 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 7548 7549 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 7550 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 7551 7552 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 7553 SourceRange RemovalRange; 7554 if (IsFirstArgZero) { 7555 RemovalRange = SourceRange(FirstRange.getBegin(), 7556 SecondRange.getBegin().getLocWithOffset(-1)); 7557 } else { 7558 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 7559 SecondRange.getEnd()); 7560 } 7561 7562 Diag(Call->getExprLoc(), diag::note_remove_max_call) 7563 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 7564 << FixItHint::CreateRemoval(RemovalRange); 7565 } 7566 7567 //===--- CHECK: Standard memory functions ---------------------------------===// 7568 7569 /// Takes the expression passed to the size_t parameter of functions 7570 /// such as memcmp, strncat, etc and warns if it's a comparison. 7571 /// 7572 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 7573 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 7574 IdentifierInfo *FnName, 7575 SourceLocation FnLoc, 7576 SourceLocation RParenLoc) { 7577 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 7578 if (!Size) 7579 return false; 7580 7581 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 7582 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 7583 return false; 7584 7585 SourceRange SizeRange = Size->getSourceRange(); 7586 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 7587 << SizeRange << FnName; 7588 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 7589 << FnName << FixItHint::CreateInsertion( 7590 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")") 7591 << FixItHint::CreateRemoval(RParenLoc); 7592 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 7593 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 7594 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 7595 ")"); 7596 7597 return true; 7598 } 7599 7600 /// Determine whether the given type is or contains a dynamic class type 7601 /// (e.g., whether it has a vtable). 7602 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 7603 bool &IsContained) { 7604 // Look through array types while ignoring qualifiers. 7605 const Type *Ty = T->getBaseElementTypeUnsafe(); 7606 IsContained = false; 7607 7608 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 7609 RD = RD ? RD->getDefinition() : nullptr; 7610 if (!RD || RD->isInvalidDecl()) 7611 return nullptr; 7612 7613 if (RD->isDynamicClass()) 7614 return RD; 7615 7616 // Check all the fields. If any bases were dynamic, the class is dynamic. 7617 // It's impossible for a class to transitively contain itself by value, so 7618 // infinite recursion is impossible. 7619 for (auto *FD : RD->fields()) { 7620 bool SubContained; 7621 if (const CXXRecordDecl *ContainedRD = 7622 getContainedDynamicClass(FD->getType(), SubContained)) { 7623 IsContained = true; 7624 return ContainedRD; 7625 } 7626 } 7627 7628 return nullptr; 7629 } 7630 7631 /// If E is a sizeof expression, returns its argument expression, 7632 /// otherwise returns NULL. 7633 static const Expr *getSizeOfExprArg(const Expr *E) { 7634 if (const UnaryExprOrTypeTraitExpr *SizeOf = 7635 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 7636 if (SizeOf->getKind() == UETT_SizeOf && !SizeOf->isArgumentType()) 7637 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 7638 7639 return nullptr; 7640 } 7641 7642 /// If E is a sizeof expression, returns its argument type. 7643 static QualType getSizeOfArgType(const Expr *E) { 7644 if (const UnaryExprOrTypeTraitExpr *SizeOf = 7645 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 7646 if (SizeOf->getKind() == UETT_SizeOf) 7647 return SizeOf->getTypeOfArgument(); 7648 7649 return QualType(); 7650 } 7651 7652 namespace { 7653 7654 struct SearchNonTrivialToInitializeField 7655 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 7656 using Super = 7657 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 7658 7659 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 7660 7661 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 7662 SourceLocation SL) { 7663 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 7664 asDerived().visitArray(PDIK, AT, SL); 7665 return; 7666 } 7667 7668 Super::visitWithKind(PDIK, FT, SL); 7669 } 7670 7671 void visitARCStrong(QualType FT, SourceLocation SL) { 7672 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 7673 } 7674 void visitARCWeak(QualType FT, SourceLocation SL) { 7675 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 7676 } 7677 void visitStruct(QualType FT, SourceLocation SL) { 7678 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 7679 visit(FD->getType(), FD->getLocation()); 7680 } 7681 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 7682 const ArrayType *AT, SourceLocation SL) { 7683 visit(getContext().getBaseElementType(AT), SL); 7684 } 7685 void visitTrivial(QualType FT, SourceLocation SL) {} 7686 7687 static void diag(QualType RT, const Expr *E, Sema &S) { 7688 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 7689 } 7690 7691 ASTContext &getContext() { return S.getASTContext(); } 7692 7693 const Expr *E; 7694 Sema &S; 7695 }; 7696 7697 struct SearchNonTrivialToCopyField 7698 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 7699 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 7700 7701 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 7702 7703 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 7704 SourceLocation SL) { 7705 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 7706 asDerived().visitArray(PCK, AT, SL); 7707 return; 7708 } 7709 7710 Super::visitWithKind(PCK, FT, SL); 7711 } 7712 7713 void visitARCStrong(QualType FT, SourceLocation SL) { 7714 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 7715 } 7716 void visitARCWeak(QualType FT, SourceLocation SL) { 7717 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 7718 } 7719 void visitStruct(QualType FT, SourceLocation SL) { 7720 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 7721 visit(FD->getType(), FD->getLocation()); 7722 } 7723 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 7724 SourceLocation SL) { 7725 visit(getContext().getBaseElementType(AT), SL); 7726 } 7727 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 7728 SourceLocation SL) {} 7729 void visitTrivial(QualType FT, SourceLocation SL) {} 7730 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 7731 7732 static void diag(QualType RT, const Expr *E, Sema &S) { 7733 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 7734 } 7735 7736 ASTContext &getContext() { return S.getASTContext(); } 7737 7738 const Expr *E; 7739 Sema &S; 7740 }; 7741 7742 } 7743 7744 /// Check for dangerous or invalid arguments to memset(). 7745 /// 7746 /// This issues warnings on known problematic, dangerous or unspecified 7747 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 7748 /// function calls. 7749 /// 7750 /// \param Call The call expression to diagnose. 7751 void Sema::CheckMemaccessArguments(const CallExpr *Call, 7752 unsigned BId, 7753 IdentifierInfo *FnName) { 7754 assert(BId != 0); 7755 7756 // It is possible to have a non-standard definition of memset. Validate 7757 // we have enough arguments, and if not, abort further checking. 7758 unsigned ExpectedNumArgs = 7759 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 7760 if (Call->getNumArgs() < ExpectedNumArgs) 7761 return; 7762 7763 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 7764 BId == Builtin::BIstrndup ? 1 : 2); 7765 unsigned LenArg = 7766 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 7767 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 7768 7769 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 7770 Call->getLocStart(), Call->getRParenLoc())) 7771 return; 7772 7773 // We have special checking when the length is a sizeof expression. 7774 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 7775 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 7776 llvm::FoldingSetNodeID SizeOfArgID; 7777 7778 // Although widely used, 'bzero' is not a standard function. Be more strict 7779 // with the argument types before allowing diagnostics and only allow the 7780 // form bzero(ptr, sizeof(...)). 7781 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 7782 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 7783 return; 7784 7785 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 7786 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 7787 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 7788 7789 QualType DestTy = Dest->getType(); 7790 QualType PointeeTy; 7791 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 7792 PointeeTy = DestPtrTy->getPointeeType(); 7793 7794 // Never warn about void type pointers. This can be used to suppress 7795 // false positives. 7796 if (PointeeTy->isVoidType()) 7797 continue; 7798 7799 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 7800 // actually comparing the expressions for equality. Because computing the 7801 // expression IDs can be expensive, we only do this if the diagnostic is 7802 // enabled. 7803 if (SizeOfArg && 7804 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 7805 SizeOfArg->getExprLoc())) { 7806 // We only compute IDs for expressions if the warning is enabled, and 7807 // cache the sizeof arg's ID. 7808 if (SizeOfArgID == llvm::FoldingSetNodeID()) 7809 SizeOfArg->Profile(SizeOfArgID, Context, true); 7810 llvm::FoldingSetNodeID DestID; 7811 Dest->Profile(DestID, Context, true); 7812 if (DestID == SizeOfArgID) { 7813 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 7814 // over sizeof(src) as well. 7815 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 7816 StringRef ReadableName = FnName->getName(); 7817 7818 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 7819 if (UnaryOp->getOpcode() == UO_AddrOf) 7820 ActionIdx = 1; // If its an address-of operator, just remove it. 7821 if (!PointeeTy->isIncompleteType() && 7822 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 7823 ActionIdx = 2; // If the pointee's size is sizeof(char), 7824 // suggest an explicit length. 7825 7826 // If the function is defined as a builtin macro, do not show macro 7827 // expansion. 7828 SourceLocation SL = SizeOfArg->getExprLoc(); 7829 SourceRange DSR = Dest->getSourceRange(); 7830 SourceRange SSR = SizeOfArg->getSourceRange(); 7831 SourceManager &SM = getSourceManager(); 7832 7833 if (SM.isMacroArgExpansion(SL)) { 7834 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 7835 SL = SM.getSpellingLoc(SL); 7836 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 7837 SM.getSpellingLoc(DSR.getEnd())); 7838 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 7839 SM.getSpellingLoc(SSR.getEnd())); 7840 } 7841 7842 DiagRuntimeBehavior(SL, SizeOfArg, 7843 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 7844 << ReadableName 7845 << PointeeTy 7846 << DestTy 7847 << DSR 7848 << SSR); 7849 DiagRuntimeBehavior(SL, SizeOfArg, 7850 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 7851 << ActionIdx 7852 << SSR); 7853 7854 break; 7855 } 7856 } 7857 7858 // Also check for cases where the sizeof argument is the exact same 7859 // type as the memory argument, and where it points to a user-defined 7860 // record type. 7861 if (SizeOfArgTy != QualType()) { 7862 if (PointeeTy->isRecordType() && 7863 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 7864 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 7865 PDiag(diag::warn_sizeof_pointer_type_memaccess) 7866 << FnName << SizeOfArgTy << ArgIdx 7867 << PointeeTy << Dest->getSourceRange() 7868 << LenExpr->getSourceRange()); 7869 break; 7870 } 7871 } 7872 } else if (DestTy->isArrayType()) { 7873 PointeeTy = DestTy; 7874 } 7875 7876 if (PointeeTy == QualType()) 7877 continue; 7878 7879 // Always complain about dynamic classes. 7880 bool IsContained; 7881 if (const CXXRecordDecl *ContainedRD = 7882 getContainedDynamicClass(PointeeTy, IsContained)) { 7883 7884 unsigned OperationType = 0; 7885 // "overwritten" if we're warning about the destination for any call 7886 // but memcmp; otherwise a verb appropriate to the call. 7887 if (ArgIdx != 0 || BId == Builtin::BImemcmp) { 7888 if (BId == Builtin::BImemcpy) 7889 OperationType = 1; 7890 else if(BId == Builtin::BImemmove) 7891 OperationType = 2; 7892 else if (BId == Builtin::BImemcmp) 7893 OperationType = 3; 7894 } 7895 7896 DiagRuntimeBehavior( 7897 Dest->getExprLoc(), Dest, 7898 PDiag(diag::warn_dyn_class_memaccess) 7899 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx) 7900 << FnName << IsContained << ContainedRD << OperationType 7901 << Call->getCallee()->getSourceRange()); 7902 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 7903 BId != Builtin::BImemset) 7904 DiagRuntimeBehavior( 7905 Dest->getExprLoc(), Dest, 7906 PDiag(diag::warn_arc_object_memaccess) 7907 << ArgIdx << FnName << PointeeTy 7908 << Call->getCallee()->getSourceRange()); 7909 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 7910 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 7911 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 7912 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 7913 PDiag(diag::warn_cstruct_memaccess) 7914 << ArgIdx << FnName << PointeeTy << 0); 7915 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 7916 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 7917 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 7918 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 7919 PDiag(diag::warn_cstruct_memaccess) 7920 << ArgIdx << FnName << PointeeTy << 1); 7921 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 7922 } else { 7923 continue; 7924 } 7925 } else 7926 continue; 7927 7928 DiagRuntimeBehavior( 7929 Dest->getExprLoc(), Dest, 7930 PDiag(diag::note_bad_memaccess_silence) 7931 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 7932 break; 7933 } 7934 } 7935 7936 // A little helper routine: ignore addition and subtraction of integer literals. 7937 // This intentionally does not ignore all integer constant expressions because 7938 // we don't want to remove sizeof(). 7939 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 7940 Ex = Ex->IgnoreParenCasts(); 7941 7942 while (true) { 7943 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 7944 if (!BO || !BO->isAdditiveOp()) 7945 break; 7946 7947 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 7948 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 7949 7950 if (isa<IntegerLiteral>(RHS)) 7951 Ex = LHS; 7952 else if (isa<IntegerLiteral>(LHS)) 7953 Ex = RHS; 7954 else 7955 break; 7956 } 7957 7958 return Ex; 7959 } 7960 7961 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 7962 ASTContext &Context) { 7963 // Only handle constant-sized or VLAs, but not flexible members. 7964 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 7965 // Only issue the FIXIT for arrays of size > 1. 7966 if (CAT->getSize().getSExtValue() <= 1) 7967 return false; 7968 } else if (!Ty->isVariableArrayType()) { 7969 return false; 7970 } 7971 return true; 7972 } 7973 7974 // Warn if the user has made the 'size' argument to strlcpy or strlcat 7975 // be the size of the source, instead of the destination. 7976 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 7977 IdentifierInfo *FnName) { 7978 7979 // Don't crash if the user has the wrong number of arguments 7980 unsigned NumArgs = Call->getNumArgs(); 7981 if ((NumArgs != 3) && (NumArgs != 4)) 7982 return; 7983 7984 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 7985 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 7986 const Expr *CompareWithSrc = nullptr; 7987 7988 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 7989 Call->getLocStart(), Call->getRParenLoc())) 7990 return; 7991 7992 // Look for 'strlcpy(dst, x, sizeof(x))' 7993 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 7994 CompareWithSrc = Ex; 7995 else { 7996 // Look for 'strlcpy(dst, x, strlen(x))' 7997 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 7998 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 7999 SizeCall->getNumArgs() == 1) 8000 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 8001 } 8002 } 8003 8004 if (!CompareWithSrc) 8005 return; 8006 8007 // Determine if the argument to sizeof/strlen is equal to the source 8008 // argument. In principle there's all kinds of things you could do 8009 // here, for instance creating an == expression and evaluating it with 8010 // EvaluateAsBooleanCondition, but this uses a more direct technique: 8011 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 8012 if (!SrcArgDRE) 8013 return; 8014 8015 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 8016 if (!CompareWithSrcDRE || 8017 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 8018 return; 8019 8020 const Expr *OriginalSizeArg = Call->getArg(2); 8021 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size) 8022 << OriginalSizeArg->getSourceRange() << FnName; 8023 8024 // Output a FIXIT hint if the destination is an array (rather than a 8025 // pointer to an array). This could be enhanced to handle some 8026 // pointers if we know the actual size, like if DstArg is 'array+2' 8027 // we could say 'sizeof(array)-2'. 8028 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 8029 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 8030 return; 8031 8032 SmallString<128> sizeString; 8033 llvm::raw_svector_ostream OS(sizeString); 8034 OS << "sizeof("; 8035 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 8036 OS << ")"; 8037 8038 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size) 8039 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 8040 OS.str()); 8041 } 8042 8043 /// Check if two expressions refer to the same declaration. 8044 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 8045 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 8046 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 8047 return D1->getDecl() == D2->getDecl(); 8048 return false; 8049 } 8050 8051 static const Expr *getStrlenExprArg(const Expr *E) { 8052 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 8053 const FunctionDecl *FD = CE->getDirectCallee(); 8054 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 8055 return nullptr; 8056 return CE->getArg(0)->IgnoreParenCasts(); 8057 } 8058 return nullptr; 8059 } 8060 8061 // Warn on anti-patterns as the 'size' argument to strncat. 8062 // The correct size argument should look like following: 8063 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 8064 void Sema::CheckStrncatArguments(const CallExpr *CE, 8065 IdentifierInfo *FnName) { 8066 // Don't crash if the user has the wrong number of arguments. 8067 if (CE->getNumArgs() < 3) 8068 return; 8069 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 8070 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 8071 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 8072 8073 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(), 8074 CE->getRParenLoc())) 8075 return; 8076 8077 // Identify common expressions, which are wrongly used as the size argument 8078 // to strncat and may lead to buffer overflows. 8079 unsigned PatternType = 0; 8080 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 8081 // - sizeof(dst) 8082 if (referToTheSameDecl(SizeOfArg, DstArg)) 8083 PatternType = 1; 8084 // - sizeof(src) 8085 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 8086 PatternType = 2; 8087 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 8088 if (BE->getOpcode() == BO_Sub) { 8089 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 8090 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 8091 // - sizeof(dst) - strlen(dst) 8092 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 8093 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 8094 PatternType = 1; 8095 // - sizeof(src) - (anything) 8096 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 8097 PatternType = 2; 8098 } 8099 } 8100 8101 if (PatternType == 0) 8102 return; 8103 8104 // Generate the diagnostic. 8105 SourceLocation SL = LenArg->getLocStart(); 8106 SourceRange SR = LenArg->getSourceRange(); 8107 SourceManager &SM = getSourceManager(); 8108 8109 // If the function is defined as a builtin macro, do not show macro expansion. 8110 if (SM.isMacroArgExpansion(SL)) { 8111 SL = SM.getSpellingLoc(SL); 8112 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 8113 SM.getSpellingLoc(SR.getEnd())); 8114 } 8115 8116 // Check if the destination is an array (rather than a pointer to an array). 8117 QualType DstTy = DstArg->getType(); 8118 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 8119 Context); 8120 if (!isKnownSizeArray) { 8121 if (PatternType == 1) 8122 Diag(SL, diag::warn_strncat_wrong_size) << SR; 8123 else 8124 Diag(SL, diag::warn_strncat_src_size) << SR; 8125 return; 8126 } 8127 8128 if (PatternType == 1) 8129 Diag(SL, diag::warn_strncat_large_size) << SR; 8130 else 8131 Diag(SL, diag::warn_strncat_src_size) << SR; 8132 8133 SmallString<128> sizeString; 8134 llvm::raw_svector_ostream OS(sizeString); 8135 OS << "sizeof("; 8136 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 8137 OS << ") - "; 8138 OS << "strlen("; 8139 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 8140 OS << ") - 1"; 8141 8142 Diag(SL, diag::note_strncat_wrong_size) 8143 << FixItHint::CreateReplacement(SR, OS.str()); 8144 } 8145 8146 //===--- CHECK: Return Address of Stack Variable --------------------------===// 8147 8148 static const Expr *EvalVal(const Expr *E, 8149 SmallVectorImpl<const DeclRefExpr *> &refVars, 8150 const Decl *ParentDecl); 8151 static const Expr *EvalAddr(const Expr *E, 8152 SmallVectorImpl<const DeclRefExpr *> &refVars, 8153 const Decl *ParentDecl); 8154 8155 /// CheckReturnStackAddr - Check if a return statement returns the address 8156 /// of a stack variable. 8157 static void 8158 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType, 8159 SourceLocation ReturnLoc) { 8160 const Expr *stackE = nullptr; 8161 SmallVector<const DeclRefExpr *, 8> refVars; 8162 8163 // Perform checking for returned stack addresses, local blocks, 8164 // label addresses or references to temporaries. 8165 if (lhsType->isPointerType() || 8166 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) { 8167 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr); 8168 } else if (lhsType->isReferenceType()) { 8169 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr); 8170 } 8171 8172 if (!stackE) 8173 return; // Nothing suspicious was found. 8174 8175 // Parameters are initialized in the calling scope, so taking the address 8176 // of a parameter reference doesn't need a warning. 8177 for (auto *DRE : refVars) 8178 if (isa<ParmVarDecl>(DRE->getDecl())) 8179 return; 8180 8181 SourceLocation diagLoc; 8182 SourceRange diagRange; 8183 if (refVars.empty()) { 8184 diagLoc = stackE->getLocStart(); 8185 diagRange = stackE->getSourceRange(); 8186 } else { 8187 // We followed through a reference variable. 'stackE' contains the 8188 // problematic expression but we will warn at the return statement pointing 8189 // at the reference variable. We will later display the "trail" of 8190 // reference variables using notes. 8191 diagLoc = refVars[0]->getLocStart(); 8192 diagRange = refVars[0]->getSourceRange(); 8193 } 8194 8195 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { 8196 // address of local var 8197 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType() 8198 << DR->getDecl()->getDeclName() << diagRange; 8199 } else if (isa<BlockExpr>(stackE)) { // local block. 8200 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange; 8201 } else if (isa<AddrLabelExpr>(stackE)) { // address of label. 8202 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange; 8203 } else { // local temporary. 8204 // If there is an LValue->RValue conversion, then the value of the 8205 // reference type is used, not the reference. 8206 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) { 8207 if (ICE->getCastKind() == CK_LValueToRValue) { 8208 return; 8209 } 8210 } 8211 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref) 8212 << lhsType->isReferenceType() << diagRange; 8213 } 8214 8215 // Display the "trail" of reference variables that we followed until we 8216 // found the problematic expression using notes. 8217 for (unsigned i = 0, e = refVars.size(); i != e; ++i) { 8218 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl()); 8219 // If this var binds to another reference var, show the range of the next 8220 // var, otherwise the var binds to the problematic expression, in which case 8221 // show the range of the expression. 8222 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange() 8223 : stackE->getSourceRange(); 8224 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind) 8225 << VD->getDeclName() << range; 8226 } 8227 } 8228 8229 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that 8230 /// check if the expression in a return statement evaluates to an address 8231 /// to a location on the stack, a local block, an address of a label, or a 8232 /// reference to local temporary. The recursion is used to traverse the 8233 /// AST of the return expression, with recursion backtracking when we 8234 /// encounter a subexpression that (1) clearly does not lead to one of the 8235 /// above problematic expressions (2) is something we cannot determine leads to 8236 /// a problematic expression based on such local checking. 8237 /// 8238 /// Both EvalAddr and EvalVal follow through reference variables to evaluate 8239 /// the expression that they point to. Such variables are added to the 8240 /// 'refVars' vector so that we know what the reference variable "trail" was. 8241 /// 8242 /// EvalAddr processes expressions that are pointers that are used as 8243 /// references (and not L-values). EvalVal handles all other values. 8244 /// At the base case of the recursion is a check for the above problematic 8245 /// expressions. 8246 /// 8247 /// This implementation handles: 8248 /// 8249 /// * pointer-to-pointer casts 8250 /// * implicit conversions from array references to pointers 8251 /// * taking the address of fields 8252 /// * arbitrary interplay between "&" and "*" operators 8253 /// * pointer arithmetic from an address of a stack variable 8254 /// * taking the address of an array element where the array is on the stack 8255 static const Expr *EvalAddr(const Expr *E, 8256 SmallVectorImpl<const DeclRefExpr *> &refVars, 8257 const Decl *ParentDecl) { 8258 if (E->isTypeDependent()) 8259 return nullptr; 8260 8261 // We should only be called for evaluating pointer expressions. 8262 assert((E->getType()->isAnyPointerType() || 8263 E->getType()->isBlockPointerType() || 8264 E->getType()->isObjCQualifiedIdType()) && 8265 "EvalAddr only works on pointers"); 8266 8267 E = E->IgnoreParens(); 8268 8269 // Our "symbolic interpreter" is just a dispatch off the currently 8270 // viewed AST node. We then recursively traverse the AST by calling 8271 // EvalAddr and EvalVal appropriately. 8272 switch (E->getStmtClass()) { 8273 case Stmt::DeclRefExprClass: { 8274 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 8275 8276 // If we leave the immediate function, the lifetime isn't about to end. 8277 if (DR->refersToEnclosingVariableOrCapture()) 8278 return nullptr; 8279 8280 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) 8281 // If this is a reference variable, follow through to the expression that 8282 // it points to. 8283 if (V->hasLocalStorage() && 8284 V->getType()->isReferenceType() && V->hasInit()) { 8285 // Add the reference variable to the "trail". 8286 refVars.push_back(DR); 8287 return EvalAddr(V->getInit(), refVars, ParentDecl); 8288 } 8289 8290 return nullptr; 8291 } 8292 8293 case Stmt::UnaryOperatorClass: { 8294 // The only unary operator that make sense to handle here 8295 // is AddrOf. All others don't make sense as pointers. 8296 const UnaryOperator *U = cast<UnaryOperator>(E); 8297 8298 if (U->getOpcode() == UO_AddrOf) 8299 return EvalVal(U->getSubExpr(), refVars, ParentDecl); 8300 return nullptr; 8301 } 8302 8303 case Stmt::BinaryOperatorClass: { 8304 // Handle pointer arithmetic. All other binary operators are not valid 8305 // in this context. 8306 const BinaryOperator *B = cast<BinaryOperator>(E); 8307 BinaryOperatorKind op = B->getOpcode(); 8308 8309 if (op != BO_Add && op != BO_Sub) 8310 return nullptr; 8311 8312 const Expr *Base = B->getLHS(); 8313 8314 // Determine which argument is the real pointer base. It could be 8315 // the RHS argument instead of the LHS. 8316 if (!Base->getType()->isPointerType()) 8317 Base = B->getRHS(); 8318 8319 assert(Base->getType()->isPointerType()); 8320 return EvalAddr(Base, refVars, ParentDecl); 8321 } 8322 8323 // For conditional operators we need to see if either the LHS or RHS are 8324 // valid DeclRefExpr*s. If one of them is valid, we return it. 8325 case Stmt::ConditionalOperatorClass: { 8326 const ConditionalOperator *C = cast<ConditionalOperator>(E); 8327 8328 // Handle the GNU extension for missing LHS. 8329 // FIXME: That isn't a ConditionalOperator, so doesn't get here. 8330 if (const Expr *LHSExpr = C->getLHS()) { 8331 // In C++, we can have a throw-expression, which has 'void' type. 8332 if (!LHSExpr->getType()->isVoidType()) 8333 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl)) 8334 return LHS; 8335 } 8336 8337 // In C++, we can have a throw-expression, which has 'void' type. 8338 if (C->getRHS()->getType()->isVoidType()) 8339 return nullptr; 8340 8341 return EvalAddr(C->getRHS(), refVars, ParentDecl); 8342 } 8343 8344 case Stmt::BlockExprClass: 8345 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures()) 8346 return E; // local block. 8347 return nullptr; 8348 8349 case Stmt::AddrLabelExprClass: 8350 return E; // address of label. 8351 8352 case Stmt::ExprWithCleanupsClass: 8353 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars, 8354 ParentDecl); 8355 8356 // For casts, we need to handle conversions from arrays to 8357 // pointer values, and pointer-to-pointer conversions. 8358 case Stmt::ImplicitCastExprClass: 8359 case Stmt::CStyleCastExprClass: 8360 case Stmt::CXXFunctionalCastExprClass: 8361 case Stmt::ObjCBridgedCastExprClass: 8362 case Stmt::CXXStaticCastExprClass: 8363 case Stmt::CXXDynamicCastExprClass: 8364 case Stmt::CXXConstCastExprClass: 8365 case Stmt::CXXReinterpretCastExprClass: { 8366 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr(); 8367 switch (cast<CastExpr>(E)->getCastKind()) { 8368 case CK_LValueToRValue: 8369 case CK_NoOp: 8370 case CK_BaseToDerived: 8371 case CK_DerivedToBase: 8372 case CK_UncheckedDerivedToBase: 8373 case CK_Dynamic: 8374 case CK_CPointerToObjCPointerCast: 8375 case CK_BlockPointerToObjCPointerCast: 8376 case CK_AnyPointerToBlockPointerCast: 8377 return EvalAddr(SubExpr, refVars, ParentDecl); 8378 8379 case CK_ArrayToPointerDecay: 8380 return EvalVal(SubExpr, refVars, ParentDecl); 8381 8382 case CK_BitCast: 8383 if (SubExpr->getType()->isAnyPointerType() || 8384 SubExpr->getType()->isBlockPointerType() || 8385 SubExpr->getType()->isObjCQualifiedIdType()) 8386 return EvalAddr(SubExpr, refVars, ParentDecl); 8387 else 8388 return nullptr; 8389 8390 default: 8391 return nullptr; 8392 } 8393 } 8394 8395 case Stmt::MaterializeTemporaryExprClass: 8396 if (const Expr *Result = 8397 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 8398 refVars, ParentDecl)) 8399 return Result; 8400 return E; 8401 8402 // Everything else: we simply don't reason about them. 8403 default: 8404 return nullptr; 8405 } 8406 } 8407 8408 /// EvalVal - This function is complements EvalAddr in the mutual recursion. 8409 /// See the comments for EvalAddr for more details. 8410 static const Expr *EvalVal(const Expr *E, 8411 SmallVectorImpl<const DeclRefExpr *> &refVars, 8412 const Decl *ParentDecl) { 8413 do { 8414 // We should only be called for evaluating non-pointer expressions, or 8415 // expressions with a pointer type that are not used as references but 8416 // instead 8417 // are l-values (e.g., DeclRefExpr with a pointer type). 8418 8419 // Our "symbolic interpreter" is just a dispatch off the currently 8420 // viewed AST node. We then recursively traverse the AST by calling 8421 // EvalAddr and EvalVal appropriately. 8422 8423 E = E->IgnoreParens(); 8424 switch (E->getStmtClass()) { 8425 case Stmt::ImplicitCastExprClass: { 8426 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E); 8427 if (IE->getValueKind() == VK_LValue) { 8428 E = IE->getSubExpr(); 8429 continue; 8430 } 8431 return nullptr; 8432 } 8433 8434 case Stmt::ExprWithCleanupsClass: 8435 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars, 8436 ParentDecl); 8437 8438 case Stmt::DeclRefExprClass: { 8439 // When we hit a DeclRefExpr we are looking at code that refers to a 8440 // variable's name. If it's not a reference variable we check if it has 8441 // local storage within the function, and if so, return the expression. 8442 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 8443 8444 // If we leave the immediate function, the lifetime isn't about to end. 8445 if (DR->refersToEnclosingVariableOrCapture()) 8446 return nullptr; 8447 8448 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) { 8449 // Check if it refers to itself, e.g. "int& i = i;". 8450 if (V == ParentDecl) 8451 return DR; 8452 8453 if (V->hasLocalStorage()) { 8454 if (!V->getType()->isReferenceType()) 8455 return DR; 8456 8457 // Reference variable, follow through to the expression that 8458 // it points to. 8459 if (V->hasInit()) { 8460 // Add the reference variable to the "trail". 8461 refVars.push_back(DR); 8462 return EvalVal(V->getInit(), refVars, V); 8463 } 8464 } 8465 } 8466 8467 return nullptr; 8468 } 8469 8470 case Stmt::UnaryOperatorClass: { 8471 // The only unary operator that make sense to handle here 8472 // is Deref. All others don't resolve to a "name." This includes 8473 // handling all sorts of rvalues passed to a unary operator. 8474 const UnaryOperator *U = cast<UnaryOperator>(E); 8475 8476 if (U->getOpcode() == UO_Deref) 8477 return EvalAddr(U->getSubExpr(), refVars, ParentDecl); 8478 8479 return nullptr; 8480 } 8481 8482 case Stmt::ArraySubscriptExprClass: { 8483 // Array subscripts are potential references to data on the stack. We 8484 // retrieve the DeclRefExpr* for the array variable if it indeed 8485 // has local storage. 8486 const auto *ASE = cast<ArraySubscriptExpr>(E); 8487 if (ASE->isTypeDependent()) 8488 return nullptr; 8489 return EvalAddr(ASE->getBase(), refVars, ParentDecl); 8490 } 8491 8492 case Stmt::OMPArraySectionExprClass: { 8493 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars, 8494 ParentDecl); 8495 } 8496 8497 case Stmt::ConditionalOperatorClass: { 8498 // For conditional operators we need to see if either the LHS or RHS are 8499 // non-NULL Expr's. If one is non-NULL, we return it. 8500 const ConditionalOperator *C = cast<ConditionalOperator>(E); 8501 8502 // Handle the GNU extension for missing LHS. 8503 if (const Expr *LHSExpr = C->getLHS()) { 8504 // In C++, we can have a throw-expression, which has 'void' type. 8505 if (!LHSExpr->getType()->isVoidType()) 8506 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl)) 8507 return LHS; 8508 } 8509 8510 // In C++, we can have a throw-expression, which has 'void' type. 8511 if (C->getRHS()->getType()->isVoidType()) 8512 return nullptr; 8513 8514 return EvalVal(C->getRHS(), refVars, ParentDecl); 8515 } 8516 8517 // Accesses to members are potential references to data on the stack. 8518 case Stmt::MemberExprClass: { 8519 const MemberExpr *M = cast<MemberExpr>(E); 8520 8521 // Check for indirect access. We only want direct field accesses. 8522 if (M->isArrow()) 8523 return nullptr; 8524 8525 // Check whether the member type is itself a reference, in which case 8526 // we're not going to refer to the member, but to what the member refers 8527 // to. 8528 if (M->getMemberDecl()->getType()->isReferenceType()) 8529 return nullptr; 8530 8531 return EvalVal(M->getBase(), refVars, ParentDecl); 8532 } 8533 8534 case Stmt::MaterializeTemporaryExprClass: 8535 if (const Expr *Result = 8536 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 8537 refVars, ParentDecl)) 8538 return Result; 8539 return E; 8540 8541 default: 8542 // Check that we don't return or take the address of a reference to a 8543 // temporary. This is only useful in C++. 8544 if (!E->isTypeDependent() && E->isRValue()) 8545 return E; 8546 8547 // Everything else: we simply don't reason about them. 8548 return nullptr; 8549 } 8550 } while (true); 8551 } 8552 8553 void 8554 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 8555 SourceLocation ReturnLoc, 8556 bool isObjCMethod, 8557 const AttrVec *Attrs, 8558 const FunctionDecl *FD) { 8559 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc); 8560 8561 // Check if the return value is null but should not be. 8562 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 8563 (!isObjCMethod && isNonNullType(Context, lhsType))) && 8564 CheckNonNullExpr(*this, RetValExp)) 8565 Diag(ReturnLoc, diag::warn_null_ret) 8566 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 8567 8568 // C++11 [basic.stc.dynamic.allocation]p4: 8569 // If an allocation function declared with a non-throwing 8570 // exception-specification fails to allocate storage, it shall return 8571 // a null pointer. Any other allocation function that fails to allocate 8572 // storage shall indicate failure only by throwing an exception [...] 8573 if (FD) { 8574 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 8575 if (Op == OO_New || Op == OO_Array_New) { 8576 const FunctionProtoType *Proto 8577 = FD->getType()->castAs<FunctionProtoType>(); 8578 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 8579 CheckNonNullExpr(*this, RetValExp)) 8580 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 8581 << FD << getLangOpts().CPlusPlus11; 8582 } 8583 } 8584 } 8585 8586 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 8587 8588 /// Check for comparisons of floating point operands using != and ==. 8589 /// Issue a warning if these are no self-comparisons, as they are not likely 8590 /// to do what the programmer intended. 8591 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 8592 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 8593 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 8594 8595 // Special case: check for x == x (which is OK). 8596 // Do not emit warnings for such cases. 8597 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 8598 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 8599 if (DRL->getDecl() == DRR->getDecl()) 8600 return; 8601 8602 // Special case: check for comparisons against literals that can be exactly 8603 // represented by APFloat. In such cases, do not emit a warning. This 8604 // is a heuristic: often comparison against such literals are used to 8605 // detect if a value in a variable has not changed. This clearly can 8606 // lead to false negatives. 8607 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 8608 if (FLL->isExact()) 8609 return; 8610 } else 8611 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 8612 if (FLR->isExact()) 8613 return; 8614 8615 // Check for comparisons with builtin types. 8616 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 8617 if (CL->getBuiltinCallee()) 8618 return; 8619 8620 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 8621 if (CR->getBuiltinCallee()) 8622 return; 8623 8624 // Emit the diagnostic. 8625 Diag(Loc, diag::warn_floatingpoint_eq) 8626 << LHS->getSourceRange() << RHS->getSourceRange(); 8627 } 8628 8629 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 8630 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 8631 8632 namespace { 8633 8634 /// Structure recording the 'active' range of an integer-valued 8635 /// expression. 8636 struct IntRange { 8637 /// The number of bits active in the int. 8638 unsigned Width; 8639 8640 /// True if the int is known not to have negative values. 8641 bool NonNegative; 8642 8643 IntRange(unsigned Width, bool NonNegative) 8644 : Width(Width), NonNegative(NonNegative) {} 8645 8646 /// Returns the range of the bool type. 8647 static IntRange forBoolType() { 8648 return IntRange(1, true); 8649 } 8650 8651 /// Returns the range of an opaque value of the given integral type. 8652 static IntRange forValueOfType(ASTContext &C, QualType T) { 8653 return forValueOfCanonicalType(C, 8654 T->getCanonicalTypeInternal().getTypePtr()); 8655 } 8656 8657 /// Returns the range of an opaque value of a canonical integral type. 8658 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 8659 assert(T->isCanonicalUnqualified()); 8660 8661 if (const VectorType *VT = dyn_cast<VectorType>(T)) 8662 T = VT->getElementType().getTypePtr(); 8663 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 8664 T = CT->getElementType().getTypePtr(); 8665 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 8666 T = AT->getValueType().getTypePtr(); 8667 8668 if (!C.getLangOpts().CPlusPlus) { 8669 // For enum types in C code, use the underlying datatype. 8670 if (const EnumType *ET = dyn_cast<EnumType>(T)) 8671 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 8672 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 8673 // For enum types in C++, use the known bit width of the enumerators. 8674 EnumDecl *Enum = ET->getDecl(); 8675 // In C++11, enums can have a fixed underlying type. Use this type to 8676 // compute the range. 8677 if (Enum->isFixed()) { 8678 return IntRange(C.getIntWidth(QualType(T, 0)), 8679 !ET->isSignedIntegerOrEnumerationType()); 8680 } 8681 8682 unsigned NumPositive = Enum->getNumPositiveBits(); 8683 unsigned NumNegative = Enum->getNumNegativeBits(); 8684 8685 if (NumNegative == 0) 8686 return IntRange(NumPositive, true/*NonNegative*/); 8687 else 8688 return IntRange(std::max(NumPositive + 1, NumNegative), 8689 false/*NonNegative*/); 8690 } 8691 8692 const BuiltinType *BT = cast<BuiltinType>(T); 8693 assert(BT->isInteger()); 8694 8695 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 8696 } 8697 8698 /// Returns the "target" range of a canonical integral type, i.e. 8699 /// the range of values expressible in the type. 8700 /// 8701 /// This matches forValueOfCanonicalType except that enums have the 8702 /// full range of their type, not the range of their enumerators. 8703 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 8704 assert(T->isCanonicalUnqualified()); 8705 8706 if (const VectorType *VT = dyn_cast<VectorType>(T)) 8707 T = VT->getElementType().getTypePtr(); 8708 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 8709 T = CT->getElementType().getTypePtr(); 8710 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 8711 T = AT->getValueType().getTypePtr(); 8712 if (const EnumType *ET = dyn_cast<EnumType>(T)) 8713 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 8714 8715 const BuiltinType *BT = cast<BuiltinType>(T); 8716 assert(BT->isInteger()); 8717 8718 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 8719 } 8720 8721 /// Returns the supremum of two ranges: i.e. their conservative merge. 8722 static IntRange join(IntRange L, IntRange R) { 8723 return IntRange(std::max(L.Width, R.Width), 8724 L.NonNegative && R.NonNegative); 8725 } 8726 8727 /// Returns the infinum of two ranges: i.e. their aggressive merge. 8728 static IntRange meet(IntRange L, IntRange R) { 8729 return IntRange(std::min(L.Width, R.Width), 8730 L.NonNegative || R.NonNegative); 8731 } 8732 }; 8733 8734 } // namespace 8735 8736 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 8737 unsigned MaxWidth) { 8738 if (value.isSigned() && value.isNegative()) 8739 return IntRange(value.getMinSignedBits(), false); 8740 8741 if (value.getBitWidth() > MaxWidth) 8742 value = value.trunc(MaxWidth); 8743 8744 // isNonNegative() just checks the sign bit without considering 8745 // signedness. 8746 return IntRange(value.getActiveBits(), true); 8747 } 8748 8749 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 8750 unsigned MaxWidth) { 8751 if (result.isInt()) 8752 return GetValueRange(C, result.getInt(), MaxWidth); 8753 8754 if (result.isVector()) { 8755 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 8756 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 8757 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 8758 R = IntRange::join(R, El); 8759 } 8760 return R; 8761 } 8762 8763 if (result.isComplexInt()) { 8764 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 8765 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 8766 return IntRange::join(R, I); 8767 } 8768 8769 // This can happen with lossless casts to intptr_t of "based" lvalues. 8770 // Assume it might use arbitrary bits. 8771 // FIXME: The only reason we need to pass the type in here is to get 8772 // the sign right on this one case. It would be nice if APValue 8773 // preserved this. 8774 assert(result.isLValue() || result.isAddrLabelDiff()); 8775 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 8776 } 8777 8778 static QualType GetExprType(const Expr *E) { 8779 QualType Ty = E->getType(); 8780 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 8781 Ty = AtomicRHS->getValueType(); 8782 return Ty; 8783 } 8784 8785 /// Pseudo-evaluate the given integer expression, estimating the 8786 /// range of values it might take. 8787 /// 8788 /// \param MaxWidth - the width to which the value will be truncated 8789 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) { 8790 E = E->IgnoreParens(); 8791 8792 // Try a full evaluation first. 8793 Expr::EvalResult result; 8794 if (E->EvaluateAsRValue(result, C)) 8795 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 8796 8797 // I think we only want to look through implicit casts here; if the 8798 // user has an explicit widening cast, we should treat the value as 8799 // being of the new, wider type. 8800 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 8801 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 8802 return GetExprRange(C, CE->getSubExpr(), MaxWidth); 8803 8804 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 8805 8806 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 8807 CE->getCastKind() == CK_BooleanToSignedIntegral; 8808 8809 // Assume that non-integer casts can span the full range of the type. 8810 if (!isIntegerCast) 8811 return OutputTypeRange; 8812 8813 IntRange SubRange 8814 = GetExprRange(C, CE->getSubExpr(), 8815 std::min(MaxWidth, OutputTypeRange.Width)); 8816 8817 // Bail out if the subexpr's range is as wide as the cast type. 8818 if (SubRange.Width >= OutputTypeRange.Width) 8819 return OutputTypeRange; 8820 8821 // Otherwise, we take the smaller width, and we're non-negative if 8822 // either the output type or the subexpr is. 8823 return IntRange(SubRange.Width, 8824 SubRange.NonNegative || OutputTypeRange.NonNegative); 8825 } 8826 8827 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 8828 // If we can fold the condition, just take that operand. 8829 bool CondResult; 8830 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 8831 return GetExprRange(C, CondResult ? CO->getTrueExpr() 8832 : CO->getFalseExpr(), 8833 MaxWidth); 8834 8835 // Otherwise, conservatively merge. 8836 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth); 8837 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth); 8838 return IntRange::join(L, R); 8839 } 8840 8841 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 8842 switch (BO->getOpcode()) { 8843 case BO_Cmp: 8844 llvm_unreachable("builtin <=> should have class type"); 8845 8846 // Boolean-valued operations are single-bit and positive. 8847 case BO_LAnd: 8848 case BO_LOr: 8849 case BO_LT: 8850 case BO_GT: 8851 case BO_LE: 8852 case BO_GE: 8853 case BO_EQ: 8854 case BO_NE: 8855 return IntRange::forBoolType(); 8856 8857 // The type of the assignments is the type of the LHS, so the RHS 8858 // is not necessarily the same type. 8859 case BO_MulAssign: 8860 case BO_DivAssign: 8861 case BO_RemAssign: 8862 case BO_AddAssign: 8863 case BO_SubAssign: 8864 case BO_XorAssign: 8865 case BO_OrAssign: 8866 // TODO: bitfields? 8867 return IntRange::forValueOfType(C, GetExprType(E)); 8868 8869 // Simple assignments just pass through the RHS, which will have 8870 // been coerced to the LHS type. 8871 case BO_Assign: 8872 // TODO: bitfields? 8873 return GetExprRange(C, BO->getRHS(), MaxWidth); 8874 8875 // Operations with opaque sources are black-listed. 8876 case BO_PtrMemD: 8877 case BO_PtrMemI: 8878 return IntRange::forValueOfType(C, GetExprType(E)); 8879 8880 // Bitwise-and uses the *infinum* of the two source ranges. 8881 case BO_And: 8882 case BO_AndAssign: 8883 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth), 8884 GetExprRange(C, BO->getRHS(), MaxWidth)); 8885 8886 // Left shift gets black-listed based on a judgement call. 8887 case BO_Shl: 8888 // ...except that we want to treat '1 << (blah)' as logically 8889 // positive. It's an important idiom. 8890 if (IntegerLiteral *I 8891 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 8892 if (I->getValue() == 1) { 8893 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 8894 return IntRange(R.Width, /*NonNegative*/ true); 8895 } 8896 } 8897 LLVM_FALLTHROUGH; 8898 8899 case BO_ShlAssign: 8900 return IntRange::forValueOfType(C, GetExprType(E)); 8901 8902 // Right shift by a constant can narrow its left argument. 8903 case BO_Shr: 8904 case BO_ShrAssign: { 8905 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 8906 8907 // If the shift amount is a positive constant, drop the width by 8908 // that much. 8909 llvm::APSInt shift; 8910 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 8911 shift.isNonNegative()) { 8912 unsigned zext = shift.getZExtValue(); 8913 if (zext >= L.Width) 8914 L.Width = (L.NonNegative ? 0 : 1); 8915 else 8916 L.Width -= zext; 8917 } 8918 8919 return L; 8920 } 8921 8922 // Comma acts as its right operand. 8923 case BO_Comma: 8924 return GetExprRange(C, BO->getRHS(), MaxWidth); 8925 8926 // Black-list pointer subtractions. 8927 case BO_Sub: 8928 if (BO->getLHS()->getType()->isPointerType()) 8929 return IntRange::forValueOfType(C, GetExprType(E)); 8930 break; 8931 8932 // The width of a division result is mostly determined by the size 8933 // of the LHS. 8934 case BO_Div: { 8935 // Don't 'pre-truncate' the operands. 8936 unsigned opWidth = C.getIntWidth(GetExprType(E)); 8937 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 8938 8939 // If the divisor is constant, use that. 8940 llvm::APSInt divisor; 8941 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 8942 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 8943 if (log2 >= L.Width) 8944 L.Width = (L.NonNegative ? 0 : 1); 8945 else 8946 L.Width = std::min(L.Width - log2, MaxWidth); 8947 return L; 8948 } 8949 8950 // Otherwise, just use the LHS's width. 8951 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 8952 return IntRange(L.Width, L.NonNegative && R.NonNegative); 8953 } 8954 8955 // The result of a remainder can't be larger than the result of 8956 // either side. 8957 case BO_Rem: { 8958 // Don't 'pre-truncate' the operands. 8959 unsigned opWidth = C.getIntWidth(GetExprType(E)); 8960 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 8961 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 8962 8963 IntRange meet = IntRange::meet(L, R); 8964 meet.Width = std::min(meet.Width, MaxWidth); 8965 return meet; 8966 } 8967 8968 // The default behavior is okay for these. 8969 case BO_Mul: 8970 case BO_Add: 8971 case BO_Xor: 8972 case BO_Or: 8973 break; 8974 } 8975 8976 // The default case is to treat the operation as if it were closed 8977 // on the narrowest type that encompasses both operands. 8978 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 8979 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth); 8980 return IntRange::join(L, R); 8981 } 8982 8983 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 8984 switch (UO->getOpcode()) { 8985 // Boolean-valued operations are white-listed. 8986 case UO_LNot: 8987 return IntRange::forBoolType(); 8988 8989 // Operations with opaque sources are black-listed. 8990 case UO_Deref: 8991 case UO_AddrOf: // should be impossible 8992 return IntRange::forValueOfType(C, GetExprType(E)); 8993 8994 default: 8995 return GetExprRange(C, UO->getSubExpr(), MaxWidth); 8996 } 8997 } 8998 8999 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 9000 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth); 9001 9002 if (const auto *BitField = E->getSourceBitField()) 9003 return IntRange(BitField->getBitWidthValue(C), 9004 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 9005 9006 return IntRange::forValueOfType(C, GetExprType(E)); 9007 } 9008 9009 static IntRange GetExprRange(ASTContext &C, const Expr *E) { 9010 return GetExprRange(C, E, C.getIntWidth(GetExprType(E))); 9011 } 9012 9013 /// Checks whether the given value, which currently has the given 9014 /// source semantics, has the same value when coerced through the 9015 /// target semantics. 9016 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 9017 const llvm::fltSemantics &Src, 9018 const llvm::fltSemantics &Tgt) { 9019 llvm::APFloat truncated = value; 9020 9021 bool ignored; 9022 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 9023 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 9024 9025 return truncated.bitwiseIsEqual(value); 9026 } 9027 9028 /// Checks whether the given value, which currently has the given 9029 /// source semantics, has the same value when coerced through the 9030 /// target semantics. 9031 /// 9032 /// The value might be a vector of floats (or a complex number). 9033 static bool IsSameFloatAfterCast(const APValue &value, 9034 const llvm::fltSemantics &Src, 9035 const llvm::fltSemantics &Tgt) { 9036 if (value.isFloat()) 9037 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 9038 9039 if (value.isVector()) { 9040 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 9041 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 9042 return false; 9043 return true; 9044 } 9045 9046 assert(value.isComplexFloat()); 9047 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 9048 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 9049 } 9050 9051 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC); 9052 9053 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 9054 // Suppress cases where we are comparing against an enum constant. 9055 if (const DeclRefExpr *DR = 9056 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 9057 if (isa<EnumConstantDecl>(DR->getDecl())) 9058 return true; 9059 9060 // Suppress cases where the '0' value is expanded from a macro. 9061 if (E->getLocStart().isMacroID()) 9062 return true; 9063 9064 return false; 9065 } 9066 9067 static bool isKnownToHaveUnsignedValue(Expr *E) { 9068 return E->getType()->isIntegerType() && 9069 (!E->getType()->isSignedIntegerType() || 9070 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 9071 } 9072 9073 namespace { 9074 /// The promoted range of values of a type. In general this has the 9075 /// following structure: 9076 /// 9077 /// |-----------| . . . |-----------| 9078 /// ^ ^ ^ ^ 9079 /// Min HoleMin HoleMax Max 9080 /// 9081 /// ... where there is only a hole if a signed type is promoted to unsigned 9082 /// (in which case Min and Max are the smallest and largest representable 9083 /// values). 9084 struct PromotedRange { 9085 // Min, or HoleMax if there is a hole. 9086 llvm::APSInt PromotedMin; 9087 // Max, or HoleMin if there is a hole. 9088 llvm::APSInt PromotedMax; 9089 9090 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 9091 if (R.Width == 0) 9092 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 9093 else if (R.Width >= BitWidth && !Unsigned) { 9094 // Promotion made the type *narrower*. This happens when promoting 9095 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 9096 // Treat all values of 'signed int' as being in range for now. 9097 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 9098 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 9099 } else { 9100 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 9101 .extOrTrunc(BitWidth); 9102 PromotedMin.setIsUnsigned(Unsigned); 9103 9104 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 9105 .extOrTrunc(BitWidth); 9106 PromotedMax.setIsUnsigned(Unsigned); 9107 } 9108 } 9109 9110 // Determine whether this range is contiguous (has no hole). 9111 bool isContiguous() const { return PromotedMin <= PromotedMax; } 9112 9113 // Where a constant value is within the range. 9114 enum ComparisonResult { 9115 LT = 0x1, 9116 LE = 0x2, 9117 GT = 0x4, 9118 GE = 0x8, 9119 EQ = 0x10, 9120 NE = 0x20, 9121 InRangeFlag = 0x40, 9122 9123 Less = LE | LT | NE, 9124 Min = LE | InRangeFlag, 9125 InRange = InRangeFlag, 9126 Max = GE | InRangeFlag, 9127 Greater = GE | GT | NE, 9128 9129 OnlyValue = LE | GE | EQ | InRangeFlag, 9130 InHole = NE 9131 }; 9132 9133 ComparisonResult compare(const llvm::APSInt &Value) const { 9134 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 9135 Value.isUnsigned() == PromotedMin.isUnsigned()); 9136 if (!isContiguous()) { 9137 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 9138 if (Value.isMinValue()) return Min; 9139 if (Value.isMaxValue()) return Max; 9140 if (Value >= PromotedMin) return InRange; 9141 if (Value <= PromotedMax) return InRange; 9142 return InHole; 9143 } 9144 9145 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 9146 case -1: return Less; 9147 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 9148 case 1: 9149 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 9150 case -1: return InRange; 9151 case 0: return Max; 9152 case 1: return Greater; 9153 } 9154 } 9155 9156 llvm_unreachable("impossible compare result"); 9157 } 9158 9159 static llvm::Optional<StringRef> 9160 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 9161 if (Op == BO_Cmp) { 9162 ComparisonResult LTFlag = LT, GTFlag = GT; 9163 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 9164 9165 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 9166 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 9167 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 9168 return llvm::None; 9169 } 9170 9171 ComparisonResult TrueFlag, FalseFlag; 9172 if (Op == BO_EQ) { 9173 TrueFlag = EQ; 9174 FalseFlag = NE; 9175 } else if (Op == BO_NE) { 9176 TrueFlag = NE; 9177 FalseFlag = EQ; 9178 } else { 9179 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 9180 TrueFlag = LT; 9181 FalseFlag = GE; 9182 } else { 9183 TrueFlag = GT; 9184 FalseFlag = LE; 9185 } 9186 if (Op == BO_GE || Op == BO_LE) 9187 std::swap(TrueFlag, FalseFlag); 9188 } 9189 if (R & TrueFlag) 9190 return StringRef("true"); 9191 if (R & FalseFlag) 9192 return StringRef("false"); 9193 return llvm::None; 9194 } 9195 }; 9196 } 9197 9198 static bool HasEnumType(Expr *E) { 9199 // Strip off implicit integral promotions. 9200 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 9201 if (ICE->getCastKind() != CK_IntegralCast && 9202 ICE->getCastKind() != CK_NoOp) 9203 break; 9204 E = ICE->getSubExpr(); 9205 } 9206 9207 return E->getType()->isEnumeralType(); 9208 } 9209 9210 static int classifyConstantValue(Expr *Constant) { 9211 // The values of this enumeration are used in the diagnostics 9212 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 9213 enum ConstantValueKind { 9214 Miscellaneous = 0, 9215 LiteralTrue, 9216 LiteralFalse 9217 }; 9218 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 9219 return BL->getValue() ? ConstantValueKind::LiteralTrue 9220 : ConstantValueKind::LiteralFalse; 9221 return ConstantValueKind::Miscellaneous; 9222 } 9223 9224 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 9225 Expr *Constant, Expr *Other, 9226 const llvm::APSInt &Value, 9227 bool RhsConstant) { 9228 if (S.inTemplateInstantiation()) 9229 return false; 9230 9231 Expr *OriginalOther = Other; 9232 9233 Constant = Constant->IgnoreParenImpCasts(); 9234 Other = Other->IgnoreParenImpCasts(); 9235 9236 // Suppress warnings on tautological comparisons between values of the same 9237 // enumeration type. There are only two ways we could warn on this: 9238 // - If the constant is outside the range of representable values of 9239 // the enumeration. In such a case, we should warn about the cast 9240 // to enumeration type, not about the comparison. 9241 // - If the constant is the maximum / minimum in-range value. For an 9242 // enumeratin type, such comparisons can be meaningful and useful. 9243 if (Constant->getType()->isEnumeralType() && 9244 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 9245 return false; 9246 9247 // TODO: Investigate using GetExprRange() to get tighter bounds 9248 // on the bit ranges. 9249 QualType OtherT = Other->getType(); 9250 if (const auto *AT = OtherT->getAs<AtomicType>()) 9251 OtherT = AT->getValueType(); 9252 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); 9253 9254 // Whether we're treating Other as being a bool because of the form of 9255 // expression despite it having another type (typically 'int' in C). 9256 bool OtherIsBooleanDespiteType = 9257 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 9258 if (OtherIsBooleanDespiteType) 9259 OtherRange = IntRange::forBoolType(); 9260 9261 // Determine the promoted range of the other type and see if a comparison of 9262 // the constant against that range is tautological. 9263 PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(), 9264 Value.isUnsigned()); 9265 auto Cmp = OtherPromotedRange.compare(Value); 9266 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 9267 if (!Result) 9268 return false; 9269 9270 // Suppress the diagnostic for an in-range comparison if the constant comes 9271 // from a macro or enumerator. We don't want to diagnose 9272 // 9273 // some_long_value <= INT_MAX 9274 // 9275 // when sizeof(int) == sizeof(long). 9276 bool InRange = Cmp & PromotedRange::InRangeFlag; 9277 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 9278 return false; 9279 9280 // If this is a comparison to an enum constant, include that 9281 // constant in the diagnostic. 9282 const EnumConstantDecl *ED = nullptr; 9283 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 9284 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 9285 9286 // Should be enough for uint128 (39 decimal digits) 9287 SmallString<64> PrettySourceValue; 9288 llvm::raw_svector_ostream OS(PrettySourceValue); 9289 if (ED) 9290 OS << '\'' << *ED << "' (" << Value << ")"; 9291 else 9292 OS << Value; 9293 9294 // FIXME: We use a somewhat different formatting for the in-range cases and 9295 // cases involving boolean values for historical reasons. We should pick a 9296 // consistent way of presenting these diagnostics. 9297 if (!InRange || Other->isKnownToHaveBooleanValue()) { 9298 S.DiagRuntimeBehavior( 9299 E->getOperatorLoc(), E, 9300 S.PDiag(!InRange ? diag::warn_out_of_range_compare 9301 : diag::warn_tautological_bool_compare) 9302 << OS.str() << classifyConstantValue(Constant) 9303 << OtherT << OtherIsBooleanDespiteType << *Result 9304 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 9305 } else { 9306 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 9307 ? (HasEnumType(OriginalOther) 9308 ? diag::warn_unsigned_enum_always_true_comparison 9309 : diag::warn_unsigned_always_true_comparison) 9310 : diag::warn_tautological_constant_compare; 9311 9312 S.Diag(E->getOperatorLoc(), Diag) 9313 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 9314 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 9315 } 9316 9317 return true; 9318 } 9319 9320 /// Analyze the operands of the given comparison. Implements the 9321 /// fallback case from AnalyzeComparison. 9322 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 9323 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 9324 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 9325 } 9326 9327 /// Implements -Wsign-compare. 9328 /// 9329 /// \param E the binary operator to check for warnings 9330 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 9331 // The type the comparison is being performed in. 9332 QualType T = E->getLHS()->getType(); 9333 9334 // Only analyze comparison operators where both sides have been converted to 9335 // the same type. 9336 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 9337 return AnalyzeImpConvsInComparison(S, E); 9338 9339 // Don't analyze value-dependent comparisons directly. 9340 if (E->isValueDependent()) 9341 return AnalyzeImpConvsInComparison(S, E); 9342 9343 Expr *LHS = E->getLHS(); 9344 Expr *RHS = E->getRHS(); 9345 9346 if (T->isIntegralType(S.Context)) { 9347 llvm::APSInt RHSValue; 9348 llvm::APSInt LHSValue; 9349 9350 bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context); 9351 bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context); 9352 9353 // We don't care about expressions whose result is a constant. 9354 if (IsRHSIntegralLiteral && IsLHSIntegralLiteral) 9355 return AnalyzeImpConvsInComparison(S, E); 9356 9357 // We only care about expressions where just one side is literal 9358 if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) { 9359 // Is the constant on the RHS or LHS? 9360 const bool RhsConstant = IsRHSIntegralLiteral; 9361 Expr *Const = RhsConstant ? RHS : LHS; 9362 Expr *Other = RhsConstant ? LHS : RHS; 9363 const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue; 9364 9365 // Check whether an integer constant comparison results in a value 9366 // of 'true' or 'false'. 9367 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 9368 return AnalyzeImpConvsInComparison(S, E); 9369 } 9370 } 9371 9372 if (!T->hasUnsignedIntegerRepresentation()) { 9373 // We don't do anything special if this isn't an unsigned integral 9374 // comparison: we're only interested in integral comparisons, and 9375 // signed comparisons only happen in cases we don't care to warn about. 9376 return AnalyzeImpConvsInComparison(S, E); 9377 } 9378 9379 LHS = LHS->IgnoreParenImpCasts(); 9380 RHS = RHS->IgnoreParenImpCasts(); 9381 9382 if (!S.getLangOpts().CPlusPlus) { 9383 // Avoid warning about comparison of integers with different signs when 9384 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 9385 // the type of `E`. 9386 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 9387 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 9388 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 9389 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 9390 } 9391 9392 // Check to see if one of the (unmodified) operands is of different 9393 // signedness. 9394 Expr *signedOperand, *unsignedOperand; 9395 if (LHS->getType()->hasSignedIntegerRepresentation()) { 9396 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 9397 "unsigned comparison between two signed integer expressions?"); 9398 signedOperand = LHS; 9399 unsignedOperand = RHS; 9400 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 9401 signedOperand = RHS; 9402 unsignedOperand = LHS; 9403 } else { 9404 return AnalyzeImpConvsInComparison(S, E); 9405 } 9406 9407 // Otherwise, calculate the effective range of the signed operand. 9408 IntRange signedRange = GetExprRange(S.Context, signedOperand); 9409 9410 // Go ahead and analyze implicit conversions in the operands. Note 9411 // that we skip the implicit conversions on both sides. 9412 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 9413 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 9414 9415 // If the signed range is non-negative, -Wsign-compare won't fire. 9416 if (signedRange.NonNegative) 9417 return; 9418 9419 // For (in)equality comparisons, if the unsigned operand is a 9420 // constant which cannot collide with a overflowed signed operand, 9421 // then reinterpreting the signed operand as unsigned will not 9422 // change the result of the comparison. 9423 if (E->isEqualityOp()) { 9424 unsigned comparisonWidth = S.Context.getIntWidth(T); 9425 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand); 9426 9427 // We should never be unable to prove that the unsigned operand is 9428 // non-negative. 9429 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 9430 9431 if (unsignedRange.Width < comparisonWidth) 9432 return; 9433 } 9434 9435 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 9436 S.PDiag(diag::warn_mixed_sign_comparison) 9437 << LHS->getType() << RHS->getType() 9438 << LHS->getSourceRange() << RHS->getSourceRange()); 9439 } 9440 9441 /// Analyzes an attempt to assign the given value to a bitfield. 9442 /// 9443 /// Returns true if there was something fishy about the attempt. 9444 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 9445 SourceLocation InitLoc) { 9446 assert(Bitfield->isBitField()); 9447 if (Bitfield->isInvalidDecl()) 9448 return false; 9449 9450 // White-list bool bitfields. 9451 QualType BitfieldType = Bitfield->getType(); 9452 if (BitfieldType->isBooleanType()) 9453 return false; 9454 9455 if (BitfieldType->isEnumeralType()) { 9456 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl(); 9457 // If the underlying enum type was not explicitly specified as an unsigned 9458 // type and the enum contain only positive values, MSVC++ will cause an 9459 // inconsistency by storing this as a signed type. 9460 if (S.getLangOpts().CPlusPlus11 && 9461 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 9462 BitfieldEnumDecl->getNumPositiveBits() > 0 && 9463 BitfieldEnumDecl->getNumNegativeBits() == 0) { 9464 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 9465 << BitfieldEnumDecl->getNameAsString(); 9466 } 9467 } 9468 9469 if (Bitfield->getType()->isBooleanType()) 9470 return false; 9471 9472 // Ignore value- or type-dependent expressions. 9473 if (Bitfield->getBitWidth()->isValueDependent() || 9474 Bitfield->getBitWidth()->isTypeDependent() || 9475 Init->isValueDependent() || 9476 Init->isTypeDependent()) 9477 return false; 9478 9479 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 9480 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 9481 9482 llvm::APSInt Value; 9483 if (!OriginalInit->EvaluateAsInt(Value, S.Context, 9484 Expr::SE_AllowSideEffects)) { 9485 // The RHS is not constant. If the RHS has an enum type, make sure the 9486 // bitfield is wide enough to hold all the values of the enum without 9487 // truncation. 9488 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 9489 EnumDecl *ED = EnumTy->getDecl(); 9490 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 9491 9492 // Enum types are implicitly signed on Windows, so check if there are any 9493 // negative enumerators to see if the enum was intended to be signed or 9494 // not. 9495 bool SignedEnum = ED->getNumNegativeBits() > 0; 9496 9497 // Check for surprising sign changes when assigning enum values to a 9498 // bitfield of different signedness. If the bitfield is signed and we 9499 // have exactly the right number of bits to store this unsigned enum, 9500 // suggest changing the enum to an unsigned type. This typically happens 9501 // on Windows where unfixed enums always use an underlying type of 'int'. 9502 unsigned DiagID = 0; 9503 if (SignedEnum && !SignedBitfield) { 9504 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 9505 } else if (SignedBitfield && !SignedEnum && 9506 ED->getNumPositiveBits() == FieldWidth) { 9507 DiagID = diag::warn_signed_bitfield_enum_conversion; 9508 } 9509 9510 if (DiagID) { 9511 S.Diag(InitLoc, DiagID) << Bitfield << ED; 9512 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 9513 SourceRange TypeRange = 9514 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 9515 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 9516 << SignedEnum << TypeRange; 9517 } 9518 9519 // Compute the required bitwidth. If the enum has negative values, we need 9520 // one more bit than the normal number of positive bits to represent the 9521 // sign bit. 9522 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 9523 ED->getNumNegativeBits()) 9524 : ED->getNumPositiveBits(); 9525 9526 // Check the bitwidth. 9527 if (BitsNeeded > FieldWidth) { 9528 Expr *WidthExpr = Bitfield->getBitWidth(); 9529 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 9530 << Bitfield << ED; 9531 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 9532 << BitsNeeded << ED << WidthExpr->getSourceRange(); 9533 } 9534 } 9535 9536 return false; 9537 } 9538 9539 unsigned OriginalWidth = Value.getBitWidth(); 9540 9541 if (!Value.isSigned() || Value.isNegative()) 9542 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 9543 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 9544 OriginalWidth = Value.getMinSignedBits(); 9545 9546 if (OriginalWidth <= FieldWidth) 9547 return false; 9548 9549 // Compute the value which the bitfield will contain. 9550 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 9551 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 9552 9553 // Check whether the stored value is equal to the original value. 9554 TruncatedValue = TruncatedValue.extend(OriginalWidth); 9555 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 9556 return false; 9557 9558 // Special-case bitfields of width 1: booleans are naturally 0/1, and 9559 // therefore don't strictly fit into a signed bitfield of width 1. 9560 if (FieldWidth == 1 && Value == 1) 9561 return false; 9562 9563 std::string PrettyValue = Value.toString(10); 9564 std::string PrettyTrunc = TruncatedValue.toString(10); 9565 9566 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 9567 << PrettyValue << PrettyTrunc << OriginalInit->getType() 9568 << Init->getSourceRange(); 9569 9570 return true; 9571 } 9572 9573 /// Analyze the given simple or compound assignment for warning-worthy 9574 /// operations. 9575 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 9576 // Just recurse on the LHS. 9577 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 9578 9579 // We want to recurse on the RHS as normal unless we're assigning to 9580 // a bitfield. 9581 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 9582 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 9583 E->getOperatorLoc())) { 9584 // Recurse, ignoring any implicit conversions on the RHS. 9585 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 9586 E->getOperatorLoc()); 9587 } 9588 } 9589 9590 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 9591 } 9592 9593 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 9594 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 9595 SourceLocation CContext, unsigned diag, 9596 bool pruneControlFlow = false) { 9597 if (pruneControlFlow) { 9598 S.DiagRuntimeBehavior(E->getExprLoc(), E, 9599 S.PDiag(diag) 9600 << SourceType << T << E->getSourceRange() 9601 << SourceRange(CContext)); 9602 return; 9603 } 9604 S.Diag(E->getExprLoc(), diag) 9605 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 9606 } 9607 9608 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 9609 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 9610 SourceLocation CContext, 9611 unsigned diag, bool pruneControlFlow = false) { 9612 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 9613 } 9614 9615 /// Analyze the given compound assignment for the possible losing of 9616 /// floating-point precision. 9617 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 9618 assert(isa<CompoundAssignOperator>(E) && 9619 "Must be compound assignment operation"); 9620 // Recurse on the LHS and RHS in here 9621 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 9622 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 9623 9624 // Now check the outermost expression 9625 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 9626 const auto *RBT = cast<CompoundAssignOperator>(E) 9627 ->getComputationResultType() 9628 ->getAs<BuiltinType>(); 9629 9630 // If both source and target are floating points. 9631 if (ResultBT && ResultBT->isFloatingPoint() && RBT && RBT->isFloatingPoint()) 9632 // Builtin FP kinds are ordered by increasing FP rank. 9633 if (ResultBT->getKind() < RBT->getKind()) 9634 // We don't want to warn for system macro. 9635 if (!S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 9636 // warn about dropping FP rank. 9637 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), 9638 E->getOperatorLoc(), 9639 diag::warn_impcast_float_result_precision); 9640 } 9641 9642 /// Diagnose an implicit cast from a floating point value to an integer value. 9643 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 9644 SourceLocation CContext) { 9645 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 9646 const bool PruneWarnings = S.inTemplateInstantiation(); 9647 9648 Expr *InnerE = E->IgnoreParenImpCasts(); 9649 // We also want to warn on, e.g., "int i = -1.234" 9650 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 9651 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 9652 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 9653 9654 const bool IsLiteral = 9655 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 9656 9657 llvm::APFloat Value(0.0); 9658 bool IsConstant = 9659 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 9660 if (!IsConstant) { 9661 return DiagnoseImpCast(S, E, T, CContext, 9662 diag::warn_impcast_float_integer, PruneWarnings); 9663 } 9664 9665 bool isExact = false; 9666 9667 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 9668 T->hasUnsignedIntegerRepresentation()); 9669 llvm::APFloat::opStatus Result = Value.convertToInteger( 9670 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 9671 9672 if (Result == llvm::APFloat::opOK && isExact) { 9673 if (IsLiteral) return; 9674 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 9675 PruneWarnings); 9676 } 9677 9678 // Conversion of a floating-point value to a non-bool integer where the 9679 // integral part cannot be represented by the integer type is undefined. 9680 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 9681 return DiagnoseImpCast( 9682 S, E, T, CContext, 9683 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 9684 : diag::warn_impcast_float_to_integer_out_of_range, 9685 PruneWarnings); 9686 9687 unsigned DiagID = 0; 9688 if (IsLiteral) { 9689 // Warn on floating point literal to integer. 9690 DiagID = diag::warn_impcast_literal_float_to_integer; 9691 } else if (IntegerValue == 0) { 9692 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 9693 return DiagnoseImpCast(S, E, T, CContext, 9694 diag::warn_impcast_float_integer, PruneWarnings); 9695 } 9696 // Warn on non-zero to zero conversion. 9697 DiagID = diag::warn_impcast_float_to_integer_zero; 9698 } else { 9699 if (IntegerValue.isUnsigned()) { 9700 if (!IntegerValue.isMaxValue()) { 9701 return DiagnoseImpCast(S, E, T, CContext, 9702 diag::warn_impcast_float_integer, PruneWarnings); 9703 } 9704 } else { // IntegerValue.isSigned() 9705 if (!IntegerValue.isMaxSignedValue() && 9706 !IntegerValue.isMinSignedValue()) { 9707 return DiagnoseImpCast(S, E, T, CContext, 9708 diag::warn_impcast_float_integer, PruneWarnings); 9709 } 9710 } 9711 // Warn on evaluatable floating point expression to integer conversion. 9712 DiagID = diag::warn_impcast_float_to_integer; 9713 } 9714 9715 // FIXME: Force the precision of the source value down so we don't print 9716 // digits which are usually useless (we don't really care here if we 9717 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 9718 // would automatically print the shortest representation, but it's a bit 9719 // tricky to implement. 9720 SmallString<16> PrettySourceValue; 9721 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 9722 precision = (precision * 59 + 195) / 196; 9723 Value.toString(PrettySourceValue, precision); 9724 9725 SmallString<16> PrettyTargetValue; 9726 if (IsBool) 9727 PrettyTargetValue = Value.isZero() ? "false" : "true"; 9728 else 9729 IntegerValue.toString(PrettyTargetValue); 9730 9731 if (PruneWarnings) { 9732 S.DiagRuntimeBehavior(E->getExprLoc(), E, 9733 S.PDiag(DiagID) 9734 << E->getType() << T.getUnqualifiedType() 9735 << PrettySourceValue << PrettyTargetValue 9736 << E->getSourceRange() << SourceRange(CContext)); 9737 } else { 9738 S.Diag(E->getExprLoc(), DiagID) 9739 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 9740 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 9741 } 9742 } 9743 9744 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 9745 IntRange Range) { 9746 if (!Range.Width) return "0"; 9747 9748 llvm::APSInt ValueInRange = Value; 9749 ValueInRange.setIsSigned(!Range.NonNegative); 9750 ValueInRange = ValueInRange.trunc(Range.Width); 9751 return ValueInRange.toString(10); 9752 } 9753 9754 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 9755 if (!isa<ImplicitCastExpr>(Ex)) 9756 return false; 9757 9758 Expr *InnerE = Ex->IgnoreParenImpCasts(); 9759 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 9760 const Type *Source = 9761 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 9762 if (Target->isDependentType()) 9763 return false; 9764 9765 const BuiltinType *FloatCandidateBT = 9766 dyn_cast<BuiltinType>(ToBool ? Source : Target); 9767 const Type *BoolCandidateType = ToBool ? Target : Source; 9768 9769 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 9770 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 9771 } 9772 9773 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 9774 SourceLocation CC) { 9775 unsigned NumArgs = TheCall->getNumArgs(); 9776 for (unsigned i = 0; i < NumArgs; ++i) { 9777 Expr *CurrA = TheCall->getArg(i); 9778 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 9779 continue; 9780 9781 bool IsSwapped = ((i > 0) && 9782 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 9783 IsSwapped |= ((i < (NumArgs - 1)) && 9784 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 9785 if (IsSwapped) { 9786 // Warn on this floating-point to bool conversion. 9787 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 9788 CurrA->getType(), CC, 9789 diag::warn_impcast_floating_point_to_bool); 9790 } 9791 } 9792 } 9793 9794 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 9795 SourceLocation CC) { 9796 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 9797 E->getExprLoc())) 9798 return; 9799 9800 // Don't warn on functions which have return type nullptr_t. 9801 if (isa<CallExpr>(E)) 9802 return; 9803 9804 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 9805 const Expr::NullPointerConstantKind NullKind = 9806 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 9807 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 9808 return; 9809 9810 // Return if target type is a safe conversion. 9811 if (T->isAnyPointerType() || T->isBlockPointerType() || 9812 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 9813 return; 9814 9815 SourceLocation Loc = E->getSourceRange().getBegin(); 9816 9817 // Venture through the macro stacks to get to the source of macro arguments. 9818 // The new location is a better location than the complete location that was 9819 // passed in. 9820 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 9821 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 9822 9823 // __null is usually wrapped in a macro. Go up a macro if that is the case. 9824 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 9825 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 9826 Loc, S.SourceMgr, S.getLangOpts()); 9827 if (MacroName == "NULL") 9828 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 9829 } 9830 9831 // Only warn if the null and context location are in the same macro expansion. 9832 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 9833 return; 9834 9835 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 9836 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 9837 << FixItHint::CreateReplacement(Loc, 9838 S.getFixItZeroLiteralForType(T, Loc)); 9839 } 9840 9841 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 9842 ObjCArrayLiteral *ArrayLiteral); 9843 9844 static void 9845 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 9846 ObjCDictionaryLiteral *DictionaryLiteral); 9847 9848 /// Check a single element within a collection literal against the 9849 /// target element type. 9850 static void checkObjCCollectionLiteralElement(Sema &S, 9851 QualType TargetElementType, 9852 Expr *Element, 9853 unsigned ElementKind) { 9854 // Skip a bitcast to 'id' or qualified 'id'. 9855 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 9856 if (ICE->getCastKind() == CK_BitCast && 9857 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 9858 Element = ICE->getSubExpr(); 9859 } 9860 9861 QualType ElementType = Element->getType(); 9862 ExprResult ElementResult(Element); 9863 if (ElementType->getAs<ObjCObjectPointerType>() && 9864 S.CheckSingleAssignmentConstraints(TargetElementType, 9865 ElementResult, 9866 false, false) 9867 != Sema::Compatible) { 9868 S.Diag(Element->getLocStart(), 9869 diag::warn_objc_collection_literal_element) 9870 << ElementType << ElementKind << TargetElementType 9871 << Element->getSourceRange(); 9872 } 9873 9874 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 9875 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 9876 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 9877 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 9878 } 9879 9880 /// Check an Objective-C array literal being converted to the given 9881 /// target type. 9882 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 9883 ObjCArrayLiteral *ArrayLiteral) { 9884 if (!S.NSArrayDecl) 9885 return; 9886 9887 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 9888 if (!TargetObjCPtr) 9889 return; 9890 9891 if (TargetObjCPtr->isUnspecialized() || 9892 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 9893 != S.NSArrayDecl->getCanonicalDecl()) 9894 return; 9895 9896 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 9897 if (TypeArgs.size() != 1) 9898 return; 9899 9900 QualType TargetElementType = TypeArgs[0]; 9901 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 9902 checkObjCCollectionLiteralElement(S, TargetElementType, 9903 ArrayLiteral->getElement(I), 9904 0); 9905 } 9906 } 9907 9908 /// Check an Objective-C dictionary literal being converted to the given 9909 /// target type. 9910 static void 9911 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 9912 ObjCDictionaryLiteral *DictionaryLiteral) { 9913 if (!S.NSDictionaryDecl) 9914 return; 9915 9916 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 9917 if (!TargetObjCPtr) 9918 return; 9919 9920 if (TargetObjCPtr->isUnspecialized() || 9921 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 9922 != S.NSDictionaryDecl->getCanonicalDecl()) 9923 return; 9924 9925 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 9926 if (TypeArgs.size() != 2) 9927 return; 9928 9929 QualType TargetKeyType = TypeArgs[0]; 9930 QualType TargetObjectType = TypeArgs[1]; 9931 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 9932 auto Element = DictionaryLiteral->getKeyValueElement(I); 9933 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 9934 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 9935 } 9936 } 9937 9938 // Helper function to filter out cases for constant width constant conversion. 9939 // Don't warn on char array initialization or for non-decimal values. 9940 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 9941 SourceLocation CC) { 9942 // If initializing from a constant, and the constant starts with '0', 9943 // then it is a binary, octal, or hexadecimal. Allow these constants 9944 // to fill all the bits, even if there is a sign change. 9945 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 9946 const char FirstLiteralCharacter = 9947 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0]; 9948 if (FirstLiteralCharacter == '0') 9949 return false; 9950 } 9951 9952 // If the CC location points to a '{', and the type is char, then assume 9953 // assume it is an array initialization. 9954 if (CC.isValid() && T->isCharType()) { 9955 const char FirstContextCharacter = 9956 S.getSourceManager().getCharacterData(CC)[0]; 9957 if (FirstContextCharacter == '{') 9958 return false; 9959 } 9960 9961 return true; 9962 } 9963 9964 static void 9965 CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC, 9966 bool *ICContext = nullptr) { 9967 if (E->isTypeDependent() || E->isValueDependent()) return; 9968 9969 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 9970 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 9971 if (Source == Target) return; 9972 if (Target->isDependentType()) return; 9973 9974 // If the conversion context location is invalid don't complain. We also 9975 // don't want to emit a warning if the issue occurs from the expansion of 9976 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 9977 // delay this check as long as possible. Once we detect we are in that 9978 // scenario, we just return. 9979 if (CC.isInvalid()) 9980 return; 9981 9982 // Diagnose implicit casts to bool. 9983 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 9984 if (isa<StringLiteral>(E)) 9985 // Warn on string literal to bool. Checks for string literals in logical 9986 // and expressions, for instance, assert(0 && "error here"), are 9987 // prevented by a check in AnalyzeImplicitConversions(). 9988 return DiagnoseImpCast(S, E, T, CC, 9989 diag::warn_impcast_string_literal_to_bool); 9990 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 9991 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 9992 // This covers the literal expressions that evaluate to Objective-C 9993 // objects. 9994 return DiagnoseImpCast(S, E, T, CC, 9995 diag::warn_impcast_objective_c_literal_to_bool); 9996 } 9997 if (Source->isPointerType() || Source->canDecayToPointerType()) { 9998 // Warn on pointer to bool conversion that is always true. 9999 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 10000 SourceRange(CC)); 10001 } 10002 } 10003 10004 // Check implicit casts from Objective-C collection literals to specialized 10005 // collection types, e.g., NSArray<NSString *> *. 10006 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 10007 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 10008 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 10009 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 10010 10011 // Strip vector types. 10012 if (isa<VectorType>(Source)) { 10013 if (!isa<VectorType>(Target)) { 10014 if (S.SourceMgr.isInSystemMacro(CC)) 10015 return; 10016 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 10017 } 10018 10019 // If the vector cast is cast between two vectors of the same size, it is 10020 // a bitcast, not a conversion. 10021 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 10022 return; 10023 10024 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 10025 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 10026 } 10027 if (auto VecTy = dyn_cast<VectorType>(Target)) 10028 Target = VecTy->getElementType().getTypePtr(); 10029 10030 // Strip complex types. 10031 if (isa<ComplexType>(Source)) { 10032 if (!isa<ComplexType>(Target)) { 10033 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 10034 return; 10035 10036 return DiagnoseImpCast(S, E, T, CC, 10037 S.getLangOpts().CPlusPlus 10038 ? diag::err_impcast_complex_scalar 10039 : diag::warn_impcast_complex_scalar); 10040 } 10041 10042 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 10043 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 10044 } 10045 10046 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 10047 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 10048 10049 // If the source is floating point... 10050 if (SourceBT && SourceBT->isFloatingPoint()) { 10051 // ...and the target is floating point... 10052 if (TargetBT && TargetBT->isFloatingPoint()) { 10053 // ...then warn if we're dropping FP rank. 10054 10055 // Builtin FP kinds are ordered by increasing FP rank. 10056 if (SourceBT->getKind() > TargetBT->getKind()) { 10057 // Don't warn about float constants that are precisely 10058 // representable in the target type. 10059 Expr::EvalResult result; 10060 if (E->EvaluateAsRValue(result, S.Context)) { 10061 // Value might be a float, a float vector, or a float complex. 10062 if (IsSameFloatAfterCast(result.Val, 10063 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 10064 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 10065 return; 10066 } 10067 10068 if (S.SourceMgr.isInSystemMacro(CC)) 10069 return; 10070 10071 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 10072 } 10073 // ... or possibly if we're increasing rank, too 10074 else if (TargetBT->getKind() > SourceBT->getKind()) { 10075 if (S.SourceMgr.isInSystemMacro(CC)) 10076 return; 10077 10078 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 10079 } 10080 return; 10081 } 10082 10083 // If the target is integral, always warn. 10084 if (TargetBT && TargetBT->isInteger()) { 10085 if (S.SourceMgr.isInSystemMacro(CC)) 10086 return; 10087 10088 DiagnoseFloatingImpCast(S, E, T, CC); 10089 } 10090 10091 // Detect the case where a call result is converted from floating-point to 10092 // to bool, and the final argument to the call is converted from bool, to 10093 // discover this typo: 10094 // 10095 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 10096 // 10097 // FIXME: This is an incredibly special case; is there some more general 10098 // way to detect this class of misplaced-parentheses bug? 10099 if (Target->isBooleanType() && isa<CallExpr>(E)) { 10100 // Check last argument of function call to see if it is an 10101 // implicit cast from a type matching the type the result 10102 // is being cast to. 10103 CallExpr *CEx = cast<CallExpr>(E); 10104 if (unsigned NumArgs = CEx->getNumArgs()) { 10105 Expr *LastA = CEx->getArg(NumArgs - 1); 10106 Expr *InnerE = LastA->IgnoreParenImpCasts(); 10107 if (isa<ImplicitCastExpr>(LastA) && 10108 InnerE->getType()->isBooleanType()) { 10109 // Warn on this floating-point to bool conversion 10110 DiagnoseImpCast(S, E, T, CC, 10111 diag::warn_impcast_floating_point_to_bool); 10112 } 10113 } 10114 } 10115 return; 10116 } 10117 10118 DiagnoseNullConversion(S, E, T, CC); 10119 10120 S.DiscardMisalignedMemberAddress(Target, E); 10121 10122 if (!Source->isIntegerType() || !Target->isIntegerType()) 10123 return; 10124 10125 // TODO: remove this early return once the false positives for constant->bool 10126 // in templates, macros, etc, are reduced or removed. 10127 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 10128 return; 10129 10130 IntRange SourceRange = GetExprRange(S.Context, E); 10131 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 10132 10133 if (SourceRange.Width > TargetRange.Width) { 10134 // If the source is a constant, use a default-on diagnostic. 10135 // TODO: this should happen for bitfield stores, too. 10136 llvm::APSInt Value(32); 10137 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) { 10138 if (S.SourceMgr.isInSystemMacro(CC)) 10139 return; 10140 10141 std::string PrettySourceValue = Value.toString(10); 10142 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 10143 10144 S.DiagRuntimeBehavior(E->getExprLoc(), E, 10145 S.PDiag(diag::warn_impcast_integer_precision_constant) 10146 << PrettySourceValue << PrettyTargetValue 10147 << E->getType() << T << E->getSourceRange() 10148 << clang::SourceRange(CC)); 10149 return; 10150 } 10151 10152 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 10153 if (S.SourceMgr.isInSystemMacro(CC)) 10154 return; 10155 10156 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 10157 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 10158 /* pruneControlFlow */ true); 10159 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 10160 } 10161 10162 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative && 10163 SourceRange.NonNegative && Source->isSignedIntegerType()) { 10164 // Warn when doing a signed to signed conversion, warn if the positive 10165 // source value is exactly the width of the target type, which will 10166 // cause a negative value to be stored. 10167 10168 llvm::APSInt Value; 10169 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) && 10170 !S.SourceMgr.isInSystemMacro(CC)) { 10171 if (isSameWidthConstantConversion(S, E, T, CC)) { 10172 std::string PrettySourceValue = Value.toString(10); 10173 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 10174 10175 S.DiagRuntimeBehavior( 10176 E->getExprLoc(), E, 10177 S.PDiag(diag::warn_impcast_integer_precision_constant) 10178 << PrettySourceValue << PrettyTargetValue << E->getType() << T 10179 << E->getSourceRange() << clang::SourceRange(CC)); 10180 return; 10181 } 10182 } 10183 10184 // Fall through for non-constants to give a sign conversion warning. 10185 } 10186 10187 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 10188 (!TargetRange.NonNegative && SourceRange.NonNegative && 10189 SourceRange.Width == TargetRange.Width)) { 10190 if (S.SourceMgr.isInSystemMacro(CC)) 10191 return; 10192 10193 unsigned DiagID = diag::warn_impcast_integer_sign; 10194 10195 // Traditionally, gcc has warned about this under -Wsign-compare. 10196 // We also want to warn about it in -Wconversion. 10197 // So if -Wconversion is off, use a completely identical diagnostic 10198 // in the sign-compare group. 10199 // The conditional-checking code will 10200 if (ICContext) { 10201 DiagID = diag::warn_impcast_integer_sign_conditional; 10202 *ICContext = true; 10203 } 10204 10205 return DiagnoseImpCast(S, E, T, CC, DiagID); 10206 } 10207 10208 // Diagnose conversions between different enumeration types. 10209 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 10210 // type, to give us better diagnostics. 10211 QualType SourceType = E->getType(); 10212 if (!S.getLangOpts().CPlusPlus) { 10213 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 10214 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 10215 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 10216 SourceType = S.Context.getTypeDeclType(Enum); 10217 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 10218 } 10219 } 10220 10221 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 10222 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 10223 if (SourceEnum->getDecl()->hasNameForLinkage() && 10224 TargetEnum->getDecl()->hasNameForLinkage() && 10225 SourceEnum != TargetEnum) { 10226 if (S.SourceMgr.isInSystemMacro(CC)) 10227 return; 10228 10229 return DiagnoseImpCast(S, E, SourceType, T, CC, 10230 diag::warn_impcast_different_enum_types); 10231 } 10232 } 10233 10234 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 10235 SourceLocation CC, QualType T); 10236 10237 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 10238 SourceLocation CC, bool &ICContext) { 10239 E = E->IgnoreParenImpCasts(); 10240 10241 if (isa<ConditionalOperator>(E)) 10242 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T); 10243 10244 AnalyzeImplicitConversions(S, E, CC); 10245 if (E->getType() != T) 10246 return CheckImplicitConversion(S, E, T, CC, &ICContext); 10247 } 10248 10249 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 10250 SourceLocation CC, QualType T) { 10251 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 10252 10253 bool Suspicious = false; 10254 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 10255 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 10256 10257 // If -Wconversion would have warned about either of the candidates 10258 // for a signedness conversion to the context type... 10259 if (!Suspicious) return; 10260 10261 // ...but it's currently ignored... 10262 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 10263 return; 10264 10265 // ...then check whether it would have warned about either of the 10266 // candidates for a signedness conversion to the condition type. 10267 if (E->getType() == T) return; 10268 10269 Suspicious = false; 10270 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 10271 E->getType(), CC, &Suspicious); 10272 if (!Suspicious) 10273 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 10274 E->getType(), CC, &Suspicious); 10275 } 10276 10277 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 10278 /// Input argument E is a logical expression. 10279 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 10280 if (S.getLangOpts().Bool) 10281 return; 10282 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 10283 } 10284 10285 /// AnalyzeImplicitConversions - Find and report any interesting 10286 /// implicit conversions in the given expression. There are a couple 10287 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 10288 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, 10289 SourceLocation CC) { 10290 QualType T = OrigE->getType(); 10291 Expr *E = OrigE->IgnoreParenImpCasts(); 10292 10293 if (E->isTypeDependent() || E->isValueDependent()) 10294 return; 10295 10296 // For conditional operators, we analyze the arguments as if they 10297 // were being fed directly into the output. 10298 if (isa<ConditionalOperator>(E)) { 10299 ConditionalOperator *CO = cast<ConditionalOperator>(E); 10300 CheckConditionalOperator(S, CO, CC, T); 10301 return; 10302 } 10303 10304 // Check implicit argument conversions for function calls. 10305 if (CallExpr *Call = dyn_cast<CallExpr>(E)) 10306 CheckImplicitArgumentConversions(S, Call, CC); 10307 10308 // Go ahead and check any implicit conversions we might have skipped. 10309 // The non-canonical typecheck is just an optimization; 10310 // CheckImplicitConversion will filter out dead implicit conversions. 10311 if (E->getType() != T) 10312 CheckImplicitConversion(S, E, T, CC); 10313 10314 // Now continue drilling into this expression. 10315 10316 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 10317 // The bound subexpressions in a PseudoObjectExpr are not reachable 10318 // as transitive children. 10319 // FIXME: Use a more uniform representation for this. 10320 for (auto *SE : POE->semantics()) 10321 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 10322 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC); 10323 } 10324 10325 // Skip past explicit casts. 10326 if (isa<ExplicitCastExpr>(E)) { 10327 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts(); 10328 return AnalyzeImplicitConversions(S, E, CC); 10329 } 10330 10331 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 10332 // Do a somewhat different check with comparison operators. 10333 if (BO->isComparisonOp()) 10334 return AnalyzeComparison(S, BO); 10335 10336 // And with simple assignments. 10337 if (BO->getOpcode() == BO_Assign) 10338 return AnalyzeAssignment(S, BO); 10339 // And with compound assignments. 10340 if (BO->isAssignmentOp()) 10341 return AnalyzeCompoundAssignment(S, BO); 10342 } 10343 10344 // These break the otherwise-useful invariant below. Fortunately, 10345 // we don't really need to recurse into them, because any internal 10346 // expressions should have been analyzed already when they were 10347 // built into statements. 10348 if (isa<StmtExpr>(E)) return; 10349 10350 // Don't descend into unevaluated contexts. 10351 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 10352 10353 // Now just recurse over the expression's children. 10354 CC = E->getExprLoc(); 10355 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 10356 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 10357 for (Stmt *SubStmt : E->children()) { 10358 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 10359 if (!ChildExpr) 10360 continue; 10361 10362 if (IsLogicalAndOperator && 10363 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 10364 // Ignore checking string literals that are in logical and operators. 10365 // This is a common pattern for asserts. 10366 continue; 10367 AnalyzeImplicitConversions(S, ChildExpr, CC); 10368 } 10369 10370 if (BO && BO->isLogicalOp()) { 10371 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 10372 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 10373 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 10374 10375 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 10376 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 10377 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 10378 } 10379 10380 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) 10381 if (U->getOpcode() == UO_LNot) 10382 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 10383 } 10384 10385 /// Diagnose integer type and any valid implicit conversion to it. 10386 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 10387 // Taking into account implicit conversions, 10388 // allow any integer. 10389 if (!E->getType()->isIntegerType()) { 10390 S.Diag(E->getLocStart(), 10391 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 10392 return true; 10393 } 10394 // Potentially emit standard warnings for implicit conversions if enabled 10395 // using -Wconversion. 10396 CheckImplicitConversion(S, E, IntT, E->getLocStart()); 10397 return false; 10398 } 10399 10400 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 10401 // Returns true when emitting a warning about taking the address of a reference. 10402 static bool CheckForReference(Sema &SemaRef, const Expr *E, 10403 const PartialDiagnostic &PD) { 10404 E = E->IgnoreParenImpCasts(); 10405 10406 const FunctionDecl *FD = nullptr; 10407 10408 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 10409 if (!DRE->getDecl()->getType()->isReferenceType()) 10410 return false; 10411 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 10412 if (!M->getMemberDecl()->getType()->isReferenceType()) 10413 return false; 10414 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 10415 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 10416 return false; 10417 FD = Call->getDirectCallee(); 10418 } else { 10419 return false; 10420 } 10421 10422 SemaRef.Diag(E->getExprLoc(), PD); 10423 10424 // If possible, point to location of function. 10425 if (FD) { 10426 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 10427 } 10428 10429 return true; 10430 } 10431 10432 // Returns true if the SourceLocation is expanded from any macro body. 10433 // Returns false if the SourceLocation is invalid, is from not in a macro 10434 // expansion, or is from expanded from a top-level macro argument. 10435 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 10436 if (Loc.isInvalid()) 10437 return false; 10438 10439 while (Loc.isMacroID()) { 10440 if (SM.isMacroBodyExpansion(Loc)) 10441 return true; 10442 Loc = SM.getImmediateMacroCallerLoc(Loc); 10443 } 10444 10445 return false; 10446 } 10447 10448 /// Diagnose pointers that are always non-null. 10449 /// \param E the expression containing the pointer 10450 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 10451 /// compared to a null pointer 10452 /// \param IsEqual True when the comparison is equal to a null pointer 10453 /// \param Range Extra SourceRange to highlight in the diagnostic 10454 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 10455 Expr::NullPointerConstantKind NullKind, 10456 bool IsEqual, SourceRange Range) { 10457 if (!E) 10458 return; 10459 10460 // Don't warn inside macros. 10461 if (E->getExprLoc().isMacroID()) { 10462 const SourceManager &SM = getSourceManager(); 10463 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 10464 IsInAnyMacroBody(SM, Range.getBegin())) 10465 return; 10466 } 10467 E = E->IgnoreImpCasts(); 10468 10469 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 10470 10471 if (isa<CXXThisExpr>(E)) { 10472 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 10473 : diag::warn_this_bool_conversion; 10474 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 10475 return; 10476 } 10477 10478 bool IsAddressOf = false; 10479 10480 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 10481 if (UO->getOpcode() != UO_AddrOf) 10482 return; 10483 IsAddressOf = true; 10484 E = UO->getSubExpr(); 10485 } 10486 10487 if (IsAddressOf) { 10488 unsigned DiagID = IsCompare 10489 ? diag::warn_address_of_reference_null_compare 10490 : diag::warn_address_of_reference_bool_conversion; 10491 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 10492 << IsEqual; 10493 if (CheckForReference(*this, E, PD)) { 10494 return; 10495 } 10496 } 10497 10498 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 10499 bool IsParam = isa<NonNullAttr>(NonnullAttr); 10500 std::string Str; 10501 llvm::raw_string_ostream S(Str); 10502 E->printPretty(S, nullptr, getPrintingPolicy()); 10503 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 10504 : diag::warn_cast_nonnull_to_bool; 10505 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 10506 << E->getSourceRange() << Range << IsEqual; 10507 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 10508 }; 10509 10510 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 10511 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 10512 if (auto *Callee = Call->getDirectCallee()) { 10513 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 10514 ComplainAboutNonnullParamOrCall(A); 10515 return; 10516 } 10517 } 10518 } 10519 10520 // Expect to find a single Decl. Skip anything more complicated. 10521 ValueDecl *D = nullptr; 10522 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 10523 D = R->getDecl(); 10524 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 10525 D = M->getMemberDecl(); 10526 } 10527 10528 // Weak Decls can be null. 10529 if (!D || D->isWeak()) 10530 return; 10531 10532 // Check for parameter decl with nonnull attribute 10533 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 10534 if (getCurFunction() && 10535 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 10536 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 10537 ComplainAboutNonnullParamOrCall(A); 10538 return; 10539 } 10540 10541 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 10542 auto ParamIter = llvm::find(FD->parameters(), PV); 10543 assert(ParamIter != FD->param_end()); 10544 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 10545 10546 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 10547 if (!NonNull->args_size()) { 10548 ComplainAboutNonnullParamOrCall(NonNull); 10549 return; 10550 } 10551 10552 for (const ParamIdx &ArgNo : NonNull->args()) { 10553 if (ArgNo.getASTIndex() == ParamNo) { 10554 ComplainAboutNonnullParamOrCall(NonNull); 10555 return; 10556 } 10557 } 10558 } 10559 } 10560 } 10561 } 10562 10563 QualType T = D->getType(); 10564 const bool IsArray = T->isArrayType(); 10565 const bool IsFunction = T->isFunctionType(); 10566 10567 // Address of function is used to silence the function warning. 10568 if (IsAddressOf && IsFunction) { 10569 return; 10570 } 10571 10572 // Found nothing. 10573 if (!IsAddressOf && !IsFunction && !IsArray) 10574 return; 10575 10576 // Pretty print the expression for the diagnostic. 10577 std::string Str; 10578 llvm::raw_string_ostream S(Str); 10579 E->printPretty(S, nullptr, getPrintingPolicy()); 10580 10581 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 10582 : diag::warn_impcast_pointer_to_bool; 10583 enum { 10584 AddressOf, 10585 FunctionPointer, 10586 ArrayPointer 10587 } DiagType; 10588 if (IsAddressOf) 10589 DiagType = AddressOf; 10590 else if (IsFunction) 10591 DiagType = FunctionPointer; 10592 else if (IsArray) 10593 DiagType = ArrayPointer; 10594 else 10595 llvm_unreachable("Could not determine diagnostic."); 10596 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 10597 << Range << IsEqual; 10598 10599 if (!IsFunction) 10600 return; 10601 10602 // Suggest '&' to silence the function warning. 10603 Diag(E->getExprLoc(), diag::note_function_warning_silence) 10604 << FixItHint::CreateInsertion(E->getLocStart(), "&"); 10605 10606 // Check to see if '()' fixit should be emitted. 10607 QualType ReturnType; 10608 UnresolvedSet<4> NonTemplateOverloads; 10609 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 10610 if (ReturnType.isNull()) 10611 return; 10612 10613 if (IsCompare) { 10614 // There are two cases here. If there is null constant, the only suggest 10615 // for a pointer return type. If the null is 0, then suggest if the return 10616 // type is a pointer or an integer type. 10617 if (!ReturnType->isPointerType()) { 10618 if (NullKind == Expr::NPCK_ZeroExpression || 10619 NullKind == Expr::NPCK_ZeroLiteral) { 10620 if (!ReturnType->isIntegerType()) 10621 return; 10622 } else { 10623 return; 10624 } 10625 } 10626 } else { // !IsCompare 10627 // For function to bool, only suggest if the function pointer has bool 10628 // return type. 10629 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 10630 return; 10631 } 10632 Diag(E->getExprLoc(), diag::note_function_to_function_call) 10633 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()"); 10634 } 10635 10636 /// Diagnoses "dangerous" implicit conversions within the given 10637 /// expression (which is a full expression). Implements -Wconversion 10638 /// and -Wsign-compare. 10639 /// 10640 /// \param CC the "context" location of the implicit conversion, i.e. 10641 /// the most location of the syntactic entity requiring the implicit 10642 /// conversion 10643 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 10644 // Don't diagnose in unevaluated contexts. 10645 if (isUnevaluatedContext()) 10646 return; 10647 10648 // Don't diagnose for value- or type-dependent expressions. 10649 if (E->isTypeDependent() || E->isValueDependent()) 10650 return; 10651 10652 // Check for array bounds violations in cases where the check isn't triggered 10653 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 10654 // ArraySubscriptExpr is on the RHS of a variable initialization. 10655 CheckArrayAccess(E); 10656 10657 // This is not the right CC for (e.g.) a variable initialization. 10658 AnalyzeImplicitConversions(*this, E, CC); 10659 } 10660 10661 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 10662 /// Input argument E is a logical expression. 10663 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 10664 ::CheckBoolLikeConversion(*this, E, CC); 10665 } 10666 10667 /// Diagnose when expression is an integer constant expression and its evaluation 10668 /// results in integer overflow 10669 void Sema::CheckForIntOverflow (Expr *E) { 10670 // Use a work list to deal with nested struct initializers. 10671 SmallVector<Expr *, 2> Exprs(1, E); 10672 10673 do { 10674 Expr *OriginalE = Exprs.pop_back_val(); 10675 Expr *E = OriginalE->IgnoreParenCasts(); 10676 10677 if (isa<BinaryOperator>(E)) { 10678 E->EvaluateForOverflow(Context); 10679 continue; 10680 } 10681 10682 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 10683 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 10684 else if (isa<ObjCBoxedExpr>(OriginalE)) 10685 E->EvaluateForOverflow(Context); 10686 else if (auto Call = dyn_cast<CallExpr>(E)) 10687 Exprs.append(Call->arg_begin(), Call->arg_end()); 10688 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 10689 Exprs.append(Message->arg_begin(), Message->arg_end()); 10690 } while (!Exprs.empty()); 10691 } 10692 10693 namespace { 10694 10695 /// Visitor for expressions which looks for unsequenced operations on the 10696 /// same object. 10697 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> { 10698 using Base = EvaluatedExprVisitor<SequenceChecker>; 10699 10700 /// A tree of sequenced regions within an expression. Two regions are 10701 /// unsequenced if one is an ancestor or a descendent of the other. When we 10702 /// finish processing an expression with sequencing, such as a comma 10703 /// expression, we fold its tree nodes into its parent, since they are 10704 /// unsequenced with respect to nodes we will visit later. 10705 class SequenceTree { 10706 struct Value { 10707 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 10708 unsigned Parent : 31; 10709 unsigned Merged : 1; 10710 }; 10711 SmallVector<Value, 8> Values; 10712 10713 public: 10714 /// A region within an expression which may be sequenced with respect 10715 /// to some other region. 10716 class Seq { 10717 friend class SequenceTree; 10718 10719 unsigned Index = 0; 10720 10721 explicit Seq(unsigned N) : Index(N) {} 10722 10723 public: 10724 Seq() = default; 10725 }; 10726 10727 SequenceTree() { Values.push_back(Value(0)); } 10728 Seq root() const { return Seq(0); } 10729 10730 /// Create a new sequence of operations, which is an unsequenced 10731 /// subset of \p Parent. This sequence of operations is sequenced with 10732 /// respect to other children of \p Parent. 10733 Seq allocate(Seq Parent) { 10734 Values.push_back(Value(Parent.Index)); 10735 return Seq(Values.size() - 1); 10736 } 10737 10738 /// Merge a sequence of operations into its parent. 10739 void merge(Seq S) { 10740 Values[S.Index].Merged = true; 10741 } 10742 10743 /// Determine whether two operations are unsequenced. This operation 10744 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 10745 /// should have been merged into its parent as appropriate. 10746 bool isUnsequenced(Seq Cur, Seq Old) { 10747 unsigned C = representative(Cur.Index); 10748 unsigned Target = representative(Old.Index); 10749 while (C >= Target) { 10750 if (C == Target) 10751 return true; 10752 C = Values[C].Parent; 10753 } 10754 return false; 10755 } 10756 10757 private: 10758 /// Pick a representative for a sequence. 10759 unsigned representative(unsigned K) { 10760 if (Values[K].Merged) 10761 // Perform path compression as we go. 10762 return Values[K].Parent = representative(Values[K].Parent); 10763 return K; 10764 } 10765 }; 10766 10767 /// An object for which we can track unsequenced uses. 10768 using Object = NamedDecl *; 10769 10770 /// Different flavors of object usage which we track. We only track the 10771 /// least-sequenced usage of each kind. 10772 enum UsageKind { 10773 /// A read of an object. Multiple unsequenced reads are OK. 10774 UK_Use, 10775 10776 /// A modification of an object which is sequenced before the value 10777 /// computation of the expression, such as ++n in C++. 10778 UK_ModAsValue, 10779 10780 /// A modification of an object which is not sequenced before the value 10781 /// computation of the expression, such as n++. 10782 UK_ModAsSideEffect, 10783 10784 UK_Count = UK_ModAsSideEffect + 1 10785 }; 10786 10787 struct Usage { 10788 Expr *Use = nullptr; 10789 SequenceTree::Seq Seq; 10790 10791 Usage() = default; 10792 }; 10793 10794 struct UsageInfo { 10795 Usage Uses[UK_Count]; 10796 10797 /// Have we issued a diagnostic for this variable already? 10798 bool Diagnosed = false; 10799 10800 UsageInfo() = default; 10801 }; 10802 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 10803 10804 Sema &SemaRef; 10805 10806 /// Sequenced regions within the expression. 10807 SequenceTree Tree; 10808 10809 /// Declaration modifications and references which we have seen. 10810 UsageInfoMap UsageMap; 10811 10812 /// The region we are currently within. 10813 SequenceTree::Seq Region; 10814 10815 /// Filled in with declarations which were modified as a side-effect 10816 /// (that is, post-increment operations). 10817 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 10818 10819 /// Expressions to check later. We defer checking these to reduce 10820 /// stack usage. 10821 SmallVectorImpl<Expr *> &WorkList; 10822 10823 /// RAII object wrapping the visitation of a sequenced subexpression of an 10824 /// expression. At the end of this process, the side-effects of the evaluation 10825 /// become sequenced with respect to the value computation of the result, so 10826 /// we downgrade any UK_ModAsSideEffect within the evaluation to 10827 /// UK_ModAsValue. 10828 struct SequencedSubexpression { 10829 SequencedSubexpression(SequenceChecker &Self) 10830 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 10831 Self.ModAsSideEffect = &ModAsSideEffect; 10832 } 10833 10834 ~SequencedSubexpression() { 10835 for (auto &M : llvm::reverse(ModAsSideEffect)) { 10836 UsageInfo &U = Self.UsageMap[M.first]; 10837 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect]; 10838 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue); 10839 SideEffectUsage = M.second; 10840 } 10841 Self.ModAsSideEffect = OldModAsSideEffect; 10842 } 10843 10844 SequenceChecker &Self; 10845 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 10846 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 10847 }; 10848 10849 /// RAII object wrapping the visitation of a subexpression which we might 10850 /// choose to evaluate as a constant. If any subexpression is evaluated and 10851 /// found to be non-constant, this allows us to suppress the evaluation of 10852 /// the outer expression. 10853 class EvaluationTracker { 10854 public: 10855 EvaluationTracker(SequenceChecker &Self) 10856 : Self(Self), Prev(Self.EvalTracker) { 10857 Self.EvalTracker = this; 10858 } 10859 10860 ~EvaluationTracker() { 10861 Self.EvalTracker = Prev; 10862 if (Prev) 10863 Prev->EvalOK &= EvalOK; 10864 } 10865 10866 bool evaluate(const Expr *E, bool &Result) { 10867 if (!EvalOK || E->isValueDependent()) 10868 return false; 10869 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context); 10870 return EvalOK; 10871 } 10872 10873 private: 10874 SequenceChecker &Self; 10875 EvaluationTracker *Prev; 10876 bool EvalOK = true; 10877 } *EvalTracker = nullptr; 10878 10879 /// Find the object which is produced by the specified expression, 10880 /// if any. 10881 Object getObject(Expr *E, bool Mod) const { 10882 E = E->IgnoreParenCasts(); 10883 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 10884 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 10885 return getObject(UO->getSubExpr(), Mod); 10886 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 10887 if (BO->getOpcode() == BO_Comma) 10888 return getObject(BO->getRHS(), Mod); 10889 if (Mod && BO->isAssignmentOp()) 10890 return getObject(BO->getLHS(), Mod); 10891 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 10892 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 10893 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 10894 return ME->getMemberDecl(); 10895 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 10896 // FIXME: If this is a reference, map through to its value. 10897 return DRE->getDecl(); 10898 return nullptr; 10899 } 10900 10901 /// Note that an object was modified or used by an expression. 10902 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) { 10903 Usage &U = UI.Uses[UK]; 10904 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) { 10905 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 10906 ModAsSideEffect->push_back(std::make_pair(O, U)); 10907 U.Use = Ref; 10908 U.Seq = Region; 10909 } 10910 } 10911 10912 /// Check whether a modification or use conflicts with a prior usage. 10913 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind, 10914 bool IsModMod) { 10915 if (UI.Diagnosed) 10916 return; 10917 10918 const Usage &U = UI.Uses[OtherKind]; 10919 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) 10920 return; 10921 10922 Expr *Mod = U.Use; 10923 Expr *ModOrUse = Ref; 10924 if (OtherKind == UK_Use) 10925 std::swap(Mod, ModOrUse); 10926 10927 SemaRef.Diag(Mod->getExprLoc(), 10928 IsModMod ? diag::warn_unsequenced_mod_mod 10929 : diag::warn_unsequenced_mod_use) 10930 << O << SourceRange(ModOrUse->getExprLoc()); 10931 UI.Diagnosed = true; 10932 } 10933 10934 void notePreUse(Object O, Expr *Use) { 10935 UsageInfo &U = UsageMap[O]; 10936 // Uses conflict with other modifications. 10937 checkUsage(O, U, Use, UK_ModAsValue, false); 10938 } 10939 10940 void notePostUse(Object O, Expr *Use) { 10941 UsageInfo &U = UsageMap[O]; 10942 checkUsage(O, U, Use, UK_ModAsSideEffect, false); 10943 addUsage(U, O, Use, UK_Use); 10944 } 10945 10946 void notePreMod(Object O, Expr *Mod) { 10947 UsageInfo &U = UsageMap[O]; 10948 // Modifications conflict with other modifications and with uses. 10949 checkUsage(O, U, Mod, UK_ModAsValue, true); 10950 checkUsage(O, U, Mod, UK_Use, false); 10951 } 10952 10953 void notePostMod(Object O, Expr *Use, UsageKind UK) { 10954 UsageInfo &U = UsageMap[O]; 10955 checkUsage(O, U, Use, UK_ModAsSideEffect, true); 10956 addUsage(U, O, Use, UK); 10957 } 10958 10959 public: 10960 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList) 10961 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 10962 Visit(E); 10963 } 10964 10965 void VisitStmt(Stmt *S) { 10966 // Skip all statements which aren't expressions for now. 10967 } 10968 10969 void VisitExpr(Expr *E) { 10970 // By default, just recurse to evaluated subexpressions. 10971 Base::VisitStmt(E); 10972 } 10973 10974 void VisitCastExpr(CastExpr *E) { 10975 Object O = Object(); 10976 if (E->getCastKind() == CK_LValueToRValue) 10977 O = getObject(E->getSubExpr(), false); 10978 10979 if (O) 10980 notePreUse(O, E); 10981 VisitExpr(E); 10982 if (O) 10983 notePostUse(O, E); 10984 } 10985 10986 void VisitBinComma(BinaryOperator *BO) { 10987 // C++11 [expr.comma]p1: 10988 // Every value computation and side effect associated with the left 10989 // expression is sequenced before every value computation and side 10990 // effect associated with the right expression. 10991 SequenceTree::Seq LHS = Tree.allocate(Region); 10992 SequenceTree::Seq RHS = Tree.allocate(Region); 10993 SequenceTree::Seq OldRegion = Region; 10994 10995 { 10996 SequencedSubexpression SeqLHS(*this); 10997 Region = LHS; 10998 Visit(BO->getLHS()); 10999 } 11000 11001 Region = RHS; 11002 Visit(BO->getRHS()); 11003 11004 Region = OldRegion; 11005 11006 // Forget that LHS and RHS are sequenced. They are both unsequenced 11007 // with respect to other stuff. 11008 Tree.merge(LHS); 11009 Tree.merge(RHS); 11010 } 11011 11012 void VisitBinAssign(BinaryOperator *BO) { 11013 // The modification is sequenced after the value computation of the LHS 11014 // and RHS, so check it before inspecting the operands and update the 11015 // map afterwards. 11016 Object O = getObject(BO->getLHS(), true); 11017 if (!O) 11018 return VisitExpr(BO); 11019 11020 notePreMod(O, BO); 11021 11022 // C++11 [expr.ass]p7: 11023 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated 11024 // only once. 11025 // 11026 // Therefore, for a compound assignment operator, O is considered used 11027 // everywhere except within the evaluation of E1 itself. 11028 if (isa<CompoundAssignOperator>(BO)) 11029 notePreUse(O, BO); 11030 11031 Visit(BO->getLHS()); 11032 11033 if (isa<CompoundAssignOperator>(BO)) 11034 notePostUse(O, BO); 11035 11036 Visit(BO->getRHS()); 11037 11038 // C++11 [expr.ass]p1: 11039 // the assignment is sequenced [...] before the value computation of the 11040 // assignment expression. 11041 // C11 6.5.16/3 has no such rule. 11042 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 11043 : UK_ModAsSideEffect); 11044 } 11045 11046 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) { 11047 VisitBinAssign(CAO); 11048 } 11049 11050 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 11051 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 11052 void VisitUnaryPreIncDec(UnaryOperator *UO) { 11053 Object O = getObject(UO->getSubExpr(), true); 11054 if (!O) 11055 return VisitExpr(UO); 11056 11057 notePreMod(O, UO); 11058 Visit(UO->getSubExpr()); 11059 // C++11 [expr.pre.incr]p1: 11060 // the expression ++x is equivalent to x+=1 11061 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 11062 : UK_ModAsSideEffect); 11063 } 11064 11065 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 11066 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 11067 void VisitUnaryPostIncDec(UnaryOperator *UO) { 11068 Object O = getObject(UO->getSubExpr(), true); 11069 if (!O) 11070 return VisitExpr(UO); 11071 11072 notePreMod(O, UO); 11073 Visit(UO->getSubExpr()); 11074 notePostMod(O, UO, UK_ModAsSideEffect); 11075 } 11076 11077 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated. 11078 void VisitBinLOr(BinaryOperator *BO) { 11079 // The side-effects of the LHS of an '&&' are sequenced before the 11080 // value computation of the RHS, and hence before the value computation 11081 // of the '&&' itself, unless the LHS evaluates to zero. We treat them 11082 // as if they were unconditionally sequenced. 11083 EvaluationTracker Eval(*this); 11084 { 11085 SequencedSubexpression Sequenced(*this); 11086 Visit(BO->getLHS()); 11087 } 11088 11089 bool Result; 11090 if (Eval.evaluate(BO->getLHS(), Result)) { 11091 if (!Result) 11092 Visit(BO->getRHS()); 11093 } else { 11094 // Check for unsequenced operations in the RHS, treating it as an 11095 // entirely separate evaluation. 11096 // 11097 // FIXME: If there are operations in the RHS which are unsequenced 11098 // with respect to operations outside the RHS, and those operations 11099 // are unconditionally evaluated, diagnose them. 11100 WorkList.push_back(BO->getRHS()); 11101 } 11102 } 11103 void VisitBinLAnd(BinaryOperator *BO) { 11104 EvaluationTracker Eval(*this); 11105 { 11106 SequencedSubexpression Sequenced(*this); 11107 Visit(BO->getLHS()); 11108 } 11109 11110 bool Result; 11111 if (Eval.evaluate(BO->getLHS(), Result)) { 11112 if (Result) 11113 Visit(BO->getRHS()); 11114 } else { 11115 WorkList.push_back(BO->getRHS()); 11116 } 11117 } 11118 11119 // Only visit the condition, unless we can be sure which subexpression will 11120 // be chosen. 11121 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) { 11122 EvaluationTracker Eval(*this); 11123 { 11124 SequencedSubexpression Sequenced(*this); 11125 Visit(CO->getCond()); 11126 } 11127 11128 bool Result; 11129 if (Eval.evaluate(CO->getCond(), Result)) 11130 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr()); 11131 else { 11132 WorkList.push_back(CO->getTrueExpr()); 11133 WorkList.push_back(CO->getFalseExpr()); 11134 } 11135 } 11136 11137 void VisitCallExpr(CallExpr *CE) { 11138 // C++11 [intro.execution]p15: 11139 // When calling a function [...], every value computation and side effect 11140 // associated with any argument expression, or with the postfix expression 11141 // designating the called function, is sequenced before execution of every 11142 // expression or statement in the body of the function [and thus before 11143 // the value computation of its result]. 11144 SequencedSubexpression Sequenced(*this); 11145 Base::VisitCallExpr(CE); 11146 11147 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 11148 } 11149 11150 void VisitCXXConstructExpr(CXXConstructExpr *CCE) { 11151 // This is a call, so all subexpressions are sequenced before the result. 11152 SequencedSubexpression Sequenced(*this); 11153 11154 if (!CCE->isListInitialization()) 11155 return VisitExpr(CCE); 11156 11157 // In C++11, list initializations are sequenced. 11158 SmallVector<SequenceTree::Seq, 32> Elts; 11159 SequenceTree::Seq Parent = Region; 11160 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(), 11161 E = CCE->arg_end(); 11162 I != E; ++I) { 11163 Region = Tree.allocate(Parent); 11164 Elts.push_back(Region); 11165 Visit(*I); 11166 } 11167 11168 // Forget that the initializers are sequenced. 11169 Region = Parent; 11170 for (unsigned I = 0; I < Elts.size(); ++I) 11171 Tree.merge(Elts[I]); 11172 } 11173 11174 void VisitInitListExpr(InitListExpr *ILE) { 11175 if (!SemaRef.getLangOpts().CPlusPlus11) 11176 return VisitExpr(ILE); 11177 11178 // In C++11, list initializations are sequenced. 11179 SmallVector<SequenceTree::Seq, 32> Elts; 11180 SequenceTree::Seq Parent = Region; 11181 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 11182 Expr *E = ILE->getInit(I); 11183 if (!E) continue; 11184 Region = Tree.allocate(Parent); 11185 Elts.push_back(Region); 11186 Visit(E); 11187 } 11188 11189 // Forget that the initializers are sequenced. 11190 Region = Parent; 11191 for (unsigned I = 0; I < Elts.size(); ++I) 11192 Tree.merge(Elts[I]); 11193 } 11194 }; 11195 11196 } // namespace 11197 11198 void Sema::CheckUnsequencedOperations(Expr *E) { 11199 SmallVector<Expr *, 8> WorkList; 11200 WorkList.push_back(E); 11201 while (!WorkList.empty()) { 11202 Expr *Item = WorkList.pop_back_val(); 11203 SequenceChecker(*this, Item, WorkList); 11204 } 11205 } 11206 11207 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 11208 bool IsConstexpr) { 11209 CheckImplicitConversions(E, CheckLoc); 11210 if (!E->isInstantiationDependent()) 11211 CheckUnsequencedOperations(E); 11212 if (!IsConstexpr && !E->isValueDependent()) 11213 CheckForIntOverflow(E); 11214 DiagnoseMisalignedMembers(); 11215 } 11216 11217 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 11218 FieldDecl *BitField, 11219 Expr *Init) { 11220 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 11221 } 11222 11223 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 11224 SourceLocation Loc) { 11225 if (!PType->isVariablyModifiedType()) 11226 return; 11227 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 11228 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 11229 return; 11230 } 11231 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 11232 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 11233 return; 11234 } 11235 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 11236 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 11237 return; 11238 } 11239 11240 const ArrayType *AT = S.Context.getAsArrayType(PType); 11241 if (!AT) 11242 return; 11243 11244 if (AT->getSizeModifier() != ArrayType::Star) { 11245 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 11246 return; 11247 } 11248 11249 S.Diag(Loc, diag::err_array_star_in_function_definition); 11250 } 11251 11252 /// CheckParmsForFunctionDef - Check that the parameters of the given 11253 /// function are appropriate for the definition of a function. This 11254 /// takes care of any checks that cannot be performed on the 11255 /// declaration itself, e.g., that the types of each of the function 11256 /// parameters are complete. 11257 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 11258 bool CheckParameterNames) { 11259 bool HasInvalidParm = false; 11260 for (ParmVarDecl *Param : Parameters) { 11261 // C99 6.7.5.3p4: the parameters in a parameter type list in a 11262 // function declarator that is part of a function definition of 11263 // that function shall not have incomplete type. 11264 // 11265 // This is also C++ [dcl.fct]p6. 11266 if (!Param->isInvalidDecl() && 11267 RequireCompleteType(Param->getLocation(), Param->getType(), 11268 diag::err_typecheck_decl_incomplete_type)) { 11269 Param->setInvalidDecl(); 11270 HasInvalidParm = true; 11271 } 11272 11273 // C99 6.9.1p5: If the declarator includes a parameter type list, the 11274 // declaration of each parameter shall include an identifier. 11275 if (CheckParameterNames && 11276 Param->getIdentifier() == nullptr && 11277 !Param->isImplicit() && 11278 !getLangOpts().CPlusPlus) 11279 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 11280 11281 // C99 6.7.5.3p12: 11282 // If the function declarator is not part of a definition of that 11283 // function, parameters may have incomplete type and may use the [*] 11284 // notation in their sequences of declarator specifiers to specify 11285 // variable length array types. 11286 QualType PType = Param->getOriginalType(); 11287 // FIXME: This diagnostic should point the '[*]' if source-location 11288 // information is added for it. 11289 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 11290 11291 // If the parameter is a c++ class type and it has to be destructed in the 11292 // callee function, declare the destructor so that it can be called by the 11293 // callee function. Do not perform any direct access check on the dtor here. 11294 if (!Param->isInvalidDecl()) { 11295 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 11296 if (!ClassDecl->isInvalidDecl() && 11297 !ClassDecl->hasIrrelevantDestructor() && 11298 !ClassDecl->isDependentContext() && 11299 ClassDecl->isParamDestroyedInCallee()) { 11300 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 11301 MarkFunctionReferenced(Param->getLocation(), Destructor); 11302 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 11303 } 11304 } 11305 } 11306 11307 // Parameters with the pass_object_size attribute only need to be marked 11308 // constant at function definitions. Because we lack information about 11309 // whether we're on a declaration or definition when we're instantiating the 11310 // attribute, we need to check for constness here. 11311 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 11312 if (!Param->getType().isConstQualified()) 11313 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 11314 << Attr->getSpelling() << 1; 11315 } 11316 11317 return HasInvalidParm; 11318 } 11319 11320 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr 11321 /// or MemberExpr. 11322 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign, 11323 ASTContext &Context) { 11324 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 11325 return Context.getDeclAlign(DRE->getDecl()); 11326 11327 if (const auto *ME = dyn_cast<MemberExpr>(E)) 11328 return Context.getDeclAlign(ME->getMemberDecl()); 11329 11330 return TypeAlign; 11331 } 11332 11333 /// CheckCastAlign - Implements -Wcast-align, which warns when a 11334 /// pointer cast increases the alignment requirements. 11335 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 11336 // This is actually a lot of work to potentially be doing on every 11337 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 11338 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 11339 return; 11340 11341 // Ignore dependent types. 11342 if (T->isDependentType() || Op->getType()->isDependentType()) 11343 return; 11344 11345 // Require that the destination be a pointer type. 11346 const PointerType *DestPtr = T->getAs<PointerType>(); 11347 if (!DestPtr) return; 11348 11349 // If the destination has alignment 1, we're done. 11350 QualType DestPointee = DestPtr->getPointeeType(); 11351 if (DestPointee->isIncompleteType()) return; 11352 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 11353 if (DestAlign.isOne()) return; 11354 11355 // Require that the source be a pointer type. 11356 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 11357 if (!SrcPtr) return; 11358 QualType SrcPointee = SrcPtr->getPointeeType(); 11359 11360 // Whitelist casts from cv void*. We already implicitly 11361 // whitelisted casts to cv void*, since they have alignment 1. 11362 // Also whitelist casts involving incomplete types, which implicitly 11363 // includes 'void'. 11364 if (SrcPointee->isIncompleteType()) return; 11365 11366 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee); 11367 11368 if (auto *CE = dyn_cast<CastExpr>(Op)) { 11369 if (CE->getCastKind() == CK_ArrayToPointerDecay) 11370 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context); 11371 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) { 11372 if (UO->getOpcode() == UO_AddrOf) 11373 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context); 11374 } 11375 11376 if (SrcAlign >= DestAlign) return; 11377 11378 Diag(TRange.getBegin(), diag::warn_cast_align) 11379 << Op->getType() << T 11380 << static_cast<unsigned>(SrcAlign.getQuantity()) 11381 << static_cast<unsigned>(DestAlign.getQuantity()) 11382 << TRange << Op->getSourceRange(); 11383 } 11384 11385 /// Check whether this array fits the idiom of a size-one tail padded 11386 /// array member of a struct. 11387 /// 11388 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 11389 /// commonly used to emulate flexible arrays in C89 code. 11390 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 11391 const NamedDecl *ND) { 11392 if (Size != 1 || !ND) return false; 11393 11394 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 11395 if (!FD) return false; 11396 11397 // Don't consider sizes resulting from macro expansions or template argument 11398 // substitution to form C89 tail-padded arrays. 11399 11400 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 11401 while (TInfo) { 11402 TypeLoc TL = TInfo->getTypeLoc(); 11403 // Look through typedefs. 11404 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 11405 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 11406 TInfo = TDL->getTypeSourceInfo(); 11407 continue; 11408 } 11409 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 11410 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 11411 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 11412 return false; 11413 } 11414 break; 11415 } 11416 11417 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 11418 if (!RD) return false; 11419 if (RD->isUnion()) return false; 11420 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 11421 if (!CRD->isStandardLayout()) return false; 11422 } 11423 11424 // See if this is the last field decl in the record. 11425 const Decl *D = FD; 11426 while ((D = D->getNextDeclInContext())) 11427 if (isa<FieldDecl>(D)) 11428 return false; 11429 return true; 11430 } 11431 11432 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 11433 const ArraySubscriptExpr *ASE, 11434 bool AllowOnePastEnd, bool IndexNegated) { 11435 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 11436 if (IndexExpr->isValueDependent()) 11437 return; 11438 11439 const Type *EffectiveType = 11440 BaseExpr->getType()->getPointeeOrArrayElementType(); 11441 BaseExpr = BaseExpr->IgnoreParenCasts(); 11442 const ConstantArrayType *ArrayTy = 11443 Context.getAsConstantArrayType(BaseExpr->getType()); 11444 if (!ArrayTy) 11445 return; 11446 11447 llvm::APSInt index; 11448 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects)) 11449 return; 11450 if (IndexNegated) 11451 index = -index; 11452 11453 const NamedDecl *ND = nullptr; 11454 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 11455 ND = DRE->getDecl(); 11456 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 11457 ND = ME->getMemberDecl(); 11458 11459 if (index.isUnsigned() || !index.isNegative()) { 11460 llvm::APInt size = ArrayTy->getSize(); 11461 if (!size.isStrictlyPositive()) 11462 return; 11463 11464 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType(); 11465 if (BaseType != EffectiveType) { 11466 // Make sure we're comparing apples to apples when comparing index to size 11467 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 11468 uint64_t array_typesize = Context.getTypeSize(BaseType); 11469 // Handle ptrarith_typesize being zero, such as when casting to void* 11470 if (!ptrarith_typesize) ptrarith_typesize = 1; 11471 if (ptrarith_typesize != array_typesize) { 11472 // There's a cast to a different size type involved 11473 uint64_t ratio = array_typesize / ptrarith_typesize; 11474 // TODO: Be smarter about handling cases where array_typesize is not a 11475 // multiple of ptrarith_typesize 11476 if (ptrarith_typesize * ratio == array_typesize) 11477 size *= llvm::APInt(size.getBitWidth(), ratio); 11478 } 11479 } 11480 11481 if (size.getBitWidth() > index.getBitWidth()) 11482 index = index.zext(size.getBitWidth()); 11483 else if (size.getBitWidth() < index.getBitWidth()) 11484 size = size.zext(index.getBitWidth()); 11485 11486 // For array subscripting the index must be less than size, but for pointer 11487 // arithmetic also allow the index (offset) to be equal to size since 11488 // computing the next address after the end of the array is legal and 11489 // commonly done e.g. in C++ iterators and range-based for loops. 11490 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 11491 return; 11492 11493 // Also don't warn for arrays of size 1 which are members of some 11494 // structure. These are often used to approximate flexible arrays in C89 11495 // code. 11496 if (IsTailPaddedMemberArray(*this, size, ND)) 11497 return; 11498 11499 // Suppress the warning if the subscript expression (as identified by the 11500 // ']' location) and the index expression are both from macro expansions 11501 // within a system header. 11502 if (ASE) { 11503 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 11504 ASE->getRBracketLoc()); 11505 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 11506 SourceLocation IndexLoc = SourceMgr.getSpellingLoc( 11507 IndexExpr->getLocStart()); 11508 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 11509 return; 11510 } 11511 } 11512 11513 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 11514 if (ASE) 11515 DiagID = diag::warn_array_index_exceeds_bounds; 11516 11517 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 11518 PDiag(DiagID) << index.toString(10, true) 11519 << size.toString(10, true) 11520 << (unsigned)size.getLimitedValue(~0U) 11521 << IndexExpr->getSourceRange()); 11522 } else { 11523 unsigned DiagID = diag::warn_array_index_precedes_bounds; 11524 if (!ASE) { 11525 DiagID = diag::warn_ptr_arith_precedes_bounds; 11526 if (index.isNegative()) index = -index; 11527 } 11528 11529 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 11530 PDiag(DiagID) << index.toString(10, true) 11531 << IndexExpr->getSourceRange()); 11532 } 11533 11534 if (!ND) { 11535 // Try harder to find a NamedDecl to point at in the note. 11536 while (const ArraySubscriptExpr *ASE = 11537 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 11538 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 11539 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 11540 ND = DRE->getDecl(); 11541 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 11542 ND = ME->getMemberDecl(); 11543 } 11544 11545 if (ND) 11546 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr, 11547 PDiag(diag::note_array_index_out_of_bounds) 11548 << ND->getDeclName()); 11549 } 11550 11551 void Sema::CheckArrayAccess(const Expr *expr) { 11552 int AllowOnePastEnd = 0; 11553 while (expr) { 11554 expr = expr->IgnoreParenImpCasts(); 11555 switch (expr->getStmtClass()) { 11556 case Stmt::ArraySubscriptExprClass: { 11557 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 11558 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 11559 AllowOnePastEnd > 0); 11560 expr = ASE->getBase(); 11561 break; 11562 } 11563 case Stmt::MemberExprClass: { 11564 expr = cast<MemberExpr>(expr)->getBase(); 11565 break; 11566 } 11567 case Stmt::OMPArraySectionExprClass: { 11568 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 11569 if (ASE->getLowerBound()) 11570 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 11571 /*ASE=*/nullptr, AllowOnePastEnd > 0); 11572 return; 11573 } 11574 case Stmt::UnaryOperatorClass: { 11575 // Only unwrap the * and & unary operators 11576 const UnaryOperator *UO = cast<UnaryOperator>(expr); 11577 expr = UO->getSubExpr(); 11578 switch (UO->getOpcode()) { 11579 case UO_AddrOf: 11580 AllowOnePastEnd++; 11581 break; 11582 case UO_Deref: 11583 AllowOnePastEnd--; 11584 break; 11585 default: 11586 return; 11587 } 11588 break; 11589 } 11590 case Stmt::ConditionalOperatorClass: { 11591 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 11592 if (const Expr *lhs = cond->getLHS()) 11593 CheckArrayAccess(lhs); 11594 if (const Expr *rhs = cond->getRHS()) 11595 CheckArrayAccess(rhs); 11596 return; 11597 } 11598 case Stmt::CXXOperatorCallExprClass: { 11599 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 11600 for (const auto *Arg : OCE->arguments()) 11601 CheckArrayAccess(Arg); 11602 return; 11603 } 11604 default: 11605 return; 11606 } 11607 } 11608 } 11609 11610 //===--- CHECK: Objective-C retain cycles ----------------------------------// 11611 11612 namespace { 11613 11614 struct RetainCycleOwner { 11615 VarDecl *Variable = nullptr; 11616 SourceRange Range; 11617 SourceLocation Loc; 11618 bool Indirect = false; 11619 11620 RetainCycleOwner() = default; 11621 11622 void setLocsFrom(Expr *e) { 11623 Loc = e->getExprLoc(); 11624 Range = e->getSourceRange(); 11625 } 11626 }; 11627 11628 } // namespace 11629 11630 /// Consider whether capturing the given variable can possibly lead to 11631 /// a retain cycle. 11632 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 11633 // In ARC, it's captured strongly iff the variable has __strong 11634 // lifetime. In MRR, it's captured strongly if the variable is 11635 // __block and has an appropriate type. 11636 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 11637 return false; 11638 11639 owner.Variable = var; 11640 if (ref) 11641 owner.setLocsFrom(ref); 11642 return true; 11643 } 11644 11645 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 11646 while (true) { 11647 e = e->IgnoreParens(); 11648 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 11649 switch (cast->getCastKind()) { 11650 case CK_BitCast: 11651 case CK_LValueBitCast: 11652 case CK_LValueToRValue: 11653 case CK_ARCReclaimReturnedObject: 11654 e = cast->getSubExpr(); 11655 continue; 11656 11657 default: 11658 return false; 11659 } 11660 } 11661 11662 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 11663 ObjCIvarDecl *ivar = ref->getDecl(); 11664 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 11665 return false; 11666 11667 // Try to find a retain cycle in the base. 11668 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 11669 return false; 11670 11671 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 11672 owner.Indirect = true; 11673 return true; 11674 } 11675 11676 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 11677 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 11678 if (!var) return false; 11679 return considerVariable(var, ref, owner); 11680 } 11681 11682 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 11683 if (member->isArrow()) return false; 11684 11685 // Don't count this as an indirect ownership. 11686 e = member->getBase(); 11687 continue; 11688 } 11689 11690 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 11691 // Only pay attention to pseudo-objects on property references. 11692 ObjCPropertyRefExpr *pre 11693 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 11694 ->IgnoreParens()); 11695 if (!pre) return false; 11696 if (pre->isImplicitProperty()) return false; 11697 ObjCPropertyDecl *property = pre->getExplicitProperty(); 11698 if (!property->isRetaining() && 11699 !(property->getPropertyIvarDecl() && 11700 property->getPropertyIvarDecl()->getType() 11701 .getObjCLifetime() == Qualifiers::OCL_Strong)) 11702 return false; 11703 11704 owner.Indirect = true; 11705 if (pre->isSuperReceiver()) { 11706 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 11707 if (!owner.Variable) 11708 return false; 11709 owner.Loc = pre->getLocation(); 11710 owner.Range = pre->getSourceRange(); 11711 return true; 11712 } 11713 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 11714 ->getSourceExpr()); 11715 continue; 11716 } 11717 11718 // Array ivars? 11719 11720 return false; 11721 } 11722 } 11723 11724 namespace { 11725 11726 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 11727 ASTContext &Context; 11728 VarDecl *Variable; 11729 Expr *Capturer = nullptr; 11730 bool VarWillBeReased = false; 11731 11732 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 11733 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 11734 Context(Context), Variable(variable) {} 11735 11736 void VisitDeclRefExpr(DeclRefExpr *ref) { 11737 if (ref->getDecl() == Variable && !Capturer) 11738 Capturer = ref; 11739 } 11740 11741 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 11742 if (Capturer) return; 11743 Visit(ref->getBase()); 11744 if (Capturer && ref->isFreeIvar()) 11745 Capturer = ref; 11746 } 11747 11748 void VisitBlockExpr(BlockExpr *block) { 11749 // Look inside nested blocks 11750 if (block->getBlockDecl()->capturesVariable(Variable)) 11751 Visit(block->getBlockDecl()->getBody()); 11752 } 11753 11754 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 11755 if (Capturer) return; 11756 if (OVE->getSourceExpr()) 11757 Visit(OVE->getSourceExpr()); 11758 } 11759 11760 void VisitBinaryOperator(BinaryOperator *BinOp) { 11761 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 11762 return; 11763 Expr *LHS = BinOp->getLHS(); 11764 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 11765 if (DRE->getDecl() != Variable) 11766 return; 11767 if (Expr *RHS = BinOp->getRHS()) { 11768 RHS = RHS->IgnoreParenCasts(); 11769 llvm::APSInt Value; 11770 VarWillBeReased = 11771 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0); 11772 } 11773 } 11774 } 11775 }; 11776 11777 } // namespace 11778 11779 /// Check whether the given argument is a block which captures a 11780 /// variable. 11781 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 11782 assert(owner.Variable && owner.Loc.isValid()); 11783 11784 e = e->IgnoreParenCasts(); 11785 11786 // Look through [^{...} copy] and Block_copy(^{...}). 11787 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 11788 Selector Cmd = ME->getSelector(); 11789 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 11790 e = ME->getInstanceReceiver(); 11791 if (!e) 11792 return nullptr; 11793 e = e->IgnoreParenCasts(); 11794 } 11795 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 11796 if (CE->getNumArgs() == 1) { 11797 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 11798 if (Fn) { 11799 const IdentifierInfo *FnI = Fn->getIdentifier(); 11800 if (FnI && FnI->isStr("_Block_copy")) { 11801 e = CE->getArg(0)->IgnoreParenCasts(); 11802 } 11803 } 11804 } 11805 } 11806 11807 BlockExpr *block = dyn_cast<BlockExpr>(e); 11808 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 11809 return nullptr; 11810 11811 FindCaptureVisitor visitor(S.Context, owner.Variable); 11812 visitor.Visit(block->getBlockDecl()->getBody()); 11813 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 11814 } 11815 11816 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 11817 RetainCycleOwner &owner) { 11818 assert(capturer); 11819 assert(owner.Variable && owner.Loc.isValid()); 11820 11821 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 11822 << owner.Variable << capturer->getSourceRange(); 11823 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 11824 << owner.Indirect << owner.Range; 11825 } 11826 11827 /// Check for a keyword selector that starts with the word 'add' or 11828 /// 'set'. 11829 static bool isSetterLikeSelector(Selector sel) { 11830 if (sel.isUnarySelector()) return false; 11831 11832 StringRef str = sel.getNameForSlot(0); 11833 while (!str.empty() && str.front() == '_') str = str.substr(1); 11834 if (str.startswith("set")) 11835 str = str.substr(3); 11836 else if (str.startswith("add")) { 11837 // Specially whitelist 'addOperationWithBlock:'. 11838 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 11839 return false; 11840 str = str.substr(3); 11841 } 11842 else 11843 return false; 11844 11845 if (str.empty()) return true; 11846 return !isLowercase(str.front()); 11847 } 11848 11849 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 11850 ObjCMessageExpr *Message) { 11851 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 11852 Message->getReceiverInterface(), 11853 NSAPI::ClassId_NSMutableArray); 11854 if (!IsMutableArray) { 11855 return None; 11856 } 11857 11858 Selector Sel = Message->getSelector(); 11859 11860 Optional<NSAPI::NSArrayMethodKind> MKOpt = 11861 S.NSAPIObj->getNSArrayMethodKind(Sel); 11862 if (!MKOpt) { 11863 return None; 11864 } 11865 11866 NSAPI::NSArrayMethodKind MK = *MKOpt; 11867 11868 switch (MK) { 11869 case NSAPI::NSMutableArr_addObject: 11870 case NSAPI::NSMutableArr_insertObjectAtIndex: 11871 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 11872 return 0; 11873 case NSAPI::NSMutableArr_replaceObjectAtIndex: 11874 return 1; 11875 11876 default: 11877 return None; 11878 } 11879 11880 return None; 11881 } 11882 11883 static 11884 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 11885 ObjCMessageExpr *Message) { 11886 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 11887 Message->getReceiverInterface(), 11888 NSAPI::ClassId_NSMutableDictionary); 11889 if (!IsMutableDictionary) { 11890 return None; 11891 } 11892 11893 Selector Sel = Message->getSelector(); 11894 11895 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 11896 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 11897 if (!MKOpt) { 11898 return None; 11899 } 11900 11901 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 11902 11903 switch (MK) { 11904 case NSAPI::NSMutableDict_setObjectForKey: 11905 case NSAPI::NSMutableDict_setValueForKey: 11906 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 11907 return 0; 11908 11909 default: 11910 return None; 11911 } 11912 11913 return None; 11914 } 11915 11916 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 11917 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 11918 Message->getReceiverInterface(), 11919 NSAPI::ClassId_NSMutableSet); 11920 11921 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 11922 Message->getReceiverInterface(), 11923 NSAPI::ClassId_NSMutableOrderedSet); 11924 if (!IsMutableSet && !IsMutableOrderedSet) { 11925 return None; 11926 } 11927 11928 Selector Sel = Message->getSelector(); 11929 11930 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 11931 if (!MKOpt) { 11932 return None; 11933 } 11934 11935 NSAPI::NSSetMethodKind MK = *MKOpt; 11936 11937 switch (MK) { 11938 case NSAPI::NSMutableSet_addObject: 11939 case NSAPI::NSOrderedSet_setObjectAtIndex: 11940 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 11941 case NSAPI::NSOrderedSet_insertObjectAtIndex: 11942 return 0; 11943 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 11944 return 1; 11945 } 11946 11947 return None; 11948 } 11949 11950 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 11951 if (!Message->isInstanceMessage()) { 11952 return; 11953 } 11954 11955 Optional<int> ArgOpt; 11956 11957 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 11958 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 11959 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 11960 return; 11961 } 11962 11963 int ArgIndex = *ArgOpt; 11964 11965 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 11966 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 11967 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 11968 } 11969 11970 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 11971 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 11972 if (ArgRE->isObjCSelfExpr()) { 11973 Diag(Message->getSourceRange().getBegin(), 11974 diag::warn_objc_circular_container) 11975 << ArgRE->getDecl() << StringRef("'super'"); 11976 } 11977 } 11978 } else { 11979 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 11980 11981 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 11982 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 11983 } 11984 11985 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 11986 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 11987 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 11988 ValueDecl *Decl = ReceiverRE->getDecl(); 11989 Diag(Message->getSourceRange().getBegin(), 11990 diag::warn_objc_circular_container) 11991 << Decl << Decl; 11992 if (!ArgRE->isObjCSelfExpr()) { 11993 Diag(Decl->getLocation(), 11994 diag::note_objc_circular_container_declared_here) 11995 << Decl; 11996 } 11997 } 11998 } 11999 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 12000 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 12001 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 12002 ObjCIvarDecl *Decl = IvarRE->getDecl(); 12003 Diag(Message->getSourceRange().getBegin(), 12004 diag::warn_objc_circular_container) 12005 << Decl << Decl; 12006 Diag(Decl->getLocation(), 12007 diag::note_objc_circular_container_declared_here) 12008 << Decl; 12009 } 12010 } 12011 } 12012 } 12013 } 12014 12015 /// Check a message send to see if it's likely to cause a retain cycle. 12016 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 12017 // Only check instance methods whose selector looks like a setter. 12018 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 12019 return; 12020 12021 // Try to find a variable that the receiver is strongly owned by. 12022 RetainCycleOwner owner; 12023 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 12024 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 12025 return; 12026 } else { 12027 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 12028 owner.Variable = getCurMethodDecl()->getSelfDecl(); 12029 owner.Loc = msg->getSuperLoc(); 12030 owner.Range = msg->getSuperLoc(); 12031 } 12032 12033 // Check whether the receiver is captured by any of the arguments. 12034 const ObjCMethodDecl *MD = msg->getMethodDecl(); 12035 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 12036 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 12037 // noescape blocks should not be retained by the method. 12038 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 12039 continue; 12040 return diagnoseRetainCycle(*this, capturer, owner); 12041 } 12042 } 12043 } 12044 12045 /// Check a property assign to see if it's likely to cause a retain cycle. 12046 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 12047 RetainCycleOwner owner; 12048 if (!findRetainCycleOwner(*this, receiver, owner)) 12049 return; 12050 12051 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 12052 diagnoseRetainCycle(*this, capturer, owner); 12053 } 12054 12055 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 12056 RetainCycleOwner Owner; 12057 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 12058 return; 12059 12060 // Because we don't have an expression for the variable, we have to set the 12061 // location explicitly here. 12062 Owner.Loc = Var->getLocation(); 12063 Owner.Range = Var->getSourceRange(); 12064 12065 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 12066 diagnoseRetainCycle(*this, Capturer, Owner); 12067 } 12068 12069 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 12070 Expr *RHS, bool isProperty) { 12071 // Check if RHS is an Objective-C object literal, which also can get 12072 // immediately zapped in a weak reference. Note that we explicitly 12073 // allow ObjCStringLiterals, since those are designed to never really die. 12074 RHS = RHS->IgnoreParenImpCasts(); 12075 12076 // This enum needs to match with the 'select' in 12077 // warn_objc_arc_literal_assign (off-by-1). 12078 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 12079 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 12080 return false; 12081 12082 S.Diag(Loc, diag::warn_arc_literal_assign) 12083 << (unsigned) Kind 12084 << (isProperty ? 0 : 1) 12085 << RHS->getSourceRange(); 12086 12087 return true; 12088 } 12089 12090 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 12091 Qualifiers::ObjCLifetime LT, 12092 Expr *RHS, bool isProperty) { 12093 // Strip off any implicit cast added to get to the one ARC-specific. 12094 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 12095 if (cast->getCastKind() == CK_ARCConsumeObject) { 12096 S.Diag(Loc, diag::warn_arc_retained_assign) 12097 << (LT == Qualifiers::OCL_ExplicitNone) 12098 << (isProperty ? 0 : 1) 12099 << RHS->getSourceRange(); 12100 return true; 12101 } 12102 RHS = cast->getSubExpr(); 12103 } 12104 12105 if (LT == Qualifiers::OCL_Weak && 12106 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 12107 return true; 12108 12109 return false; 12110 } 12111 12112 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 12113 QualType LHS, Expr *RHS) { 12114 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 12115 12116 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 12117 return false; 12118 12119 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 12120 return true; 12121 12122 return false; 12123 } 12124 12125 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 12126 Expr *LHS, Expr *RHS) { 12127 QualType LHSType; 12128 // PropertyRef on LHS type need be directly obtained from 12129 // its declaration as it has a PseudoType. 12130 ObjCPropertyRefExpr *PRE 12131 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 12132 if (PRE && !PRE->isImplicitProperty()) { 12133 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 12134 if (PD) 12135 LHSType = PD->getType(); 12136 } 12137 12138 if (LHSType.isNull()) 12139 LHSType = LHS->getType(); 12140 12141 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 12142 12143 if (LT == Qualifiers::OCL_Weak) { 12144 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 12145 getCurFunction()->markSafeWeakUse(LHS); 12146 } 12147 12148 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 12149 return; 12150 12151 // FIXME. Check for other life times. 12152 if (LT != Qualifiers::OCL_None) 12153 return; 12154 12155 if (PRE) { 12156 if (PRE->isImplicitProperty()) 12157 return; 12158 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 12159 if (!PD) 12160 return; 12161 12162 unsigned Attributes = PD->getPropertyAttributes(); 12163 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) { 12164 // when 'assign' attribute was not explicitly specified 12165 // by user, ignore it and rely on property type itself 12166 // for lifetime info. 12167 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 12168 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) && 12169 LHSType->isObjCRetainableType()) 12170 return; 12171 12172 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 12173 if (cast->getCastKind() == CK_ARCConsumeObject) { 12174 Diag(Loc, diag::warn_arc_retained_property_assign) 12175 << RHS->getSourceRange(); 12176 return; 12177 } 12178 RHS = cast->getSubExpr(); 12179 } 12180 } 12181 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) { 12182 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 12183 return; 12184 } 12185 } 12186 } 12187 12188 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 12189 12190 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 12191 SourceLocation StmtLoc, 12192 const NullStmt *Body) { 12193 // Do not warn if the body is a macro that expands to nothing, e.g: 12194 // 12195 // #define CALL(x) 12196 // if (condition) 12197 // CALL(0); 12198 if (Body->hasLeadingEmptyMacro()) 12199 return false; 12200 12201 // Get line numbers of statement and body. 12202 bool StmtLineInvalid; 12203 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 12204 &StmtLineInvalid); 12205 if (StmtLineInvalid) 12206 return false; 12207 12208 bool BodyLineInvalid; 12209 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 12210 &BodyLineInvalid); 12211 if (BodyLineInvalid) 12212 return false; 12213 12214 // Warn if null statement and body are on the same line. 12215 if (StmtLine != BodyLine) 12216 return false; 12217 12218 return true; 12219 } 12220 12221 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 12222 const Stmt *Body, 12223 unsigned DiagID) { 12224 // Since this is a syntactic check, don't emit diagnostic for template 12225 // instantiations, this just adds noise. 12226 if (CurrentInstantiationScope) 12227 return; 12228 12229 // The body should be a null statement. 12230 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 12231 if (!NBody) 12232 return; 12233 12234 // Do the usual checks. 12235 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 12236 return; 12237 12238 Diag(NBody->getSemiLoc(), DiagID); 12239 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 12240 } 12241 12242 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 12243 const Stmt *PossibleBody) { 12244 assert(!CurrentInstantiationScope); // Ensured by caller 12245 12246 SourceLocation StmtLoc; 12247 const Stmt *Body; 12248 unsigned DiagID; 12249 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 12250 StmtLoc = FS->getRParenLoc(); 12251 Body = FS->getBody(); 12252 DiagID = diag::warn_empty_for_body; 12253 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 12254 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 12255 Body = WS->getBody(); 12256 DiagID = diag::warn_empty_while_body; 12257 } else 12258 return; // Neither `for' nor `while'. 12259 12260 // The body should be a null statement. 12261 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 12262 if (!NBody) 12263 return; 12264 12265 // Skip expensive checks if diagnostic is disabled. 12266 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 12267 return; 12268 12269 // Do the usual checks. 12270 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 12271 return; 12272 12273 // `for(...);' and `while(...);' are popular idioms, so in order to keep 12274 // noise level low, emit diagnostics only if for/while is followed by a 12275 // CompoundStmt, e.g.: 12276 // for (int i = 0; i < n; i++); 12277 // { 12278 // a(i); 12279 // } 12280 // or if for/while is followed by a statement with more indentation 12281 // than for/while itself: 12282 // for (int i = 0; i < n; i++); 12283 // a(i); 12284 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 12285 if (!ProbableTypo) { 12286 bool BodyColInvalid; 12287 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 12288 PossibleBody->getLocStart(), 12289 &BodyColInvalid); 12290 if (BodyColInvalid) 12291 return; 12292 12293 bool StmtColInvalid; 12294 unsigned StmtCol = SourceMgr.getPresumedColumnNumber( 12295 S->getLocStart(), 12296 &StmtColInvalid); 12297 if (StmtColInvalid) 12298 return; 12299 12300 if (BodyCol > StmtCol) 12301 ProbableTypo = true; 12302 } 12303 12304 if (ProbableTypo) { 12305 Diag(NBody->getSemiLoc(), DiagID); 12306 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 12307 } 12308 } 12309 12310 //===--- CHECK: Warn on self move with std::move. -------------------------===// 12311 12312 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 12313 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 12314 SourceLocation OpLoc) { 12315 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 12316 return; 12317 12318 if (inTemplateInstantiation()) 12319 return; 12320 12321 // Strip parens and casts away. 12322 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 12323 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 12324 12325 // Check for a call expression 12326 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 12327 if (!CE || CE->getNumArgs() != 1) 12328 return; 12329 12330 // Check for a call to std::move 12331 if (!CE->isCallToStdMove()) 12332 return; 12333 12334 // Get argument from std::move 12335 RHSExpr = CE->getArg(0); 12336 12337 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 12338 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 12339 12340 // Two DeclRefExpr's, check that the decls are the same. 12341 if (LHSDeclRef && RHSDeclRef) { 12342 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 12343 return; 12344 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 12345 RHSDeclRef->getDecl()->getCanonicalDecl()) 12346 return; 12347 12348 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 12349 << LHSExpr->getSourceRange() 12350 << RHSExpr->getSourceRange(); 12351 return; 12352 } 12353 12354 // Member variables require a different approach to check for self moves. 12355 // MemberExpr's are the same if every nested MemberExpr refers to the same 12356 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 12357 // the base Expr's are CXXThisExpr's. 12358 const Expr *LHSBase = LHSExpr; 12359 const Expr *RHSBase = RHSExpr; 12360 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 12361 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 12362 if (!LHSME || !RHSME) 12363 return; 12364 12365 while (LHSME && RHSME) { 12366 if (LHSME->getMemberDecl()->getCanonicalDecl() != 12367 RHSME->getMemberDecl()->getCanonicalDecl()) 12368 return; 12369 12370 LHSBase = LHSME->getBase(); 12371 RHSBase = RHSME->getBase(); 12372 LHSME = dyn_cast<MemberExpr>(LHSBase); 12373 RHSME = dyn_cast<MemberExpr>(RHSBase); 12374 } 12375 12376 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 12377 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 12378 if (LHSDeclRef && RHSDeclRef) { 12379 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 12380 return; 12381 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 12382 RHSDeclRef->getDecl()->getCanonicalDecl()) 12383 return; 12384 12385 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 12386 << LHSExpr->getSourceRange() 12387 << RHSExpr->getSourceRange(); 12388 return; 12389 } 12390 12391 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 12392 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 12393 << LHSExpr->getSourceRange() 12394 << RHSExpr->getSourceRange(); 12395 } 12396 12397 //===--- Layout compatibility ----------------------------------------------// 12398 12399 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 12400 12401 /// Check if two enumeration types are layout-compatible. 12402 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 12403 // C++11 [dcl.enum] p8: 12404 // Two enumeration types are layout-compatible if they have the same 12405 // underlying type. 12406 return ED1->isComplete() && ED2->isComplete() && 12407 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 12408 } 12409 12410 /// Check if two fields are layout-compatible. 12411 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 12412 FieldDecl *Field2) { 12413 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 12414 return false; 12415 12416 if (Field1->isBitField() != Field2->isBitField()) 12417 return false; 12418 12419 if (Field1->isBitField()) { 12420 // Make sure that the bit-fields are the same length. 12421 unsigned Bits1 = Field1->getBitWidthValue(C); 12422 unsigned Bits2 = Field2->getBitWidthValue(C); 12423 12424 if (Bits1 != Bits2) 12425 return false; 12426 } 12427 12428 return true; 12429 } 12430 12431 /// Check if two standard-layout structs are layout-compatible. 12432 /// (C++11 [class.mem] p17) 12433 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 12434 RecordDecl *RD2) { 12435 // If both records are C++ classes, check that base classes match. 12436 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 12437 // If one of records is a CXXRecordDecl we are in C++ mode, 12438 // thus the other one is a CXXRecordDecl, too. 12439 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 12440 // Check number of base classes. 12441 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 12442 return false; 12443 12444 // Check the base classes. 12445 for (CXXRecordDecl::base_class_const_iterator 12446 Base1 = D1CXX->bases_begin(), 12447 BaseEnd1 = D1CXX->bases_end(), 12448 Base2 = D2CXX->bases_begin(); 12449 Base1 != BaseEnd1; 12450 ++Base1, ++Base2) { 12451 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 12452 return false; 12453 } 12454 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 12455 // If only RD2 is a C++ class, it should have zero base classes. 12456 if (D2CXX->getNumBases() > 0) 12457 return false; 12458 } 12459 12460 // Check the fields. 12461 RecordDecl::field_iterator Field2 = RD2->field_begin(), 12462 Field2End = RD2->field_end(), 12463 Field1 = RD1->field_begin(), 12464 Field1End = RD1->field_end(); 12465 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 12466 if (!isLayoutCompatible(C, *Field1, *Field2)) 12467 return false; 12468 } 12469 if (Field1 != Field1End || Field2 != Field2End) 12470 return false; 12471 12472 return true; 12473 } 12474 12475 /// Check if two standard-layout unions are layout-compatible. 12476 /// (C++11 [class.mem] p18) 12477 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 12478 RecordDecl *RD2) { 12479 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 12480 for (auto *Field2 : RD2->fields()) 12481 UnmatchedFields.insert(Field2); 12482 12483 for (auto *Field1 : RD1->fields()) { 12484 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 12485 I = UnmatchedFields.begin(), 12486 E = UnmatchedFields.end(); 12487 12488 for ( ; I != E; ++I) { 12489 if (isLayoutCompatible(C, Field1, *I)) { 12490 bool Result = UnmatchedFields.erase(*I); 12491 (void) Result; 12492 assert(Result); 12493 break; 12494 } 12495 } 12496 if (I == E) 12497 return false; 12498 } 12499 12500 return UnmatchedFields.empty(); 12501 } 12502 12503 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 12504 RecordDecl *RD2) { 12505 if (RD1->isUnion() != RD2->isUnion()) 12506 return false; 12507 12508 if (RD1->isUnion()) 12509 return isLayoutCompatibleUnion(C, RD1, RD2); 12510 else 12511 return isLayoutCompatibleStruct(C, RD1, RD2); 12512 } 12513 12514 /// Check if two types are layout-compatible in C++11 sense. 12515 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 12516 if (T1.isNull() || T2.isNull()) 12517 return false; 12518 12519 // C++11 [basic.types] p11: 12520 // If two types T1 and T2 are the same type, then T1 and T2 are 12521 // layout-compatible types. 12522 if (C.hasSameType(T1, T2)) 12523 return true; 12524 12525 T1 = T1.getCanonicalType().getUnqualifiedType(); 12526 T2 = T2.getCanonicalType().getUnqualifiedType(); 12527 12528 const Type::TypeClass TC1 = T1->getTypeClass(); 12529 const Type::TypeClass TC2 = T2->getTypeClass(); 12530 12531 if (TC1 != TC2) 12532 return false; 12533 12534 if (TC1 == Type::Enum) { 12535 return isLayoutCompatible(C, 12536 cast<EnumType>(T1)->getDecl(), 12537 cast<EnumType>(T2)->getDecl()); 12538 } else if (TC1 == Type::Record) { 12539 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 12540 return false; 12541 12542 return isLayoutCompatible(C, 12543 cast<RecordType>(T1)->getDecl(), 12544 cast<RecordType>(T2)->getDecl()); 12545 } 12546 12547 return false; 12548 } 12549 12550 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 12551 12552 /// Given a type tag expression find the type tag itself. 12553 /// 12554 /// \param TypeExpr Type tag expression, as it appears in user's code. 12555 /// 12556 /// \param VD Declaration of an identifier that appears in a type tag. 12557 /// 12558 /// \param MagicValue Type tag magic value. 12559 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 12560 const ValueDecl **VD, uint64_t *MagicValue) { 12561 while(true) { 12562 if (!TypeExpr) 12563 return false; 12564 12565 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 12566 12567 switch (TypeExpr->getStmtClass()) { 12568 case Stmt::UnaryOperatorClass: { 12569 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 12570 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 12571 TypeExpr = UO->getSubExpr(); 12572 continue; 12573 } 12574 return false; 12575 } 12576 12577 case Stmt::DeclRefExprClass: { 12578 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 12579 *VD = DRE->getDecl(); 12580 return true; 12581 } 12582 12583 case Stmt::IntegerLiteralClass: { 12584 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 12585 llvm::APInt MagicValueAPInt = IL->getValue(); 12586 if (MagicValueAPInt.getActiveBits() <= 64) { 12587 *MagicValue = MagicValueAPInt.getZExtValue(); 12588 return true; 12589 } else 12590 return false; 12591 } 12592 12593 case Stmt::BinaryConditionalOperatorClass: 12594 case Stmt::ConditionalOperatorClass: { 12595 const AbstractConditionalOperator *ACO = 12596 cast<AbstractConditionalOperator>(TypeExpr); 12597 bool Result; 12598 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) { 12599 if (Result) 12600 TypeExpr = ACO->getTrueExpr(); 12601 else 12602 TypeExpr = ACO->getFalseExpr(); 12603 continue; 12604 } 12605 return false; 12606 } 12607 12608 case Stmt::BinaryOperatorClass: { 12609 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 12610 if (BO->getOpcode() == BO_Comma) { 12611 TypeExpr = BO->getRHS(); 12612 continue; 12613 } 12614 return false; 12615 } 12616 12617 default: 12618 return false; 12619 } 12620 } 12621 } 12622 12623 /// Retrieve the C type corresponding to type tag TypeExpr. 12624 /// 12625 /// \param TypeExpr Expression that specifies a type tag. 12626 /// 12627 /// \param MagicValues Registered magic values. 12628 /// 12629 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 12630 /// kind. 12631 /// 12632 /// \param TypeInfo Information about the corresponding C type. 12633 /// 12634 /// \returns true if the corresponding C type was found. 12635 static bool GetMatchingCType( 12636 const IdentifierInfo *ArgumentKind, 12637 const Expr *TypeExpr, const ASTContext &Ctx, 12638 const llvm::DenseMap<Sema::TypeTagMagicValue, 12639 Sema::TypeTagData> *MagicValues, 12640 bool &FoundWrongKind, 12641 Sema::TypeTagData &TypeInfo) { 12642 FoundWrongKind = false; 12643 12644 // Variable declaration that has type_tag_for_datatype attribute. 12645 const ValueDecl *VD = nullptr; 12646 12647 uint64_t MagicValue; 12648 12649 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue)) 12650 return false; 12651 12652 if (VD) { 12653 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 12654 if (I->getArgumentKind() != ArgumentKind) { 12655 FoundWrongKind = true; 12656 return false; 12657 } 12658 TypeInfo.Type = I->getMatchingCType(); 12659 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 12660 TypeInfo.MustBeNull = I->getMustBeNull(); 12661 return true; 12662 } 12663 return false; 12664 } 12665 12666 if (!MagicValues) 12667 return false; 12668 12669 llvm::DenseMap<Sema::TypeTagMagicValue, 12670 Sema::TypeTagData>::const_iterator I = 12671 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 12672 if (I == MagicValues->end()) 12673 return false; 12674 12675 TypeInfo = I->second; 12676 return true; 12677 } 12678 12679 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 12680 uint64_t MagicValue, QualType Type, 12681 bool LayoutCompatible, 12682 bool MustBeNull) { 12683 if (!TypeTagForDatatypeMagicValues) 12684 TypeTagForDatatypeMagicValues.reset( 12685 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 12686 12687 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 12688 (*TypeTagForDatatypeMagicValues)[Magic] = 12689 TypeTagData(Type, LayoutCompatible, MustBeNull); 12690 } 12691 12692 static bool IsSameCharType(QualType T1, QualType T2) { 12693 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 12694 if (!BT1) 12695 return false; 12696 12697 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 12698 if (!BT2) 12699 return false; 12700 12701 BuiltinType::Kind T1Kind = BT1->getKind(); 12702 BuiltinType::Kind T2Kind = BT2->getKind(); 12703 12704 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 12705 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 12706 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 12707 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 12708 } 12709 12710 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 12711 const ArrayRef<const Expr *> ExprArgs, 12712 SourceLocation CallSiteLoc) { 12713 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 12714 bool IsPointerAttr = Attr->getIsPointer(); 12715 12716 // Retrieve the argument representing the 'type_tag'. 12717 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 12718 if (TypeTagIdxAST >= ExprArgs.size()) { 12719 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 12720 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 12721 return; 12722 } 12723 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 12724 bool FoundWrongKind; 12725 TypeTagData TypeInfo; 12726 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 12727 TypeTagForDatatypeMagicValues.get(), 12728 FoundWrongKind, TypeInfo)) { 12729 if (FoundWrongKind) 12730 Diag(TypeTagExpr->getExprLoc(), 12731 diag::warn_type_tag_for_datatype_wrong_kind) 12732 << TypeTagExpr->getSourceRange(); 12733 return; 12734 } 12735 12736 // Retrieve the argument representing the 'arg_idx'. 12737 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 12738 if (ArgumentIdxAST >= ExprArgs.size()) { 12739 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 12740 << 1 << Attr->getArgumentIdx().getSourceIndex(); 12741 return; 12742 } 12743 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 12744 if (IsPointerAttr) { 12745 // Skip implicit cast of pointer to `void *' (as a function argument). 12746 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 12747 if (ICE->getType()->isVoidPointerType() && 12748 ICE->getCastKind() == CK_BitCast) 12749 ArgumentExpr = ICE->getSubExpr(); 12750 } 12751 QualType ArgumentType = ArgumentExpr->getType(); 12752 12753 // Passing a `void*' pointer shouldn't trigger a warning. 12754 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 12755 return; 12756 12757 if (TypeInfo.MustBeNull) { 12758 // Type tag with matching void type requires a null pointer. 12759 if (!ArgumentExpr->isNullPointerConstant(Context, 12760 Expr::NPC_ValueDependentIsNotNull)) { 12761 Diag(ArgumentExpr->getExprLoc(), 12762 diag::warn_type_safety_null_pointer_required) 12763 << ArgumentKind->getName() 12764 << ArgumentExpr->getSourceRange() 12765 << TypeTagExpr->getSourceRange(); 12766 } 12767 return; 12768 } 12769 12770 QualType RequiredType = TypeInfo.Type; 12771 if (IsPointerAttr) 12772 RequiredType = Context.getPointerType(RequiredType); 12773 12774 bool mismatch = false; 12775 if (!TypeInfo.LayoutCompatible) { 12776 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 12777 12778 // C++11 [basic.fundamental] p1: 12779 // Plain char, signed char, and unsigned char are three distinct types. 12780 // 12781 // But we treat plain `char' as equivalent to `signed char' or `unsigned 12782 // char' depending on the current char signedness mode. 12783 if (mismatch) 12784 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 12785 RequiredType->getPointeeType())) || 12786 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 12787 mismatch = false; 12788 } else 12789 if (IsPointerAttr) 12790 mismatch = !isLayoutCompatible(Context, 12791 ArgumentType->getPointeeType(), 12792 RequiredType->getPointeeType()); 12793 else 12794 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 12795 12796 if (mismatch) 12797 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 12798 << ArgumentType << ArgumentKind 12799 << TypeInfo.LayoutCompatible << RequiredType 12800 << ArgumentExpr->getSourceRange() 12801 << TypeTagExpr->getSourceRange(); 12802 } 12803 12804 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 12805 CharUnits Alignment) { 12806 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 12807 } 12808 12809 void Sema::DiagnoseMisalignedMembers() { 12810 for (MisalignedMember &m : MisalignedMembers) { 12811 const NamedDecl *ND = m.RD; 12812 if (ND->getName().empty()) { 12813 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 12814 ND = TD; 12815 } 12816 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member) 12817 << m.MD << ND << m.E->getSourceRange(); 12818 } 12819 MisalignedMembers.clear(); 12820 } 12821 12822 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 12823 E = E->IgnoreParens(); 12824 if (!T->isPointerType() && !T->isIntegerType()) 12825 return; 12826 if (isa<UnaryOperator>(E) && 12827 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 12828 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 12829 if (isa<MemberExpr>(Op)) { 12830 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(), 12831 MisalignedMember(Op)); 12832 if (MA != MisalignedMembers.end() && 12833 (T->isIntegerType() || 12834 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 12835 Context.getTypeAlignInChars( 12836 T->getPointeeType()) <= MA->Alignment)))) 12837 MisalignedMembers.erase(MA); 12838 } 12839 } 12840 } 12841 12842 void Sema::RefersToMemberWithReducedAlignment( 12843 Expr *E, 12844 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 12845 Action) { 12846 const auto *ME = dyn_cast<MemberExpr>(E); 12847 if (!ME) 12848 return; 12849 12850 // No need to check expressions with an __unaligned-qualified type. 12851 if (E->getType().getQualifiers().hasUnaligned()) 12852 return; 12853 12854 // For a chain of MemberExpr like "a.b.c.d" this list 12855 // will keep FieldDecl's like [d, c, b]. 12856 SmallVector<FieldDecl *, 4> ReverseMemberChain; 12857 const MemberExpr *TopME = nullptr; 12858 bool AnyIsPacked = false; 12859 do { 12860 QualType BaseType = ME->getBase()->getType(); 12861 if (ME->isArrow()) 12862 BaseType = BaseType->getPointeeType(); 12863 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl(); 12864 if (RD->isInvalidDecl()) 12865 return; 12866 12867 ValueDecl *MD = ME->getMemberDecl(); 12868 auto *FD = dyn_cast<FieldDecl>(MD); 12869 // We do not care about non-data members. 12870 if (!FD || FD->isInvalidDecl()) 12871 return; 12872 12873 AnyIsPacked = 12874 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 12875 ReverseMemberChain.push_back(FD); 12876 12877 TopME = ME; 12878 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 12879 } while (ME); 12880 assert(TopME && "We did not compute a topmost MemberExpr!"); 12881 12882 // Not the scope of this diagnostic. 12883 if (!AnyIsPacked) 12884 return; 12885 12886 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 12887 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 12888 // TODO: The innermost base of the member expression may be too complicated. 12889 // For now, just disregard these cases. This is left for future 12890 // improvement. 12891 if (!DRE && !isa<CXXThisExpr>(TopBase)) 12892 return; 12893 12894 // Alignment expected by the whole expression. 12895 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 12896 12897 // No need to do anything else with this case. 12898 if (ExpectedAlignment.isOne()) 12899 return; 12900 12901 // Synthesize offset of the whole access. 12902 CharUnits Offset; 12903 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 12904 I++) { 12905 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 12906 } 12907 12908 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 12909 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 12910 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 12911 12912 // The base expression of the innermost MemberExpr may give 12913 // stronger guarantees than the class containing the member. 12914 if (DRE && !TopME->isArrow()) { 12915 const ValueDecl *VD = DRE->getDecl(); 12916 if (!VD->getType()->isReferenceType()) 12917 CompleteObjectAlignment = 12918 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 12919 } 12920 12921 // Check if the synthesized offset fulfills the alignment. 12922 if (Offset % ExpectedAlignment != 0 || 12923 // It may fulfill the offset it but the effective alignment may still be 12924 // lower than the expected expression alignment. 12925 CompleteObjectAlignment < ExpectedAlignment) { 12926 // If this happens, we want to determine a sensible culprit of this. 12927 // Intuitively, watching the chain of member expressions from right to 12928 // left, we start with the required alignment (as required by the field 12929 // type) but some packed attribute in that chain has reduced the alignment. 12930 // It may happen that another packed structure increases it again. But if 12931 // we are here such increase has not been enough. So pointing the first 12932 // FieldDecl that either is packed or else its RecordDecl is, 12933 // seems reasonable. 12934 FieldDecl *FD = nullptr; 12935 CharUnits Alignment; 12936 for (FieldDecl *FDI : ReverseMemberChain) { 12937 if (FDI->hasAttr<PackedAttr>() || 12938 FDI->getParent()->hasAttr<PackedAttr>()) { 12939 FD = FDI; 12940 Alignment = std::min( 12941 Context.getTypeAlignInChars(FD->getType()), 12942 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 12943 break; 12944 } 12945 } 12946 assert(FD && "We did not find a packed FieldDecl!"); 12947 Action(E, FD->getParent(), FD, Alignment); 12948 } 12949 } 12950 12951 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 12952 using namespace std::placeholders; 12953 12954 RefersToMemberWithReducedAlignment( 12955 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 12956 _2, _3, _4)); 12957 } 12958