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 ExprResult Arg = TheCall->getArg(I); 201 QualType Ty = Arg.get()->getType(); 202 if (!Ty->isIntegerType()) { 203 S.Diag(Arg.get()->getLocStart(), diag::err_overflow_builtin_must_be_int) 204 << Ty << Arg.get()->getSourceRange(); 205 return true; 206 } 207 InitializedEntity Entity = InitializedEntity::InitializeParameter( 208 S.getASTContext(), Ty, /*consume*/ false); 209 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 210 if (Arg.isInvalid()) 211 return true; 212 TheCall->setArg(I, Arg.get()); 213 } 214 215 // Third argument should be a pointer to a non-const integer. 216 // IRGen correctly handles volatile, restrict, and address spaces, and 217 // the other qualifiers aren't possible. 218 { 219 ExprResult Arg = TheCall->getArg(2); 220 QualType Ty = Arg.get()->getType(); 221 const auto *PtrTy = Ty->getAs<PointerType>(); 222 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() && 223 !PtrTy->getPointeeType().isConstQualified())) { 224 S.Diag(Arg.get()->getLocStart(), 225 diag::err_overflow_builtin_must_be_ptr_int) 226 << Ty << Arg.get()->getSourceRange(); 227 return true; 228 } 229 InitializedEntity Entity = InitializedEntity::InitializeParameter( 230 S.getASTContext(), Ty, /*consume*/ false); 231 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 232 if (Arg.isInvalid()) 233 return true; 234 TheCall->setArg(2, Arg.get()); 235 } 236 return false; 237 } 238 239 static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl, 240 CallExpr *TheCall, unsigned SizeIdx, 241 unsigned DstSizeIdx) { 242 if (TheCall->getNumArgs() <= SizeIdx || 243 TheCall->getNumArgs() <= DstSizeIdx) 244 return; 245 246 const Expr *SizeArg = TheCall->getArg(SizeIdx); 247 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx); 248 249 llvm::APSInt Size, DstSize; 250 251 // find out if both sizes are known at compile time 252 if (!SizeArg->EvaluateAsInt(Size, S.Context) || 253 !DstSizeArg->EvaluateAsInt(DstSize, S.Context)) 254 return; 255 256 if (Size.ule(DstSize)) 257 return; 258 259 // confirmed overflow so generate the diagnostic. 260 IdentifierInfo *FnName = FDecl->getIdentifier(); 261 SourceLocation SL = TheCall->getLocStart(); 262 SourceRange SR = TheCall->getSourceRange(); 263 264 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName; 265 } 266 267 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { 268 if (checkArgCount(S, BuiltinCall, 2)) 269 return true; 270 271 SourceLocation BuiltinLoc = BuiltinCall->getLocStart(); 272 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); 273 Expr *Call = BuiltinCall->getArg(0); 274 Expr *Chain = BuiltinCall->getArg(1); 275 276 if (Call->getStmtClass() != Stmt::CallExprClass) { 277 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) 278 << Call->getSourceRange(); 279 return true; 280 } 281 282 auto CE = cast<CallExpr>(Call); 283 if (CE->getCallee()->getType()->isBlockPointerType()) { 284 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) 285 << Call->getSourceRange(); 286 return true; 287 } 288 289 const Decl *TargetDecl = CE->getCalleeDecl(); 290 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 291 if (FD->getBuiltinID()) { 292 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) 293 << Call->getSourceRange(); 294 return true; 295 } 296 297 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { 298 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) 299 << Call->getSourceRange(); 300 return true; 301 } 302 303 ExprResult ChainResult = S.UsualUnaryConversions(Chain); 304 if (ChainResult.isInvalid()) 305 return true; 306 if (!ChainResult.get()->getType()->isPointerType()) { 307 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) 308 << Chain->getSourceRange(); 309 return true; 310 } 311 312 QualType ReturnTy = CE->getCallReturnType(S.Context); 313 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; 314 QualType BuiltinTy = S.Context.getFunctionType( 315 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); 316 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); 317 318 Builtin = 319 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); 320 321 BuiltinCall->setType(CE->getType()); 322 BuiltinCall->setValueKind(CE->getValueKind()); 323 BuiltinCall->setObjectKind(CE->getObjectKind()); 324 BuiltinCall->setCallee(Builtin); 325 BuiltinCall->setArg(1, ChainResult.get()); 326 327 return false; 328 } 329 330 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 331 Scope::ScopeFlags NeededScopeFlags, 332 unsigned DiagID) { 333 // Scopes aren't available during instantiation. Fortunately, builtin 334 // functions cannot be template args so they cannot be formed through template 335 // instantiation. Therefore checking once during the parse is sufficient. 336 if (SemaRef.inTemplateInstantiation()) 337 return false; 338 339 Scope *S = SemaRef.getCurScope(); 340 while (S && !S->isSEHExceptScope()) 341 S = S->getParent(); 342 if (!S || !(S->getFlags() & NeededScopeFlags)) { 343 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 344 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 345 << DRE->getDecl()->getIdentifier(); 346 return true; 347 } 348 349 return false; 350 } 351 352 static inline bool isBlockPointer(Expr *Arg) { 353 return Arg->getType()->isBlockPointerType(); 354 } 355 356 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local 357 /// void*, which is a requirement of device side enqueue. 358 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { 359 const BlockPointerType *BPT = 360 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 361 ArrayRef<QualType> Params = 362 BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes(); 363 unsigned ArgCounter = 0; 364 bool IllegalParams = false; 365 // Iterate through the block parameters until either one is found that is not 366 // a local void*, or the block is valid. 367 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); 368 I != E; ++I, ++ArgCounter) { 369 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || 370 (*I)->getPointeeType().getQualifiers().getAddressSpace() != 371 LangAS::opencl_local) { 372 // Get the location of the error. If a block literal has been passed 373 // (BlockExpr) then we can point straight to the offending argument, 374 // else we just point to the variable reference. 375 SourceLocation ErrorLoc; 376 if (isa<BlockExpr>(BlockArg)) { 377 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); 378 ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart(); 379 } else if (isa<DeclRefExpr>(BlockArg)) { 380 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart(); 381 } 382 S.Diag(ErrorLoc, 383 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); 384 IllegalParams = true; 385 } 386 } 387 388 return IllegalParams; 389 } 390 391 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) { 392 if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) { 393 S.Diag(Call->getLocStart(), diag::err_opencl_requires_extension) 394 << 1 << Call->getDirectCallee() << "cl_khr_subgroups"; 395 return true; 396 } 397 return false; 398 } 399 400 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) { 401 if (checkArgCount(S, TheCall, 2)) 402 return true; 403 404 if (checkOpenCLSubgroupExt(S, TheCall)) 405 return true; 406 407 // First argument is an ndrange_t type. 408 Expr *NDRangeArg = TheCall->getArg(0); 409 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 410 S.Diag(NDRangeArg->getLocStart(), 411 diag::err_opencl_builtin_expected_type) 412 << TheCall->getDirectCallee() << "'ndrange_t'"; 413 return true; 414 } 415 416 Expr *BlockArg = TheCall->getArg(1); 417 if (!isBlockPointer(BlockArg)) { 418 S.Diag(BlockArg->getLocStart(), 419 diag::err_opencl_builtin_expected_type) 420 << TheCall->getDirectCallee() << "block"; 421 return true; 422 } 423 return checkOpenCLBlockArgs(S, BlockArg); 424 } 425 426 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the 427 /// get_kernel_work_group_size 428 /// and get_kernel_preferred_work_group_size_multiple builtin functions. 429 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { 430 if (checkArgCount(S, TheCall, 1)) 431 return true; 432 433 Expr *BlockArg = TheCall->getArg(0); 434 if (!isBlockPointer(BlockArg)) { 435 S.Diag(BlockArg->getLocStart(), 436 diag::err_opencl_builtin_expected_type) 437 << TheCall->getDirectCallee() << "block"; 438 return true; 439 } 440 return checkOpenCLBlockArgs(S, BlockArg); 441 } 442 443 /// Diagnose integer type and any valid implicit conversion to it. 444 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, 445 const QualType &IntType); 446 447 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 448 unsigned Start, unsigned End) { 449 bool IllegalParams = false; 450 for (unsigned I = Start; I <= End; ++I) 451 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), 452 S.Context.getSizeType()); 453 return IllegalParams; 454 } 455 456 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 457 /// 'local void*' parameter of passed block. 458 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 459 Expr *BlockArg, 460 unsigned NumNonVarArgs) { 461 const BlockPointerType *BPT = 462 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 463 unsigned NumBlockParams = 464 BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams(); 465 unsigned TotalNumArgs = TheCall->getNumArgs(); 466 467 // For each argument passed to the block, a corresponding uint needs to 468 // be passed to describe the size of the local memory. 469 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 470 S.Diag(TheCall->getLocStart(), 471 diag::err_opencl_enqueue_kernel_local_size_args); 472 return true; 473 } 474 475 // Check that the sizes of the local memory are specified by integers. 476 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 477 TotalNumArgs - 1); 478 } 479 480 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 481 /// overload formats specified in Table 6.13.17.1. 482 /// int enqueue_kernel(queue_t queue, 483 /// kernel_enqueue_flags_t flags, 484 /// const ndrange_t ndrange, 485 /// void (^block)(void)) 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)(void)) 493 /// int enqueue_kernel(queue_t queue, 494 /// kernel_enqueue_flags_t flags, 495 /// const ndrange_t ndrange, 496 /// void (^block)(local void*, ...), 497 /// uint size0, ...) 498 /// int enqueue_kernel(queue_t queue, 499 /// kernel_enqueue_flags_t flags, 500 /// const ndrange_t ndrange, 501 /// uint num_events_in_wait_list, 502 /// clk_event_t *event_wait_list, 503 /// clk_event_t *event_ret, 504 /// void (^block)(local void*, ...), 505 /// uint size0, ...) 506 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 507 unsigned NumArgs = TheCall->getNumArgs(); 508 509 if (NumArgs < 4) { 510 S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args); 511 return true; 512 } 513 514 Expr *Arg0 = TheCall->getArg(0); 515 Expr *Arg1 = TheCall->getArg(1); 516 Expr *Arg2 = TheCall->getArg(2); 517 Expr *Arg3 = TheCall->getArg(3); 518 519 // First argument always needs to be a queue_t type. 520 if (!Arg0->getType()->isQueueT()) { 521 S.Diag(TheCall->getArg(0)->getLocStart(), 522 diag::err_opencl_builtin_expected_type) 523 << TheCall->getDirectCallee() << S.Context.OCLQueueTy; 524 return true; 525 } 526 527 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 528 if (!Arg1->getType()->isIntegerType()) { 529 S.Diag(TheCall->getArg(1)->getLocStart(), 530 diag::err_opencl_builtin_expected_type) 531 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)"; 532 return true; 533 } 534 535 // Third argument is always an ndrange_t type. 536 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 537 S.Diag(TheCall->getArg(2)->getLocStart(), 538 diag::err_opencl_builtin_expected_type) 539 << TheCall->getDirectCallee() << "'ndrange_t'"; 540 return true; 541 } 542 543 // With four arguments, there is only one form that the function could be 544 // called in: no events and no variable arguments. 545 if (NumArgs == 4) { 546 // check that the last argument is the right block type. 547 if (!isBlockPointer(Arg3)) { 548 S.Diag(Arg3->getLocStart(), diag::err_opencl_builtin_expected_type) 549 << TheCall->getDirectCallee() << "block"; 550 return true; 551 } 552 // we have a block type, check the prototype 553 const BlockPointerType *BPT = 554 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 555 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) { 556 S.Diag(Arg3->getLocStart(), 557 diag::err_opencl_enqueue_kernel_blocks_no_args); 558 return true; 559 } 560 return false; 561 } 562 // we can have block + varargs. 563 if (isBlockPointer(Arg3)) 564 return (checkOpenCLBlockArgs(S, Arg3) || 565 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 566 // last two cases with either exactly 7 args or 7 args and varargs. 567 if (NumArgs >= 7) { 568 // check common block argument. 569 Expr *Arg6 = TheCall->getArg(6); 570 if (!isBlockPointer(Arg6)) { 571 S.Diag(Arg6->getLocStart(), diag::err_opencl_builtin_expected_type) 572 << TheCall->getDirectCallee() << "block"; 573 return true; 574 } 575 if (checkOpenCLBlockArgs(S, Arg6)) 576 return true; 577 578 // Forth argument has to be any integer type. 579 if (!Arg3->getType()->isIntegerType()) { 580 S.Diag(TheCall->getArg(3)->getLocStart(), 581 diag::err_opencl_builtin_expected_type) 582 << TheCall->getDirectCallee() << "integer"; 583 return true; 584 } 585 // check remaining common arguments. 586 Expr *Arg4 = TheCall->getArg(4); 587 Expr *Arg5 = TheCall->getArg(5); 588 589 // Fifth argument is always passed as a pointer to clk_event_t. 590 if (!Arg4->isNullPointerConstant(S.Context, 591 Expr::NPC_ValueDependentIsNotNull) && 592 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 593 S.Diag(TheCall->getArg(4)->getLocStart(), 594 diag::err_opencl_builtin_expected_type) 595 << TheCall->getDirectCallee() 596 << S.Context.getPointerType(S.Context.OCLClkEventTy); 597 return true; 598 } 599 600 // Sixth argument is always passed as a pointer to clk_event_t. 601 if (!Arg5->isNullPointerConstant(S.Context, 602 Expr::NPC_ValueDependentIsNotNull) && 603 !(Arg5->getType()->isPointerType() && 604 Arg5->getType()->getPointeeType()->isClkEventT())) { 605 S.Diag(TheCall->getArg(5)->getLocStart(), 606 diag::err_opencl_builtin_expected_type) 607 << TheCall->getDirectCallee() 608 << S.Context.getPointerType(S.Context.OCLClkEventTy); 609 return true; 610 } 611 612 if (NumArgs == 7) 613 return false; 614 615 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 616 } 617 618 // None of the specific case has been detected, give generic error 619 S.Diag(TheCall->getLocStart(), 620 diag::err_opencl_enqueue_kernel_incorrect_args); 621 return true; 622 } 623 624 /// Returns OpenCL access qual. 625 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 626 return D->getAttr<OpenCLAccessAttr>(); 627 } 628 629 /// Returns true if pipe element type is different from the pointer. 630 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 631 const Expr *Arg0 = Call->getArg(0); 632 // First argument type should always be pipe. 633 if (!Arg0->getType()->isPipeType()) { 634 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg) 635 << Call->getDirectCallee() << Arg0->getSourceRange(); 636 return true; 637 } 638 OpenCLAccessAttr *AccessQual = 639 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 640 // Validates the access qualifier is compatible with the call. 641 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 642 // read_only and write_only, and assumed to be read_only if no qualifier is 643 // specified. 644 switch (Call->getDirectCallee()->getBuiltinID()) { 645 case Builtin::BIread_pipe: 646 case Builtin::BIreserve_read_pipe: 647 case Builtin::BIcommit_read_pipe: 648 case Builtin::BIwork_group_reserve_read_pipe: 649 case Builtin::BIsub_group_reserve_read_pipe: 650 case Builtin::BIwork_group_commit_read_pipe: 651 case Builtin::BIsub_group_commit_read_pipe: 652 if (!(!AccessQual || AccessQual->isReadOnly())) { 653 S.Diag(Arg0->getLocStart(), 654 diag::err_opencl_builtin_pipe_invalid_access_modifier) 655 << "read_only" << Arg0->getSourceRange(); 656 return true; 657 } 658 break; 659 case Builtin::BIwrite_pipe: 660 case Builtin::BIreserve_write_pipe: 661 case Builtin::BIcommit_write_pipe: 662 case Builtin::BIwork_group_reserve_write_pipe: 663 case Builtin::BIsub_group_reserve_write_pipe: 664 case Builtin::BIwork_group_commit_write_pipe: 665 case Builtin::BIsub_group_commit_write_pipe: 666 if (!(AccessQual && AccessQual->isWriteOnly())) { 667 S.Diag(Arg0->getLocStart(), 668 diag::err_opencl_builtin_pipe_invalid_access_modifier) 669 << "write_only" << Arg0->getSourceRange(); 670 return true; 671 } 672 break; 673 default: 674 break; 675 } 676 return false; 677 } 678 679 /// Returns true if pipe element type is different from the pointer. 680 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 681 const Expr *Arg0 = Call->getArg(0); 682 const Expr *ArgIdx = Call->getArg(Idx); 683 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 684 const QualType EltTy = PipeTy->getElementType(); 685 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 686 // The Idx argument should be a pointer and the type of the pointer and 687 // the type of pipe element should also be the same. 688 if (!ArgTy || 689 !S.Context.hasSameType( 690 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 691 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 692 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 693 << ArgIdx->getType() << ArgIdx->getSourceRange(); 694 return true; 695 } 696 return false; 697 } 698 699 // Performs semantic analysis for the read/write_pipe call. 700 // \param S Reference to the semantic analyzer. 701 // \param Call A pointer to the builtin call. 702 // \return True if a semantic error has been found, false otherwise. 703 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 704 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 705 // functions have two forms. 706 switch (Call->getNumArgs()) { 707 case 2: 708 if (checkOpenCLPipeArg(S, Call)) 709 return true; 710 // The call with 2 arguments should be 711 // read/write_pipe(pipe T, T*). 712 // Check packet type T. 713 if (checkOpenCLPipePacketType(S, Call, 1)) 714 return true; 715 break; 716 717 case 4: { 718 if (checkOpenCLPipeArg(S, Call)) 719 return true; 720 // The call with 4 arguments should be 721 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 722 // Check reserve_id_t. 723 if (!Call->getArg(1)->getType()->isReserveIDT()) { 724 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 725 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 726 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 727 return true; 728 } 729 730 // Check the index. 731 const Expr *Arg2 = Call->getArg(2); 732 if (!Arg2->getType()->isIntegerType() && 733 !Arg2->getType()->isUnsignedIntegerType()) { 734 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 735 << Call->getDirectCallee() << S.Context.UnsignedIntTy 736 << Arg2->getType() << Arg2->getSourceRange(); 737 return true; 738 } 739 740 // Check packet type T. 741 if (checkOpenCLPipePacketType(S, Call, 3)) 742 return true; 743 } break; 744 default: 745 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num) 746 << Call->getDirectCallee() << Call->getSourceRange(); 747 return true; 748 } 749 750 return false; 751 } 752 753 // Performs a semantic analysis on the {work_group_/sub_group_ 754 // /_}reserve_{read/write}_pipe 755 // \param S Reference to the semantic analyzer. 756 // \param Call The call to the builtin function to be analyzed. 757 // \return True if a semantic error was found, false otherwise. 758 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 759 if (checkArgCount(S, Call, 2)) 760 return true; 761 762 if (checkOpenCLPipeArg(S, Call)) 763 return true; 764 765 // Check the reserve size. 766 if (!Call->getArg(1)->getType()->isIntegerType() && 767 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 768 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 769 << Call->getDirectCallee() << S.Context.UnsignedIntTy 770 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 771 return true; 772 } 773 774 // Since return type of reserve_read/write_pipe built-in function is 775 // reserve_id_t, which is not defined in the builtin def file , we used int 776 // as return type and need to override the return type of these functions. 777 Call->setType(S.Context.OCLReserveIDTy); 778 779 return false; 780 } 781 782 // Performs a semantic analysis on {work_group_/sub_group_ 783 // /_}commit_{read/write}_pipe 784 // \param S Reference to the semantic analyzer. 785 // \param Call The call to the builtin function to be analyzed. 786 // \return True if a semantic error was found, false otherwise. 787 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 788 if (checkArgCount(S, Call, 2)) 789 return true; 790 791 if (checkOpenCLPipeArg(S, Call)) 792 return true; 793 794 // Check reserve_id_t. 795 if (!Call->getArg(1)->getType()->isReserveIDT()) { 796 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 797 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 798 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 799 return true; 800 } 801 802 return false; 803 } 804 805 // Performs a semantic analysis on the call to built-in Pipe 806 // Query Functions. 807 // \param S Reference to the semantic analyzer. 808 // \param Call The call to the builtin function to be analyzed. 809 // \return True if a semantic error was found, false otherwise. 810 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 811 if (checkArgCount(S, Call, 1)) 812 return true; 813 814 if (!Call->getArg(0)->getType()->isPipeType()) { 815 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg) 816 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 817 return true; 818 } 819 820 return false; 821 } 822 823 // OpenCL v2.0 s6.13.9 - Address space qualifier functions. 824 // Performs semantic analysis for the to_global/local/private call. 825 // \param S Reference to the semantic analyzer. 826 // \param BuiltinID ID of the builtin function. 827 // \param Call A pointer to the builtin call. 828 // \return True if a semantic error has been found, false otherwise. 829 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 830 CallExpr *Call) { 831 if (Call->getNumArgs() != 1) { 832 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num) 833 << Call->getDirectCallee() << Call->getSourceRange(); 834 return true; 835 } 836 837 auto RT = Call->getArg(0)->getType(); 838 if (!RT->isPointerType() || RT->getPointeeType() 839 .getAddressSpace() == LangAS::opencl_constant) { 840 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg) 841 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 842 return true; 843 } 844 845 RT = RT->getPointeeType(); 846 auto Qual = RT.getQualifiers(); 847 switch (BuiltinID) { 848 case Builtin::BIto_global: 849 Qual.setAddressSpace(LangAS::opencl_global); 850 break; 851 case Builtin::BIto_local: 852 Qual.setAddressSpace(LangAS::opencl_local); 853 break; 854 case Builtin::BIto_private: 855 Qual.setAddressSpace(LangAS::opencl_private); 856 break; 857 default: 858 llvm_unreachable("Invalid builtin function"); 859 } 860 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 861 RT.getUnqualifiedType(), Qual))); 862 863 return false; 864 } 865 866 // Emit an error and return true if the current architecture is not in the list 867 // of supported architectures. 868 static bool 869 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall, 870 ArrayRef<llvm::Triple::ArchType> SupportedArchs) { 871 llvm::Triple::ArchType CurArch = 872 S.getASTContext().getTargetInfo().getTriple().getArch(); 873 if (llvm::is_contained(SupportedArchs, CurArch)) 874 return false; 875 S.Diag(TheCall->getLocStart(), diag::err_builtin_target_unsupported) 876 << TheCall->getSourceRange(); 877 return true; 878 } 879 880 ExprResult 881 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 882 CallExpr *TheCall) { 883 ExprResult TheCallResult(TheCall); 884 885 // Find out if any arguments are required to be integer constant expressions. 886 unsigned ICEArguments = 0; 887 ASTContext::GetBuiltinTypeError Error; 888 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 889 if (Error != ASTContext::GE_None) 890 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 891 892 // If any arguments are required to be ICE's, check and diagnose. 893 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 894 // Skip arguments not required to be ICE's. 895 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 896 897 llvm::APSInt Result; 898 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 899 return true; 900 ICEArguments &= ~(1 << ArgNo); 901 } 902 903 switch (BuiltinID) { 904 case Builtin::BI__builtin___CFStringMakeConstantString: 905 assert(TheCall->getNumArgs() == 1 && 906 "Wrong # arguments to builtin CFStringMakeConstantString"); 907 if (CheckObjCString(TheCall->getArg(0))) 908 return ExprError(); 909 break; 910 case Builtin::BI__builtin_ms_va_start: 911 case Builtin::BI__builtin_stdarg_start: 912 case Builtin::BI__builtin_va_start: 913 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 914 return ExprError(); 915 break; 916 case Builtin::BI__va_start: { 917 switch (Context.getTargetInfo().getTriple().getArch()) { 918 case llvm::Triple::arm: 919 case llvm::Triple::thumb: 920 if (SemaBuiltinVAStartARMMicrosoft(TheCall)) 921 return ExprError(); 922 break; 923 default: 924 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 925 return ExprError(); 926 break; 927 } 928 break; 929 } 930 931 // The acquire, release, and no fence variants are ARM and AArch64 only. 932 case Builtin::BI_interlockedbittestandset_acq: 933 case Builtin::BI_interlockedbittestandset_rel: 934 case Builtin::BI_interlockedbittestandset_nf: 935 case Builtin::BI_interlockedbittestandreset_acq: 936 case Builtin::BI_interlockedbittestandreset_rel: 937 case Builtin::BI_interlockedbittestandreset_nf: 938 if (CheckBuiltinTargetSupport( 939 *this, BuiltinID, TheCall, 940 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64})) 941 return ExprError(); 942 break; 943 944 // The 64-bit bittest variants are x64, ARM, and AArch64 only. 945 case Builtin::BI_bittest64: 946 case Builtin::BI_bittestandcomplement64: 947 case Builtin::BI_bittestandreset64: 948 case Builtin::BI_bittestandset64: 949 case Builtin::BI_interlockedbittestandreset64: 950 case Builtin::BI_interlockedbittestandset64: 951 if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall, 952 {llvm::Triple::x86_64, llvm::Triple::arm, 953 llvm::Triple::thumb, llvm::Triple::aarch64})) 954 return ExprError(); 955 break; 956 957 case Builtin::BI__builtin_isgreater: 958 case Builtin::BI__builtin_isgreaterequal: 959 case Builtin::BI__builtin_isless: 960 case Builtin::BI__builtin_islessequal: 961 case Builtin::BI__builtin_islessgreater: 962 case Builtin::BI__builtin_isunordered: 963 if (SemaBuiltinUnorderedCompare(TheCall)) 964 return ExprError(); 965 break; 966 case Builtin::BI__builtin_fpclassify: 967 if (SemaBuiltinFPClassification(TheCall, 6)) 968 return ExprError(); 969 break; 970 case Builtin::BI__builtin_isfinite: 971 case Builtin::BI__builtin_isinf: 972 case Builtin::BI__builtin_isinf_sign: 973 case Builtin::BI__builtin_isnan: 974 case Builtin::BI__builtin_isnormal: 975 case Builtin::BI__builtin_signbit: 976 case Builtin::BI__builtin_signbitf: 977 case Builtin::BI__builtin_signbitl: 978 if (SemaBuiltinFPClassification(TheCall, 1)) 979 return ExprError(); 980 break; 981 case Builtin::BI__builtin_shufflevector: 982 return SemaBuiltinShuffleVector(TheCall); 983 // TheCall will be freed by the smart pointer here, but that's fine, since 984 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 985 case Builtin::BI__builtin_prefetch: 986 if (SemaBuiltinPrefetch(TheCall)) 987 return ExprError(); 988 break; 989 case Builtin::BI__builtin_alloca_with_align: 990 if (SemaBuiltinAllocaWithAlign(TheCall)) 991 return ExprError(); 992 break; 993 case Builtin::BI__assume: 994 case Builtin::BI__builtin_assume: 995 if (SemaBuiltinAssume(TheCall)) 996 return ExprError(); 997 break; 998 case Builtin::BI__builtin_assume_aligned: 999 if (SemaBuiltinAssumeAligned(TheCall)) 1000 return ExprError(); 1001 break; 1002 case Builtin::BI__builtin_object_size: 1003 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 1004 return ExprError(); 1005 break; 1006 case Builtin::BI__builtin_longjmp: 1007 if (SemaBuiltinLongjmp(TheCall)) 1008 return ExprError(); 1009 break; 1010 case Builtin::BI__builtin_setjmp: 1011 if (SemaBuiltinSetjmp(TheCall)) 1012 return ExprError(); 1013 break; 1014 case Builtin::BI_setjmp: 1015 case Builtin::BI_setjmpex: 1016 if (checkArgCount(*this, TheCall, 1)) 1017 return true; 1018 break; 1019 case Builtin::BI__builtin_classify_type: 1020 if (checkArgCount(*this, TheCall, 1)) return true; 1021 TheCall->setType(Context.IntTy); 1022 break; 1023 case Builtin::BI__builtin_constant_p: 1024 if (checkArgCount(*this, TheCall, 1)) return true; 1025 TheCall->setType(Context.IntTy); 1026 break; 1027 case Builtin::BI__sync_fetch_and_add: 1028 case Builtin::BI__sync_fetch_and_add_1: 1029 case Builtin::BI__sync_fetch_and_add_2: 1030 case Builtin::BI__sync_fetch_and_add_4: 1031 case Builtin::BI__sync_fetch_and_add_8: 1032 case Builtin::BI__sync_fetch_and_add_16: 1033 case Builtin::BI__sync_fetch_and_sub: 1034 case Builtin::BI__sync_fetch_and_sub_1: 1035 case Builtin::BI__sync_fetch_and_sub_2: 1036 case Builtin::BI__sync_fetch_and_sub_4: 1037 case Builtin::BI__sync_fetch_and_sub_8: 1038 case Builtin::BI__sync_fetch_and_sub_16: 1039 case Builtin::BI__sync_fetch_and_or: 1040 case Builtin::BI__sync_fetch_and_or_1: 1041 case Builtin::BI__sync_fetch_and_or_2: 1042 case Builtin::BI__sync_fetch_and_or_4: 1043 case Builtin::BI__sync_fetch_and_or_8: 1044 case Builtin::BI__sync_fetch_and_or_16: 1045 case Builtin::BI__sync_fetch_and_and: 1046 case Builtin::BI__sync_fetch_and_and_1: 1047 case Builtin::BI__sync_fetch_and_and_2: 1048 case Builtin::BI__sync_fetch_and_and_4: 1049 case Builtin::BI__sync_fetch_and_and_8: 1050 case Builtin::BI__sync_fetch_and_and_16: 1051 case Builtin::BI__sync_fetch_and_xor: 1052 case Builtin::BI__sync_fetch_and_xor_1: 1053 case Builtin::BI__sync_fetch_and_xor_2: 1054 case Builtin::BI__sync_fetch_and_xor_4: 1055 case Builtin::BI__sync_fetch_and_xor_8: 1056 case Builtin::BI__sync_fetch_and_xor_16: 1057 case Builtin::BI__sync_fetch_and_nand: 1058 case Builtin::BI__sync_fetch_and_nand_1: 1059 case Builtin::BI__sync_fetch_and_nand_2: 1060 case Builtin::BI__sync_fetch_and_nand_4: 1061 case Builtin::BI__sync_fetch_and_nand_8: 1062 case Builtin::BI__sync_fetch_and_nand_16: 1063 case Builtin::BI__sync_add_and_fetch: 1064 case Builtin::BI__sync_add_and_fetch_1: 1065 case Builtin::BI__sync_add_and_fetch_2: 1066 case Builtin::BI__sync_add_and_fetch_4: 1067 case Builtin::BI__sync_add_and_fetch_8: 1068 case Builtin::BI__sync_add_and_fetch_16: 1069 case Builtin::BI__sync_sub_and_fetch: 1070 case Builtin::BI__sync_sub_and_fetch_1: 1071 case Builtin::BI__sync_sub_and_fetch_2: 1072 case Builtin::BI__sync_sub_and_fetch_4: 1073 case Builtin::BI__sync_sub_and_fetch_8: 1074 case Builtin::BI__sync_sub_and_fetch_16: 1075 case Builtin::BI__sync_and_and_fetch: 1076 case Builtin::BI__sync_and_and_fetch_1: 1077 case Builtin::BI__sync_and_and_fetch_2: 1078 case Builtin::BI__sync_and_and_fetch_4: 1079 case Builtin::BI__sync_and_and_fetch_8: 1080 case Builtin::BI__sync_and_and_fetch_16: 1081 case Builtin::BI__sync_or_and_fetch: 1082 case Builtin::BI__sync_or_and_fetch_1: 1083 case Builtin::BI__sync_or_and_fetch_2: 1084 case Builtin::BI__sync_or_and_fetch_4: 1085 case Builtin::BI__sync_or_and_fetch_8: 1086 case Builtin::BI__sync_or_and_fetch_16: 1087 case Builtin::BI__sync_xor_and_fetch: 1088 case Builtin::BI__sync_xor_and_fetch_1: 1089 case Builtin::BI__sync_xor_and_fetch_2: 1090 case Builtin::BI__sync_xor_and_fetch_4: 1091 case Builtin::BI__sync_xor_and_fetch_8: 1092 case Builtin::BI__sync_xor_and_fetch_16: 1093 case Builtin::BI__sync_nand_and_fetch: 1094 case Builtin::BI__sync_nand_and_fetch_1: 1095 case Builtin::BI__sync_nand_and_fetch_2: 1096 case Builtin::BI__sync_nand_and_fetch_4: 1097 case Builtin::BI__sync_nand_and_fetch_8: 1098 case Builtin::BI__sync_nand_and_fetch_16: 1099 case Builtin::BI__sync_val_compare_and_swap: 1100 case Builtin::BI__sync_val_compare_and_swap_1: 1101 case Builtin::BI__sync_val_compare_and_swap_2: 1102 case Builtin::BI__sync_val_compare_and_swap_4: 1103 case Builtin::BI__sync_val_compare_and_swap_8: 1104 case Builtin::BI__sync_val_compare_and_swap_16: 1105 case Builtin::BI__sync_bool_compare_and_swap: 1106 case Builtin::BI__sync_bool_compare_and_swap_1: 1107 case Builtin::BI__sync_bool_compare_and_swap_2: 1108 case Builtin::BI__sync_bool_compare_and_swap_4: 1109 case Builtin::BI__sync_bool_compare_and_swap_8: 1110 case Builtin::BI__sync_bool_compare_and_swap_16: 1111 case Builtin::BI__sync_lock_test_and_set: 1112 case Builtin::BI__sync_lock_test_and_set_1: 1113 case Builtin::BI__sync_lock_test_and_set_2: 1114 case Builtin::BI__sync_lock_test_and_set_4: 1115 case Builtin::BI__sync_lock_test_and_set_8: 1116 case Builtin::BI__sync_lock_test_and_set_16: 1117 case Builtin::BI__sync_lock_release: 1118 case Builtin::BI__sync_lock_release_1: 1119 case Builtin::BI__sync_lock_release_2: 1120 case Builtin::BI__sync_lock_release_4: 1121 case Builtin::BI__sync_lock_release_8: 1122 case Builtin::BI__sync_lock_release_16: 1123 case Builtin::BI__sync_swap: 1124 case Builtin::BI__sync_swap_1: 1125 case Builtin::BI__sync_swap_2: 1126 case Builtin::BI__sync_swap_4: 1127 case Builtin::BI__sync_swap_8: 1128 case Builtin::BI__sync_swap_16: 1129 return SemaBuiltinAtomicOverloaded(TheCallResult); 1130 case Builtin::BI__builtin_nontemporal_load: 1131 case Builtin::BI__builtin_nontemporal_store: 1132 return SemaBuiltinNontemporalOverloaded(TheCallResult); 1133 #define BUILTIN(ID, TYPE, ATTRS) 1134 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 1135 case Builtin::BI##ID: \ 1136 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 1137 #include "clang/Basic/Builtins.def" 1138 case Builtin::BI__annotation: 1139 if (SemaBuiltinMSVCAnnotation(*this, TheCall)) 1140 return ExprError(); 1141 break; 1142 case Builtin::BI__builtin_annotation: 1143 if (SemaBuiltinAnnotation(*this, TheCall)) 1144 return ExprError(); 1145 break; 1146 case Builtin::BI__builtin_addressof: 1147 if (SemaBuiltinAddressof(*this, TheCall)) 1148 return ExprError(); 1149 break; 1150 case Builtin::BI__builtin_add_overflow: 1151 case Builtin::BI__builtin_sub_overflow: 1152 case Builtin::BI__builtin_mul_overflow: 1153 if (SemaBuiltinOverflow(*this, TheCall)) 1154 return ExprError(); 1155 break; 1156 case Builtin::BI__builtin_operator_new: 1157 case Builtin::BI__builtin_operator_delete: { 1158 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete; 1159 ExprResult Res = 1160 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete); 1161 if (Res.isInvalid()) 1162 CorrectDelayedTyposInExpr(TheCallResult.get()); 1163 return Res; 1164 } 1165 case Builtin::BI__builtin_dump_struct: { 1166 // We first want to ensure we are called with 2 arguments 1167 if (checkArgCount(*this, TheCall, 2)) 1168 return ExprError(); 1169 // Ensure that the first argument is of type 'struct XX *' 1170 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts(); 1171 const QualType PtrArgType = PtrArg->getType(); 1172 if (!PtrArgType->isPointerType() || 1173 !PtrArgType->getPointeeType()->isRecordType()) { 1174 Diag(PtrArg->getLocStart(), diag::err_typecheck_convert_incompatible) 1175 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType 1176 << "structure pointer"; 1177 return ExprError(); 1178 } 1179 1180 // Ensure that the second argument is of type 'FunctionType' 1181 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts(); 1182 const QualType FnPtrArgType = FnPtrArg->getType(); 1183 if (!FnPtrArgType->isPointerType()) { 1184 Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible) 1185 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1186 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1187 return ExprError(); 1188 } 1189 1190 const auto *FuncType = 1191 FnPtrArgType->getPointeeType()->getAs<FunctionType>(); 1192 1193 if (!FuncType) { 1194 Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible) 1195 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1196 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1197 return ExprError(); 1198 } 1199 1200 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) { 1201 if (!FT->getNumParams()) { 1202 Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible) 1203 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1204 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1205 return ExprError(); 1206 } 1207 QualType PT = FT->getParamType(0); 1208 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy || 1209 !PT->isPointerType() || !PT->getPointeeType()->isCharType() || 1210 !PT->getPointeeType().isConstQualified()) { 1211 Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible) 1212 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1213 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1214 return ExprError(); 1215 } 1216 } 1217 1218 TheCall->setType(Context.IntTy); 1219 break; 1220 } 1221 1222 // check secure string manipulation functions where overflows 1223 // are detectable at compile time 1224 case Builtin::BI__builtin___memcpy_chk: 1225 case Builtin::BI__builtin___memmove_chk: 1226 case Builtin::BI__builtin___memset_chk: 1227 case Builtin::BI__builtin___strlcat_chk: 1228 case Builtin::BI__builtin___strlcpy_chk: 1229 case Builtin::BI__builtin___strncat_chk: 1230 case Builtin::BI__builtin___strncpy_chk: 1231 case Builtin::BI__builtin___stpncpy_chk: 1232 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3); 1233 break; 1234 case Builtin::BI__builtin___memccpy_chk: 1235 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4); 1236 break; 1237 case Builtin::BI__builtin___snprintf_chk: 1238 case Builtin::BI__builtin___vsnprintf_chk: 1239 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3); 1240 break; 1241 case Builtin::BI__builtin_call_with_static_chain: 1242 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 1243 return ExprError(); 1244 break; 1245 case Builtin::BI__exception_code: 1246 case Builtin::BI_exception_code: 1247 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1248 diag::err_seh___except_block)) 1249 return ExprError(); 1250 break; 1251 case Builtin::BI__exception_info: 1252 case Builtin::BI_exception_info: 1253 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1254 diag::err_seh___except_filter)) 1255 return ExprError(); 1256 break; 1257 case Builtin::BI__GetExceptionInfo: 1258 if (checkArgCount(*this, TheCall, 1)) 1259 return ExprError(); 1260 1261 if (CheckCXXThrowOperand( 1262 TheCall->getLocStart(), 1263 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1264 TheCall)) 1265 return ExprError(); 1266 1267 TheCall->setType(Context.VoidPtrTy); 1268 break; 1269 // OpenCL v2.0, s6.13.16 - Pipe functions 1270 case Builtin::BIread_pipe: 1271 case Builtin::BIwrite_pipe: 1272 // Since those two functions are declared with var args, we need a semantic 1273 // check for the argument. 1274 if (SemaBuiltinRWPipe(*this, TheCall)) 1275 return ExprError(); 1276 TheCall->setType(Context.IntTy); 1277 break; 1278 case Builtin::BIreserve_read_pipe: 1279 case Builtin::BIreserve_write_pipe: 1280 case Builtin::BIwork_group_reserve_read_pipe: 1281 case Builtin::BIwork_group_reserve_write_pipe: 1282 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1283 return ExprError(); 1284 break; 1285 case Builtin::BIsub_group_reserve_read_pipe: 1286 case Builtin::BIsub_group_reserve_write_pipe: 1287 if (checkOpenCLSubgroupExt(*this, TheCall) || 1288 SemaBuiltinReserveRWPipe(*this, TheCall)) 1289 return ExprError(); 1290 break; 1291 case Builtin::BIcommit_read_pipe: 1292 case Builtin::BIcommit_write_pipe: 1293 case Builtin::BIwork_group_commit_read_pipe: 1294 case Builtin::BIwork_group_commit_write_pipe: 1295 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1296 return ExprError(); 1297 break; 1298 case Builtin::BIsub_group_commit_read_pipe: 1299 case Builtin::BIsub_group_commit_write_pipe: 1300 if (checkOpenCLSubgroupExt(*this, TheCall) || 1301 SemaBuiltinCommitRWPipe(*this, TheCall)) 1302 return ExprError(); 1303 break; 1304 case Builtin::BIget_pipe_num_packets: 1305 case Builtin::BIget_pipe_max_packets: 1306 if (SemaBuiltinPipePackets(*this, TheCall)) 1307 return ExprError(); 1308 TheCall->setType(Context.UnsignedIntTy); 1309 break; 1310 case Builtin::BIto_global: 1311 case Builtin::BIto_local: 1312 case Builtin::BIto_private: 1313 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1314 return ExprError(); 1315 break; 1316 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1317 case Builtin::BIenqueue_kernel: 1318 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1319 return ExprError(); 1320 break; 1321 case Builtin::BIget_kernel_work_group_size: 1322 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1323 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1324 return ExprError(); 1325 break; 1326 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 1327 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 1328 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) 1329 return ExprError(); 1330 break; 1331 case Builtin::BI__builtin_os_log_format: 1332 case Builtin::BI__builtin_os_log_format_buffer_size: 1333 if (SemaBuiltinOSLogFormat(TheCall)) 1334 return ExprError(); 1335 break; 1336 } 1337 1338 // Since the target specific builtins for each arch overlap, only check those 1339 // of the arch we are compiling for. 1340 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 1341 switch (Context.getTargetInfo().getTriple().getArch()) { 1342 case llvm::Triple::arm: 1343 case llvm::Triple::armeb: 1344 case llvm::Triple::thumb: 1345 case llvm::Triple::thumbeb: 1346 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall)) 1347 return ExprError(); 1348 break; 1349 case llvm::Triple::aarch64: 1350 case llvm::Triple::aarch64_be: 1351 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall)) 1352 return ExprError(); 1353 break; 1354 case llvm::Triple::hexagon: 1355 if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall)) 1356 return ExprError(); 1357 break; 1358 case llvm::Triple::mips: 1359 case llvm::Triple::mipsel: 1360 case llvm::Triple::mips64: 1361 case llvm::Triple::mips64el: 1362 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall)) 1363 return ExprError(); 1364 break; 1365 case llvm::Triple::systemz: 1366 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall)) 1367 return ExprError(); 1368 break; 1369 case llvm::Triple::x86: 1370 case llvm::Triple::x86_64: 1371 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall)) 1372 return ExprError(); 1373 break; 1374 case llvm::Triple::ppc: 1375 case llvm::Triple::ppc64: 1376 case llvm::Triple::ppc64le: 1377 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall)) 1378 return ExprError(); 1379 break; 1380 default: 1381 break; 1382 } 1383 } 1384 1385 return TheCallResult; 1386 } 1387 1388 // Get the valid immediate range for the specified NEON type code. 1389 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 1390 NeonTypeFlags Type(t); 1391 int IsQuad = ForceQuad ? true : Type.isQuad(); 1392 switch (Type.getEltType()) { 1393 case NeonTypeFlags::Int8: 1394 case NeonTypeFlags::Poly8: 1395 return shift ? 7 : (8 << IsQuad) - 1; 1396 case NeonTypeFlags::Int16: 1397 case NeonTypeFlags::Poly16: 1398 return shift ? 15 : (4 << IsQuad) - 1; 1399 case NeonTypeFlags::Int32: 1400 return shift ? 31 : (2 << IsQuad) - 1; 1401 case NeonTypeFlags::Int64: 1402 case NeonTypeFlags::Poly64: 1403 return shift ? 63 : (1 << IsQuad) - 1; 1404 case NeonTypeFlags::Poly128: 1405 return shift ? 127 : (1 << IsQuad) - 1; 1406 case NeonTypeFlags::Float16: 1407 assert(!shift && "cannot shift float types!"); 1408 return (4 << IsQuad) - 1; 1409 case NeonTypeFlags::Float32: 1410 assert(!shift && "cannot shift float types!"); 1411 return (2 << IsQuad) - 1; 1412 case NeonTypeFlags::Float64: 1413 assert(!shift && "cannot shift float types!"); 1414 return (1 << IsQuad) - 1; 1415 } 1416 llvm_unreachable("Invalid NeonTypeFlag!"); 1417 } 1418 1419 /// getNeonEltType - Return the QualType corresponding to the elements of 1420 /// the vector type specified by the NeonTypeFlags. This is used to check 1421 /// the pointer arguments for Neon load/store intrinsics. 1422 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 1423 bool IsPolyUnsigned, bool IsInt64Long) { 1424 switch (Flags.getEltType()) { 1425 case NeonTypeFlags::Int8: 1426 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 1427 case NeonTypeFlags::Int16: 1428 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 1429 case NeonTypeFlags::Int32: 1430 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 1431 case NeonTypeFlags::Int64: 1432 if (IsInt64Long) 1433 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 1434 else 1435 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 1436 : Context.LongLongTy; 1437 case NeonTypeFlags::Poly8: 1438 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 1439 case NeonTypeFlags::Poly16: 1440 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 1441 case NeonTypeFlags::Poly64: 1442 if (IsInt64Long) 1443 return Context.UnsignedLongTy; 1444 else 1445 return Context.UnsignedLongLongTy; 1446 case NeonTypeFlags::Poly128: 1447 break; 1448 case NeonTypeFlags::Float16: 1449 return Context.HalfTy; 1450 case NeonTypeFlags::Float32: 1451 return Context.FloatTy; 1452 case NeonTypeFlags::Float64: 1453 return Context.DoubleTy; 1454 } 1455 llvm_unreachable("Invalid NeonTypeFlag!"); 1456 } 1457 1458 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1459 llvm::APSInt Result; 1460 uint64_t mask = 0; 1461 unsigned TV = 0; 1462 int PtrArgNum = -1; 1463 bool HasConstPtr = false; 1464 switch (BuiltinID) { 1465 #define GET_NEON_OVERLOAD_CHECK 1466 #include "clang/Basic/arm_neon.inc" 1467 #include "clang/Basic/arm_fp16.inc" 1468 #undef GET_NEON_OVERLOAD_CHECK 1469 } 1470 1471 // For NEON intrinsics which are overloaded on vector element type, validate 1472 // the immediate which specifies which variant to emit. 1473 unsigned ImmArg = TheCall->getNumArgs()-1; 1474 if (mask) { 1475 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 1476 return true; 1477 1478 TV = Result.getLimitedValue(64); 1479 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 1480 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code) 1481 << TheCall->getArg(ImmArg)->getSourceRange(); 1482 } 1483 1484 if (PtrArgNum >= 0) { 1485 // Check that pointer arguments have the specified type. 1486 Expr *Arg = TheCall->getArg(PtrArgNum); 1487 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 1488 Arg = ICE->getSubExpr(); 1489 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 1490 QualType RHSTy = RHS.get()->getType(); 1491 1492 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 1493 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 1494 Arch == llvm::Triple::aarch64_be; 1495 bool IsInt64Long = 1496 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong; 1497 QualType EltTy = 1498 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 1499 if (HasConstPtr) 1500 EltTy = EltTy.withConst(); 1501 QualType LHSTy = Context.getPointerType(EltTy); 1502 AssignConvertType ConvTy; 1503 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 1504 if (RHS.isInvalid()) 1505 return true; 1506 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy, 1507 RHS.get(), AA_Assigning)) 1508 return true; 1509 } 1510 1511 // For NEON intrinsics which take an immediate value as part of the 1512 // instruction, range check them here. 1513 unsigned i = 0, l = 0, u = 0; 1514 switch (BuiltinID) { 1515 default: 1516 return false; 1517 #define GET_NEON_IMMEDIATE_CHECK 1518 #include "clang/Basic/arm_neon.inc" 1519 #include "clang/Basic/arm_fp16.inc" 1520 #undef GET_NEON_IMMEDIATE_CHECK 1521 } 1522 1523 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1524 } 1525 1526 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 1527 unsigned MaxWidth) { 1528 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 1529 BuiltinID == ARM::BI__builtin_arm_ldaex || 1530 BuiltinID == ARM::BI__builtin_arm_strex || 1531 BuiltinID == ARM::BI__builtin_arm_stlex || 1532 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1533 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1534 BuiltinID == AArch64::BI__builtin_arm_strex || 1535 BuiltinID == AArch64::BI__builtin_arm_stlex) && 1536 "unexpected ARM builtin"); 1537 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 1538 BuiltinID == ARM::BI__builtin_arm_ldaex || 1539 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1540 BuiltinID == AArch64::BI__builtin_arm_ldaex; 1541 1542 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 1543 1544 // Ensure that we have the proper number of arguments. 1545 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 1546 return true; 1547 1548 // Inspect the pointer argument of the atomic builtin. This should always be 1549 // a pointer type, whose element is an integral scalar or pointer type. 1550 // Because it is a pointer type, we don't have to worry about any implicit 1551 // casts here. 1552 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 1553 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 1554 if (PointerArgRes.isInvalid()) 1555 return true; 1556 PointerArg = PointerArgRes.get(); 1557 1558 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 1559 if (!pointerType) { 1560 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 1561 << PointerArg->getType() << PointerArg->getSourceRange(); 1562 return true; 1563 } 1564 1565 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 1566 // task is to insert the appropriate casts into the AST. First work out just 1567 // what the appropriate type is. 1568 QualType ValType = pointerType->getPointeeType(); 1569 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 1570 if (IsLdrex) 1571 AddrType.addConst(); 1572 1573 // Issue a warning if the cast is dodgy. 1574 CastKind CastNeeded = CK_NoOp; 1575 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 1576 CastNeeded = CK_BitCast; 1577 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers) 1578 << PointerArg->getType() 1579 << Context.getPointerType(AddrType) 1580 << AA_Passing << PointerArg->getSourceRange(); 1581 } 1582 1583 // Finally, do the cast and replace the argument with the corrected version. 1584 AddrType = Context.getPointerType(AddrType); 1585 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 1586 if (PointerArgRes.isInvalid()) 1587 return true; 1588 PointerArg = PointerArgRes.get(); 1589 1590 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 1591 1592 // In general, we allow ints, floats and pointers to be loaded and stored. 1593 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 1594 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 1595 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 1596 << PointerArg->getType() << PointerArg->getSourceRange(); 1597 return true; 1598 } 1599 1600 // But ARM doesn't have instructions to deal with 128-bit versions. 1601 if (Context.getTypeSize(ValType) > MaxWidth) { 1602 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 1603 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size) 1604 << PointerArg->getType() << PointerArg->getSourceRange(); 1605 return true; 1606 } 1607 1608 switch (ValType.getObjCLifetime()) { 1609 case Qualifiers::OCL_None: 1610 case Qualifiers::OCL_ExplicitNone: 1611 // okay 1612 break; 1613 1614 case Qualifiers::OCL_Weak: 1615 case Qualifiers::OCL_Strong: 1616 case Qualifiers::OCL_Autoreleasing: 1617 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 1618 << ValType << PointerArg->getSourceRange(); 1619 return true; 1620 } 1621 1622 if (IsLdrex) { 1623 TheCall->setType(ValType); 1624 return false; 1625 } 1626 1627 // Initialize the argument to be stored. 1628 ExprResult ValArg = TheCall->getArg(0); 1629 InitializedEntity Entity = InitializedEntity::InitializeParameter( 1630 Context, ValType, /*consume*/ false); 1631 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 1632 if (ValArg.isInvalid()) 1633 return true; 1634 TheCall->setArg(0, ValArg.get()); 1635 1636 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 1637 // but the custom checker bypasses all default analysis. 1638 TheCall->setType(Context.IntTy); 1639 return false; 1640 } 1641 1642 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1643 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 1644 BuiltinID == ARM::BI__builtin_arm_ldaex || 1645 BuiltinID == ARM::BI__builtin_arm_strex || 1646 BuiltinID == ARM::BI__builtin_arm_stlex) { 1647 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 1648 } 1649 1650 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 1651 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1652 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 1653 } 1654 1655 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 1656 BuiltinID == ARM::BI__builtin_arm_wsr64) 1657 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 1658 1659 if (BuiltinID == ARM::BI__builtin_arm_rsr || 1660 BuiltinID == ARM::BI__builtin_arm_rsrp || 1661 BuiltinID == ARM::BI__builtin_arm_wsr || 1662 BuiltinID == ARM::BI__builtin_arm_wsrp) 1663 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1664 1665 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1666 return true; 1667 1668 // For intrinsics which take an immediate value as part of the instruction, 1669 // range check them here. 1670 // FIXME: VFP Intrinsics should error if VFP not present. 1671 switch (BuiltinID) { 1672 default: return false; 1673 case ARM::BI__builtin_arm_ssat: 1674 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32); 1675 case ARM::BI__builtin_arm_usat: 1676 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31); 1677 case ARM::BI__builtin_arm_ssat16: 1678 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 1679 case ARM::BI__builtin_arm_usat16: 1680 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 1681 case ARM::BI__builtin_arm_vcvtr_f: 1682 case ARM::BI__builtin_arm_vcvtr_d: 1683 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 1684 case ARM::BI__builtin_arm_dmb: 1685 case ARM::BI__builtin_arm_dsb: 1686 case ARM::BI__builtin_arm_isb: 1687 case ARM::BI__builtin_arm_dbg: 1688 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15); 1689 } 1690 } 1691 1692 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, 1693 CallExpr *TheCall) { 1694 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 1695 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1696 BuiltinID == AArch64::BI__builtin_arm_strex || 1697 BuiltinID == AArch64::BI__builtin_arm_stlex) { 1698 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 1699 } 1700 1701 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 1702 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1703 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 1704 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 1705 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 1706 } 1707 1708 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 1709 BuiltinID == AArch64::BI__builtin_arm_wsr64) 1710 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1711 1712 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 1713 BuiltinID == AArch64::BI__builtin_arm_rsrp || 1714 BuiltinID == AArch64::BI__builtin_arm_wsr || 1715 BuiltinID == AArch64::BI__builtin_arm_wsrp) 1716 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1717 1718 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1719 return true; 1720 1721 // For intrinsics which take an immediate value as part of the instruction, 1722 // range check them here. 1723 unsigned i = 0, l = 0, u = 0; 1724 switch (BuiltinID) { 1725 default: return false; 1726 case AArch64::BI__builtin_arm_dmb: 1727 case AArch64::BI__builtin_arm_dsb: 1728 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 1729 } 1730 1731 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1732 } 1733 1734 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, 1735 CallExpr *TheCall) { 1736 struct ArgInfo { 1737 ArgInfo(unsigned O, bool S, unsigned W, unsigned A) 1738 : OpNum(O), IsSigned(S), BitWidth(W), Align(A) {} 1739 unsigned OpNum = 0; 1740 bool IsSigned = false; 1741 unsigned BitWidth = 0; 1742 unsigned Align = 0; 1743 }; 1744 1745 static const std::map<unsigned, std::vector<ArgInfo>> Infos = { 1746 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} }, 1747 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} }, 1748 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} }, 1749 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 0 }} }, 1750 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} }, 1751 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} }, 1752 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} }, 1753 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} }, 1754 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} }, 1755 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} }, 1756 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} }, 1757 1758 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} }, 1759 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} }, 1760 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} }, 1761 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} }, 1762 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} }, 1763 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} }, 1764 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} }, 1765 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} }, 1766 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} }, 1767 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} }, 1768 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} }, 1769 1770 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} }, 1771 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} }, 1772 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} }, 1773 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} }, 1774 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} }, 1775 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} }, 1776 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} }, 1777 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} }, 1778 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} }, 1779 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} }, 1780 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} }, 1781 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} }, 1782 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} }, 1783 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} }, 1784 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} }, 1785 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} }, 1786 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} }, 1787 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} }, 1788 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} }, 1789 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} }, 1790 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} }, 1791 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} }, 1792 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} }, 1793 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} }, 1794 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} }, 1795 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} }, 1796 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} }, 1797 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} }, 1798 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} }, 1799 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} }, 1800 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} }, 1801 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} }, 1802 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} }, 1803 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} }, 1804 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} }, 1805 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} }, 1806 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} }, 1807 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} }, 1808 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} }, 1809 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} }, 1810 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} }, 1811 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} }, 1812 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} }, 1813 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} }, 1814 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} }, 1815 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} }, 1816 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} }, 1817 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} }, 1818 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} }, 1819 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} }, 1820 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} }, 1821 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax, 1822 {{ 1, false, 6, 0 }} }, 1823 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} }, 1824 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} }, 1825 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} }, 1826 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} }, 1827 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} }, 1828 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} }, 1829 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax, 1830 {{ 1, false, 5, 0 }} }, 1831 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} }, 1832 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} }, 1833 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} }, 1834 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} }, 1835 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} }, 1836 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 }, 1837 { 2, false, 5, 0 }} }, 1838 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 }, 1839 { 2, false, 6, 0 }} }, 1840 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 }, 1841 { 3, false, 5, 0 }} }, 1842 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 }, 1843 { 3, false, 6, 0 }} }, 1844 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} }, 1845 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} }, 1846 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} }, 1847 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} }, 1848 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} }, 1849 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} }, 1850 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} }, 1851 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} }, 1852 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} }, 1853 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} }, 1854 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} }, 1855 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} }, 1856 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} }, 1857 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} }, 1858 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} }, 1859 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax, 1860 {{ 2, false, 4, 0 }, 1861 { 3, false, 5, 0 }} }, 1862 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax, 1863 {{ 2, false, 4, 0 }, 1864 { 3, false, 5, 0 }} }, 1865 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax, 1866 {{ 2, false, 4, 0 }, 1867 { 3, false, 5, 0 }} }, 1868 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax, 1869 {{ 2, false, 4, 0 }, 1870 { 3, false, 5, 0 }} }, 1871 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} }, 1872 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} }, 1873 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} }, 1874 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} }, 1875 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} }, 1876 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} }, 1877 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} }, 1878 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} }, 1879 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} }, 1880 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} }, 1881 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 }, 1882 { 2, false, 5, 0 }} }, 1883 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 }, 1884 { 2, false, 6, 0 }} }, 1885 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} }, 1886 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} }, 1887 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} }, 1888 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} }, 1889 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} }, 1890 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} }, 1891 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} }, 1892 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} }, 1893 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax, 1894 {{ 1, false, 4, 0 }} }, 1895 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} }, 1896 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax, 1897 {{ 1, false, 4, 0 }} }, 1898 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} }, 1899 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} }, 1900 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} }, 1901 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} }, 1902 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} }, 1903 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} }, 1904 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} }, 1905 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} }, 1906 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} }, 1907 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} }, 1908 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} }, 1909 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} }, 1910 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} }, 1911 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} }, 1912 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} }, 1913 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} }, 1914 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} }, 1915 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} }, 1916 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} }, 1917 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, 1918 {{ 3, false, 1, 0 }} }, 1919 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} }, 1920 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} }, 1921 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} }, 1922 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, 1923 {{ 3, false, 1, 0 }} }, 1924 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} }, 1925 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} }, 1926 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} }, 1927 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, 1928 {{ 3, false, 1, 0 }} }, 1929 }; 1930 1931 auto F = Infos.find(BuiltinID); 1932 if (F == Infos.end()) 1933 return false; 1934 1935 bool Error = false; 1936 1937 for (const ArgInfo &A : F->second) { 1938 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth-1)) : 0; 1939 int32_t Max = (1 << (A.IsSigned ? A.BitWidth-1 : A.BitWidth)) - 1; 1940 if (!A.Align) { 1941 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 1942 } else { 1943 unsigned M = 1 << A.Align; 1944 Min *= M; 1945 Max *= M; 1946 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) | 1947 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M); 1948 } 1949 } 1950 return Error; 1951 } 1952 1953 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the 1954 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 1955 // ordering for DSP is unspecified. MSA is ordered by the data format used 1956 // by the underlying instruction i.e., df/m, df/n and then by size. 1957 // 1958 // FIXME: The size tests here should instead be tablegen'd along with the 1959 // definitions from include/clang/Basic/BuiltinsMips.def. 1960 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 1961 // be too. 1962 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1963 unsigned i = 0, l = 0, u = 0, m = 0; 1964 switch (BuiltinID) { 1965 default: return false; 1966 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 1967 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 1968 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 1969 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 1970 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 1971 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 1972 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 1973 // MSA instrinsics. Instructions (which the intrinsics maps to) which use the 1974 // df/m field. 1975 // These intrinsics take an unsigned 3 bit immediate. 1976 case Mips::BI__builtin_msa_bclri_b: 1977 case Mips::BI__builtin_msa_bnegi_b: 1978 case Mips::BI__builtin_msa_bseti_b: 1979 case Mips::BI__builtin_msa_sat_s_b: 1980 case Mips::BI__builtin_msa_sat_u_b: 1981 case Mips::BI__builtin_msa_slli_b: 1982 case Mips::BI__builtin_msa_srai_b: 1983 case Mips::BI__builtin_msa_srari_b: 1984 case Mips::BI__builtin_msa_srli_b: 1985 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 1986 case Mips::BI__builtin_msa_binsli_b: 1987 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 1988 // These intrinsics take an unsigned 4 bit immediate. 1989 case Mips::BI__builtin_msa_bclri_h: 1990 case Mips::BI__builtin_msa_bnegi_h: 1991 case Mips::BI__builtin_msa_bseti_h: 1992 case Mips::BI__builtin_msa_sat_s_h: 1993 case Mips::BI__builtin_msa_sat_u_h: 1994 case Mips::BI__builtin_msa_slli_h: 1995 case Mips::BI__builtin_msa_srai_h: 1996 case Mips::BI__builtin_msa_srari_h: 1997 case Mips::BI__builtin_msa_srli_h: 1998 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 1999 case Mips::BI__builtin_msa_binsli_h: 2000 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 2001 // These intrinsics take an unsigned 5 bit immediate. 2002 // The first block of intrinsics actually have an unsigned 5 bit field, 2003 // not a df/n field. 2004 case Mips::BI__builtin_msa_clei_u_b: 2005 case Mips::BI__builtin_msa_clei_u_h: 2006 case Mips::BI__builtin_msa_clei_u_w: 2007 case Mips::BI__builtin_msa_clei_u_d: 2008 case Mips::BI__builtin_msa_clti_u_b: 2009 case Mips::BI__builtin_msa_clti_u_h: 2010 case Mips::BI__builtin_msa_clti_u_w: 2011 case Mips::BI__builtin_msa_clti_u_d: 2012 case Mips::BI__builtin_msa_maxi_u_b: 2013 case Mips::BI__builtin_msa_maxi_u_h: 2014 case Mips::BI__builtin_msa_maxi_u_w: 2015 case Mips::BI__builtin_msa_maxi_u_d: 2016 case Mips::BI__builtin_msa_mini_u_b: 2017 case Mips::BI__builtin_msa_mini_u_h: 2018 case Mips::BI__builtin_msa_mini_u_w: 2019 case Mips::BI__builtin_msa_mini_u_d: 2020 case Mips::BI__builtin_msa_addvi_b: 2021 case Mips::BI__builtin_msa_addvi_h: 2022 case Mips::BI__builtin_msa_addvi_w: 2023 case Mips::BI__builtin_msa_addvi_d: 2024 case Mips::BI__builtin_msa_bclri_w: 2025 case Mips::BI__builtin_msa_bnegi_w: 2026 case Mips::BI__builtin_msa_bseti_w: 2027 case Mips::BI__builtin_msa_sat_s_w: 2028 case Mips::BI__builtin_msa_sat_u_w: 2029 case Mips::BI__builtin_msa_slli_w: 2030 case Mips::BI__builtin_msa_srai_w: 2031 case Mips::BI__builtin_msa_srari_w: 2032 case Mips::BI__builtin_msa_srli_w: 2033 case Mips::BI__builtin_msa_srlri_w: 2034 case Mips::BI__builtin_msa_subvi_b: 2035 case Mips::BI__builtin_msa_subvi_h: 2036 case Mips::BI__builtin_msa_subvi_w: 2037 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 2038 case Mips::BI__builtin_msa_binsli_w: 2039 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 2040 // These intrinsics take an unsigned 6 bit immediate. 2041 case Mips::BI__builtin_msa_bclri_d: 2042 case Mips::BI__builtin_msa_bnegi_d: 2043 case Mips::BI__builtin_msa_bseti_d: 2044 case Mips::BI__builtin_msa_sat_s_d: 2045 case Mips::BI__builtin_msa_sat_u_d: 2046 case Mips::BI__builtin_msa_slli_d: 2047 case Mips::BI__builtin_msa_srai_d: 2048 case Mips::BI__builtin_msa_srari_d: 2049 case Mips::BI__builtin_msa_srli_d: 2050 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 2051 case Mips::BI__builtin_msa_binsli_d: 2052 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 2053 // These intrinsics take a signed 5 bit immediate. 2054 case Mips::BI__builtin_msa_ceqi_b: 2055 case Mips::BI__builtin_msa_ceqi_h: 2056 case Mips::BI__builtin_msa_ceqi_w: 2057 case Mips::BI__builtin_msa_ceqi_d: 2058 case Mips::BI__builtin_msa_clti_s_b: 2059 case Mips::BI__builtin_msa_clti_s_h: 2060 case Mips::BI__builtin_msa_clti_s_w: 2061 case Mips::BI__builtin_msa_clti_s_d: 2062 case Mips::BI__builtin_msa_clei_s_b: 2063 case Mips::BI__builtin_msa_clei_s_h: 2064 case Mips::BI__builtin_msa_clei_s_w: 2065 case Mips::BI__builtin_msa_clei_s_d: 2066 case Mips::BI__builtin_msa_maxi_s_b: 2067 case Mips::BI__builtin_msa_maxi_s_h: 2068 case Mips::BI__builtin_msa_maxi_s_w: 2069 case Mips::BI__builtin_msa_maxi_s_d: 2070 case Mips::BI__builtin_msa_mini_s_b: 2071 case Mips::BI__builtin_msa_mini_s_h: 2072 case Mips::BI__builtin_msa_mini_s_w: 2073 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 2074 // These intrinsics take an unsigned 8 bit immediate. 2075 case Mips::BI__builtin_msa_andi_b: 2076 case Mips::BI__builtin_msa_nori_b: 2077 case Mips::BI__builtin_msa_ori_b: 2078 case Mips::BI__builtin_msa_shf_b: 2079 case Mips::BI__builtin_msa_shf_h: 2080 case Mips::BI__builtin_msa_shf_w: 2081 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 2082 case Mips::BI__builtin_msa_bseli_b: 2083 case Mips::BI__builtin_msa_bmnzi_b: 2084 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 2085 // df/n format 2086 // These intrinsics take an unsigned 4 bit immediate. 2087 case Mips::BI__builtin_msa_copy_s_b: 2088 case Mips::BI__builtin_msa_copy_u_b: 2089 case Mips::BI__builtin_msa_insve_b: 2090 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 2091 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 2092 // These intrinsics take an unsigned 3 bit immediate. 2093 case Mips::BI__builtin_msa_copy_s_h: 2094 case Mips::BI__builtin_msa_copy_u_h: 2095 case Mips::BI__builtin_msa_insve_h: 2096 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 2097 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 2098 // These intrinsics take an unsigned 2 bit immediate. 2099 case Mips::BI__builtin_msa_copy_s_w: 2100 case Mips::BI__builtin_msa_copy_u_w: 2101 case Mips::BI__builtin_msa_insve_w: 2102 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 2103 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 2104 // These intrinsics take an unsigned 1 bit immediate. 2105 case Mips::BI__builtin_msa_copy_s_d: 2106 case Mips::BI__builtin_msa_copy_u_d: 2107 case Mips::BI__builtin_msa_insve_d: 2108 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 2109 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 2110 // Memory offsets and immediate loads. 2111 // These intrinsics take a signed 10 bit immediate. 2112 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 2113 case Mips::BI__builtin_msa_ldi_h: 2114 case Mips::BI__builtin_msa_ldi_w: 2115 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 2116 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break; 2117 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break; 2118 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break; 2119 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break; 2120 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break; 2121 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break; 2122 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break; 2123 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break; 2124 } 2125 2126 if (!m) 2127 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 2128 2129 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 2130 SemaBuiltinConstantArgMultiple(TheCall, i, m); 2131 } 2132 2133 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2134 unsigned i = 0, l = 0, u = 0; 2135 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde || 2136 BuiltinID == PPC::BI__builtin_divdeu || 2137 BuiltinID == PPC::BI__builtin_bpermd; 2138 bool IsTarget64Bit = Context.getTargetInfo() 2139 .getTypeWidth(Context 2140 .getTargetInfo() 2141 .getIntPtrType()) == 64; 2142 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe || 2143 BuiltinID == PPC::BI__builtin_divweu || 2144 BuiltinID == PPC::BI__builtin_divde || 2145 BuiltinID == PPC::BI__builtin_divdeu; 2146 2147 if (Is64BitBltin && !IsTarget64Bit) 2148 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt) 2149 << TheCall->getSourceRange(); 2150 2151 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) || 2152 (BuiltinID == PPC::BI__builtin_bpermd && 2153 !Context.getTargetInfo().hasFeature("bpermd"))) 2154 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7) 2155 << TheCall->getSourceRange(); 2156 2157 switch (BuiltinID) { 2158 default: return false; 2159 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 2160 case PPC::BI__builtin_altivec_crypto_vshasigmad: 2161 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2162 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 2163 case PPC::BI__builtin_tbegin: 2164 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 2165 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 2166 case PPC::BI__builtin_tabortwc: 2167 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 2168 case PPC::BI__builtin_tabortwci: 2169 case PPC::BI__builtin_tabortdci: 2170 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 2171 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 2172 case PPC::BI__builtin_vsx_xxpermdi: 2173 case PPC::BI__builtin_vsx_xxsldwi: 2174 return SemaBuiltinVSX(TheCall); 2175 } 2176 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 2177 } 2178 2179 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 2180 CallExpr *TheCall) { 2181 if (BuiltinID == SystemZ::BI__builtin_tabort) { 2182 Expr *Arg = TheCall->getArg(0); 2183 llvm::APSInt AbortCode(32); 2184 if (Arg->isIntegerConstantExpr(AbortCode, Context) && 2185 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256) 2186 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code) 2187 << Arg->getSourceRange(); 2188 } 2189 2190 // For intrinsics which take an immediate value as part of the instruction, 2191 // range check them here. 2192 unsigned i = 0, l = 0, u = 0; 2193 switch (BuiltinID) { 2194 default: return false; 2195 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 2196 case SystemZ::BI__builtin_s390_verimb: 2197 case SystemZ::BI__builtin_s390_verimh: 2198 case SystemZ::BI__builtin_s390_verimf: 2199 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 2200 case SystemZ::BI__builtin_s390_vfaeb: 2201 case SystemZ::BI__builtin_s390_vfaeh: 2202 case SystemZ::BI__builtin_s390_vfaef: 2203 case SystemZ::BI__builtin_s390_vfaebs: 2204 case SystemZ::BI__builtin_s390_vfaehs: 2205 case SystemZ::BI__builtin_s390_vfaefs: 2206 case SystemZ::BI__builtin_s390_vfaezb: 2207 case SystemZ::BI__builtin_s390_vfaezh: 2208 case SystemZ::BI__builtin_s390_vfaezf: 2209 case SystemZ::BI__builtin_s390_vfaezbs: 2210 case SystemZ::BI__builtin_s390_vfaezhs: 2211 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 2212 case SystemZ::BI__builtin_s390_vfisb: 2213 case SystemZ::BI__builtin_s390_vfidb: 2214 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 2215 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 2216 case SystemZ::BI__builtin_s390_vftcisb: 2217 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 2218 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 2219 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 2220 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 2221 case SystemZ::BI__builtin_s390_vstrcb: 2222 case SystemZ::BI__builtin_s390_vstrch: 2223 case SystemZ::BI__builtin_s390_vstrcf: 2224 case SystemZ::BI__builtin_s390_vstrczb: 2225 case SystemZ::BI__builtin_s390_vstrczh: 2226 case SystemZ::BI__builtin_s390_vstrczf: 2227 case SystemZ::BI__builtin_s390_vstrcbs: 2228 case SystemZ::BI__builtin_s390_vstrchs: 2229 case SystemZ::BI__builtin_s390_vstrcfs: 2230 case SystemZ::BI__builtin_s390_vstrczbs: 2231 case SystemZ::BI__builtin_s390_vstrczhs: 2232 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 2233 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 2234 case SystemZ::BI__builtin_s390_vfminsb: 2235 case SystemZ::BI__builtin_s390_vfmaxsb: 2236 case SystemZ::BI__builtin_s390_vfmindb: 2237 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 2238 } 2239 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 2240 } 2241 2242 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 2243 /// This checks that the target supports __builtin_cpu_supports and 2244 /// that the string argument is constant and valid. 2245 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) { 2246 Expr *Arg = TheCall->getArg(0); 2247 2248 // Check if the argument is a string literal. 2249 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 2250 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal) 2251 << Arg->getSourceRange(); 2252 2253 // Check the contents of the string. 2254 StringRef Feature = 2255 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 2256 if (!S.Context.getTargetInfo().validateCpuSupports(Feature)) 2257 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports) 2258 << Arg->getSourceRange(); 2259 return false; 2260 } 2261 2262 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 2263 /// This checks that the target supports __builtin_cpu_is and 2264 /// that the string argument is constant and valid. 2265 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) { 2266 Expr *Arg = TheCall->getArg(0); 2267 2268 // Check if the argument is a string literal. 2269 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 2270 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal) 2271 << Arg->getSourceRange(); 2272 2273 // Check the contents of the string. 2274 StringRef Feature = 2275 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 2276 if (!S.Context.getTargetInfo().validateCpuIs(Feature)) 2277 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_is) 2278 << Arg->getSourceRange(); 2279 return false; 2280 } 2281 2282 // Check if the rounding mode is legal. 2283 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 2284 // Indicates if this instruction has rounding control or just SAE. 2285 bool HasRC = false; 2286 2287 unsigned ArgNum = 0; 2288 switch (BuiltinID) { 2289 default: 2290 return false; 2291 case X86::BI__builtin_ia32_vcvttsd2si32: 2292 case X86::BI__builtin_ia32_vcvttsd2si64: 2293 case X86::BI__builtin_ia32_vcvttsd2usi32: 2294 case X86::BI__builtin_ia32_vcvttsd2usi64: 2295 case X86::BI__builtin_ia32_vcvttss2si32: 2296 case X86::BI__builtin_ia32_vcvttss2si64: 2297 case X86::BI__builtin_ia32_vcvttss2usi32: 2298 case X86::BI__builtin_ia32_vcvttss2usi64: 2299 ArgNum = 1; 2300 break; 2301 case X86::BI__builtin_ia32_maxpd512: 2302 case X86::BI__builtin_ia32_maxps512: 2303 case X86::BI__builtin_ia32_minpd512: 2304 case X86::BI__builtin_ia32_minps512: 2305 ArgNum = 2; 2306 break; 2307 case X86::BI__builtin_ia32_cvtps2pd512_mask: 2308 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 2309 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 2310 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 2311 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 2312 case X86::BI__builtin_ia32_cvttps2dq512_mask: 2313 case X86::BI__builtin_ia32_cvttps2qq512_mask: 2314 case X86::BI__builtin_ia32_cvttps2udq512_mask: 2315 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 2316 case X86::BI__builtin_ia32_exp2pd_mask: 2317 case X86::BI__builtin_ia32_exp2ps_mask: 2318 case X86::BI__builtin_ia32_getexppd512_mask: 2319 case X86::BI__builtin_ia32_getexpps512_mask: 2320 case X86::BI__builtin_ia32_rcp28pd_mask: 2321 case X86::BI__builtin_ia32_rcp28ps_mask: 2322 case X86::BI__builtin_ia32_rsqrt28pd_mask: 2323 case X86::BI__builtin_ia32_rsqrt28ps_mask: 2324 case X86::BI__builtin_ia32_vcomisd: 2325 case X86::BI__builtin_ia32_vcomiss: 2326 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 2327 ArgNum = 3; 2328 break; 2329 case X86::BI__builtin_ia32_cmppd512_mask: 2330 case X86::BI__builtin_ia32_cmpps512_mask: 2331 case X86::BI__builtin_ia32_cmpsd_mask: 2332 case X86::BI__builtin_ia32_cmpss_mask: 2333 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 2334 case X86::BI__builtin_ia32_getexpsd128_round_mask: 2335 case X86::BI__builtin_ia32_getexpss128_round_mask: 2336 case X86::BI__builtin_ia32_maxsd_round_mask: 2337 case X86::BI__builtin_ia32_maxss_round_mask: 2338 case X86::BI__builtin_ia32_minsd_round_mask: 2339 case X86::BI__builtin_ia32_minss_round_mask: 2340 case X86::BI__builtin_ia32_rcp28sd_round_mask: 2341 case X86::BI__builtin_ia32_rcp28ss_round_mask: 2342 case X86::BI__builtin_ia32_reducepd512_mask: 2343 case X86::BI__builtin_ia32_reduceps512_mask: 2344 case X86::BI__builtin_ia32_rndscalepd_mask: 2345 case X86::BI__builtin_ia32_rndscaleps_mask: 2346 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 2347 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 2348 ArgNum = 4; 2349 break; 2350 case X86::BI__builtin_ia32_fixupimmpd512_mask: 2351 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 2352 case X86::BI__builtin_ia32_fixupimmps512_mask: 2353 case X86::BI__builtin_ia32_fixupimmps512_maskz: 2354 case X86::BI__builtin_ia32_fixupimmsd_mask: 2355 case X86::BI__builtin_ia32_fixupimmsd_maskz: 2356 case X86::BI__builtin_ia32_fixupimmss_mask: 2357 case X86::BI__builtin_ia32_fixupimmss_maskz: 2358 case X86::BI__builtin_ia32_rangepd512_mask: 2359 case X86::BI__builtin_ia32_rangeps512_mask: 2360 case X86::BI__builtin_ia32_rangesd128_round_mask: 2361 case X86::BI__builtin_ia32_rangess128_round_mask: 2362 case X86::BI__builtin_ia32_reducesd_mask: 2363 case X86::BI__builtin_ia32_reducess_mask: 2364 case X86::BI__builtin_ia32_rndscalesd_round_mask: 2365 case X86::BI__builtin_ia32_rndscaless_round_mask: 2366 ArgNum = 5; 2367 break; 2368 case X86::BI__builtin_ia32_vcvtsd2si64: 2369 case X86::BI__builtin_ia32_vcvtsd2si32: 2370 case X86::BI__builtin_ia32_vcvtsd2usi32: 2371 case X86::BI__builtin_ia32_vcvtsd2usi64: 2372 case X86::BI__builtin_ia32_vcvtss2si32: 2373 case X86::BI__builtin_ia32_vcvtss2si64: 2374 case X86::BI__builtin_ia32_vcvtss2usi32: 2375 case X86::BI__builtin_ia32_vcvtss2usi64: 2376 ArgNum = 1; 2377 HasRC = true; 2378 break; 2379 case X86::BI__builtin_ia32_addpd512: 2380 case X86::BI__builtin_ia32_addps512: 2381 case X86::BI__builtin_ia32_divpd512: 2382 case X86::BI__builtin_ia32_divps512: 2383 case X86::BI__builtin_ia32_mulpd512: 2384 case X86::BI__builtin_ia32_mulps512: 2385 case X86::BI__builtin_ia32_subpd512: 2386 case X86::BI__builtin_ia32_subps512: 2387 case X86::BI__builtin_ia32_cvtsi2sd64: 2388 case X86::BI__builtin_ia32_cvtsi2ss32: 2389 case X86::BI__builtin_ia32_cvtsi2ss64: 2390 case X86::BI__builtin_ia32_cvtusi2sd64: 2391 case X86::BI__builtin_ia32_cvtusi2ss32: 2392 case X86::BI__builtin_ia32_cvtusi2ss64: 2393 ArgNum = 2; 2394 HasRC = true; 2395 break; 2396 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 2397 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 2398 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 2399 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 2400 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 2401 case X86::BI__builtin_ia32_cvtps2qq512_mask: 2402 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 2403 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 2404 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 2405 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 2406 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 2407 case X86::BI__builtin_ia32_sqrtpd512_mask: 2408 case X86::BI__builtin_ia32_sqrtps512_mask: 2409 ArgNum = 3; 2410 HasRC = true; 2411 break; 2412 case X86::BI__builtin_ia32_addss_round_mask: 2413 case X86::BI__builtin_ia32_addsd_round_mask: 2414 case X86::BI__builtin_ia32_divss_round_mask: 2415 case X86::BI__builtin_ia32_divsd_round_mask: 2416 case X86::BI__builtin_ia32_mulss_round_mask: 2417 case X86::BI__builtin_ia32_mulsd_round_mask: 2418 case X86::BI__builtin_ia32_subss_round_mask: 2419 case X86::BI__builtin_ia32_subsd_round_mask: 2420 case X86::BI__builtin_ia32_scalefpd512_mask: 2421 case X86::BI__builtin_ia32_scalefps512_mask: 2422 case X86::BI__builtin_ia32_scalefsd_round_mask: 2423 case X86::BI__builtin_ia32_scalefss_round_mask: 2424 case X86::BI__builtin_ia32_getmantpd512_mask: 2425 case X86::BI__builtin_ia32_getmantps512_mask: 2426 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 2427 case X86::BI__builtin_ia32_sqrtsd_round_mask: 2428 case X86::BI__builtin_ia32_sqrtss_round_mask: 2429 case X86::BI__builtin_ia32_vfmaddsd3_mask: 2430 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 2431 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 2432 case X86::BI__builtin_ia32_vfmaddss3_mask: 2433 case X86::BI__builtin_ia32_vfmaddss3_maskz: 2434 case X86::BI__builtin_ia32_vfmaddss3_mask3: 2435 case X86::BI__builtin_ia32_vfmaddpd512_mask: 2436 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 2437 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 2438 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 2439 case X86::BI__builtin_ia32_vfmaddps512_mask: 2440 case X86::BI__builtin_ia32_vfmaddps512_maskz: 2441 case X86::BI__builtin_ia32_vfmaddps512_mask3: 2442 case X86::BI__builtin_ia32_vfmsubps512_mask3: 2443 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 2444 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 2445 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 2446 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 2447 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 2448 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 2449 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 2450 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 2451 ArgNum = 4; 2452 HasRC = true; 2453 break; 2454 case X86::BI__builtin_ia32_getmantsd_round_mask: 2455 case X86::BI__builtin_ia32_getmantss_round_mask: 2456 ArgNum = 5; 2457 HasRC = true; 2458 break; 2459 } 2460 2461 llvm::APSInt Result; 2462 2463 // We can't check the value of a dependent argument. 2464 Expr *Arg = TheCall->getArg(ArgNum); 2465 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2466 return false; 2467 2468 // Check constant-ness first. 2469 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 2470 return true; 2471 2472 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 2473 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 2474 // combined with ROUND_NO_EXC. 2475 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 2476 Result == 8/*ROUND_NO_EXC*/ || 2477 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 2478 return false; 2479 2480 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding) 2481 << Arg->getSourceRange(); 2482 } 2483 2484 // Check if the gather/scatter scale is legal. 2485 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 2486 CallExpr *TheCall) { 2487 unsigned ArgNum = 0; 2488 switch (BuiltinID) { 2489 default: 2490 return false; 2491 case X86::BI__builtin_ia32_gatherpfdpd: 2492 case X86::BI__builtin_ia32_gatherpfdps: 2493 case X86::BI__builtin_ia32_gatherpfqpd: 2494 case X86::BI__builtin_ia32_gatherpfqps: 2495 case X86::BI__builtin_ia32_scatterpfdpd: 2496 case X86::BI__builtin_ia32_scatterpfdps: 2497 case X86::BI__builtin_ia32_scatterpfqpd: 2498 case X86::BI__builtin_ia32_scatterpfqps: 2499 ArgNum = 3; 2500 break; 2501 case X86::BI__builtin_ia32_gatherd_pd: 2502 case X86::BI__builtin_ia32_gatherd_pd256: 2503 case X86::BI__builtin_ia32_gatherq_pd: 2504 case X86::BI__builtin_ia32_gatherq_pd256: 2505 case X86::BI__builtin_ia32_gatherd_ps: 2506 case X86::BI__builtin_ia32_gatherd_ps256: 2507 case X86::BI__builtin_ia32_gatherq_ps: 2508 case X86::BI__builtin_ia32_gatherq_ps256: 2509 case X86::BI__builtin_ia32_gatherd_q: 2510 case X86::BI__builtin_ia32_gatherd_q256: 2511 case X86::BI__builtin_ia32_gatherq_q: 2512 case X86::BI__builtin_ia32_gatherq_q256: 2513 case X86::BI__builtin_ia32_gatherd_d: 2514 case X86::BI__builtin_ia32_gatherd_d256: 2515 case X86::BI__builtin_ia32_gatherq_d: 2516 case X86::BI__builtin_ia32_gatherq_d256: 2517 case X86::BI__builtin_ia32_gather3div2df: 2518 case X86::BI__builtin_ia32_gather3div2di: 2519 case X86::BI__builtin_ia32_gather3div4df: 2520 case X86::BI__builtin_ia32_gather3div4di: 2521 case X86::BI__builtin_ia32_gather3div4sf: 2522 case X86::BI__builtin_ia32_gather3div4si: 2523 case X86::BI__builtin_ia32_gather3div8sf: 2524 case X86::BI__builtin_ia32_gather3div8si: 2525 case X86::BI__builtin_ia32_gather3siv2df: 2526 case X86::BI__builtin_ia32_gather3siv2di: 2527 case X86::BI__builtin_ia32_gather3siv4df: 2528 case X86::BI__builtin_ia32_gather3siv4di: 2529 case X86::BI__builtin_ia32_gather3siv4sf: 2530 case X86::BI__builtin_ia32_gather3siv4si: 2531 case X86::BI__builtin_ia32_gather3siv8sf: 2532 case X86::BI__builtin_ia32_gather3siv8si: 2533 case X86::BI__builtin_ia32_gathersiv8df: 2534 case X86::BI__builtin_ia32_gathersiv16sf: 2535 case X86::BI__builtin_ia32_gatherdiv8df: 2536 case X86::BI__builtin_ia32_gatherdiv16sf: 2537 case X86::BI__builtin_ia32_gathersiv8di: 2538 case X86::BI__builtin_ia32_gathersiv16si: 2539 case X86::BI__builtin_ia32_gatherdiv8di: 2540 case X86::BI__builtin_ia32_gatherdiv16si: 2541 case X86::BI__builtin_ia32_scatterdiv2df: 2542 case X86::BI__builtin_ia32_scatterdiv2di: 2543 case X86::BI__builtin_ia32_scatterdiv4df: 2544 case X86::BI__builtin_ia32_scatterdiv4di: 2545 case X86::BI__builtin_ia32_scatterdiv4sf: 2546 case X86::BI__builtin_ia32_scatterdiv4si: 2547 case X86::BI__builtin_ia32_scatterdiv8sf: 2548 case X86::BI__builtin_ia32_scatterdiv8si: 2549 case X86::BI__builtin_ia32_scattersiv2df: 2550 case X86::BI__builtin_ia32_scattersiv2di: 2551 case X86::BI__builtin_ia32_scattersiv4df: 2552 case X86::BI__builtin_ia32_scattersiv4di: 2553 case X86::BI__builtin_ia32_scattersiv4sf: 2554 case X86::BI__builtin_ia32_scattersiv4si: 2555 case X86::BI__builtin_ia32_scattersiv8sf: 2556 case X86::BI__builtin_ia32_scattersiv8si: 2557 case X86::BI__builtin_ia32_scattersiv8df: 2558 case X86::BI__builtin_ia32_scattersiv16sf: 2559 case X86::BI__builtin_ia32_scatterdiv8df: 2560 case X86::BI__builtin_ia32_scatterdiv16sf: 2561 case X86::BI__builtin_ia32_scattersiv8di: 2562 case X86::BI__builtin_ia32_scattersiv16si: 2563 case X86::BI__builtin_ia32_scatterdiv8di: 2564 case X86::BI__builtin_ia32_scatterdiv16si: 2565 ArgNum = 4; 2566 break; 2567 } 2568 2569 llvm::APSInt Result; 2570 2571 // We can't check the value of a dependent argument. 2572 Expr *Arg = TheCall->getArg(ArgNum); 2573 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2574 return false; 2575 2576 // Check constant-ness first. 2577 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 2578 return true; 2579 2580 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 2581 return false; 2582 2583 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale) 2584 << Arg->getSourceRange(); 2585 } 2586 2587 static bool isX86_32Builtin(unsigned BuiltinID) { 2588 // These builtins only work on x86-32 targets. 2589 switch (BuiltinID) { 2590 case X86::BI__builtin_ia32_readeflags_u32: 2591 case X86::BI__builtin_ia32_writeeflags_u32: 2592 return true; 2593 } 2594 2595 return false; 2596 } 2597 2598 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2599 if (BuiltinID == X86::BI__builtin_cpu_supports) 2600 return SemaBuiltinCpuSupports(*this, TheCall); 2601 2602 if (BuiltinID == X86::BI__builtin_cpu_is) 2603 return SemaBuiltinCpuIs(*this, TheCall); 2604 2605 // Check for 32-bit only builtins on a 64-bit target. 2606 const llvm::Triple &TT = Context.getTargetInfo().getTriple(); 2607 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) 2608 return Diag(TheCall->getCallee()->getLocStart(), 2609 diag::err_32_bit_builtin_64_bit_tgt); 2610 2611 // If the intrinsic has rounding or SAE make sure its valid. 2612 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 2613 return true; 2614 2615 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 2616 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 2617 return true; 2618 2619 // For intrinsics which take an immediate value as part of the instruction, 2620 // range check them here. 2621 int i = 0, l = 0, u = 0; 2622 switch (BuiltinID) { 2623 default: 2624 return false; 2625 case X86::BI__builtin_ia32_vec_ext_v2si: 2626 case X86::BI__builtin_ia32_vec_ext_v2di: 2627 case X86::BI__builtin_ia32_vextractf128_pd256: 2628 case X86::BI__builtin_ia32_vextractf128_ps256: 2629 case X86::BI__builtin_ia32_vextractf128_si256: 2630 case X86::BI__builtin_ia32_extract128i256: 2631 case X86::BI__builtin_ia32_extractf64x4_mask: 2632 case X86::BI__builtin_ia32_extracti64x4_mask: 2633 case X86::BI__builtin_ia32_extractf32x8_mask: 2634 case X86::BI__builtin_ia32_extracti32x8_mask: 2635 case X86::BI__builtin_ia32_extractf64x2_256_mask: 2636 case X86::BI__builtin_ia32_extracti64x2_256_mask: 2637 case X86::BI__builtin_ia32_extractf32x4_256_mask: 2638 case X86::BI__builtin_ia32_extracti32x4_256_mask: 2639 i = 1; l = 0; u = 1; 2640 break; 2641 case X86::BI__builtin_ia32_vec_set_v2di: 2642 case X86::BI__builtin_ia32_vinsertf128_pd256: 2643 case X86::BI__builtin_ia32_vinsertf128_ps256: 2644 case X86::BI__builtin_ia32_vinsertf128_si256: 2645 case X86::BI__builtin_ia32_insert128i256: 2646 case X86::BI__builtin_ia32_insertf32x8: 2647 case X86::BI__builtin_ia32_inserti32x8: 2648 case X86::BI__builtin_ia32_insertf64x4: 2649 case X86::BI__builtin_ia32_inserti64x4: 2650 case X86::BI__builtin_ia32_insertf64x2_256: 2651 case X86::BI__builtin_ia32_inserti64x2_256: 2652 case X86::BI__builtin_ia32_insertf32x4_256: 2653 case X86::BI__builtin_ia32_inserti32x4_256: 2654 i = 2; l = 0; u = 1; 2655 break; 2656 case X86::BI__builtin_ia32_vpermilpd: 2657 case X86::BI__builtin_ia32_vec_ext_v4hi: 2658 case X86::BI__builtin_ia32_vec_ext_v4si: 2659 case X86::BI__builtin_ia32_vec_ext_v4sf: 2660 case X86::BI__builtin_ia32_vec_ext_v4di: 2661 case X86::BI__builtin_ia32_extractf32x4_mask: 2662 case X86::BI__builtin_ia32_extracti32x4_mask: 2663 case X86::BI__builtin_ia32_extractf64x2_512_mask: 2664 case X86::BI__builtin_ia32_extracti64x2_512_mask: 2665 i = 1; l = 0; u = 3; 2666 break; 2667 case X86::BI_mm_prefetch: 2668 case X86::BI__builtin_ia32_vec_ext_v8hi: 2669 case X86::BI__builtin_ia32_vec_ext_v8si: 2670 i = 1; l = 0; u = 7; 2671 break; 2672 case X86::BI__builtin_ia32_sha1rnds4: 2673 case X86::BI__builtin_ia32_blendpd: 2674 case X86::BI__builtin_ia32_shufpd: 2675 case X86::BI__builtin_ia32_vec_set_v4hi: 2676 case X86::BI__builtin_ia32_vec_set_v4si: 2677 case X86::BI__builtin_ia32_vec_set_v4di: 2678 case X86::BI__builtin_ia32_shuf_f32x4_256: 2679 case X86::BI__builtin_ia32_shuf_f64x2_256: 2680 case X86::BI__builtin_ia32_shuf_i32x4_256: 2681 case X86::BI__builtin_ia32_shuf_i64x2_256: 2682 case X86::BI__builtin_ia32_insertf64x2_512: 2683 case X86::BI__builtin_ia32_inserti64x2_512: 2684 case X86::BI__builtin_ia32_insertf32x4: 2685 case X86::BI__builtin_ia32_inserti32x4: 2686 i = 2; l = 0; u = 3; 2687 break; 2688 case X86::BI__builtin_ia32_vpermil2pd: 2689 case X86::BI__builtin_ia32_vpermil2pd256: 2690 case X86::BI__builtin_ia32_vpermil2ps: 2691 case X86::BI__builtin_ia32_vpermil2ps256: 2692 i = 3; l = 0; u = 3; 2693 break; 2694 case X86::BI__builtin_ia32_cmpb128_mask: 2695 case X86::BI__builtin_ia32_cmpw128_mask: 2696 case X86::BI__builtin_ia32_cmpd128_mask: 2697 case X86::BI__builtin_ia32_cmpq128_mask: 2698 case X86::BI__builtin_ia32_cmpb256_mask: 2699 case X86::BI__builtin_ia32_cmpw256_mask: 2700 case X86::BI__builtin_ia32_cmpd256_mask: 2701 case X86::BI__builtin_ia32_cmpq256_mask: 2702 case X86::BI__builtin_ia32_cmpb512_mask: 2703 case X86::BI__builtin_ia32_cmpw512_mask: 2704 case X86::BI__builtin_ia32_cmpd512_mask: 2705 case X86::BI__builtin_ia32_cmpq512_mask: 2706 case X86::BI__builtin_ia32_ucmpb128_mask: 2707 case X86::BI__builtin_ia32_ucmpw128_mask: 2708 case X86::BI__builtin_ia32_ucmpd128_mask: 2709 case X86::BI__builtin_ia32_ucmpq128_mask: 2710 case X86::BI__builtin_ia32_ucmpb256_mask: 2711 case X86::BI__builtin_ia32_ucmpw256_mask: 2712 case X86::BI__builtin_ia32_ucmpd256_mask: 2713 case X86::BI__builtin_ia32_ucmpq256_mask: 2714 case X86::BI__builtin_ia32_ucmpb512_mask: 2715 case X86::BI__builtin_ia32_ucmpw512_mask: 2716 case X86::BI__builtin_ia32_ucmpd512_mask: 2717 case X86::BI__builtin_ia32_ucmpq512_mask: 2718 case X86::BI__builtin_ia32_vpcomub: 2719 case X86::BI__builtin_ia32_vpcomuw: 2720 case X86::BI__builtin_ia32_vpcomud: 2721 case X86::BI__builtin_ia32_vpcomuq: 2722 case X86::BI__builtin_ia32_vpcomb: 2723 case X86::BI__builtin_ia32_vpcomw: 2724 case X86::BI__builtin_ia32_vpcomd: 2725 case X86::BI__builtin_ia32_vpcomq: 2726 case X86::BI__builtin_ia32_vec_set_v8hi: 2727 case X86::BI__builtin_ia32_vec_set_v8si: 2728 i = 2; l = 0; u = 7; 2729 break; 2730 case X86::BI__builtin_ia32_vpermilpd256: 2731 case X86::BI__builtin_ia32_roundps: 2732 case X86::BI__builtin_ia32_roundpd: 2733 case X86::BI__builtin_ia32_roundps256: 2734 case X86::BI__builtin_ia32_roundpd256: 2735 case X86::BI__builtin_ia32_getmantpd128_mask: 2736 case X86::BI__builtin_ia32_getmantpd256_mask: 2737 case X86::BI__builtin_ia32_getmantps128_mask: 2738 case X86::BI__builtin_ia32_getmantps256_mask: 2739 case X86::BI__builtin_ia32_getmantpd512_mask: 2740 case X86::BI__builtin_ia32_getmantps512_mask: 2741 case X86::BI__builtin_ia32_vec_ext_v16qi: 2742 case X86::BI__builtin_ia32_vec_ext_v16hi: 2743 i = 1; l = 0; u = 15; 2744 break; 2745 case X86::BI__builtin_ia32_pblendd128: 2746 case X86::BI__builtin_ia32_blendps: 2747 case X86::BI__builtin_ia32_blendpd256: 2748 case X86::BI__builtin_ia32_shufpd256: 2749 case X86::BI__builtin_ia32_roundss: 2750 case X86::BI__builtin_ia32_roundsd: 2751 case X86::BI__builtin_ia32_rangepd128_mask: 2752 case X86::BI__builtin_ia32_rangepd256_mask: 2753 case X86::BI__builtin_ia32_rangepd512_mask: 2754 case X86::BI__builtin_ia32_rangeps128_mask: 2755 case X86::BI__builtin_ia32_rangeps256_mask: 2756 case X86::BI__builtin_ia32_rangeps512_mask: 2757 case X86::BI__builtin_ia32_getmantsd_round_mask: 2758 case X86::BI__builtin_ia32_getmantss_round_mask: 2759 case X86::BI__builtin_ia32_vec_set_v16qi: 2760 case X86::BI__builtin_ia32_vec_set_v16hi: 2761 i = 2; l = 0; u = 15; 2762 break; 2763 case X86::BI__builtin_ia32_vec_ext_v32qi: 2764 i = 1; l = 0; u = 31; 2765 break; 2766 case X86::BI__builtin_ia32_cmpps: 2767 case X86::BI__builtin_ia32_cmpss: 2768 case X86::BI__builtin_ia32_cmppd: 2769 case X86::BI__builtin_ia32_cmpsd: 2770 case X86::BI__builtin_ia32_cmpps256: 2771 case X86::BI__builtin_ia32_cmppd256: 2772 case X86::BI__builtin_ia32_cmpps128_mask: 2773 case X86::BI__builtin_ia32_cmppd128_mask: 2774 case X86::BI__builtin_ia32_cmpps256_mask: 2775 case X86::BI__builtin_ia32_cmppd256_mask: 2776 case X86::BI__builtin_ia32_cmpps512_mask: 2777 case X86::BI__builtin_ia32_cmppd512_mask: 2778 case X86::BI__builtin_ia32_cmpsd_mask: 2779 case X86::BI__builtin_ia32_cmpss_mask: 2780 case X86::BI__builtin_ia32_vec_set_v32qi: 2781 i = 2; l = 0; u = 31; 2782 break; 2783 case X86::BI__builtin_ia32_permdf256: 2784 case X86::BI__builtin_ia32_permdi256: 2785 case X86::BI__builtin_ia32_permdf512: 2786 case X86::BI__builtin_ia32_permdi512: 2787 case X86::BI__builtin_ia32_vpermilps: 2788 case X86::BI__builtin_ia32_vpermilps256: 2789 case X86::BI__builtin_ia32_vpermilpd512: 2790 case X86::BI__builtin_ia32_vpermilps512: 2791 case X86::BI__builtin_ia32_pshufd: 2792 case X86::BI__builtin_ia32_pshufd256: 2793 case X86::BI__builtin_ia32_pshufd512: 2794 case X86::BI__builtin_ia32_pshufhw: 2795 case X86::BI__builtin_ia32_pshufhw256: 2796 case X86::BI__builtin_ia32_pshufhw512: 2797 case X86::BI__builtin_ia32_pshuflw: 2798 case X86::BI__builtin_ia32_pshuflw256: 2799 case X86::BI__builtin_ia32_pshuflw512: 2800 case X86::BI__builtin_ia32_vcvtps2ph: 2801 case X86::BI__builtin_ia32_vcvtps2ph_mask: 2802 case X86::BI__builtin_ia32_vcvtps2ph256: 2803 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 2804 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 2805 case X86::BI__builtin_ia32_rndscaleps_128_mask: 2806 case X86::BI__builtin_ia32_rndscalepd_128_mask: 2807 case X86::BI__builtin_ia32_rndscaleps_256_mask: 2808 case X86::BI__builtin_ia32_rndscalepd_256_mask: 2809 case X86::BI__builtin_ia32_rndscaleps_mask: 2810 case X86::BI__builtin_ia32_rndscalepd_mask: 2811 case X86::BI__builtin_ia32_reducepd128_mask: 2812 case X86::BI__builtin_ia32_reducepd256_mask: 2813 case X86::BI__builtin_ia32_reducepd512_mask: 2814 case X86::BI__builtin_ia32_reduceps128_mask: 2815 case X86::BI__builtin_ia32_reduceps256_mask: 2816 case X86::BI__builtin_ia32_reduceps512_mask: 2817 case X86::BI__builtin_ia32_prold512_mask: 2818 case X86::BI__builtin_ia32_prolq512_mask: 2819 case X86::BI__builtin_ia32_prold128_mask: 2820 case X86::BI__builtin_ia32_prold256_mask: 2821 case X86::BI__builtin_ia32_prolq128_mask: 2822 case X86::BI__builtin_ia32_prolq256_mask: 2823 case X86::BI__builtin_ia32_prord512_mask: 2824 case X86::BI__builtin_ia32_prorq512_mask: 2825 case X86::BI__builtin_ia32_prord128_mask: 2826 case X86::BI__builtin_ia32_prord256_mask: 2827 case X86::BI__builtin_ia32_prorq128_mask: 2828 case X86::BI__builtin_ia32_prorq256_mask: 2829 case X86::BI__builtin_ia32_fpclasspd128_mask: 2830 case X86::BI__builtin_ia32_fpclasspd256_mask: 2831 case X86::BI__builtin_ia32_fpclassps128_mask: 2832 case X86::BI__builtin_ia32_fpclassps256_mask: 2833 case X86::BI__builtin_ia32_fpclassps512_mask: 2834 case X86::BI__builtin_ia32_fpclasspd512_mask: 2835 case X86::BI__builtin_ia32_fpclasssd_mask: 2836 case X86::BI__builtin_ia32_fpclassss_mask: 2837 case X86::BI__builtin_ia32_pslldqi128_byteshift: 2838 case X86::BI__builtin_ia32_pslldqi256_byteshift: 2839 case X86::BI__builtin_ia32_pslldqi512_byteshift: 2840 case X86::BI__builtin_ia32_psrldqi128_byteshift: 2841 case X86::BI__builtin_ia32_psrldqi256_byteshift: 2842 case X86::BI__builtin_ia32_psrldqi512_byteshift: 2843 i = 1; l = 0; u = 255; 2844 break; 2845 case X86::BI__builtin_ia32_vperm2f128_pd256: 2846 case X86::BI__builtin_ia32_vperm2f128_ps256: 2847 case X86::BI__builtin_ia32_vperm2f128_si256: 2848 case X86::BI__builtin_ia32_permti256: 2849 case X86::BI__builtin_ia32_pblendw128: 2850 case X86::BI__builtin_ia32_pblendw256: 2851 case X86::BI__builtin_ia32_blendps256: 2852 case X86::BI__builtin_ia32_pblendd256: 2853 case X86::BI__builtin_ia32_palignr128: 2854 case X86::BI__builtin_ia32_palignr256: 2855 case X86::BI__builtin_ia32_palignr512: 2856 case X86::BI__builtin_ia32_alignq512: 2857 case X86::BI__builtin_ia32_alignd512: 2858 case X86::BI__builtin_ia32_alignd128: 2859 case X86::BI__builtin_ia32_alignd256: 2860 case X86::BI__builtin_ia32_alignq128: 2861 case X86::BI__builtin_ia32_alignq256: 2862 case X86::BI__builtin_ia32_vcomisd: 2863 case X86::BI__builtin_ia32_vcomiss: 2864 case X86::BI__builtin_ia32_shuf_f32x4: 2865 case X86::BI__builtin_ia32_shuf_f64x2: 2866 case X86::BI__builtin_ia32_shuf_i32x4: 2867 case X86::BI__builtin_ia32_shuf_i64x2: 2868 case X86::BI__builtin_ia32_shufpd512: 2869 case X86::BI__builtin_ia32_shufps: 2870 case X86::BI__builtin_ia32_shufps256: 2871 case X86::BI__builtin_ia32_shufps512: 2872 case X86::BI__builtin_ia32_dbpsadbw128: 2873 case X86::BI__builtin_ia32_dbpsadbw256: 2874 case X86::BI__builtin_ia32_dbpsadbw512: 2875 case X86::BI__builtin_ia32_vpshldd128: 2876 case X86::BI__builtin_ia32_vpshldd256: 2877 case X86::BI__builtin_ia32_vpshldd512: 2878 case X86::BI__builtin_ia32_vpshldq128: 2879 case X86::BI__builtin_ia32_vpshldq256: 2880 case X86::BI__builtin_ia32_vpshldq512: 2881 case X86::BI__builtin_ia32_vpshldw128: 2882 case X86::BI__builtin_ia32_vpshldw256: 2883 case X86::BI__builtin_ia32_vpshldw512: 2884 case X86::BI__builtin_ia32_vpshrdd128: 2885 case X86::BI__builtin_ia32_vpshrdd256: 2886 case X86::BI__builtin_ia32_vpshrdd512: 2887 case X86::BI__builtin_ia32_vpshrdq128: 2888 case X86::BI__builtin_ia32_vpshrdq256: 2889 case X86::BI__builtin_ia32_vpshrdq512: 2890 case X86::BI__builtin_ia32_vpshrdw128: 2891 case X86::BI__builtin_ia32_vpshrdw256: 2892 case X86::BI__builtin_ia32_vpshrdw512: 2893 i = 2; l = 0; u = 255; 2894 break; 2895 case X86::BI__builtin_ia32_fixupimmpd512_mask: 2896 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 2897 case X86::BI__builtin_ia32_fixupimmps512_mask: 2898 case X86::BI__builtin_ia32_fixupimmps512_maskz: 2899 case X86::BI__builtin_ia32_fixupimmsd_mask: 2900 case X86::BI__builtin_ia32_fixupimmsd_maskz: 2901 case X86::BI__builtin_ia32_fixupimmss_mask: 2902 case X86::BI__builtin_ia32_fixupimmss_maskz: 2903 case X86::BI__builtin_ia32_fixupimmpd128_mask: 2904 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 2905 case X86::BI__builtin_ia32_fixupimmpd256_mask: 2906 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 2907 case X86::BI__builtin_ia32_fixupimmps128_mask: 2908 case X86::BI__builtin_ia32_fixupimmps128_maskz: 2909 case X86::BI__builtin_ia32_fixupimmps256_mask: 2910 case X86::BI__builtin_ia32_fixupimmps256_maskz: 2911 case X86::BI__builtin_ia32_pternlogd512_mask: 2912 case X86::BI__builtin_ia32_pternlogd512_maskz: 2913 case X86::BI__builtin_ia32_pternlogq512_mask: 2914 case X86::BI__builtin_ia32_pternlogq512_maskz: 2915 case X86::BI__builtin_ia32_pternlogd128_mask: 2916 case X86::BI__builtin_ia32_pternlogd128_maskz: 2917 case X86::BI__builtin_ia32_pternlogd256_mask: 2918 case X86::BI__builtin_ia32_pternlogd256_maskz: 2919 case X86::BI__builtin_ia32_pternlogq128_mask: 2920 case X86::BI__builtin_ia32_pternlogq128_maskz: 2921 case X86::BI__builtin_ia32_pternlogq256_mask: 2922 case X86::BI__builtin_ia32_pternlogq256_maskz: 2923 i = 3; l = 0; u = 255; 2924 break; 2925 case X86::BI__builtin_ia32_gatherpfdpd: 2926 case X86::BI__builtin_ia32_gatherpfdps: 2927 case X86::BI__builtin_ia32_gatherpfqpd: 2928 case X86::BI__builtin_ia32_gatherpfqps: 2929 case X86::BI__builtin_ia32_scatterpfdpd: 2930 case X86::BI__builtin_ia32_scatterpfdps: 2931 case X86::BI__builtin_ia32_scatterpfqpd: 2932 case X86::BI__builtin_ia32_scatterpfqps: 2933 i = 4; l = 2; u = 3; 2934 break; 2935 case X86::BI__builtin_ia32_rndscalesd_round_mask: 2936 case X86::BI__builtin_ia32_rndscaless_round_mask: 2937 i = 4; l = 0; u = 255; 2938 break; 2939 } 2940 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 2941 } 2942 2943 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 2944 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 2945 /// Returns true when the format fits the function and the FormatStringInfo has 2946 /// been populated. 2947 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 2948 FormatStringInfo *FSI) { 2949 FSI->HasVAListArg = Format->getFirstArg() == 0; 2950 FSI->FormatIdx = Format->getFormatIdx() - 1; 2951 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 2952 2953 // The way the format attribute works in GCC, the implicit this argument 2954 // of member functions is counted. However, it doesn't appear in our own 2955 // lists, so decrement format_idx in that case. 2956 if (IsCXXMember) { 2957 if(FSI->FormatIdx == 0) 2958 return false; 2959 --FSI->FormatIdx; 2960 if (FSI->FirstDataArg != 0) 2961 --FSI->FirstDataArg; 2962 } 2963 return true; 2964 } 2965 2966 /// Checks if a the given expression evaluates to null. 2967 /// 2968 /// Returns true if the value evaluates to null. 2969 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 2970 // If the expression has non-null type, it doesn't evaluate to null. 2971 if (auto nullability 2972 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 2973 if (*nullability == NullabilityKind::NonNull) 2974 return false; 2975 } 2976 2977 // As a special case, transparent unions initialized with zero are 2978 // considered null for the purposes of the nonnull attribute. 2979 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 2980 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 2981 if (const CompoundLiteralExpr *CLE = 2982 dyn_cast<CompoundLiteralExpr>(Expr)) 2983 if (const InitListExpr *ILE = 2984 dyn_cast<InitListExpr>(CLE->getInitializer())) 2985 Expr = ILE->getInit(0); 2986 } 2987 2988 bool Result; 2989 return (!Expr->isValueDependent() && 2990 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 2991 !Result); 2992 } 2993 2994 static void CheckNonNullArgument(Sema &S, 2995 const Expr *ArgExpr, 2996 SourceLocation CallSiteLoc) { 2997 if (CheckNonNullExpr(S, ArgExpr)) 2998 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 2999 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange()); 3000 } 3001 3002 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 3003 FormatStringInfo FSI; 3004 if ((GetFormatStringType(Format) == FST_NSString) && 3005 getFormatStringInfo(Format, false, &FSI)) { 3006 Idx = FSI.FormatIdx; 3007 return true; 3008 } 3009 return false; 3010 } 3011 3012 /// Diagnose use of %s directive in an NSString which is being passed 3013 /// as formatting string to formatting method. 3014 static void 3015 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 3016 const NamedDecl *FDecl, 3017 Expr **Args, 3018 unsigned NumArgs) { 3019 unsigned Idx = 0; 3020 bool Format = false; 3021 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 3022 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 3023 Idx = 2; 3024 Format = true; 3025 } 3026 else 3027 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 3028 if (S.GetFormatNSStringIdx(I, Idx)) { 3029 Format = true; 3030 break; 3031 } 3032 } 3033 if (!Format || NumArgs <= Idx) 3034 return; 3035 const Expr *FormatExpr = Args[Idx]; 3036 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 3037 FormatExpr = CSCE->getSubExpr(); 3038 const StringLiteral *FormatString; 3039 if (const ObjCStringLiteral *OSL = 3040 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 3041 FormatString = OSL->getString(); 3042 else 3043 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 3044 if (!FormatString) 3045 return; 3046 if (S.FormatStringHasSArg(FormatString)) { 3047 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 3048 << "%s" << 1 << 1; 3049 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 3050 << FDecl->getDeclName(); 3051 } 3052 } 3053 3054 /// Determine whether the given type has a non-null nullability annotation. 3055 static bool isNonNullType(ASTContext &ctx, QualType type) { 3056 if (auto nullability = type->getNullability(ctx)) 3057 return *nullability == NullabilityKind::NonNull; 3058 3059 return false; 3060 } 3061 3062 static void CheckNonNullArguments(Sema &S, 3063 const NamedDecl *FDecl, 3064 const FunctionProtoType *Proto, 3065 ArrayRef<const Expr *> Args, 3066 SourceLocation CallSiteLoc) { 3067 assert((FDecl || Proto) && "Need a function declaration or prototype"); 3068 3069 // Check the attributes attached to the method/function itself. 3070 llvm::SmallBitVector NonNullArgs; 3071 if (FDecl) { 3072 // Handle the nonnull attribute on the function/method declaration itself. 3073 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 3074 if (!NonNull->args_size()) { 3075 // Easy case: all pointer arguments are nonnull. 3076 for (const auto *Arg : Args) 3077 if (S.isValidPointerAttrType(Arg->getType())) 3078 CheckNonNullArgument(S, Arg, CallSiteLoc); 3079 return; 3080 } 3081 3082 for (const ParamIdx &Idx : NonNull->args()) { 3083 unsigned IdxAST = Idx.getASTIndex(); 3084 if (IdxAST >= Args.size()) 3085 continue; 3086 if (NonNullArgs.empty()) 3087 NonNullArgs.resize(Args.size()); 3088 NonNullArgs.set(IdxAST); 3089 } 3090 } 3091 } 3092 3093 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 3094 // Handle the nonnull attribute on the parameters of the 3095 // function/method. 3096 ArrayRef<ParmVarDecl*> parms; 3097 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 3098 parms = FD->parameters(); 3099 else 3100 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 3101 3102 unsigned ParamIndex = 0; 3103 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 3104 I != E; ++I, ++ParamIndex) { 3105 const ParmVarDecl *PVD = *I; 3106 if (PVD->hasAttr<NonNullAttr>() || 3107 isNonNullType(S.Context, PVD->getType())) { 3108 if (NonNullArgs.empty()) 3109 NonNullArgs.resize(Args.size()); 3110 3111 NonNullArgs.set(ParamIndex); 3112 } 3113 } 3114 } else { 3115 // If we have a non-function, non-method declaration but no 3116 // function prototype, try to dig out the function prototype. 3117 if (!Proto) { 3118 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 3119 QualType type = VD->getType().getNonReferenceType(); 3120 if (auto pointerType = type->getAs<PointerType>()) 3121 type = pointerType->getPointeeType(); 3122 else if (auto blockType = type->getAs<BlockPointerType>()) 3123 type = blockType->getPointeeType(); 3124 // FIXME: data member pointers? 3125 3126 // Dig out the function prototype, if there is one. 3127 Proto = type->getAs<FunctionProtoType>(); 3128 } 3129 } 3130 3131 // Fill in non-null argument information from the nullability 3132 // information on the parameter types (if we have them). 3133 if (Proto) { 3134 unsigned Index = 0; 3135 for (auto paramType : Proto->getParamTypes()) { 3136 if (isNonNullType(S.Context, paramType)) { 3137 if (NonNullArgs.empty()) 3138 NonNullArgs.resize(Args.size()); 3139 3140 NonNullArgs.set(Index); 3141 } 3142 3143 ++Index; 3144 } 3145 } 3146 } 3147 3148 // Check for non-null arguments. 3149 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 3150 ArgIndex != ArgIndexEnd; ++ArgIndex) { 3151 if (NonNullArgs[ArgIndex]) 3152 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 3153 } 3154 } 3155 3156 /// Handles the checks for format strings, non-POD arguments to vararg 3157 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 3158 /// attributes. 3159 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 3160 const Expr *ThisArg, ArrayRef<const Expr *> Args, 3161 bool IsMemberFunction, SourceLocation Loc, 3162 SourceRange Range, VariadicCallType CallType) { 3163 // FIXME: We should check as much as we can in the template definition. 3164 if (CurContext->isDependentContext()) 3165 return; 3166 3167 // Printf and scanf checking. 3168 llvm::SmallBitVector CheckedVarArgs; 3169 if (FDecl) { 3170 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 3171 // Only create vector if there are format attributes. 3172 CheckedVarArgs.resize(Args.size()); 3173 3174 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 3175 CheckedVarArgs); 3176 } 3177 } 3178 3179 // Refuse POD arguments that weren't caught by the format string 3180 // checks above. 3181 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 3182 if (CallType != VariadicDoesNotApply && 3183 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 3184 unsigned NumParams = Proto ? Proto->getNumParams() 3185 : FDecl && isa<FunctionDecl>(FDecl) 3186 ? cast<FunctionDecl>(FDecl)->getNumParams() 3187 : FDecl && isa<ObjCMethodDecl>(FDecl) 3188 ? cast<ObjCMethodDecl>(FDecl)->param_size() 3189 : 0; 3190 3191 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 3192 // Args[ArgIdx] can be null in malformed code. 3193 if (const Expr *Arg = Args[ArgIdx]) { 3194 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 3195 checkVariadicArgument(Arg, CallType); 3196 } 3197 } 3198 } 3199 3200 if (FDecl || Proto) { 3201 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 3202 3203 // Type safety checking. 3204 if (FDecl) { 3205 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 3206 CheckArgumentWithTypeTag(I, Args, Loc); 3207 } 3208 } 3209 3210 if (FD) 3211 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 3212 } 3213 3214 /// CheckConstructorCall - Check a constructor call for correctness and safety 3215 /// properties not enforced by the C type system. 3216 void Sema::CheckConstructorCall(FunctionDecl *FDecl, 3217 ArrayRef<const Expr *> Args, 3218 const FunctionProtoType *Proto, 3219 SourceLocation Loc) { 3220 VariadicCallType CallType = 3221 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 3222 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 3223 Loc, SourceRange(), CallType); 3224 } 3225 3226 /// CheckFunctionCall - Check a direct function call for various correctness 3227 /// and safety properties not strictly enforced by the C type system. 3228 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 3229 const FunctionProtoType *Proto) { 3230 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 3231 isa<CXXMethodDecl>(FDecl); 3232 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 3233 IsMemberOperatorCall; 3234 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 3235 TheCall->getCallee()); 3236 Expr** Args = TheCall->getArgs(); 3237 unsigned NumArgs = TheCall->getNumArgs(); 3238 3239 Expr *ImplicitThis = nullptr; 3240 if (IsMemberOperatorCall) { 3241 // If this is a call to a member operator, hide the first argument 3242 // from checkCall. 3243 // FIXME: Our choice of AST representation here is less than ideal. 3244 ImplicitThis = Args[0]; 3245 ++Args; 3246 --NumArgs; 3247 } else if (IsMemberFunction) 3248 ImplicitThis = 3249 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 3250 3251 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 3252 IsMemberFunction, TheCall->getRParenLoc(), 3253 TheCall->getCallee()->getSourceRange(), CallType); 3254 3255 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 3256 // None of the checks below are needed for functions that don't have 3257 // simple names (e.g., C++ conversion functions). 3258 if (!FnInfo) 3259 return false; 3260 3261 CheckAbsoluteValueFunction(TheCall, FDecl); 3262 CheckMaxUnsignedZero(TheCall, FDecl); 3263 3264 if (getLangOpts().ObjC1) 3265 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 3266 3267 unsigned CMId = FDecl->getMemoryFunctionKind(); 3268 if (CMId == 0) 3269 return false; 3270 3271 // Handle memory setting and copying functions. 3272 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 3273 CheckStrlcpycatArguments(TheCall, FnInfo); 3274 else if (CMId == Builtin::BIstrncat) 3275 CheckStrncatArguments(TheCall, FnInfo); 3276 else 3277 CheckMemaccessArguments(TheCall, CMId, FnInfo); 3278 3279 return false; 3280 } 3281 3282 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 3283 ArrayRef<const Expr *> Args) { 3284 VariadicCallType CallType = 3285 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 3286 3287 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 3288 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 3289 CallType); 3290 3291 return false; 3292 } 3293 3294 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 3295 const FunctionProtoType *Proto) { 3296 QualType Ty; 3297 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 3298 Ty = V->getType().getNonReferenceType(); 3299 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 3300 Ty = F->getType().getNonReferenceType(); 3301 else 3302 return false; 3303 3304 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 3305 !Ty->isFunctionProtoType()) 3306 return false; 3307 3308 VariadicCallType CallType; 3309 if (!Proto || !Proto->isVariadic()) { 3310 CallType = VariadicDoesNotApply; 3311 } else if (Ty->isBlockPointerType()) { 3312 CallType = VariadicBlock; 3313 } else { // Ty->isFunctionPointerType() 3314 CallType = VariadicFunction; 3315 } 3316 3317 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 3318 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 3319 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 3320 TheCall->getCallee()->getSourceRange(), CallType); 3321 3322 return false; 3323 } 3324 3325 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 3326 /// such as function pointers returned from functions. 3327 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 3328 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 3329 TheCall->getCallee()); 3330 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 3331 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 3332 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 3333 TheCall->getCallee()->getSourceRange(), CallType); 3334 3335 return false; 3336 } 3337 3338 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 3339 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 3340 return false; 3341 3342 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 3343 switch (Op) { 3344 case AtomicExpr::AO__c11_atomic_init: 3345 case AtomicExpr::AO__opencl_atomic_init: 3346 llvm_unreachable("There is no ordering argument for an init"); 3347 3348 case AtomicExpr::AO__c11_atomic_load: 3349 case AtomicExpr::AO__opencl_atomic_load: 3350 case AtomicExpr::AO__atomic_load_n: 3351 case AtomicExpr::AO__atomic_load: 3352 return OrderingCABI != llvm::AtomicOrderingCABI::release && 3353 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 3354 3355 case AtomicExpr::AO__c11_atomic_store: 3356 case AtomicExpr::AO__opencl_atomic_store: 3357 case AtomicExpr::AO__atomic_store: 3358 case AtomicExpr::AO__atomic_store_n: 3359 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 3360 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 3361 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 3362 3363 default: 3364 return true; 3365 } 3366 } 3367 3368 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 3369 AtomicExpr::AtomicOp Op) { 3370 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 3371 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 3372 3373 // All the non-OpenCL operations take one of the following forms. 3374 // The OpenCL operations take the __c11 forms with one extra argument for 3375 // synchronization scope. 3376 enum { 3377 // C __c11_atomic_init(A *, C) 3378 Init, 3379 3380 // C __c11_atomic_load(A *, int) 3381 Load, 3382 3383 // void __atomic_load(A *, CP, int) 3384 LoadCopy, 3385 3386 // void __atomic_store(A *, CP, int) 3387 Copy, 3388 3389 // C __c11_atomic_add(A *, M, int) 3390 Arithmetic, 3391 3392 // C __atomic_exchange_n(A *, CP, int) 3393 Xchg, 3394 3395 // void __atomic_exchange(A *, C *, CP, int) 3396 GNUXchg, 3397 3398 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 3399 C11CmpXchg, 3400 3401 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 3402 GNUCmpXchg 3403 } Form = Init; 3404 3405 const unsigned NumForm = GNUCmpXchg + 1; 3406 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 3407 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 3408 // where: 3409 // C is an appropriate type, 3410 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 3411 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 3412 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 3413 // the int parameters are for orderings. 3414 3415 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 3416 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 3417 "need to update code for modified forms"); 3418 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 3419 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == 3420 AtomicExpr::AO__atomic_load, 3421 "need to update code for modified C11 atomics"); 3422 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 3423 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 3424 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 3425 Op <= AtomicExpr::AO__c11_atomic_fetch_xor) || 3426 IsOpenCL; 3427 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 3428 Op == AtomicExpr::AO__atomic_store_n || 3429 Op == AtomicExpr::AO__atomic_exchange_n || 3430 Op == AtomicExpr::AO__atomic_compare_exchange_n; 3431 bool IsAddSub = false; 3432 bool IsMinMax = false; 3433 3434 switch (Op) { 3435 case AtomicExpr::AO__c11_atomic_init: 3436 case AtomicExpr::AO__opencl_atomic_init: 3437 Form = Init; 3438 break; 3439 3440 case AtomicExpr::AO__c11_atomic_load: 3441 case AtomicExpr::AO__opencl_atomic_load: 3442 case AtomicExpr::AO__atomic_load_n: 3443 Form = Load; 3444 break; 3445 3446 case AtomicExpr::AO__atomic_load: 3447 Form = LoadCopy; 3448 break; 3449 3450 case AtomicExpr::AO__c11_atomic_store: 3451 case AtomicExpr::AO__opencl_atomic_store: 3452 case AtomicExpr::AO__atomic_store: 3453 case AtomicExpr::AO__atomic_store_n: 3454 Form = Copy; 3455 break; 3456 3457 case AtomicExpr::AO__c11_atomic_fetch_add: 3458 case AtomicExpr::AO__c11_atomic_fetch_sub: 3459 case AtomicExpr::AO__opencl_atomic_fetch_add: 3460 case AtomicExpr::AO__opencl_atomic_fetch_sub: 3461 case AtomicExpr::AO__opencl_atomic_fetch_min: 3462 case AtomicExpr::AO__opencl_atomic_fetch_max: 3463 case AtomicExpr::AO__atomic_fetch_add: 3464 case AtomicExpr::AO__atomic_fetch_sub: 3465 case AtomicExpr::AO__atomic_add_fetch: 3466 case AtomicExpr::AO__atomic_sub_fetch: 3467 IsAddSub = true; 3468 LLVM_FALLTHROUGH; 3469 case AtomicExpr::AO__c11_atomic_fetch_and: 3470 case AtomicExpr::AO__c11_atomic_fetch_or: 3471 case AtomicExpr::AO__c11_atomic_fetch_xor: 3472 case AtomicExpr::AO__opencl_atomic_fetch_and: 3473 case AtomicExpr::AO__opencl_atomic_fetch_or: 3474 case AtomicExpr::AO__opencl_atomic_fetch_xor: 3475 case AtomicExpr::AO__atomic_fetch_and: 3476 case AtomicExpr::AO__atomic_fetch_or: 3477 case AtomicExpr::AO__atomic_fetch_xor: 3478 case AtomicExpr::AO__atomic_fetch_nand: 3479 case AtomicExpr::AO__atomic_and_fetch: 3480 case AtomicExpr::AO__atomic_or_fetch: 3481 case AtomicExpr::AO__atomic_xor_fetch: 3482 case AtomicExpr::AO__atomic_nand_fetch: 3483 Form = Arithmetic; 3484 break; 3485 3486 case AtomicExpr::AO__atomic_fetch_min: 3487 case AtomicExpr::AO__atomic_fetch_max: 3488 IsMinMax = true; 3489 Form = Arithmetic; 3490 break; 3491 3492 case AtomicExpr::AO__c11_atomic_exchange: 3493 case AtomicExpr::AO__opencl_atomic_exchange: 3494 case AtomicExpr::AO__atomic_exchange_n: 3495 Form = Xchg; 3496 break; 3497 3498 case AtomicExpr::AO__atomic_exchange: 3499 Form = GNUXchg; 3500 break; 3501 3502 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 3503 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 3504 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 3505 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 3506 Form = C11CmpXchg; 3507 break; 3508 3509 case AtomicExpr::AO__atomic_compare_exchange: 3510 case AtomicExpr::AO__atomic_compare_exchange_n: 3511 Form = GNUCmpXchg; 3512 break; 3513 } 3514 3515 unsigned AdjustedNumArgs = NumArgs[Form]; 3516 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 3517 ++AdjustedNumArgs; 3518 // Check we have the right number of arguments. 3519 if (TheCall->getNumArgs() < AdjustedNumArgs) { 3520 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 3521 << 0 << AdjustedNumArgs << TheCall->getNumArgs() 3522 << TheCall->getCallee()->getSourceRange(); 3523 return ExprError(); 3524 } else if (TheCall->getNumArgs() > AdjustedNumArgs) { 3525 Diag(TheCall->getArg(AdjustedNumArgs)->getLocStart(), 3526 diag::err_typecheck_call_too_many_args) 3527 << 0 << AdjustedNumArgs << TheCall->getNumArgs() 3528 << TheCall->getCallee()->getSourceRange(); 3529 return ExprError(); 3530 } 3531 3532 // Inspect the first argument of the atomic operation. 3533 Expr *Ptr = TheCall->getArg(0); 3534 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 3535 if (ConvertedPtr.isInvalid()) 3536 return ExprError(); 3537 3538 Ptr = ConvertedPtr.get(); 3539 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 3540 if (!pointerType) { 3541 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 3542 << Ptr->getType() << Ptr->getSourceRange(); 3543 return ExprError(); 3544 } 3545 3546 // For a __c11 builtin, this should be a pointer to an _Atomic type. 3547 QualType AtomTy = pointerType->getPointeeType(); // 'A' 3548 QualType ValType = AtomTy; // 'C' 3549 if (IsC11) { 3550 if (!AtomTy->isAtomicType()) { 3551 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic) 3552 << Ptr->getType() << Ptr->getSourceRange(); 3553 return ExprError(); 3554 } 3555 if (AtomTy.isConstQualified() || 3556 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 3557 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic) 3558 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 3559 << Ptr->getSourceRange(); 3560 return ExprError(); 3561 } 3562 ValType = AtomTy->getAs<AtomicType>()->getValueType(); 3563 } else if (Form != Load && Form != LoadCopy) { 3564 if (ValType.isConstQualified()) { 3565 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer) 3566 << Ptr->getType() << Ptr->getSourceRange(); 3567 return ExprError(); 3568 } 3569 } 3570 3571 // For an arithmetic operation, the implied arithmetic must be well-formed. 3572 if (Form == Arithmetic) { 3573 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 3574 if (IsAddSub && !ValType->isIntegerType() 3575 && !ValType->isPointerType()) { 3576 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 3577 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 3578 return ExprError(); 3579 } 3580 if (IsMinMax) { 3581 const BuiltinType *BT = ValType->getAs<BuiltinType>(); 3582 if (!BT || (BT->getKind() != BuiltinType::Int && 3583 BT->getKind() != BuiltinType::UInt)) { 3584 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_int32_or_ptr); 3585 return ExprError(); 3586 } 3587 } 3588 if (!IsAddSub && !IsMinMax && !ValType->isIntegerType()) { 3589 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int) 3590 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 3591 return ExprError(); 3592 } 3593 if (IsC11 && ValType->isPointerType() && 3594 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(), 3595 diag::err_incomplete_type)) { 3596 return ExprError(); 3597 } 3598 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 3599 // For __atomic_*_n operations, the value type must be a scalar integral or 3600 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 3601 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 3602 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 3603 return ExprError(); 3604 } 3605 3606 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 3607 !AtomTy->isScalarType()) { 3608 // For GNU atomics, require a trivially-copyable type. This is not part of 3609 // the GNU atomics specification, but we enforce it for sanity. 3610 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy) 3611 << Ptr->getType() << Ptr->getSourceRange(); 3612 return ExprError(); 3613 } 3614 3615 switch (ValType.getObjCLifetime()) { 3616 case Qualifiers::OCL_None: 3617 case Qualifiers::OCL_ExplicitNone: 3618 // okay 3619 break; 3620 3621 case Qualifiers::OCL_Weak: 3622 case Qualifiers::OCL_Strong: 3623 case Qualifiers::OCL_Autoreleasing: 3624 // FIXME: Can this happen? By this point, ValType should be known 3625 // to be trivially copyable. 3626 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 3627 << ValType << Ptr->getSourceRange(); 3628 return ExprError(); 3629 } 3630 3631 // All atomic operations have an overload which takes a pointer to a volatile 3632 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself 3633 // into the result or the other operands. Similarly atomic_load takes a 3634 // pointer to a const 'A'. 3635 ValType.removeLocalVolatile(); 3636 ValType.removeLocalConst(); 3637 QualType ResultType = ValType; 3638 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 3639 Form == Init) 3640 ResultType = Context.VoidTy; 3641 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 3642 ResultType = Context.BoolTy; 3643 3644 // The type of a parameter passed 'by value'. In the GNU atomics, such 3645 // arguments are actually passed as pointers. 3646 QualType ByValType = ValType; // 'CP' 3647 bool IsPassedByAddress = false; 3648 if (!IsC11 && !IsN) { 3649 ByValType = Ptr->getType(); 3650 IsPassedByAddress = true; 3651 } 3652 3653 // The first argument's non-CV pointer type is used to deduce the type of 3654 // subsequent arguments, except for: 3655 // - weak flag (always converted to bool) 3656 // - memory order (always converted to int) 3657 // - scope (always converted to int) 3658 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) { 3659 QualType Ty; 3660 if (i < NumVals[Form] + 1) { 3661 switch (i) { 3662 case 0: 3663 // The first argument is always a pointer. It has a fixed type. 3664 // It is always dereferenced, a nullptr is undefined. 3665 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getLocStart()); 3666 // Nothing else to do: we already know all we want about this pointer. 3667 continue; 3668 case 1: 3669 // The second argument is the non-atomic operand. For arithmetic, this 3670 // is always passed by value, and for a compare_exchange it is always 3671 // passed by address. For the rest, GNU uses by-address and C11 uses 3672 // by-value. 3673 assert(Form != Load); 3674 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 3675 Ty = ValType; 3676 else if (Form == Copy || Form == Xchg) { 3677 if (IsPassedByAddress) 3678 // The value pointer is always dereferenced, a nullptr is undefined. 3679 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getLocStart()); 3680 Ty = ByValType; 3681 } else if (Form == Arithmetic) 3682 Ty = Context.getPointerDiffType(); 3683 else { 3684 Expr *ValArg = TheCall->getArg(i); 3685 // The value pointer is always dereferenced, a nullptr is undefined. 3686 CheckNonNullArgument(*this, ValArg, DRE->getLocStart()); 3687 LangAS AS = LangAS::Default; 3688 // Keep address space of non-atomic pointer type. 3689 if (const PointerType *PtrTy = 3690 ValArg->getType()->getAs<PointerType>()) { 3691 AS = PtrTy->getPointeeType().getAddressSpace(); 3692 } 3693 Ty = Context.getPointerType( 3694 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 3695 } 3696 break; 3697 case 2: 3698 // The third argument to compare_exchange / GNU exchange is the desired 3699 // value, either by-value (for the C11 and *_n variant) or as a pointer. 3700 if (IsPassedByAddress) 3701 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getLocStart()); 3702 Ty = ByValType; 3703 break; 3704 case 3: 3705 // The fourth argument to GNU compare_exchange is a 'weak' flag. 3706 Ty = Context.BoolTy; 3707 break; 3708 } 3709 } else { 3710 // The order(s) and scope are always converted to int. 3711 Ty = Context.IntTy; 3712 } 3713 3714 InitializedEntity Entity = 3715 InitializedEntity::InitializeParameter(Context, Ty, false); 3716 ExprResult Arg = TheCall->getArg(i); 3717 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 3718 if (Arg.isInvalid()) 3719 return true; 3720 TheCall->setArg(i, Arg.get()); 3721 } 3722 3723 // Permute the arguments into a 'consistent' order. 3724 SmallVector<Expr*, 5> SubExprs; 3725 SubExprs.push_back(Ptr); 3726 switch (Form) { 3727 case Init: 3728 // Note, AtomicExpr::getVal1() has a special case for this atomic. 3729 SubExprs.push_back(TheCall->getArg(1)); // Val1 3730 break; 3731 case Load: 3732 SubExprs.push_back(TheCall->getArg(1)); // Order 3733 break; 3734 case LoadCopy: 3735 case Copy: 3736 case Arithmetic: 3737 case Xchg: 3738 SubExprs.push_back(TheCall->getArg(2)); // Order 3739 SubExprs.push_back(TheCall->getArg(1)); // Val1 3740 break; 3741 case GNUXchg: 3742 // Note, AtomicExpr::getVal2() has a special case for this atomic. 3743 SubExprs.push_back(TheCall->getArg(3)); // Order 3744 SubExprs.push_back(TheCall->getArg(1)); // Val1 3745 SubExprs.push_back(TheCall->getArg(2)); // Val2 3746 break; 3747 case C11CmpXchg: 3748 SubExprs.push_back(TheCall->getArg(3)); // Order 3749 SubExprs.push_back(TheCall->getArg(1)); // Val1 3750 SubExprs.push_back(TheCall->getArg(4)); // OrderFail 3751 SubExprs.push_back(TheCall->getArg(2)); // Val2 3752 break; 3753 case GNUCmpXchg: 3754 SubExprs.push_back(TheCall->getArg(4)); // Order 3755 SubExprs.push_back(TheCall->getArg(1)); // Val1 3756 SubExprs.push_back(TheCall->getArg(5)); // OrderFail 3757 SubExprs.push_back(TheCall->getArg(2)); // Val2 3758 SubExprs.push_back(TheCall->getArg(3)); // Weak 3759 break; 3760 } 3761 3762 if (SubExprs.size() >= 2 && Form != Init) { 3763 llvm::APSInt Result(32); 3764 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) && 3765 !isValidOrderingForOp(Result.getSExtValue(), Op)) 3766 Diag(SubExprs[1]->getLocStart(), 3767 diag::warn_atomic_op_has_invalid_memory_order) 3768 << SubExprs[1]->getSourceRange(); 3769 } 3770 3771 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 3772 auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1); 3773 llvm::APSInt Result(32); 3774 if (Scope->isIntegerConstantExpr(Result, Context) && 3775 !ScopeModel->isValid(Result.getZExtValue())) { 3776 Diag(Scope->getLocStart(), diag::err_atomic_op_has_invalid_synch_scope) 3777 << Scope->getSourceRange(); 3778 } 3779 SubExprs.push_back(Scope); 3780 } 3781 3782 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(), 3783 SubExprs, ResultType, Op, 3784 TheCall->getRParenLoc()); 3785 3786 if ((Op == AtomicExpr::AO__c11_atomic_load || 3787 Op == AtomicExpr::AO__c11_atomic_store || 3788 Op == AtomicExpr::AO__opencl_atomic_load || 3789 Op == AtomicExpr::AO__opencl_atomic_store ) && 3790 Context.AtomicUsesUnsupportedLibcall(AE)) 3791 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) 3792 << ((Op == AtomicExpr::AO__c11_atomic_load || 3793 Op == AtomicExpr::AO__opencl_atomic_load) 3794 ? 0 : 1); 3795 3796 return AE; 3797 } 3798 3799 /// checkBuiltinArgument - Given a call to a builtin function, perform 3800 /// normal type-checking on the given argument, updating the call in 3801 /// place. This is useful when a builtin function requires custom 3802 /// type-checking for some of its arguments but not necessarily all of 3803 /// them. 3804 /// 3805 /// Returns true on error. 3806 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 3807 FunctionDecl *Fn = E->getDirectCallee(); 3808 assert(Fn && "builtin call without direct callee!"); 3809 3810 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 3811 InitializedEntity Entity = 3812 InitializedEntity::InitializeParameter(S.Context, Param); 3813 3814 ExprResult Arg = E->getArg(0); 3815 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 3816 if (Arg.isInvalid()) 3817 return true; 3818 3819 E->setArg(ArgIndex, Arg.get()); 3820 return false; 3821 } 3822 3823 /// SemaBuiltinAtomicOverloaded - We have a call to a function like 3824 /// __sync_fetch_and_add, which is an overloaded function based on the pointer 3825 /// type of its first argument. The main ActOnCallExpr routines have already 3826 /// promoted the types of arguments because all of these calls are prototyped as 3827 /// void(...). 3828 /// 3829 /// This function goes through and does final semantic checking for these 3830 /// builtins, 3831 ExprResult 3832 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 3833 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 3834 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 3835 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 3836 3837 // Ensure that we have at least one argument to do type inference from. 3838 if (TheCall->getNumArgs() < 1) { 3839 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 3840 << 0 << 1 << TheCall->getNumArgs() 3841 << TheCall->getCallee()->getSourceRange(); 3842 return ExprError(); 3843 } 3844 3845 // Inspect the first argument of the atomic builtin. This should always be 3846 // a pointer type, whose element is an integral scalar or pointer type. 3847 // Because it is a pointer type, we don't have to worry about any implicit 3848 // casts here. 3849 // FIXME: We don't allow floating point scalars as input. 3850 Expr *FirstArg = TheCall->getArg(0); 3851 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 3852 if (FirstArgResult.isInvalid()) 3853 return ExprError(); 3854 FirstArg = FirstArgResult.get(); 3855 TheCall->setArg(0, FirstArg); 3856 3857 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 3858 if (!pointerType) { 3859 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 3860 << FirstArg->getType() << FirstArg->getSourceRange(); 3861 return ExprError(); 3862 } 3863 3864 QualType ValType = pointerType->getPointeeType(); 3865 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 3866 !ValType->isBlockPointerType()) { 3867 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr) 3868 << FirstArg->getType() << FirstArg->getSourceRange(); 3869 return ExprError(); 3870 } 3871 3872 if (ValType.isConstQualified()) { 3873 Diag(DRE->getLocStart(), diag::err_atomic_builtin_cannot_be_const) 3874 << FirstArg->getType() << FirstArg->getSourceRange(); 3875 return ExprError(); 3876 } 3877 3878 switch (ValType.getObjCLifetime()) { 3879 case Qualifiers::OCL_None: 3880 case Qualifiers::OCL_ExplicitNone: 3881 // okay 3882 break; 3883 3884 case Qualifiers::OCL_Weak: 3885 case Qualifiers::OCL_Strong: 3886 case Qualifiers::OCL_Autoreleasing: 3887 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 3888 << ValType << FirstArg->getSourceRange(); 3889 return ExprError(); 3890 } 3891 3892 // Strip any qualifiers off ValType. 3893 ValType = ValType.getUnqualifiedType(); 3894 3895 // The majority of builtins return a value, but a few have special return 3896 // types, so allow them to override appropriately below. 3897 QualType ResultType = ValType; 3898 3899 // We need to figure out which concrete builtin this maps onto. For example, 3900 // __sync_fetch_and_add with a 2 byte object turns into 3901 // __sync_fetch_and_add_2. 3902 #define BUILTIN_ROW(x) \ 3903 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 3904 Builtin::BI##x##_8, Builtin::BI##x##_16 } 3905 3906 static const unsigned BuiltinIndices[][5] = { 3907 BUILTIN_ROW(__sync_fetch_and_add), 3908 BUILTIN_ROW(__sync_fetch_and_sub), 3909 BUILTIN_ROW(__sync_fetch_and_or), 3910 BUILTIN_ROW(__sync_fetch_and_and), 3911 BUILTIN_ROW(__sync_fetch_and_xor), 3912 BUILTIN_ROW(__sync_fetch_and_nand), 3913 3914 BUILTIN_ROW(__sync_add_and_fetch), 3915 BUILTIN_ROW(__sync_sub_and_fetch), 3916 BUILTIN_ROW(__sync_and_and_fetch), 3917 BUILTIN_ROW(__sync_or_and_fetch), 3918 BUILTIN_ROW(__sync_xor_and_fetch), 3919 BUILTIN_ROW(__sync_nand_and_fetch), 3920 3921 BUILTIN_ROW(__sync_val_compare_and_swap), 3922 BUILTIN_ROW(__sync_bool_compare_and_swap), 3923 BUILTIN_ROW(__sync_lock_test_and_set), 3924 BUILTIN_ROW(__sync_lock_release), 3925 BUILTIN_ROW(__sync_swap) 3926 }; 3927 #undef BUILTIN_ROW 3928 3929 // Determine the index of the size. 3930 unsigned SizeIndex; 3931 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 3932 case 1: SizeIndex = 0; break; 3933 case 2: SizeIndex = 1; break; 3934 case 4: SizeIndex = 2; break; 3935 case 8: SizeIndex = 3; break; 3936 case 16: SizeIndex = 4; break; 3937 default: 3938 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size) 3939 << FirstArg->getType() << FirstArg->getSourceRange(); 3940 return ExprError(); 3941 } 3942 3943 // Each of these builtins has one pointer argument, followed by some number of 3944 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 3945 // that we ignore. Find out which row of BuiltinIndices to read from as well 3946 // as the number of fixed args. 3947 unsigned BuiltinID = FDecl->getBuiltinID(); 3948 unsigned BuiltinIndex, NumFixed = 1; 3949 bool WarnAboutSemanticsChange = false; 3950 switch (BuiltinID) { 3951 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 3952 case Builtin::BI__sync_fetch_and_add: 3953 case Builtin::BI__sync_fetch_and_add_1: 3954 case Builtin::BI__sync_fetch_and_add_2: 3955 case Builtin::BI__sync_fetch_and_add_4: 3956 case Builtin::BI__sync_fetch_and_add_8: 3957 case Builtin::BI__sync_fetch_and_add_16: 3958 BuiltinIndex = 0; 3959 break; 3960 3961 case Builtin::BI__sync_fetch_and_sub: 3962 case Builtin::BI__sync_fetch_and_sub_1: 3963 case Builtin::BI__sync_fetch_and_sub_2: 3964 case Builtin::BI__sync_fetch_and_sub_4: 3965 case Builtin::BI__sync_fetch_and_sub_8: 3966 case Builtin::BI__sync_fetch_and_sub_16: 3967 BuiltinIndex = 1; 3968 break; 3969 3970 case Builtin::BI__sync_fetch_and_or: 3971 case Builtin::BI__sync_fetch_and_or_1: 3972 case Builtin::BI__sync_fetch_and_or_2: 3973 case Builtin::BI__sync_fetch_and_or_4: 3974 case Builtin::BI__sync_fetch_and_or_8: 3975 case Builtin::BI__sync_fetch_and_or_16: 3976 BuiltinIndex = 2; 3977 break; 3978 3979 case Builtin::BI__sync_fetch_and_and: 3980 case Builtin::BI__sync_fetch_and_and_1: 3981 case Builtin::BI__sync_fetch_and_and_2: 3982 case Builtin::BI__sync_fetch_and_and_4: 3983 case Builtin::BI__sync_fetch_and_and_8: 3984 case Builtin::BI__sync_fetch_and_and_16: 3985 BuiltinIndex = 3; 3986 break; 3987 3988 case Builtin::BI__sync_fetch_and_xor: 3989 case Builtin::BI__sync_fetch_and_xor_1: 3990 case Builtin::BI__sync_fetch_and_xor_2: 3991 case Builtin::BI__sync_fetch_and_xor_4: 3992 case Builtin::BI__sync_fetch_and_xor_8: 3993 case Builtin::BI__sync_fetch_and_xor_16: 3994 BuiltinIndex = 4; 3995 break; 3996 3997 case Builtin::BI__sync_fetch_and_nand: 3998 case Builtin::BI__sync_fetch_and_nand_1: 3999 case Builtin::BI__sync_fetch_and_nand_2: 4000 case Builtin::BI__sync_fetch_and_nand_4: 4001 case Builtin::BI__sync_fetch_and_nand_8: 4002 case Builtin::BI__sync_fetch_and_nand_16: 4003 BuiltinIndex = 5; 4004 WarnAboutSemanticsChange = true; 4005 break; 4006 4007 case Builtin::BI__sync_add_and_fetch: 4008 case Builtin::BI__sync_add_and_fetch_1: 4009 case Builtin::BI__sync_add_and_fetch_2: 4010 case Builtin::BI__sync_add_and_fetch_4: 4011 case Builtin::BI__sync_add_and_fetch_8: 4012 case Builtin::BI__sync_add_and_fetch_16: 4013 BuiltinIndex = 6; 4014 break; 4015 4016 case Builtin::BI__sync_sub_and_fetch: 4017 case Builtin::BI__sync_sub_and_fetch_1: 4018 case Builtin::BI__sync_sub_and_fetch_2: 4019 case Builtin::BI__sync_sub_and_fetch_4: 4020 case Builtin::BI__sync_sub_and_fetch_8: 4021 case Builtin::BI__sync_sub_and_fetch_16: 4022 BuiltinIndex = 7; 4023 break; 4024 4025 case Builtin::BI__sync_and_and_fetch: 4026 case Builtin::BI__sync_and_and_fetch_1: 4027 case Builtin::BI__sync_and_and_fetch_2: 4028 case Builtin::BI__sync_and_and_fetch_4: 4029 case Builtin::BI__sync_and_and_fetch_8: 4030 case Builtin::BI__sync_and_and_fetch_16: 4031 BuiltinIndex = 8; 4032 break; 4033 4034 case Builtin::BI__sync_or_and_fetch: 4035 case Builtin::BI__sync_or_and_fetch_1: 4036 case Builtin::BI__sync_or_and_fetch_2: 4037 case Builtin::BI__sync_or_and_fetch_4: 4038 case Builtin::BI__sync_or_and_fetch_8: 4039 case Builtin::BI__sync_or_and_fetch_16: 4040 BuiltinIndex = 9; 4041 break; 4042 4043 case Builtin::BI__sync_xor_and_fetch: 4044 case Builtin::BI__sync_xor_and_fetch_1: 4045 case Builtin::BI__sync_xor_and_fetch_2: 4046 case Builtin::BI__sync_xor_and_fetch_4: 4047 case Builtin::BI__sync_xor_and_fetch_8: 4048 case Builtin::BI__sync_xor_and_fetch_16: 4049 BuiltinIndex = 10; 4050 break; 4051 4052 case Builtin::BI__sync_nand_and_fetch: 4053 case Builtin::BI__sync_nand_and_fetch_1: 4054 case Builtin::BI__sync_nand_and_fetch_2: 4055 case Builtin::BI__sync_nand_and_fetch_4: 4056 case Builtin::BI__sync_nand_and_fetch_8: 4057 case Builtin::BI__sync_nand_and_fetch_16: 4058 BuiltinIndex = 11; 4059 WarnAboutSemanticsChange = true; 4060 break; 4061 4062 case Builtin::BI__sync_val_compare_and_swap: 4063 case Builtin::BI__sync_val_compare_and_swap_1: 4064 case Builtin::BI__sync_val_compare_and_swap_2: 4065 case Builtin::BI__sync_val_compare_and_swap_4: 4066 case Builtin::BI__sync_val_compare_and_swap_8: 4067 case Builtin::BI__sync_val_compare_and_swap_16: 4068 BuiltinIndex = 12; 4069 NumFixed = 2; 4070 break; 4071 4072 case Builtin::BI__sync_bool_compare_and_swap: 4073 case Builtin::BI__sync_bool_compare_and_swap_1: 4074 case Builtin::BI__sync_bool_compare_and_swap_2: 4075 case Builtin::BI__sync_bool_compare_and_swap_4: 4076 case Builtin::BI__sync_bool_compare_and_swap_8: 4077 case Builtin::BI__sync_bool_compare_and_swap_16: 4078 BuiltinIndex = 13; 4079 NumFixed = 2; 4080 ResultType = Context.BoolTy; 4081 break; 4082 4083 case Builtin::BI__sync_lock_test_and_set: 4084 case Builtin::BI__sync_lock_test_and_set_1: 4085 case Builtin::BI__sync_lock_test_and_set_2: 4086 case Builtin::BI__sync_lock_test_and_set_4: 4087 case Builtin::BI__sync_lock_test_and_set_8: 4088 case Builtin::BI__sync_lock_test_and_set_16: 4089 BuiltinIndex = 14; 4090 break; 4091 4092 case Builtin::BI__sync_lock_release: 4093 case Builtin::BI__sync_lock_release_1: 4094 case Builtin::BI__sync_lock_release_2: 4095 case Builtin::BI__sync_lock_release_4: 4096 case Builtin::BI__sync_lock_release_8: 4097 case Builtin::BI__sync_lock_release_16: 4098 BuiltinIndex = 15; 4099 NumFixed = 0; 4100 ResultType = Context.VoidTy; 4101 break; 4102 4103 case Builtin::BI__sync_swap: 4104 case Builtin::BI__sync_swap_1: 4105 case Builtin::BI__sync_swap_2: 4106 case Builtin::BI__sync_swap_4: 4107 case Builtin::BI__sync_swap_8: 4108 case Builtin::BI__sync_swap_16: 4109 BuiltinIndex = 16; 4110 break; 4111 } 4112 4113 // Now that we know how many fixed arguments we expect, first check that we 4114 // have at least that many. 4115 if (TheCall->getNumArgs() < 1+NumFixed) { 4116 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 4117 << 0 << 1+NumFixed << TheCall->getNumArgs() 4118 << TheCall->getCallee()->getSourceRange(); 4119 return ExprError(); 4120 } 4121 4122 if (WarnAboutSemanticsChange) { 4123 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change) 4124 << TheCall->getCallee()->getSourceRange(); 4125 } 4126 4127 // Get the decl for the concrete builtin from this, we can tell what the 4128 // concrete integer type we should convert to is. 4129 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 4130 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 4131 FunctionDecl *NewBuiltinDecl; 4132 if (NewBuiltinID == BuiltinID) 4133 NewBuiltinDecl = FDecl; 4134 else { 4135 // Perform builtin lookup to avoid redeclaring it. 4136 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 4137 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName); 4138 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 4139 assert(Res.getFoundDecl()); 4140 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 4141 if (!NewBuiltinDecl) 4142 return ExprError(); 4143 } 4144 4145 // The first argument --- the pointer --- has a fixed type; we 4146 // deduce the types of the rest of the arguments accordingly. Walk 4147 // the remaining arguments, converting them to the deduced value type. 4148 for (unsigned i = 0; i != NumFixed; ++i) { 4149 ExprResult Arg = TheCall->getArg(i+1); 4150 4151 // GCC does an implicit conversion to the pointer or integer ValType. This 4152 // can fail in some cases (1i -> int**), check for this error case now. 4153 // Initialize the argument. 4154 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 4155 ValType, /*consume*/ false); 4156 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4157 if (Arg.isInvalid()) 4158 return ExprError(); 4159 4160 // Okay, we have something that *can* be converted to the right type. Check 4161 // to see if there is a potentially weird extension going on here. This can 4162 // happen when you do an atomic operation on something like an char* and 4163 // pass in 42. The 42 gets converted to char. This is even more strange 4164 // for things like 45.123 -> char, etc. 4165 // FIXME: Do this check. 4166 TheCall->setArg(i+1, Arg.get()); 4167 } 4168 4169 ASTContext& Context = this->getASTContext(); 4170 4171 // Create a new DeclRefExpr to refer to the new decl. 4172 DeclRefExpr* NewDRE = DeclRefExpr::Create( 4173 Context, 4174 DRE->getQualifierLoc(), 4175 SourceLocation(), 4176 NewBuiltinDecl, 4177 /*enclosing*/ false, 4178 DRE->getLocation(), 4179 Context.BuiltinFnTy, 4180 DRE->getValueKind()); 4181 4182 // Set the callee in the CallExpr. 4183 // FIXME: This loses syntactic information. 4184 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 4185 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 4186 CK_BuiltinFnToFnPtr); 4187 TheCall->setCallee(PromotedCall.get()); 4188 4189 // Change the result type of the call to match the original value type. This 4190 // is arbitrary, but the codegen for these builtins ins design to handle it 4191 // gracefully. 4192 TheCall->setType(ResultType); 4193 4194 return TheCallResult; 4195 } 4196 4197 /// SemaBuiltinNontemporalOverloaded - We have a call to 4198 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 4199 /// overloaded function based on the pointer type of its last argument. 4200 /// 4201 /// This function goes through and does final semantic checking for these 4202 /// builtins. 4203 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 4204 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 4205 DeclRefExpr *DRE = 4206 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4207 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 4208 unsigned BuiltinID = FDecl->getBuiltinID(); 4209 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 4210 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 4211 "Unexpected nontemporal load/store builtin!"); 4212 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 4213 unsigned numArgs = isStore ? 2 : 1; 4214 4215 // Ensure that we have the proper number of arguments. 4216 if (checkArgCount(*this, TheCall, numArgs)) 4217 return ExprError(); 4218 4219 // Inspect the last argument of the nontemporal builtin. This should always 4220 // be a pointer type, from which we imply the type of the memory access. 4221 // Because it is a pointer type, we don't have to worry about any implicit 4222 // casts here. 4223 Expr *PointerArg = TheCall->getArg(numArgs - 1); 4224 ExprResult PointerArgResult = 4225 DefaultFunctionArrayLvalueConversion(PointerArg); 4226 4227 if (PointerArgResult.isInvalid()) 4228 return ExprError(); 4229 PointerArg = PointerArgResult.get(); 4230 TheCall->setArg(numArgs - 1, PointerArg); 4231 4232 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 4233 if (!pointerType) { 4234 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer) 4235 << PointerArg->getType() << PointerArg->getSourceRange(); 4236 return ExprError(); 4237 } 4238 4239 QualType ValType = pointerType->getPointeeType(); 4240 4241 // Strip any qualifiers off ValType. 4242 ValType = ValType.getUnqualifiedType(); 4243 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 4244 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 4245 !ValType->isVectorType()) { 4246 Diag(DRE->getLocStart(), 4247 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 4248 << PointerArg->getType() << PointerArg->getSourceRange(); 4249 return ExprError(); 4250 } 4251 4252 if (!isStore) { 4253 TheCall->setType(ValType); 4254 return TheCallResult; 4255 } 4256 4257 ExprResult ValArg = TheCall->getArg(0); 4258 InitializedEntity Entity = InitializedEntity::InitializeParameter( 4259 Context, ValType, /*consume*/ false); 4260 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 4261 if (ValArg.isInvalid()) 4262 return ExprError(); 4263 4264 TheCall->setArg(0, ValArg.get()); 4265 TheCall->setType(Context.VoidTy); 4266 return TheCallResult; 4267 } 4268 4269 /// CheckObjCString - Checks that the argument to the builtin 4270 /// CFString constructor is correct 4271 /// Note: It might also make sense to do the UTF-16 conversion here (would 4272 /// simplify the backend). 4273 bool Sema::CheckObjCString(Expr *Arg) { 4274 Arg = Arg->IgnoreParenCasts(); 4275 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 4276 4277 if (!Literal || !Literal->isAscii()) { 4278 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant) 4279 << Arg->getSourceRange(); 4280 return true; 4281 } 4282 4283 if (Literal->containsNonAsciiOrNull()) { 4284 StringRef String = Literal->getString(); 4285 unsigned NumBytes = String.size(); 4286 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 4287 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 4288 llvm::UTF16 *ToPtr = &ToBuf[0]; 4289 4290 llvm::ConversionResult Result = 4291 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 4292 ToPtr + NumBytes, llvm::strictConversion); 4293 // Check for conversion failure. 4294 if (Result != llvm::conversionOK) 4295 Diag(Arg->getLocStart(), 4296 diag::warn_cfstring_truncated) << Arg->getSourceRange(); 4297 } 4298 return false; 4299 } 4300 4301 /// CheckObjCString - Checks that the format string argument to the os_log() 4302 /// and os_trace() functions is correct, and converts it to const char *. 4303 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 4304 Arg = Arg->IgnoreParenCasts(); 4305 auto *Literal = dyn_cast<StringLiteral>(Arg); 4306 if (!Literal) { 4307 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 4308 Literal = ObjcLiteral->getString(); 4309 } 4310 } 4311 4312 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 4313 return ExprError( 4314 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant) 4315 << Arg->getSourceRange()); 4316 } 4317 4318 ExprResult Result(Literal); 4319 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 4320 InitializedEntity Entity = 4321 InitializedEntity::InitializeParameter(Context, ResultTy, false); 4322 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 4323 return Result; 4324 } 4325 4326 /// Check that the user is calling the appropriate va_start builtin for the 4327 /// target and calling convention. 4328 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 4329 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 4330 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 4331 bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64; 4332 bool IsWindows = TT.isOSWindows(); 4333 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 4334 if (IsX64 || IsAArch64) { 4335 CallingConv CC = CC_C; 4336 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 4337 CC = FD->getType()->getAs<FunctionType>()->getCallConv(); 4338 if (IsMSVAStart) { 4339 // Don't allow this in System V ABI functions. 4340 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 4341 return S.Diag(Fn->getLocStart(), 4342 diag::err_ms_va_start_used_in_sysv_function); 4343 } else { 4344 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 4345 // On x64 Windows, don't allow this in System V ABI functions. 4346 // (Yes, that means there's no corresponding way to support variadic 4347 // System V ABI functions on Windows.) 4348 if ((IsWindows && CC == CC_X86_64SysV) || 4349 (!IsWindows && CC == CC_Win64)) 4350 return S.Diag(Fn->getLocStart(), 4351 diag::err_va_start_used_in_wrong_abi_function) 4352 << !IsWindows; 4353 } 4354 return false; 4355 } 4356 4357 if (IsMSVAStart) 4358 return S.Diag(Fn->getLocStart(), diag::err_builtin_x64_aarch64_only); 4359 return false; 4360 } 4361 4362 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 4363 ParmVarDecl **LastParam = nullptr) { 4364 // Determine whether the current function, block, or obj-c method is variadic 4365 // and get its parameter list. 4366 bool IsVariadic = false; 4367 ArrayRef<ParmVarDecl *> Params; 4368 DeclContext *Caller = S.CurContext; 4369 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 4370 IsVariadic = Block->isVariadic(); 4371 Params = Block->parameters(); 4372 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 4373 IsVariadic = FD->isVariadic(); 4374 Params = FD->parameters(); 4375 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 4376 IsVariadic = MD->isVariadic(); 4377 // FIXME: This isn't correct for methods (results in bogus warning). 4378 Params = MD->parameters(); 4379 } else if (isa<CapturedDecl>(Caller)) { 4380 // We don't support va_start in a CapturedDecl. 4381 S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt); 4382 return true; 4383 } else { 4384 // This must be some other declcontext that parses exprs. 4385 S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function); 4386 return true; 4387 } 4388 4389 if (!IsVariadic) { 4390 S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function); 4391 return true; 4392 } 4393 4394 if (LastParam) 4395 *LastParam = Params.empty() ? nullptr : Params.back(); 4396 4397 return false; 4398 } 4399 4400 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 4401 /// for validity. Emit an error and return true on failure; return false 4402 /// on success. 4403 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 4404 Expr *Fn = TheCall->getCallee(); 4405 4406 if (checkVAStartABI(*this, BuiltinID, Fn)) 4407 return true; 4408 4409 if (TheCall->getNumArgs() > 2) { 4410 Diag(TheCall->getArg(2)->getLocStart(), 4411 diag::err_typecheck_call_too_many_args) 4412 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 4413 << Fn->getSourceRange() 4414 << SourceRange(TheCall->getArg(2)->getLocStart(), 4415 (*(TheCall->arg_end()-1))->getLocEnd()); 4416 return true; 4417 } 4418 4419 if (TheCall->getNumArgs() < 2) { 4420 return Diag(TheCall->getLocEnd(), 4421 diag::err_typecheck_call_too_few_args_at_least) 4422 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 4423 } 4424 4425 // Type-check the first argument normally. 4426 if (checkBuiltinArgument(*this, TheCall, 0)) 4427 return true; 4428 4429 // Check that the current function is variadic, and get its last parameter. 4430 ParmVarDecl *LastParam; 4431 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 4432 return true; 4433 4434 // Verify that the second argument to the builtin is the last argument of the 4435 // current function or method. 4436 bool SecondArgIsLastNamedArgument = false; 4437 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 4438 4439 // These are valid if SecondArgIsLastNamedArgument is false after the next 4440 // block. 4441 QualType Type; 4442 SourceLocation ParamLoc; 4443 bool IsCRegister = false; 4444 4445 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 4446 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 4447 SecondArgIsLastNamedArgument = PV == LastParam; 4448 4449 Type = PV->getType(); 4450 ParamLoc = PV->getLocation(); 4451 IsCRegister = 4452 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 4453 } 4454 } 4455 4456 if (!SecondArgIsLastNamedArgument) 4457 Diag(TheCall->getArg(1)->getLocStart(), 4458 diag::warn_second_arg_of_va_start_not_last_named_param); 4459 else if (IsCRegister || Type->isReferenceType() || 4460 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 4461 // Promotable integers are UB, but enumerations need a bit of 4462 // extra checking to see what their promotable type actually is. 4463 if (!Type->isPromotableIntegerType()) 4464 return false; 4465 if (!Type->isEnumeralType()) 4466 return true; 4467 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl(); 4468 return !(ED && 4469 Context.typesAreCompatible(ED->getPromotionType(), Type)); 4470 }()) { 4471 unsigned Reason = 0; 4472 if (Type->isReferenceType()) Reason = 1; 4473 else if (IsCRegister) Reason = 2; 4474 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason; 4475 Diag(ParamLoc, diag::note_parameter_type) << Type; 4476 } 4477 4478 TheCall->setType(Context.VoidTy); 4479 return false; 4480 } 4481 4482 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 4483 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 4484 // const char *named_addr); 4485 4486 Expr *Func = Call->getCallee(); 4487 4488 if (Call->getNumArgs() < 3) 4489 return Diag(Call->getLocEnd(), 4490 diag::err_typecheck_call_too_few_args_at_least) 4491 << 0 /*function call*/ << 3 << Call->getNumArgs(); 4492 4493 // Type-check the first argument normally. 4494 if (checkBuiltinArgument(*this, Call, 0)) 4495 return true; 4496 4497 // Check that the current function is variadic. 4498 if (checkVAStartIsInVariadicFunction(*this, Func)) 4499 return true; 4500 4501 // __va_start on Windows does not validate the parameter qualifiers 4502 4503 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 4504 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 4505 4506 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 4507 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 4508 4509 const QualType &ConstCharPtrTy = 4510 Context.getPointerType(Context.CharTy.withConst()); 4511 if (!Arg1Ty->isPointerType() || 4512 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy) 4513 Diag(Arg1->getLocStart(), diag::err_typecheck_convert_incompatible) 4514 << Arg1->getType() << ConstCharPtrTy 4515 << 1 /* different class */ 4516 << 0 /* qualifier difference */ 4517 << 3 /* parameter mismatch */ 4518 << 2 << Arg1->getType() << ConstCharPtrTy; 4519 4520 const QualType SizeTy = Context.getSizeType(); 4521 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 4522 Diag(Arg2->getLocStart(), diag::err_typecheck_convert_incompatible) 4523 << Arg2->getType() << SizeTy 4524 << 1 /* different class */ 4525 << 0 /* qualifier difference */ 4526 << 3 /* parameter mismatch */ 4527 << 3 << Arg2->getType() << SizeTy; 4528 4529 return false; 4530 } 4531 4532 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 4533 /// friends. This is declared to take (...), so we have to check everything. 4534 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 4535 if (TheCall->getNumArgs() < 2) 4536 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 4537 << 0 << 2 << TheCall->getNumArgs()/*function call*/; 4538 if (TheCall->getNumArgs() > 2) 4539 return Diag(TheCall->getArg(2)->getLocStart(), 4540 diag::err_typecheck_call_too_many_args) 4541 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 4542 << SourceRange(TheCall->getArg(2)->getLocStart(), 4543 (*(TheCall->arg_end()-1))->getLocEnd()); 4544 4545 ExprResult OrigArg0 = TheCall->getArg(0); 4546 ExprResult OrigArg1 = TheCall->getArg(1); 4547 4548 // Do standard promotions between the two arguments, returning their common 4549 // type. 4550 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false); 4551 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 4552 return true; 4553 4554 // Make sure any conversions are pushed back into the call; this is 4555 // type safe since unordered compare builtins are declared as "_Bool 4556 // foo(...)". 4557 TheCall->setArg(0, OrigArg0.get()); 4558 TheCall->setArg(1, OrigArg1.get()); 4559 4560 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 4561 return false; 4562 4563 // If the common type isn't a real floating type, then the arguments were 4564 // invalid for this operation. 4565 if (Res.isNull() || !Res->isRealFloatingType()) 4566 return Diag(OrigArg0.get()->getLocStart(), 4567 diag::err_typecheck_call_invalid_ordered_compare) 4568 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 4569 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd()); 4570 4571 return false; 4572 } 4573 4574 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 4575 /// __builtin_isnan and friends. This is declared to take (...), so we have 4576 /// to check everything. We expect the last argument to be a floating point 4577 /// value. 4578 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 4579 if (TheCall->getNumArgs() < NumArgs) 4580 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 4581 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/; 4582 if (TheCall->getNumArgs() > NumArgs) 4583 return Diag(TheCall->getArg(NumArgs)->getLocStart(), 4584 diag::err_typecheck_call_too_many_args) 4585 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 4586 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(), 4587 (*(TheCall->arg_end()-1))->getLocEnd()); 4588 4589 Expr *OrigArg = TheCall->getArg(NumArgs-1); 4590 4591 if (OrigArg->isTypeDependent()) 4592 return false; 4593 4594 // This operation requires a non-_Complex floating-point number. 4595 if (!OrigArg->getType()->isRealFloatingType()) 4596 return Diag(OrigArg->getLocStart(), 4597 diag::err_typecheck_call_invalid_unary_fp) 4598 << OrigArg->getType() << OrigArg->getSourceRange(); 4599 4600 // If this is an implicit conversion from float -> float, double, or 4601 // long double, remove it. 4602 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) { 4603 // Only remove standard FloatCasts, leaving other casts inplace 4604 if (Cast->getCastKind() == CK_FloatingCast) { 4605 Expr *CastArg = Cast->getSubExpr(); 4606 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) { 4607 assert( 4608 (Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) || 4609 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float) || 4610 Cast->getType()->isSpecificBuiltinType(BuiltinType::LongDouble)) && 4611 "promotion from float to either float, double, or long double is " 4612 "the only expected cast here"); 4613 Cast->setSubExpr(nullptr); 4614 TheCall->setArg(NumArgs-1, CastArg); 4615 } 4616 } 4617 } 4618 4619 return false; 4620 } 4621 4622 // Customized Sema Checking for VSX builtins that have the following signature: 4623 // vector [...] builtinName(vector [...], vector [...], const int); 4624 // Which takes the same type of vectors (any legal vector type) for the first 4625 // two arguments and takes compile time constant for the third argument. 4626 // Example builtins are : 4627 // vector double vec_xxpermdi(vector double, vector double, int); 4628 // vector short vec_xxsldwi(vector short, vector short, int); 4629 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 4630 unsigned ExpectedNumArgs = 3; 4631 if (TheCall->getNumArgs() < ExpectedNumArgs) 4632 return Diag(TheCall->getLocEnd(), 4633 diag::err_typecheck_call_too_few_args_at_least) 4634 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 4635 << TheCall->getSourceRange(); 4636 4637 if (TheCall->getNumArgs() > ExpectedNumArgs) 4638 return Diag(TheCall->getLocEnd(), 4639 diag::err_typecheck_call_too_many_args_at_most) 4640 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 4641 << TheCall->getSourceRange(); 4642 4643 // Check the third argument is a compile time constant 4644 llvm::APSInt Value; 4645 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context)) 4646 return Diag(TheCall->getLocStart(), 4647 diag::err_vsx_builtin_nonconstant_argument) 4648 << 3 /* argument index */ << TheCall->getDirectCallee() 4649 << SourceRange(TheCall->getArg(2)->getLocStart(), 4650 TheCall->getArg(2)->getLocEnd()); 4651 4652 QualType Arg1Ty = TheCall->getArg(0)->getType(); 4653 QualType Arg2Ty = TheCall->getArg(1)->getType(); 4654 4655 // Check the type of argument 1 and argument 2 are vectors. 4656 SourceLocation BuiltinLoc = TheCall->getLocStart(); 4657 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 4658 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 4659 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 4660 << TheCall->getDirectCallee() 4661 << SourceRange(TheCall->getArg(0)->getLocStart(), 4662 TheCall->getArg(1)->getLocEnd()); 4663 } 4664 4665 // Check the first two arguments are the same type. 4666 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 4667 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 4668 << TheCall->getDirectCallee() 4669 << SourceRange(TheCall->getArg(0)->getLocStart(), 4670 TheCall->getArg(1)->getLocEnd()); 4671 } 4672 4673 // When default clang type checking is turned off and the customized type 4674 // checking is used, the returning type of the function must be explicitly 4675 // set. Otherwise it is _Bool by default. 4676 TheCall->setType(Arg1Ty); 4677 4678 return false; 4679 } 4680 4681 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 4682 // This is declared to take (...), so we have to check everything. 4683 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 4684 if (TheCall->getNumArgs() < 2) 4685 return ExprError(Diag(TheCall->getLocEnd(), 4686 diag::err_typecheck_call_too_few_args_at_least) 4687 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 4688 << TheCall->getSourceRange()); 4689 4690 // Determine which of the following types of shufflevector we're checking: 4691 // 1) unary, vector mask: (lhs, mask) 4692 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 4693 QualType resType = TheCall->getArg(0)->getType(); 4694 unsigned numElements = 0; 4695 4696 if (!TheCall->getArg(0)->isTypeDependent() && 4697 !TheCall->getArg(1)->isTypeDependent()) { 4698 QualType LHSType = TheCall->getArg(0)->getType(); 4699 QualType RHSType = TheCall->getArg(1)->getType(); 4700 4701 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 4702 return ExprError(Diag(TheCall->getLocStart(), 4703 diag::err_vec_builtin_non_vector) 4704 << TheCall->getDirectCallee() 4705 << SourceRange(TheCall->getArg(0)->getLocStart(), 4706 TheCall->getArg(1)->getLocEnd())); 4707 4708 numElements = LHSType->getAs<VectorType>()->getNumElements(); 4709 unsigned numResElements = TheCall->getNumArgs() - 2; 4710 4711 // Check to see if we have a call with 2 vector arguments, the unary shuffle 4712 // with mask. If so, verify that RHS is an integer vector type with the 4713 // same number of elts as lhs. 4714 if (TheCall->getNumArgs() == 2) { 4715 if (!RHSType->hasIntegerRepresentation() || 4716 RHSType->getAs<VectorType>()->getNumElements() != numElements) 4717 return ExprError(Diag(TheCall->getLocStart(), 4718 diag::err_vec_builtin_incompatible_vector) 4719 << TheCall->getDirectCallee() 4720 << SourceRange(TheCall->getArg(1)->getLocStart(), 4721 TheCall->getArg(1)->getLocEnd())); 4722 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 4723 return ExprError(Diag(TheCall->getLocStart(), 4724 diag::err_vec_builtin_incompatible_vector) 4725 << TheCall->getDirectCallee() 4726 << SourceRange(TheCall->getArg(0)->getLocStart(), 4727 TheCall->getArg(1)->getLocEnd())); 4728 } else if (numElements != numResElements) { 4729 QualType eltType = LHSType->getAs<VectorType>()->getElementType(); 4730 resType = Context.getVectorType(eltType, numResElements, 4731 VectorType::GenericVector); 4732 } 4733 } 4734 4735 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 4736 if (TheCall->getArg(i)->isTypeDependent() || 4737 TheCall->getArg(i)->isValueDependent()) 4738 continue; 4739 4740 llvm::APSInt Result(32); 4741 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 4742 return ExprError(Diag(TheCall->getLocStart(), 4743 diag::err_shufflevector_nonconstant_argument) 4744 << TheCall->getArg(i)->getSourceRange()); 4745 4746 // Allow -1 which will be translated to undef in the IR. 4747 if (Result.isSigned() && Result.isAllOnesValue()) 4748 continue; 4749 4750 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 4751 return ExprError(Diag(TheCall->getLocStart(), 4752 diag::err_shufflevector_argument_too_large) 4753 << TheCall->getArg(i)->getSourceRange()); 4754 } 4755 4756 SmallVector<Expr*, 32> exprs; 4757 4758 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 4759 exprs.push_back(TheCall->getArg(i)); 4760 TheCall->setArg(i, nullptr); 4761 } 4762 4763 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 4764 TheCall->getCallee()->getLocStart(), 4765 TheCall->getRParenLoc()); 4766 } 4767 4768 /// SemaConvertVectorExpr - Handle __builtin_convertvector 4769 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 4770 SourceLocation BuiltinLoc, 4771 SourceLocation RParenLoc) { 4772 ExprValueKind VK = VK_RValue; 4773 ExprObjectKind OK = OK_Ordinary; 4774 QualType DstTy = TInfo->getType(); 4775 QualType SrcTy = E->getType(); 4776 4777 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 4778 return ExprError(Diag(BuiltinLoc, 4779 diag::err_convertvector_non_vector) 4780 << E->getSourceRange()); 4781 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 4782 return ExprError(Diag(BuiltinLoc, 4783 diag::err_convertvector_non_vector_type)); 4784 4785 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 4786 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements(); 4787 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements(); 4788 if (SrcElts != DstElts) 4789 return ExprError(Diag(BuiltinLoc, 4790 diag::err_convertvector_incompatible_vector) 4791 << E->getSourceRange()); 4792 } 4793 4794 return new (Context) 4795 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 4796 } 4797 4798 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 4799 // This is declared to take (const void*, ...) and can take two 4800 // optional constant int args. 4801 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 4802 unsigned NumArgs = TheCall->getNumArgs(); 4803 4804 if (NumArgs > 3) 4805 return Diag(TheCall->getLocEnd(), 4806 diag::err_typecheck_call_too_many_args_at_most) 4807 << 0 /*function call*/ << 3 << NumArgs 4808 << TheCall->getSourceRange(); 4809 4810 // Argument 0 is checked for us and the remaining arguments must be 4811 // constant integers. 4812 for (unsigned i = 1; i != NumArgs; ++i) 4813 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 4814 return true; 4815 4816 return false; 4817 } 4818 4819 /// SemaBuiltinAssume - Handle __assume (MS Extension). 4820 // __assume does not evaluate its arguments, and should warn if its argument 4821 // has side effects. 4822 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 4823 Expr *Arg = TheCall->getArg(0); 4824 if (Arg->isInstantiationDependent()) return false; 4825 4826 if (Arg->HasSideEffects(Context)) 4827 Diag(Arg->getLocStart(), diag::warn_assume_side_effects) 4828 << Arg->getSourceRange() 4829 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 4830 4831 return false; 4832 } 4833 4834 /// Handle __builtin_alloca_with_align. This is declared 4835 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 4836 /// than 8. 4837 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 4838 // The alignment must be a constant integer. 4839 Expr *Arg = TheCall->getArg(1); 4840 4841 // We can't check the value of a dependent argument. 4842 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 4843 if (const auto *UE = 4844 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 4845 if (UE->getKind() == UETT_AlignOf) 4846 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof) 4847 << Arg->getSourceRange(); 4848 4849 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 4850 4851 if (!Result.isPowerOf2()) 4852 return Diag(TheCall->getLocStart(), 4853 diag::err_alignment_not_power_of_two) 4854 << Arg->getSourceRange(); 4855 4856 if (Result < Context.getCharWidth()) 4857 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small) 4858 << (unsigned)Context.getCharWidth() 4859 << Arg->getSourceRange(); 4860 4861 if (Result > std::numeric_limits<int32_t>::max()) 4862 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big) 4863 << std::numeric_limits<int32_t>::max() 4864 << Arg->getSourceRange(); 4865 } 4866 4867 return false; 4868 } 4869 4870 /// Handle __builtin_assume_aligned. This is declared 4871 /// as (const void*, size_t, ...) and can take one optional constant int arg. 4872 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 4873 unsigned NumArgs = TheCall->getNumArgs(); 4874 4875 if (NumArgs > 3) 4876 return Diag(TheCall->getLocEnd(), 4877 diag::err_typecheck_call_too_many_args_at_most) 4878 << 0 /*function call*/ << 3 << NumArgs 4879 << TheCall->getSourceRange(); 4880 4881 // The alignment must be a constant integer. 4882 Expr *Arg = TheCall->getArg(1); 4883 4884 // We can't check the value of a dependent argument. 4885 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 4886 llvm::APSInt Result; 4887 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 4888 return true; 4889 4890 if (!Result.isPowerOf2()) 4891 return Diag(TheCall->getLocStart(), 4892 diag::err_alignment_not_power_of_two) 4893 << Arg->getSourceRange(); 4894 } 4895 4896 if (NumArgs > 2) { 4897 ExprResult Arg(TheCall->getArg(2)); 4898 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 4899 Context.getSizeType(), false); 4900 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4901 if (Arg.isInvalid()) return true; 4902 TheCall->setArg(2, Arg.get()); 4903 } 4904 4905 return false; 4906 } 4907 4908 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 4909 unsigned BuiltinID = 4910 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 4911 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 4912 4913 unsigned NumArgs = TheCall->getNumArgs(); 4914 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 4915 if (NumArgs < NumRequiredArgs) { 4916 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 4917 << 0 /* function call */ << NumRequiredArgs << NumArgs 4918 << TheCall->getSourceRange(); 4919 } 4920 if (NumArgs >= NumRequiredArgs + 0x100) { 4921 return Diag(TheCall->getLocEnd(), 4922 diag::err_typecheck_call_too_many_args_at_most) 4923 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 4924 << TheCall->getSourceRange(); 4925 } 4926 unsigned i = 0; 4927 4928 // For formatting call, check buffer arg. 4929 if (!IsSizeCall) { 4930 ExprResult Arg(TheCall->getArg(i)); 4931 InitializedEntity Entity = InitializedEntity::InitializeParameter( 4932 Context, Context.VoidPtrTy, false); 4933 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4934 if (Arg.isInvalid()) 4935 return true; 4936 TheCall->setArg(i, Arg.get()); 4937 i++; 4938 } 4939 4940 // Check string literal arg. 4941 unsigned FormatIdx = i; 4942 { 4943 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 4944 if (Arg.isInvalid()) 4945 return true; 4946 TheCall->setArg(i, Arg.get()); 4947 i++; 4948 } 4949 4950 // Make sure variadic args are scalar. 4951 unsigned FirstDataArg = i; 4952 while (i < NumArgs) { 4953 ExprResult Arg = DefaultVariadicArgumentPromotion( 4954 TheCall->getArg(i), VariadicFunction, nullptr); 4955 if (Arg.isInvalid()) 4956 return true; 4957 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 4958 if (ArgSize.getQuantity() >= 0x100) { 4959 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big) 4960 << i << (int)ArgSize.getQuantity() << 0xff 4961 << TheCall->getSourceRange(); 4962 } 4963 TheCall->setArg(i, Arg.get()); 4964 i++; 4965 } 4966 4967 // Check formatting specifiers. NOTE: We're only doing this for the non-size 4968 // call to avoid duplicate diagnostics. 4969 if (!IsSizeCall) { 4970 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 4971 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 4972 bool Success = CheckFormatArguments( 4973 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 4974 VariadicFunction, TheCall->getLocStart(), SourceRange(), 4975 CheckedVarArgs); 4976 if (!Success) 4977 return true; 4978 } 4979 4980 if (IsSizeCall) { 4981 TheCall->setType(Context.getSizeType()); 4982 } else { 4983 TheCall->setType(Context.VoidPtrTy); 4984 } 4985 return false; 4986 } 4987 4988 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 4989 /// TheCall is a constant expression. 4990 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 4991 llvm::APSInt &Result) { 4992 Expr *Arg = TheCall->getArg(ArgNum); 4993 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4994 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 4995 4996 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 4997 4998 if (!Arg->isIntegerConstantExpr(Result, Context)) 4999 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type) 5000 << FDecl->getDeclName() << Arg->getSourceRange(); 5001 5002 return false; 5003 } 5004 5005 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 5006 /// TheCall is a constant expression in the range [Low, High]. 5007 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 5008 int Low, int High) { 5009 llvm::APSInt Result; 5010 5011 // We can't check the value of a dependent argument. 5012 Expr *Arg = TheCall->getArg(ArgNum); 5013 if (Arg->isTypeDependent() || Arg->isValueDependent()) 5014 return false; 5015 5016 // Check constant-ness first. 5017 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 5018 return true; 5019 5020 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) 5021 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 5022 << Low << High << Arg->getSourceRange(); 5023 5024 return false; 5025 } 5026 5027 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 5028 /// TheCall is a constant expression is a multiple of Num.. 5029 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 5030 unsigned Num) { 5031 llvm::APSInt Result; 5032 5033 // We can't check the value of a dependent argument. 5034 Expr *Arg = TheCall->getArg(ArgNum); 5035 if (Arg->isTypeDependent() || Arg->isValueDependent()) 5036 return false; 5037 5038 // Check constant-ness first. 5039 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 5040 return true; 5041 5042 if (Result.getSExtValue() % Num != 0) 5043 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple) 5044 << Num << Arg->getSourceRange(); 5045 5046 return false; 5047 } 5048 5049 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 5050 /// TheCall is an ARM/AArch64 special register string literal. 5051 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 5052 int ArgNum, unsigned ExpectedFieldNum, 5053 bool AllowName) { 5054 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 5055 BuiltinID == ARM::BI__builtin_arm_wsr64 || 5056 BuiltinID == ARM::BI__builtin_arm_rsr || 5057 BuiltinID == ARM::BI__builtin_arm_rsrp || 5058 BuiltinID == ARM::BI__builtin_arm_wsr || 5059 BuiltinID == ARM::BI__builtin_arm_wsrp; 5060 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 5061 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 5062 BuiltinID == AArch64::BI__builtin_arm_rsr || 5063 BuiltinID == AArch64::BI__builtin_arm_rsrp || 5064 BuiltinID == AArch64::BI__builtin_arm_wsr || 5065 BuiltinID == AArch64::BI__builtin_arm_wsrp; 5066 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 5067 5068 // We can't check the value of a dependent argument. 5069 Expr *Arg = TheCall->getArg(ArgNum); 5070 if (Arg->isTypeDependent() || Arg->isValueDependent()) 5071 return false; 5072 5073 // Check if the argument is a string literal. 5074 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 5075 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal) 5076 << Arg->getSourceRange(); 5077 5078 // Check the type of special register given. 5079 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 5080 SmallVector<StringRef, 6> Fields; 5081 Reg.split(Fields, ":"); 5082 5083 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 5084 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg) 5085 << Arg->getSourceRange(); 5086 5087 // If the string is the name of a register then we cannot check that it is 5088 // valid here but if the string is of one the forms described in ACLE then we 5089 // can check that the supplied fields are integers and within the valid 5090 // ranges. 5091 if (Fields.size() > 1) { 5092 bool FiveFields = Fields.size() == 5; 5093 5094 bool ValidString = true; 5095 if (IsARMBuiltin) { 5096 ValidString &= Fields[0].startswith_lower("cp") || 5097 Fields[0].startswith_lower("p"); 5098 if (ValidString) 5099 Fields[0] = 5100 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 5101 5102 ValidString &= Fields[2].startswith_lower("c"); 5103 if (ValidString) 5104 Fields[2] = Fields[2].drop_front(1); 5105 5106 if (FiveFields) { 5107 ValidString &= Fields[3].startswith_lower("c"); 5108 if (ValidString) 5109 Fields[3] = Fields[3].drop_front(1); 5110 } 5111 } 5112 5113 SmallVector<int, 5> Ranges; 5114 if (FiveFields) 5115 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 5116 else 5117 Ranges.append({15, 7, 15}); 5118 5119 for (unsigned i=0; i<Fields.size(); ++i) { 5120 int IntField; 5121 ValidString &= !Fields[i].getAsInteger(10, IntField); 5122 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 5123 } 5124 5125 if (!ValidString) 5126 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg) 5127 << Arg->getSourceRange(); 5128 } else if (IsAArch64Builtin && Fields.size() == 1) { 5129 // If the register name is one of those that appear in the condition below 5130 // and the special register builtin being used is one of the write builtins, 5131 // then we require that the argument provided for writing to the register 5132 // is an integer constant expression. This is because it will be lowered to 5133 // an MSR (immediate) instruction, so we need to know the immediate at 5134 // compile time. 5135 if (TheCall->getNumArgs() != 2) 5136 return false; 5137 5138 std::string RegLower = Reg.lower(); 5139 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 5140 RegLower != "pan" && RegLower != "uao") 5141 return false; 5142 5143 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 5144 } 5145 5146 return false; 5147 } 5148 5149 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 5150 /// This checks that the target supports __builtin_longjmp and 5151 /// that val is a constant 1. 5152 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 5153 if (!Context.getTargetInfo().hasSjLjLowering()) 5154 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported) 5155 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd()); 5156 5157 Expr *Arg = TheCall->getArg(1); 5158 llvm::APSInt Result; 5159 5160 // TODO: This is less than ideal. Overload this to take a value. 5161 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 5162 return true; 5163 5164 if (Result != 1) 5165 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val) 5166 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 5167 5168 return false; 5169 } 5170 5171 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 5172 /// This checks that the target supports __builtin_setjmp. 5173 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 5174 if (!Context.getTargetInfo().hasSjLjLowering()) 5175 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported) 5176 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd()); 5177 return false; 5178 } 5179 5180 namespace { 5181 5182 class UncoveredArgHandler { 5183 enum { Unknown = -1, AllCovered = -2 }; 5184 5185 signed FirstUncoveredArg = Unknown; 5186 SmallVector<const Expr *, 4> DiagnosticExprs; 5187 5188 public: 5189 UncoveredArgHandler() = default; 5190 5191 bool hasUncoveredArg() const { 5192 return (FirstUncoveredArg >= 0); 5193 } 5194 5195 unsigned getUncoveredArg() const { 5196 assert(hasUncoveredArg() && "no uncovered argument"); 5197 return FirstUncoveredArg; 5198 } 5199 5200 void setAllCovered() { 5201 // A string has been found with all arguments covered, so clear out 5202 // the diagnostics. 5203 DiagnosticExprs.clear(); 5204 FirstUncoveredArg = AllCovered; 5205 } 5206 5207 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 5208 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 5209 5210 // Don't update if a previous string covers all arguments. 5211 if (FirstUncoveredArg == AllCovered) 5212 return; 5213 5214 // UncoveredArgHandler tracks the highest uncovered argument index 5215 // and with it all the strings that match this index. 5216 if (NewFirstUncoveredArg == FirstUncoveredArg) 5217 DiagnosticExprs.push_back(StrExpr); 5218 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 5219 DiagnosticExprs.clear(); 5220 DiagnosticExprs.push_back(StrExpr); 5221 FirstUncoveredArg = NewFirstUncoveredArg; 5222 } 5223 } 5224 5225 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 5226 }; 5227 5228 enum StringLiteralCheckType { 5229 SLCT_NotALiteral, 5230 SLCT_UncheckedLiteral, 5231 SLCT_CheckedLiteral 5232 }; 5233 5234 } // namespace 5235 5236 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 5237 BinaryOperatorKind BinOpKind, 5238 bool AddendIsRight) { 5239 unsigned BitWidth = Offset.getBitWidth(); 5240 unsigned AddendBitWidth = Addend.getBitWidth(); 5241 // There might be negative interim results. 5242 if (Addend.isUnsigned()) { 5243 Addend = Addend.zext(++AddendBitWidth); 5244 Addend.setIsSigned(true); 5245 } 5246 // Adjust the bit width of the APSInts. 5247 if (AddendBitWidth > BitWidth) { 5248 Offset = Offset.sext(AddendBitWidth); 5249 BitWidth = AddendBitWidth; 5250 } else if (BitWidth > AddendBitWidth) { 5251 Addend = Addend.sext(BitWidth); 5252 } 5253 5254 bool Ov = false; 5255 llvm::APSInt ResOffset = Offset; 5256 if (BinOpKind == BO_Add) 5257 ResOffset = Offset.sadd_ov(Addend, Ov); 5258 else { 5259 assert(AddendIsRight && BinOpKind == BO_Sub && 5260 "operator must be add or sub with addend on the right"); 5261 ResOffset = Offset.ssub_ov(Addend, Ov); 5262 } 5263 5264 // We add an offset to a pointer here so we should support an offset as big as 5265 // possible. 5266 if (Ov) { 5267 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 5268 "index (intermediate) result too big"); 5269 Offset = Offset.sext(2 * BitWidth); 5270 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 5271 return; 5272 } 5273 5274 Offset = ResOffset; 5275 } 5276 5277 namespace { 5278 5279 // This is a wrapper class around StringLiteral to support offsetted string 5280 // literals as format strings. It takes the offset into account when returning 5281 // the string and its length or the source locations to display notes correctly. 5282 class FormatStringLiteral { 5283 const StringLiteral *FExpr; 5284 int64_t Offset; 5285 5286 public: 5287 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 5288 : FExpr(fexpr), Offset(Offset) {} 5289 5290 StringRef getString() const { 5291 return FExpr->getString().drop_front(Offset); 5292 } 5293 5294 unsigned getByteLength() const { 5295 return FExpr->getByteLength() - getCharByteWidth() * Offset; 5296 } 5297 5298 unsigned getLength() const { return FExpr->getLength() - Offset; } 5299 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 5300 5301 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 5302 5303 QualType getType() const { return FExpr->getType(); } 5304 5305 bool isAscii() const { return FExpr->isAscii(); } 5306 bool isWide() const { return FExpr->isWide(); } 5307 bool isUTF8() const { return FExpr->isUTF8(); } 5308 bool isUTF16() const { return FExpr->isUTF16(); } 5309 bool isUTF32() const { return FExpr->isUTF32(); } 5310 bool isPascal() const { return FExpr->isPascal(); } 5311 5312 SourceLocation getLocationOfByte( 5313 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 5314 const TargetInfo &Target, unsigned *StartToken = nullptr, 5315 unsigned *StartTokenByteOffset = nullptr) const { 5316 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 5317 StartToken, StartTokenByteOffset); 5318 } 5319 5320 SourceLocation getLocStart() const LLVM_READONLY { 5321 return FExpr->getLocStart().getLocWithOffset(Offset); 5322 } 5323 5324 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); } 5325 }; 5326 5327 } // namespace 5328 5329 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 5330 const Expr *OrigFormatExpr, 5331 ArrayRef<const Expr *> Args, 5332 bool HasVAListArg, unsigned format_idx, 5333 unsigned firstDataArg, 5334 Sema::FormatStringType Type, 5335 bool inFunctionCall, 5336 Sema::VariadicCallType CallType, 5337 llvm::SmallBitVector &CheckedVarArgs, 5338 UncoveredArgHandler &UncoveredArg); 5339 5340 // Determine if an expression is a string literal or constant string. 5341 // If this function returns false on the arguments to a function expecting a 5342 // format string, we will usually need to emit a warning. 5343 // True string literals are then checked by CheckFormatString. 5344 static StringLiteralCheckType 5345 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 5346 bool HasVAListArg, unsigned format_idx, 5347 unsigned firstDataArg, Sema::FormatStringType Type, 5348 Sema::VariadicCallType CallType, bool InFunctionCall, 5349 llvm::SmallBitVector &CheckedVarArgs, 5350 UncoveredArgHandler &UncoveredArg, 5351 llvm::APSInt Offset) { 5352 tryAgain: 5353 assert(Offset.isSigned() && "invalid offset"); 5354 5355 if (E->isTypeDependent() || E->isValueDependent()) 5356 return SLCT_NotALiteral; 5357 5358 E = E->IgnoreParenCasts(); 5359 5360 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 5361 // Technically -Wformat-nonliteral does not warn about this case. 5362 // The behavior of printf and friends in this case is implementation 5363 // dependent. Ideally if the format string cannot be null then 5364 // it should have a 'nonnull' attribute in the function prototype. 5365 return SLCT_UncheckedLiteral; 5366 5367 switch (E->getStmtClass()) { 5368 case Stmt::BinaryConditionalOperatorClass: 5369 case Stmt::ConditionalOperatorClass: { 5370 // The expression is a literal if both sub-expressions were, and it was 5371 // completely checked only if both sub-expressions were checked. 5372 const AbstractConditionalOperator *C = 5373 cast<AbstractConditionalOperator>(E); 5374 5375 // Determine whether it is necessary to check both sub-expressions, for 5376 // example, because the condition expression is a constant that can be 5377 // evaluated at compile time. 5378 bool CheckLeft = true, CheckRight = true; 5379 5380 bool Cond; 5381 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) { 5382 if (Cond) 5383 CheckRight = false; 5384 else 5385 CheckLeft = false; 5386 } 5387 5388 // We need to maintain the offsets for the right and the left hand side 5389 // separately to check if every possible indexed expression is a valid 5390 // string literal. They might have different offsets for different string 5391 // literals in the end. 5392 StringLiteralCheckType Left; 5393 if (!CheckLeft) 5394 Left = SLCT_UncheckedLiteral; 5395 else { 5396 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 5397 HasVAListArg, format_idx, firstDataArg, 5398 Type, CallType, InFunctionCall, 5399 CheckedVarArgs, UncoveredArg, Offset); 5400 if (Left == SLCT_NotALiteral || !CheckRight) { 5401 return Left; 5402 } 5403 } 5404 5405 StringLiteralCheckType Right = 5406 checkFormatStringExpr(S, C->getFalseExpr(), Args, 5407 HasVAListArg, format_idx, firstDataArg, 5408 Type, CallType, InFunctionCall, CheckedVarArgs, 5409 UncoveredArg, Offset); 5410 5411 return (CheckLeft && Left < Right) ? Left : Right; 5412 } 5413 5414 case Stmt::ImplicitCastExprClass: 5415 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 5416 goto tryAgain; 5417 5418 case Stmt::OpaqueValueExprClass: 5419 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 5420 E = src; 5421 goto tryAgain; 5422 } 5423 return SLCT_NotALiteral; 5424 5425 case Stmt::PredefinedExprClass: 5426 // While __func__, etc., are technically not string literals, they 5427 // cannot contain format specifiers and thus are not a security 5428 // liability. 5429 return SLCT_UncheckedLiteral; 5430 5431 case Stmt::DeclRefExprClass: { 5432 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 5433 5434 // As an exception, do not flag errors for variables binding to 5435 // const string literals. 5436 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 5437 bool isConstant = false; 5438 QualType T = DR->getType(); 5439 5440 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 5441 isConstant = AT->getElementType().isConstant(S.Context); 5442 } else if (const PointerType *PT = T->getAs<PointerType>()) { 5443 isConstant = T.isConstant(S.Context) && 5444 PT->getPointeeType().isConstant(S.Context); 5445 } else if (T->isObjCObjectPointerType()) { 5446 // In ObjC, there is usually no "const ObjectPointer" type, 5447 // so don't check if the pointee type is constant. 5448 isConstant = T.isConstant(S.Context); 5449 } 5450 5451 if (isConstant) { 5452 if (const Expr *Init = VD->getAnyInitializer()) { 5453 // Look through initializers like const char c[] = { "foo" } 5454 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 5455 if (InitList->isStringLiteralInit()) 5456 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 5457 } 5458 return checkFormatStringExpr(S, Init, Args, 5459 HasVAListArg, format_idx, 5460 firstDataArg, Type, CallType, 5461 /*InFunctionCall*/ false, CheckedVarArgs, 5462 UncoveredArg, Offset); 5463 } 5464 } 5465 5466 // For vprintf* functions (i.e., HasVAListArg==true), we add a 5467 // special check to see if the format string is a function parameter 5468 // of the function calling the printf function. If the function 5469 // has an attribute indicating it is a printf-like function, then we 5470 // should suppress warnings concerning non-literals being used in a call 5471 // to a vprintf function. For example: 5472 // 5473 // void 5474 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 5475 // va_list ap; 5476 // va_start(ap, fmt); 5477 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 5478 // ... 5479 // } 5480 if (HasVAListArg) { 5481 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 5482 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 5483 int PVIndex = PV->getFunctionScopeIndex() + 1; 5484 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 5485 // adjust for implicit parameter 5486 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 5487 if (MD->isInstance()) 5488 ++PVIndex; 5489 // We also check if the formats are compatible. 5490 // We can't pass a 'scanf' string to a 'printf' function. 5491 if (PVIndex == PVFormat->getFormatIdx() && 5492 Type == S.GetFormatStringType(PVFormat)) 5493 return SLCT_UncheckedLiteral; 5494 } 5495 } 5496 } 5497 } 5498 } 5499 5500 return SLCT_NotALiteral; 5501 } 5502 5503 case Stmt::CallExprClass: 5504 case Stmt::CXXMemberCallExprClass: { 5505 const CallExpr *CE = cast<CallExpr>(E); 5506 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 5507 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) { 5508 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 5509 return checkFormatStringExpr(S, Arg, Args, 5510 HasVAListArg, format_idx, firstDataArg, 5511 Type, CallType, InFunctionCall, 5512 CheckedVarArgs, UncoveredArg, Offset); 5513 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) { 5514 unsigned BuiltinID = FD->getBuiltinID(); 5515 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 5516 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 5517 const Expr *Arg = CE->getArg(0); 5518 return checkFormatStringExpr(S, Arg, Args, 5519 HasVAListArg, format_idx, 5520 firstDataArg, Type, CallType, 5521 InFunctionCall, CheckedVarArgs, 5522 UncoveredArg, Offset); 5523 } 5524 } 5525 } 5526 5527 return SLCT_NotALiteral; 5528 } 5529 case Stmt::ObjCMessageExprClass: { 5530 const auto *ME = cast<ObjCMessageExpr>(E); 5531 if (const auto *ND = ME->getMethodDecl()) { 5532 if (const auto *FA = ND->getAttr<FormatArgAttr>()) { 5533 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 5534 return checkFormatStringExpr( 5535 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 5536 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset); 5537 } 5538 } 5539 5540 return SLCT_NotALiteral; 5541 } 5542 case Stmt::ObjCStringLiteralClass: 5543 case Stmt::StringLiteralClass: { 5544 const StringLiteral *StrE = nullptr; 5545 5546 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 5547 StrE = ObjCFExpr->getString(); 5548 else 5549 StrE = cast<StringLiteral>(E); 5550 5551 if (StrE) { 5552 if (Offset.isNegative() || Offset > StrE->getLength()) { 5553 // TODO: It would be better to have an explicit warning for out of 5554 // bounds literals. 5555 return SLCT_NotALiteral; 5556 } 5557 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 5558 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 5559 firstDataArg, Type, InFunctionCall, CallType, 5560 CheckedVarArgs, UncoveredArg); 5561 return SLCT_CheckedLiteral; 5562 } 5563 5564 return SLCT_NotALiteral; 5565 } 5566 case Stmt::BinaryOperatorClass: { 5567 llvm::APSInt LResult; 5568 llvm::APSInt RResult; 5569 5570 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 5571 5572 // A string literal + an int offset is still a string literal. 5573 if (BinOp->isAdditiveOp()) { 5574 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context); 5575 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context); 5576 5577 if (LIsInt != RIsInt) { 5578 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 5579 5580 if (LIsInt) { 5581 if (BinOpKind == BO_Add) { 5582 sumOffsets(Offset, LResult, BinOpKind, RIsInt); 5583 E = BinOp->getRHS(); 5584 goto tryAgain; 5585 } 5586 } else { 5587 sumOffsets(Offset, RResult, BinOpKind, RIsInt); 5588 E = BinOp->getLHS(); 5589 goto tryAgain; 5590 } 5591 } 5592 } 5593 5594 return SLCT_NotALiteral; 5595 } 5596 case Stmt::UnaryOperatorClass: { 5597 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 5598 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 5599 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 5600 llvm::APSInt IndexResult; 5601 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) { 5602 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true); 5603 E = ASE->getBase(); 5604 goto tryAgain; 5605 } 5606 } 5607 5608 return SLCT_NotALiteral; 5609 } 5610 5611 default: 5612 return SLCT_NotALiteral; 5613 } 5614 } 5615 5616 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 5617 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 5618 .Case("scanf", FST_Scanf) 5619 .Cases("printf", "printf0", FST_Printf) 5620 .Cases("NSString", "CFString", FST_NSString) 5621 .Case("strftime", FST_Strftime) 5622 .Case("strfmon", FST_Strfmon) 5623 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 5624 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 5625 .Case("os_trace", FST_OSLog) 5626 .Case("os_log", FST_OSLog) 5627 .Default(FST_Unknown); 5628 } 5629 5630 /// CheckFormatArguments - Check calls to printf and scanf (and similar 5631 /// functions) for correct use of format strings. 5632 /// Returns true if a format string has been fully checked. 5633 bool Sema::CheckFormatArguments(const FormatAttr *Format, 5634 ArrayRef<const Expr *> Args, 5635 bool IsCXXMember, 5636 VariadicCallType CallType, 5637 SourceLocation Loc, SourceRange Range, 5638 llvm::SmallBitVector &CheckedVarArgs) { 5639 FormatStringInfo FSI; 5640 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 5641 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 5642 FSI.FirstDataArg, GetFormatStringType(Format), 5643 CallType, Loc, Range, CheckedVarArgs); 5644 return false; 5645 } 5646 5647 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 5648 bool HasVAListArg, unsigned format_idx, 5649 unsigned firstDataArg, FormatStringType Type, 5650 VariadicCallType CallType, 5651 SourceLocation Loc, SourceRange Range, 5652 llvm::SmallBitVector &CheckedVarArgs) { 5653 // CHECK: printf/scanf-like function is called with no format string. 5654 if (format_idx >= Args.size()) { 5655 Diag(Loc, diag::warn_missing_format_string) << Range; 5656 return false; 5657 } 5658 5659 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 5660 5661 // CHECK: format string is not a string literal. 5662 // 5663 // Dynamically generated format strings are difficult to 5664 // automatically vet at compile time. Requiring that format strings 5665 // are string literals: (1) permits the checking of format strings by 5666 // the compiler and thereby (2) can practically remove the source of 5667 // many format string exploits. 5668 5669 // Format string can be either ObjC string (e.g. @"%d") or 5670 // C string (e.g. "%d") 5671 // ObjC string uses the same format specifiers as C string, so we can use 5672 // the same format string checking logic for both ObjC and C strings. 5673 UncoveredArgHandler UncoveredArg; 5674 StringLiteralCheckType CT = 5675 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 5676 format_idx, firstDataArg, Type, CallType, 5677 /*IsFunctionCall*/ true, CheckedVarArgs, 5678 UncoveredArg, 5679 /*no string offset*/ llvm::APSInt(64, false) = 0); 5680 5681 // Generate a diagnostic where an uncovered argument is detected. 5682 if (UncoveredArg.hasUncoveredArg()) { 5683 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 5684 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 5685 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 5686 } 5687 5688 if (CT != SLCT_NotALiteral) 5689 // Literal format string found, check done! 5690 return CT == SLCT_CheckedLiteral; 5691 5692 // Strftime is particular as it always uses a single 'time' argument, 5693 // so it is safe to pass a non-literal string. 5694 if (Type == FST_Strftime) 5695 return false; 5696 5697 // Do not emit diag when the string param is a macro expansion and the 5698 // format is either NSString or CFString. This is a hack to prevent 5699 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 5700 // which are usually used in place of NS and CF string literals. 5701 SourceLocation FormatLoc = Args[format_idx]->getLocStart(); 5702 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 5703 return false; 5704 5705 // If there are no arguments specified, warn with -Wformat-security, otherwise 5706 // warn only with -Wformat-nonliteral. 5707 if (Args.size() == firstDataArg) { 5708 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 5709 << OrigFormatExpr->getSourceRange(); 5710 switch (Type) { 5711 default: 5712 break; 5713 case FST_Kprintf: 5714 case FST_FreeBSDKPrintf: 5715 case FST_Printf: 5716 Diag(FormatLoc, diag::note_format_security_fixit) 5717 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 5718 break; 5719 case FST_NSString: 5720 Diag(FormatLoc, diag::note_format_security_fixit) 5721 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 5722 break; 5723 } 5724 } else { 5725 Diag(FormatLoc, diag::warn_format_nonliteral) 5726 << OrigFormatExpr->getSourceRange(); 5727 } 5728 return false; 5729 } 5730 5731 namespace { 5732 5733 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 5734 protected: 5735 Sema &S; 5736 const FormatStringLiteral *FExpr; 5737 const Expr *OrigFormatExpr; 5738 const Sema::FormatStringType FSType; 5739 const unsigned FirstDataArg; 5740 const unsigned NumDataArgs; 5741 const char *Beg; // Start of format string. 5742 const bool HasVAListArg; 5743 ArrayRef<const Expr *> Args; 5744 unsigned FormatIdx; 5745 llvm::SmallBitVector CoveredArgs; 5746 bool usesPositionalArgs = false; 5747 bool atFirstArg = true; 5748 bool inFunctionCall; 5749 Sema::VariadicCallType CallType; 5750 llvm::SmallBitVector &CheckedVarArgs; 5751 UncoveredArgHandler &UncoveredArg; 5752 5753 public: 5754 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 5755 const Expr *origFormatExpr, 5756 const Sema::FormatStringType type, unsigned firstDataArg, 5757 unsigned numDataArgs, const char *beg, bool hasVAListArg, 5758 ArrayRef<const Expr *> Args, unsigned formatIdx, 5759 bool inFunctionCall, Sema::VariadicCallType callType, 5760 llvm::SmallBitVector &CheckedVarArgs, 5761 UncoveredArgHandler &UncoveredArg) 5762 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 5763 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 5764 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 5765 inFunctionCall(inFunctionCall), CallType(callType), 5766 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 5767 CoveredArgs.resize(numDataArgs); 5768 CoveredArgs.reset(); 5769 } 5770 5771 void DoneProcessing(); 5772 5773 void HandleIncompleteSpecifier(const char *startSpecifier, 5774 unsigned specifierLen) override; 5775 5776 void HandleInvalidLengthModifier( 5777 const analyze_format_string::FormatSpecifier &FS, 5778 const analyze_format_string::ConversionSpecifier &CS, 5779 const char *startSpecifier, unsigned specifierLen, 5780 unsigned DiagID); 5781 5782 void HandleNonStandardLengthModifier( 5783 const analyze_format_string::FormatSpecifier &FS, 5784 const char *startSpecifier, unsigned specifierLen); 5785 5786 void HandleNonStandardConversionSpecifier( 5787 const analyze_format_string::ConversionSpecifier &CS, 5788 const char *startSpecifier, unsigned specifierLen); 5789 5790 void HandlePosition(const char *startPos, unsigned posLen) override; 5791 5792 void HandleInvalidPosition(const char *startSpecifier, 5793 unsigned specifierLen, 5794 analyze_format_string::PositionContext p) override; 5795 5796 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 5797 5798 void HandleNullChar(const char *nullCharacter) override; 5799 5800 template <typename Range> 5801 static void 5802 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 5803 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 5804 bool IsStringLocation, Range StringRange, 5805 ArrayRef<FixItHint> Fixit = None); 5806 5807 protected: 5808 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 5809 const char *startSpec, 5810 unsigned specifierLen, 5811 const char *csStart, unsigned csLen); 5812 5813 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 5814 const char *startSpec, 5815 unsigned specifierLen); 5816 5817 SourceRange getFormatStringRange(); 5818 CharSourceRange getSpecifierRange(const char *startSpecifier, 5819 unsigned specifierLen); 5820 SourceLocation getLocationOfByte(const char *x); 5821 5822 const Expr *getDataArg(unsigned i) const; 5823 5824 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 5825 const analyze_format_string::ConversionSpecifier &CS, 5826 const char *startSpecifier, unsigned specifierLen, 5827 unsigned argIndex); 5828 5829 template <typename Range> 5830 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 5831 bool IsStringLocation, Range StringRange, 5832 ArrayRef<FixItHint> Fixit = None); 5833 }; 5834 5835 } // namespace 5836 5837 SourceRange CheckFormatHandler::getFormatStringRange() { 5838 return OrigFormatExpr->getSourceRange(); 5839 } 5840 5841 CharSourceRange CheckFormatHandler:: 5842 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 5843 SourceLocation Start = getLocationOfByte(startSpecifier); 5844 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 5845 5846 // Advance the end SourceLocation by one due to half-open ranges. 5847 End = End.getLocWithOffset(1); 5848 5849 return CharSourceRange::getCharRange(Start, End); 5850 } 5851 5852 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 5853 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 5854 S.getLangOpts(), S.Context.getTargetInfo()); 5855 } 5856 5857 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 5858 unsigned specifierLen){ 5859 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 5860 getLocationOfByte(startSpecifier), 5861 /*IsStringLocation*/true, 5862 getSpecifierRange(startSpecifier, specifierLen)); 5863 } 5864 5865 void CheckFormatHandler::HandleInvalidLengthModifier( 5866 const analyze_format_string::FormatSpecifier &FS, 5867 const analyze_format_string::ConversionSpecifier &CS, 5868 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 5869 using namespace analyze_format_string; 5870 5871 const LengthModifier &LM = FS.getLengthModifier(); 5872 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 5873 5874 // See if we know how to fix this length modifier. 5875 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 5876 if (FixedLM) { 5877 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 5878 getLocationOfByte(LM.getStart()), 5879 /*IsStringLocation*/true, 5880 getSpecifierRange(startSpecifier, specifierLen)); 5881 5882 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 5883 << FixedLM->toString() 5884 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 5885 5886 } else { 5887 FixItHint Hint; 5888 if (DiagID == diag::warn_format_nonsensical_length) 5889 Hint = FixItHint::CreateRemoval(LMRange); 5890 5891 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 5892 getLocationOfByte(LM.getStart()), 5893 /*IsStringLocation*/true, 5894 getSpecifierRange(startSpecifier, specifierLen), 5895 Hint); 5896 } 5897 } 5898 5899 void CheckFormatHandler::HandleNonStandardLengthModifier( 5900 const analyze_format_string::FormatSpecifier &FS, 5901 const char *startSpecifier, unsigned specifierLen) { 5902 using namespace analyze_format_string; 5903 5904 const LengthModifier &LM = FS.getLengthModifier(); 5905 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 5906 5907 // See if we know how to fix this length modifier. 5908 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 5909 if (FixedLM) { 5910 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5911 << LM.toString() << 0, 5912 getLocationOfByte(LM.getStart()), 5913 /*IsStringLocation*/true, 5914 getSpecifierRange(startSpecifier, specifierLen)); 5915 5916 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 5917 << FixedLM->toString() 5918 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 5919 5920 } else { 5921 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5922 << LM.toString() << 0, 5923 getLocationOfByte(LM.getStart()), 5924 /*IsStringLocation*/true, 5925 getSpecifierRange(startSpecifier, specifierLen)); 5926 } 5927 } 5928 5929 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 5930 const analyze_format_string::ConversionSpecifier &CS, 5931 const char *startSpecifier, unsigned specifierLen) { 5932 using namespace analyze_format_string; 5933 5934 // See if we know how to fix this conversion specifier. 5935 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 5936 if (FixedCS) { 5937 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5938 << CS.toString() << /*conversion specifier*/1, 5939 getLocationOfByte(CS.getStart()), 5940 /*IsStringLocation*/true, 5941 getSpecifierRange(startSpecifier, specifierLen)); 5942 5943 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 5944 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 5945 << FixedCS->toString() 5946 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 5947 } else { 5948 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5949 << CS.toString() << /*conversion specifier*/1, 5950 getLocationOfByte(CS.getStart()), 5951 /*IsStringLocation*/true, 5952 getSpecifierRange(startSpecifier, specifierLen)); 5953 } 5954 } 5955 5956 void CheckFormatHandler::HandlePosition(const char *startPos, 5957 unsigned posLen) { 5958 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 5959 getLocationOfByte(startPos), 5960 /*IsStringLocation*/true, 5961 getSpecifierRange(startPos, posLen)); 5962 } 5963 5964 void 5965 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 5966 analyze_format_string::PositionContext p) { 5967 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 5968 << (unsigned) p, 5969 getLocationOfByte(startPos), /*IsStringLocation*/true, 5970 getSpecifierRange(startPos, posLen)); 5971 } 5972 5973 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 5974 unsigned posLen) { 5975 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 5976 getLocationOfByte(startPos), 5977 /*IsStringLocation*/true, 5978 getSpecifierRange(startPos, posLen)); 5979 } 5980 5981 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 5982 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 5983 // The presence of a null character is likely an error. 5984 EmitFormatDiagnostic( 5985 S.PDiag(diag::warn_printf_format_string_contains_null_char), 5986 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 5987 getFormatStringRange()); 5988 } 5989 } 5990 5991 // Note that this may return NULL if there was an error parsing or building 5992 // one of the argument expressions. 5993 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 5994 return Args[FirstDataArg + i]; 5995 } 5996 5997 void CheckFormatHandler::DoneProcessing() { 5998 // Does the number of data arguments exceed the number of 5999 // format conversions in the format string? 6000 if (!HasVAListArg) { 6001 // Find any arguments that weren't covered. 6002 CoveredArgs.flip(); 6003 signed notCoveredArg = CoveredArgs.find_first(); 6004 if (notCoveredArg >= 0) { 6005 assert((unsigned)notCoveredArg < NumDataArgs); 6006 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 6007 } else { 6008 UncoveredArg.setAllCovered(); 6009 } 6010 } 6011 } 6012 6013 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 6014 const Expr *ArgExpr) { 6015 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 6016 "Invalid state"); 6017 6018 if (!ArgExpr) 6019 return; 6020 6021 SourceLocation Loc = ArgExpr->getLocStart(); 6022 6023 if (S.getSourceManager().isInSystemMacro(Loc)) 6024 return; 6025 6026 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 6027 for (auto E : DiagnosticExprs) 6028 PDiag << E->getSourceRange(); 6029 6030 CheckFormatHandler::EmitFormatDiagnostic( 6031 S, IsFunctionCall, DiagnosticExprs[0], 6032 PDiag, Loc, /*IsStringLocation*/false, 6033 DiagnosticExprs[0]->getSourceRange()); 6034 } 6035 6036 bool 6037 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 6038 SourceLocation Loc, 6039 const char *startSpec, 6040 unsigned specifierLen, 6041 const char *csStart, 6042 unsigned csLen) { 6043 bool keepGoing = true; 6044 if (argIndex < NumDataArgs) { 6045 // Consider the argument coverered, even though the specifier doesn't 6046 // make sense. 6047 CoveredArgs.set(argIndex); 6048 } 6049 else { 6050 // If argIndex exceeds the number of data arguments we 6051 // don't issue a warning because that is just a cascade of warnings (and 6052 // they may have intended '%%' anyway). We don't want to continue processing 6053 // the format string after this point, however, as we will like just get 6054 // gibberish when trying to match arguments. 6055 keepGoing = false; 6056 } 6057 6058 StringRef Specifier(csStart, csLen); 6059 6060 // If the specifier in non-printable, it could be the first byte of a UTF-8 6061 // sequence. In that case, print the UTF-8 code point. If not, print the byte 6062 // hex value. 6063 std::string CodePointStr; 6064 if (!llvm::sys::locale::isPrint(*csStart)) { 6065 llvm::UTF32 CodePoint; 6066 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 6067 const llvm::UTF8 *E = 6068 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 6069 llvm::ConversionResult Result = 6070 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 6071 6072 if (Result != llvm::conversionOK) { 6073 unsigned char FirstChar = *csStart; 6074 CodePoint = (llvm::UTF32)FirstChar; 6075 } 6076 6077 llvm::raw_string_ostream OS(CodePointStr); 6078 if (CodePoint < 256) 6079 OS << "\\x" << llvm::format("%02x", CodePoint); 6080 else if (CodePoint <= 0xFFFF) 6081 OS << "\\u" << llvm::format("%04x", CodePoint); 6082 else 6083 OS << "\\U" << llvm::format("%08x", CodePoint); 6084 OS.flush(); 6085 Specifier = CodePointStr; 6086 } 6087 6088 EmitFormatDiagnostic( 6089 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 6090 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 6091 6092 return keepGoing; 6093 } 6094 6095 void 6096 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 6097 const char *startSpec, 6098 unsigned specifierLen) { 6099 EmitFormatDiagnostic( 6100 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 6101 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 6102 } 6103 6104 bool 6105 CheckFormatHandler::CheckNumArgs( 6106 const analyze_format_string::FormatSpecifier &FS, 6107 const analyze_format_string::ConversionSpecifier &CS, 6108 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 6109 6110 if (argIndex >= NumDataArgs) { 6111 PartialDiagnostic PDiag = FS.usesPositionalArg() 6112 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 6113 << (argIndex+1) << NumDataArgs) 6114 : S.PDiag(diag::warn_printf_insufficient_data_args); 6115 EmitFormatDiagnostic( 6116 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 6117 getSpecifierRange(startSpecifier, specifierLen)); 6118 6119 // Since more arguments than conversion tokens are given, by extension 6120 // all arguments are covered, so mark this as so. 6121 UncoveredArg.setAllCovered(); 6122 return false; 6123 } 6124 return true; 6125 } 6126 6127 template<typename Range> 6128 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 6129 SourceLocation Loc, 6130 bool IsStringLocation, 6131 Range StringRange, 6132 ArrayRef<FixItHint> FixIt) { 6133 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 6134 Loc, IsStringLocation, StringRange, FixIt); 6135 } 6136 6137 /// If the format string is not within the function call, emit a note 6138 /// so that the function call and string are in diagnostic messages. 6139 /// 6140 /// \param InFunctionCall if true, the format string is within the function 6141 /// call and only one diagnostic message will be produced. Otherwise, an 6142 /// extra note will be emitted pointing to location of the format string. 6143 /// 6144 /// \param ArgumentExpr the expression that is passed as the format string 6145 /// argument in the function call. Used for getting locations when two 6146 /// diagnostics are emitted. 6147 /// 6148 /// \param PDiag the callee should already have provided any strings for the 6149 /// diagnostic message. This function only adds locations and fixits 6150 /// to diagnostics. 6151 /// 6152 /// \param Loc primary location for diagnostic. If two diagnostics are 6153 /// required, one will be at Loc and a new SourceLocation will be created for 6154 /// the other one. 6155 /// 6156 /// \param IsStringLocation if true, Loc points to the format string should be 6157 /// used for the note. Otherwise, Loc points to the argument list and will 6158 /// be used with PDiag. 6159 /// 6160 /// \param StringRange some or all of the string to highlight. This is 6161 /// templated so it can accept either a CharSourceRange or a SourceRange. 6162 /// 6163 /// \param FixIt optional fix it hint for the format string. 6164 template <typename Range> 6165 void CheckFormatHandler::EmitFormatDiagnostic( 6166 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 6167 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 6168 Range StringRange, ArrayRef<FixItHint> FixIt) { 6169 if (InFunctionCall) { 6170 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 6171 D << StringRange; 6172 D << FixIt; 6173 } else { 6174 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 6175 << ArgumentExpr->getSourceRange(); 6176 6177 const Sema::SemaDiagnosticBuilder &Note = 6178 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 6179 diag::note_format_string_defined); 6180 6181 Note << StringRange; 6182 Note << FixIt; 6183 } 6184 } 6185 6186 //===--- CHECK: Printf format string checking ------------------------------===// 6187 6188 namespace { 6189 6190 class CheckPrintfHandler : public CheckFormatHandler { 6191 public: 6192 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 6193 const Expr *origFormatExpr, 6194 const Sema::FormatStringType type, unsigned firstDataArg, 6195 unsigned numDataArgs, bool isObjC, const char *beg, 6196 bool hasVAListArg, ArrayRef<const Expr *> Args, 6197 unsigned formatIdx, bool inFunctionCall, 6198 Sema::VariadicCallType CallType, 6199 llvm::SmallBitVector &CheckedVarArgs, 6200 UncoveredArgHandler &UncoveredArg) 6201 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 6202 numDataArgs, beg, hasVAListArg, Args, formatIdx, 6203 inFunctionCall, CallType, CheckedVarArgs, 6204 UncoveredArg) {} 6205 6206 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 6207 6208 /// Returns true if '%@' specifiers are allowed in the format string. 6209 bool allowsObjCArg() const { 6210 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 6211 FSType == Sema::FST_OSTrace; 6212 } 6213 6214 bool HandleInvalidPrintfConversionSpecifier( 6215 const analyze_printf::PrintfSpecifier &FS, 6216 const char *startSpecifier, 6217 unsigned specifierLen) override; 6218 6219 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 6220 const char *startSpecifier, 6221 unsigned specifierLen) override; 6222 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 6223 const char *StartSpecifier, 6224 unsigned SpecifierLen, 6225 const Expr *E); 6226 6227 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 6228 const char *startSpecifier, unsigned specifierLen); 6229 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 6230 const analyze_printf::OptionalAmount &Amt, 6231 unsigned type, 6232 const char *startSpecifier, unsigned specifierLen); 6233 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 6234 const analyze_printf::OptionalFlag &flag, 6235 const char *startSpecifier, unsigned specifierLen); 6236 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 6237 const analyze_printf::OptionalFlag &ignoredFlag, 6238 const analyze_printf::OptionalFlag &flag, 6239 const char *startSpecifier, unsigned specifierLen); 6240 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 6241 const Expr *E); 6242 6243 void HandleEmptyObjCModifierFlag(const char *startFlag, 6244 unsigned flagLen) override; 6245 6246 void HandleInvalidObjCModifierFlag(const char *startFlag, 6247 unsigned flagLen) override; 6248 6249 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 6250 const char *flagsEnd, 6251 const char *conversionPosition) 6252 override; 6253 }; 6254 6255 } // namespace 6256 6257 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 6258 const analyze_printf::PrintfSpecifier &FS, 6259 const char *startSpecifier, 6260 unsigned specifierLen) { 6261 const analyze_printf::PrintfConversionSpecifier &CS = 6262 FS.getConversionSpecifier(); 6263 6264 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 6265 getLocationOfByte(CS.getStart()), 6266 startSpecifier, specifierLen, 6267 CS.getStart(), CS.getLength()); 6268 } 6269 6270 bool CheckPrintfHandler::HandleAmount( 6271 const analyze_format_string::OptionalAmount &Amt, 6272 unsigned k, const char *startSpecifier, 6273 unsigned specifierLen) { 6274 if (Amt.hasDataArgument()) { 6275 if (!HasVAListArg) { 6276 unsigned argIndex = Amt.getArgIndex(); 6277 if (argIndex >= NumDataArgs) { 6278 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 6279 << k, 6280 getLocationOfByte(Amt.getStart()), 6281 /*IsStringLocation*/true, 6282 getSpecifierRange(startSpecifier, specifierLen)); 6283 // Don't do any more checking. We will just emit 6284 // spurious errors. 6285 return false; 6286 } 6287 6288 // Type check the data argument. It should be an 'int'. 6289 // Although not in conformance with C99, we also allow the argument to be 6290 // an 'unsigned int' as that is a reasonably safe case. GCC also 6291 // doesn't emit a warning for that case. 6292 CoveredArgs.set(argIndex); 6293 const Expr *Arg = getDataArg(argIndex); 6294 if (!Arg) 6295 return false; 6296 6297 QualType T = Arg->getType(); 6298 6299 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 6300 assert(AT.isValid()); 6301 6302 if (!AT.matchesType(S.Context, T)) { 6303 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 6304 << k << AT.getRepresentativeTypeName(S.Context) 6305 << T << Arg->getSourceRange(), 6306 getLocationOfByte(Amt.getStart()), 6307 /*IsStringLocation*/true, 6308 getSpecifierRange(startSpecifier, specifierLen)); 6309 // Don't do any more checking. We will just emit 6310 // spurious errors. 6311 return false; 6312 } 6313 } 6314 } 6315 return true; 6316 } 6317 6318 void CheckPrintfHandler::HandleInvalidAmount( 6319 const analyze_printf::PrintfSpecifier &FS, 6320 const analyze_printf::OptionalAmount &Amt, 6321 unsigned type, 6322 const char *startSpecifier, 6323 unsigned specifierLen) { 6324 const analyze_printf::PrintfConversionSpecifier &CS = 6325 FS.getConversionSpecifier(); 6326 6327 FixItHint fixit = 6328 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 6329 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 6330 Amt.getConstantLength())) 6331 : FixItHint(); 6332 6333 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 6334 << type << CS.toString(), 6335 getLocationOfByte(Amt.getStart()), 6336 /*IsStringLocation*/true, 6337 getSpecifierRange(startSpecifier, specifierLen), 6338 fixit); 6339 } 6340 6341 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 6342 const analyze_printf::OptionalFlag &flag, 6343 const char *startSpecifier, 6344 unsigned specifierLen) { 6345 // Warn about pointless flag with a fixit removal. 6346 const analyze_printf::PrintfConversionSpecifier &CS = 6347 FS.getConversionSpecifier(); 6348 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 6349 << flag.toString() << CS.toString(), 6350 getLocationOfByte(flag.getPosition()), 6351 /*IsStringLocation*/true, 6352 getSpecifierRange(startSpecifier, specifierLen), 6353 FixItHint::CreateRemoval( 6354 getSpecifierRange(flag.getPosition(), 1))); 6355 } 6356 6357 void CheckPrintfHandler::HandleIgnoredFlag( 6358 const analyze_printf::PrintfSpecifier &FS, 6359 const analyze_printf::OptionalFlag &ignoredFlag, 6360 const analyze_printf::OptionalFlag &flag, 6361 const char *startSpecifier, 6362 unsigned specifierLen) { 6363 // Warn about ignored flag with a fixit removal. 6364 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 6365 << ignoredFlag.toString() << flag.toString(), 6366 getLocationOfByte(ignoredFlag.getPosition()), 6367 /*IsStringLocation*/true, 6368 getSpecifierRange(startSpecifier, specifierLen), 6369 FixItHint::CreateRemoval( 6370 getSpecifierRange(ignoredFlag.getPosition(), 1))); 6371 } 6372 6373 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 6374 unsigned flagLen) { 6375 // Warn about an empty flag. 6376 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 6377 getLocationOfByte(startFlag), 6378 /*IsStringLocation*/true, 6379 getSpecifierRange(startFlag, flagLen)); 6380 } 6381 6382 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 6383 unsigned flagLen) { 6384 // Warn about an invalid flag. 6385 auto Range = getSpecifierRange(startFlag, flagLen); 6386 StringRef flag(startFlag, flagLen); 6387 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 6388 getLocationOfByte(startFlag), 6389 /*IsStringLocation*/true, 6390 Range, FixItHint::CreateRemoval(Range)); 6391 } 6392 6393 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 6394 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 6395 // Warn about using '[...]' without a '@' conversion. 6396 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 6397 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 6398 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 6399 getLocationOfByte(conversionPosition), 6400 /*IsStringLocation*/true, 6401 Range, FixItHint::CreateRemoval(Range)); 6402 } 6403 6404 // Determines if the specified is a C++ class or struct containing 6405 // a member with the specified name and kind (e.g. a CXXMethodDecl named 6406 // "c_str()"). 6407 template<typename MemberKind> 6408 static llvm::SmallPtrSet<MemberKind*, 1> 6409 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 6410 const RecordType *RT = Ty->getAs<RecordType>(); 6411 llvm::SmallPtrSet<MemberKind*, 1> Results; 6412 6413 if (!RT) 6414 return Results; 6415 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 6416 if (!RD || !RD->getDefinition()) 6417 return Results; 6418 6419 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 6420 Sema::LookupMemberName); 6421 R.suppressDiagnostics(); 6422 6423 // We just need to include all members of the right kind turned up by the 6424 // filter, at this point. 6425 if (S.LookupQualifiedName(R, RT->getDecl())) 6426 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 6427 NamedDecl *decl = (*I)->getUnderlyingDecl(); 6428 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 6429 Results.insert(FK); 6430 } 6431 return Results; 6432 } 6433 6434 /// Check if we could call '.c_str()' on an object. 6435 /// 6436 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 6437 /// allow the call, or if it would be ambiguous). 6438 bool Sema::hasCStrMethod(const Expr *E) { 6439 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 6440 6441 MethodSet Results = 6442 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 6443 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 6444 MI != ME; ++MI) 6445 if ((*MI)->getMinRequiredArguments() == 0) 6446 return true; 6447 return false; 6448 } 6449 6450 // Check if a (w)string was passed when a (w)char* was needed, and offer a 6451 // better diagnostic if so. AT is assumed to be valid. 6452 // Returns true when a c_str() conversion method is found. 6453 bool CheckPrintfHandler::checkForCStrMembers( 6454 const analyze_printf::ArgType &AT, const Expr *E) { 6455 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 6456 6457 MethodSet Results = 6458 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 6459 6460 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 6461 MI != ME; ++MI) { 6462 const CXXMethodDecl *Method = *MI; 6463 if (Method->getMinRequiredArguments() == 0 && 6464 AT.matchesType(S.Context, Method->getReturnType())) { 6465 // FIXME: Suggest parens if the expression needs them. 6466 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd()); 6467 S.Diag(E->getLocStart(), diag::note_printf_c_str) 6468 << "c_str()" 6469 << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 6470 return true; 6471 } 6472 } 6473 6474 return false; 6475 } 6476 6477 bool 6478 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 6479 &FS, 6480 const char *startSpecifier, 6481 unsigned specifierLen) { 6482 using namespace analyze_format_string; 6483 using namespace analyze_printf; 6484 6485 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 6486 6487 if (FS.consumesDataArgument()) { 6488 if (atFirstArg) { 6489 atFirstArg = false; 6490 usesPositionalArgs = FS.usesPositionalArg(); 6491 } 6492 else if (usesPositionalArgs != FS.usesPositionalArg()) { 6493 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 6494 startSpecifier, specifierLen); 6495 return false; 6496 } 6497 } 6498 6499 // First check if the field width, precision, and conversion specifier 6500 // have matching data arguments. 6501 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 6502 startSpecifier, specifierLen)) { 6503 return false; 6504 } 6505 6506 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 6507 startSpecifier, specifierLen)) { 6508 return false; 6509 } 6510 6511 if (!CS.consumesDataArgument()) { 6512 // FIXME: Technically specifying a precision or field width here 6513 // makes no sense. Worth issuing a warning at some point. 6514 return true; 6515 } 6516 6517 // Consume the argument. 6518 unsigned argIndex = FS.getArgIndex(); 6519 if (argIndex < NumDataArgs) { 6520 // The check to see if the argIndex is valid will come later. 6521 // We set the bit here because we may exit early from this 6522 // function if we encounter some other error. 6523 CoveredArgs.set(argIndex); 6524 } 6525 6526 // FreeBSD kernel extensions. 6527 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 6528 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 6529 // We need at least two arguments. 6530 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 6531 return false; 6532 6533 // Claim the second argument. 6534 CoveredArgs.set(argIndex + 1); 6535 6536 // Type check the first argument (int for %b, pointer for %D) 6537 const Expr *Ex = getDataArg(argIndex); 6538 const analyze_printf::ArgType &AT = 6539 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 6540 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 6541 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 6542 EmitFormatDiagnostic( 6543 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 6544 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 6545 << false << Ex->getSourceRange(), 6546 Ex->getLocStart(), /*IsStringLocation*/false, 6547 getSpecifierRange(startSpecifier, specifierLen)); 6548 6549 // Type check the second argument (char * for both %b and %D) 6550 Ex = getDataArg(argIndex + 1); 6551 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 6552 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 6553 EmitFormatDiagnostic( 6554 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 6555 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 6556 << false << Ex->getSourceRange(), 6557 Ex->getLocStart(), /*IsStringLocation*/false, 6558 getSpecifierRange(startSpecifier, specifierLen)); 6559 6560 return true; 6561 } 6562 6563 // Check for using an Objective-C specific conversion specifier 6564 // in a non-ObjC literal. 6565 if (!allowsObjCArg() && CS.isObjCArg()) { 6566 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 6567 specifierLen); 6568 } 6569 6570 // %P can only be used with os_log. 6571 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 6572 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 6573 specifierLen); 6574 } 6575 6576 // %n is not allowed with os_log. 6577 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 6578 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 6579 getLocationOfByte(CS.getStart()), 6580 /*IsStringLocation*/ false, 6581 getSpecifierRange(startSpecifier, specifierLen)); 6582 6583 return true; 6584 } 6585 6586 // Only scalars are allowed for os_trace. 6587 if (FSType == Sema::FST_OSTrace && 6588 (CS.getKind() == ConversionSpecifier::PArg || 6589 CS.getKind() == ConversionSpecifier::sArg || 6590 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 6591 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 6592 specifierLen); 6593 } 6594 6595 // Check for use of public/private annotation outside of os_log(). 6596 if (FSType != Sema::FST_OSLog) { 6597 if (FS.isPublic().isSet()) { 6598 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 6599 << "public", 6600 getLocationOfByte(FS.isPublic().getPosition()), 6601 /*IsStringLocation*/ false, 6602 getSpecifierRange(startSpecifier, specifierLen)); 6603 } 6604 if (FS.isPrivate().isSet()) { 6605 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 6606 << "private", 6607 getLocationOfByte(FS.isPrivate().getPosition()), 6608 /*IsStringLocation*/ false, 6609 getSpecifierRange(startSpecifier, specifierLen)); 6610 } 6611 } 6612 6613 // Check for invalid use of field width 6614 if (!FS.hasValidFieldWidth()) { 6615 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 6616 startSpecifier, specifierLen); 6617 } 6618 6619 // Check for invalid use of precision 6620 if (!FS.hasValidPrecision()) { 6621 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 6622 startSpecifier, specifierLen); 6623 } 6624 6625 // Precision is mandatory for %P specifier. 6626 if (CS.getKind() == ConversionSpecifier::PArg && 6627 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 6628 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 6629 getLocationOfByte(startSpecifier), 6630 /*IsStringLocation*/ false, 6631 getSpecifierRange(startSpecifier, specifierLen)); 6632 } 6633 6634 // Check each flag does not conflict with any other component. 6635 if (!FS.hasValidThousandsGroupingPrefix()) 6636 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 6637 if (!FS.hasValidLeadingZeros()) 6638 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 6639 if (!FS.hasValidPlusPrefix()) 6640 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 6641 if (!FS.hasValidSpacePrefix()) 6642 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 6643 if (!FS.hasValidAlternativeForm()) 6644 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 6645 if (!FS.hasValidLeftJustified()) 6646 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 6647 6648 // Check that flags are not ignored by another flag 6649 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 6650 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 6651 startSpecifier, specifierLen); 6652 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 6653 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 6654 startSpecifier, specifierLen); 6655 6656 // Check the length modifier is valid with the given conversion specifier. 6657 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 6658 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6659 diag::warn_format_nonsensical_length); 6660 else if (!FS.hasStandardLengthModifier()) 6661 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 6662 else if (!FS.hasStandardLengthConversionCombination()) 6663 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6664 diag::warn_format_non_standard_conversion_spec); 6665 6666 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 6667 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 6668 6669 // The remaining checks depend on the data arguments. 6670 if (HasVAListArg) 6671 return true; 6672 6673 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 6674 return false; 6675 6676 const Expr *Arg = getDataArg(argIndex); 6677 if (!Arg) 6678 return true; 6679 6680 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 6681 } 6682 6683 static bool requiresParensToAddCast(const Expr *E) { 6684 // FIXME: We should have a general way to reason about operator 6685 // precedence and whether parens are actually needed here. 6686 // Take care of a few common cases where they aren't. 6687 const Expr *Inside = E->IgnoreImpCasts(); 6688 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 6689 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 6690 6691 switch (Inside->getStmtClass()) { 6692 case Stmt::ArraySubscriptExprClass: 6693 case Stmt::CallExprClass: 6694 case Stmt::CharacterLiteralClass: 6695 case Stmt::CXXBoolLiteralExprClass: 6696 case Stmt::DeclRefExprClass: 6697 case Stmt::FloatingLiteralClass: 6698 case Stmt::IntegerLiteralClass: 6699 case Stmt::MemberExprClass: 6700 case Stmt::ObjCArrayLiteralClass: 6701 case Stmt::ObjCBoolLiteralExprClass: 6702 case Stmt::ObjCBoxedExprClass: 6703 case Stmt::ObjCDictionaryLiteralClass: 6704 case Stmt::ObjCEncodeExprClass: 6705 case Stmt::ObjCIvarRefExprClass: 6706 case Stmt::ObjCMessageExprClass: 6707 case Stmt::ObjCPropertyRefExprClass: 6708 case Stmt::ObjCStringLiteralClass: 6709 case Stmt::ObjCSubscriptRefExprClass: 6710 case Stmt::ParenExprClass: 6711 case Stmt::StringLiteralClass: 6712 case Stmt::UnaryOperatorClass: 6713 return false; 6714 default: 6715 return true; 6716 } 6717 } 6718 6719 static std::pair<QualType, StringRef> 6720 shouldNotPrintDirectly(const ASTContext &Context, 6721 QualType IntendedTy, 6722 const Expr *E) { 6723 // Use a 'while' to peel off layers of typedefs. 6724 QualType TyTy = IntendedTy; 6725 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 6726 StringRef Name = UserTy->getDecl()->getName(); 6727 QualType CastTy = llvm::StringSwitch<QualType>(Name) 6728 .Case("CFIndex", Context.getNSIntegerType()) 6729 .Case("NSInteger", Context.getNSIntegerType()) 6730 .Case("NSUInteger", Context.getNSUIntegerType()) 6731 .Case("SInt32", Context.IntTy) 6732 .Case("UInt32", Context.UnsignedIntTy) 6733 .Default(QualType()); 6734 6735 if (!CastTy.isNull()) 6736 return std::make_pair(CastTy, Name); 6737 6738 TyTy = UserTy->desugar(); 6739 } 6740 6741 // Strip parens if necessary. 6742 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 6743 return shouldNotPrintDirectly(Context, 6744 PE->getSubExpr()->getType(), 6745 PE->getSubExpr()); 6746 6747 // If this is a conditional expression, then its result type is constructed 6748 // via usual arithmetic conversions and thus there might be no necessary 6749 // typedef sugar there. Recurse to operands to check for NSInteger & 6750 // Co. usage condition. 6751 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 6752 QualType TrueTy, FalseTy; 6753 StringRef TrueName, FalseName; 6754 6755 std::tie(TrueTy, TrueName) = 6756 shouldNotPrintDirectly(Context, 6757 CO->getTrueExpr()->getType(), 6758 CO->getTrueExpr()); 6759 std::tie(FalseTy, FalseName) = 6760 shouldNotPrintDirectly(Context, 6761 CO->getFalseExpr()->getType(), 6762 CO->getFalseExpr()); 6763 6764 if (TrueTy == FalseTy) 6765 return std::make_pair(TrueTy, TrueName); 6766 else if (TrueTy.isNull()) 6767 return std::make_pair(FalseTy, FalseName); 6768 else if (FalseTy.isNull()) 6769 return std::make_pair(TrueTy, TrueName); 6770 } 6771 6772 return std::make_pair(QualType(), StringRef()); 6773 } 6774 6775 bool 6776 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 6777 const char *StartSpecifier, 6778 unsigned SpecifierLen, 6779 const Expr *E) { 6780 using namespace analyze_format_string; 6781 using namespace analyze_printf; 6782 6783 // Now type check the data expression that matches the 6784 // format specifier. 6785 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 6786 if (!AT.isValid()) 6787 return true; 6788 6789 QualType ExprTy = E->getType(); 6790 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 6791 ExprTy = TET->getUnderlyingExpr()->getType(); 6792 } 6793 6794 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy); 6795 6796 if (match == analyze_printf::ArgType::Match) { 6797 return true; 6798 } 6799 6800 // Look through argument promotions for our error message's reported type. 6801 // This includes the integral and floating promotions, but excludes array 6802 // and function pointer decay; seeing that an argument intended to be a 6803 // string has type 'char [6]' is probably more confusing than 'char *'. 6804 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 6805 if (ICE->getCastKind() == CK_IntegralCast || 6806 ICE->getCastKind() == CK_FloatingCast) { 6807 E = ICE->getSubExpr(); 6808 ExprTy = E->getType(); 6809 6810 // Check if we didn't match because of an implicit cast from a 'char' 6811 // or 'short' to an 'int'. This is done because printf is a varargs 6812 // function. 6813 if (ICE->getType() == S.Context.IntTy || 6814 ICE->getType() == S.Context.UnsignedIntTy) { 6815 // All further checking is done on the subexpression. 6816 if (AT.matchesType(S.Context, ExprTy)) 6817 return true; 6818 } 6819 } 6820 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 6821 // Special case for 'a', which has type 'int' in C. 6822 // Note, however, that we do /not/ want to treat multibyte constants like 6823 // 'MooV' as characters! This form is deprecated but still exists. 6824 if (ExprTy == S.Context.IntTy) 6825 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 6826 ExprTy = S.Context.CharTy; 6827 } 6828 6829 // Look through enums to their underlying type. 6830 bool IsEnum = false; 6831 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 6832 ExprTy = EnumTy->getDecl()->getIntegerType(); 6833 IsEnum = true; 6834 } 6835 6836 // %C in an Objective-C context prints a unichar, not a wchar_t. 6837 // If the argument is an integer of some kind, believe the %C and suggest 6838 // a cast instead of changing the conversion specifier. 6839 QualType IntendedTy = ExprTy; 6840 if (isObjCContext() && 6841 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 6842 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 6843 !ExprTy->isCharType()) { 6844 // 'unichar' is defined as a typedef of unsigned short, but we should 6845 // prefer using the typedef if it is visible. 6846 IntendedTy = S.Context.UnsignedShortTy; 6847 6848 // While we are here, check if the value is an IntegerLiteral that happens 6849 // to be within the valid range. 6850 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 6851 const llvm::APInt &V = IL->getValue(); 6852 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 6853 return true; 6854 } 6855 6856 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(), 6857 Sema::LookupOrdinaryName); 6858 if (S.LookupName(Result, S.getCurScope())) { 6859 NamedDecl *ND = Result.getFoundDecl(); 6860 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 6861 if (TD->getUnderlyingType() == IntendedTy) 6862 IntendedTy = S.Context.getTypedefType(TD); 6863 } 6864 } 6865 } 6866 6867 // Special-case some of Darwin's platform-independence types by suggesting 6868 // casts to primitive types that are known to be large enough. 6869 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 6870 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 6871 QualType CastTy; 6872 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 6873 if (!CastTy.isNull()) { 6874 IntendedTy = CastTy; 6875 ShouldNotPrintDirectly = true; 6876 } 6877 } 6878 6879 // We may be able to offer a FixItHint if it is a supported type. 6880 PrintfSpecifier fixedFS = FS; 6881 bool success = 6882 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 6883 6884 if (success) { 6885 // Get the fix string from the fixed format specifier 6886 SmallString<16> buf; 6887 llvm::raw_svector_ostream os(buf); 6888 fixedFS.toString(os); 6889 6890 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 6891 6892 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 6893 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 6894 if (match == analyze_format_string::ArgType::NoMatchPedantic) { 6895 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 6896 } 6897 // In this case, the specifier is wrong and should be changed to match 6898 // the argument. 6899 EmitFormatDiagnostic(S.PDiag(diag) 6900 << AT.getRepresentativeTypeName(S.Context) 6901 << IntendedTy << IsEnum << E->getSourceRange(), 6902 E->getLocStart(), 6903 /*IsStringLocation*/ false, SpecRange, 6904 FixItHint::CreateReplacement(SpecRange, os.str())); 6905 } else { 6906 // The canonical type for formatting this value is different from the 6907 // actual type of the expression. (This occurs, for example, with Darwin's 6908 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 6909 // should be printed as 'long' for 64-bit compatibility.) 6910 // Rather than emitting a normal format/argument mismatch, we want to 6911 // add a cast to the recommended type (and correct the format string 6912 // if necessary). 6913 SmallString<16> CastBuf; 6914 llvm::raw_svector_ostream CastFix(CastBuf); 6915 CastFix << "("; 6916 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 6917 CastFix << ")"; 6918 6919 SmallVector<FixItHint,4> Hints; 6920 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 6921 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 6922 6923 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 6924 // If there's already a cast present, just replace it. 6925 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 6926 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 6927 6928 } else if (!requiresParensToAddCast(E)) { 6929 // If the expression has high enough precedence, 6930 // just write the C-style cast. 6931 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(), 6932 CastFix.str())); 6933 } else { 6934 // Otherwise, add parens around the expression as well as the cast. 6935 CastFix << "("; 6936 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(), 6937 CastFix.str())); 6938 6939 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd()); 6940 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 6941 } 6942 6943 if (ShouldNotPrintDirectly) { 6944 // The expression has a type that should not be printed directly. 6945 // We extract the name from the typedef because we don't want to show 6946 // the underlying type in the diagnostic. 6947 StringRef Name; 6948 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 6949 Name = TypedefTy->getDecl()->getName(); 6950 else 6951 Name = CastTyName; 6952 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast) 6953 << Name << IntendedTy << IsEnum 6954 << E->getSourceRange(), 6955 E->getLocStart(), /*IsStringLocation=*/false, 6956 SpecRange, Hints); 6957 } else { 6958 // In this case, the expression could be printed using a different 6959 // specifier, but we've decided that the specifier is probably correct 6960 // and we should cast instead. Just use the normal warning message. 6961 EmitFormatDiagnostic( 6962 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 6963 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 6964 << E->getSourceRange(), 6965 E->getLocStart(), /*IsStringLocation*/false, 6966 SpecRange, Hints); 6967 } 6968 } 6969 } else { 6970 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 6971 SpecifierLen); 6972 // Since the warning for passing non-POD types to variadic functions 6973 // was deferred until now, we emit a warning for non-POD 6974 // arguments here. 6975 switch (S.isValidVarArgType(ExprTy)) { 6976 case Sema::VAK_Valid: 6977 case Sema::VAK_ValidInCXX11: { 6978 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 6979 if (match == analyze_printf::ArgType::NoMatchPedantic) { 6980 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 6981 } 6982 6983 EmitFormatDiagnostic( 6984 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 6985 << IsEnum << CSR << E->getSourceRange(), 6986 E->getLocStart(), /*IsStringLocation*/ false, CSR); 6987 break; 6988 } 6989 case Sema::VAK_Undefined: 6990 case Sema::VAK_MSVCUndefined: 6991 EmitFormatDiagnostic( 6992 S.PDiag(diag::warn_non_pod_vararg_with_format_string) 6993 << S.getLangOpts().CPlusPlus11 6994 << ExprTy 6995 << CallType 6996 << AT.getRepresentativeTypeName(S.Context) 6997 << CSR 6998 << E->getSourceRange(), 6999 E->getLocStart(), /*IsStringLocation*/false, CSR); 7000 checkForCStrMembers(AT, E); 7001 break; 7002 7003 case Sema::VAK_Invalid: 7004 if (ExprTy->isObjCObjectType()) 7005 EmitFormatDiagnostic( 7006 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 7007 << S.getLangOpts().CPlusPlus11 7008 << ExprTy 7009 << CallType 7010 << AT.getRepresentativeTypeName(S.Context) 7011 << CSR 7012 << E->getSourceRange(), 7013 E->getLocStart(), /*IsStringLocation*/false, CSR); 7014 else 7015 // FIXME: If this is an initializer list, suggest removing the braces 7016 // or inserting a cast to the target type. 7017 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format) 7018 << isa<InitListExpr>(E) << ExprTy << CallType 7019 << AT.getRepresentativeTypeName(S.Context) 7020 << E->getSourceRange(); 7021 break; 7022 } 7023 7024 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 7025 "format string specifier index out of range"); 7026 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 7027 } 7028 7029 return true; 7030 } 7031 7032 //===--- CHECK: Scanf format string checking ------------------------------===// 7033 7034 namespace { 7035 7036 class CheckScanfHandler : public CheckFormatHandler { 7037 public: 7038 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 7039 const Expr *origFormatExpr, Sema::FormatStringType type, 7040 unsigned firstDataArg, unsigned numDataArgs, 7041 const char *beg, bool hasVAListArg, 7042 ArrayRef<const Expr *> Args, unsigned formatIdx, 7043 bool inFunctionCall, Sema::VariadicCallType CallType, 7044 llvm::SmallBitVector &CheckedVarArgs, 7045 UncoveredArgHandler &UncoveredArg) 7046 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 7047 numDataArgs, beg, hasVAListArg, Args, formatIdx, 7048 inFunctionCall, CallType, CheckedVarArgs, 7049 UncoveredArg) {} 7050 7051 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 7052 const char *startSpecifier, 7053 unsigned specifierLen) override; 7054 7055 bool HandleInvalidScanfConversionSpecifier( 7056 const analyze_scanf::ScanfSpecifier &FS, 7057 const char *startSpecifier, 7058 unsigned specifierLen) override; 7059 7060 void HandleIncompleteScanList(const char *start, const char *end) override; 7061 }; 7062 7063 } // namespace 7064 7065 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 7066 const char *end) { 7067 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 7068 getLocationOfByte(end), /*IsStringLocation*/true, 7069 getSpecifierRange(start, end - start)); 7070 } 7071 7072 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 7073 const analyze_scanf::ScanfSpecifier &FS, 7074 const char *startSpecifier, 7075 unsigned specifierLen) { 7076 const analyze_scanf::ScanfConversionSpecifier &CS = 7077 FS.getConversionSpecifier(); 7078 7079 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 7080 getLocationOfByte(CS.getStart()), 7081 startSpecifier, specifierLen, 7082 CS.getStart(), CS.getLength()); 7083 } 7084 7085 bool CheckScanfHandler::HandleScanfSpecifier( 7086 const analyze_scanf::ScanfSpecifier &FS, 7087 const char *startSpecifier, 7088 unsigned specifierLen) { 7089 using namespace analyze_scanf; 7090 using namespace analyze_format_string; 7091 7092 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 7093 7094 // Handle case where '%' and '*' don't consume an argument. These shouldn't 7095 // be used to decide if we are using positional arguments consistently. 7096 if (FS.consumesDataArgument()) { 7097 if (atFirstArg) { 7098 atFirstArg = false; 7099 usesPositionalArgs = FS.usesPositionalArg(); 7100 } 7101 else if (usesPositionalArgs != FS.usesPositionalArg()) { 7102 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 7103 startSpecifier, specifierLen); 7104 return false; 7105 } 7106 } 7107 7108 // Check if the field with is non-zero. 7109 const OptionalAmount &Amt = FS.getFieldWidth(); 7110 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 7111 if (Amt.getConstantAmount() == 0) { 7112 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 7113 Amt.getConstantLength()); 7114 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 7115 getLocationOfByte(Amt.getStart()), 7116 /*IsStringLocation*/true, R, 7117 FixItHint::CreateRemoval(R)); 7118 } 7119 } 7120 7121 if (!FS.consumesDataArgument()) { 7122 // FIXME: Technically specifying a precision or field width here 7123 // makes no sense. Worth issuing a warning at some point. 7124 return true; 7125 } 7126 7127 // Consume the argument. 7128 unsigned argIndex = FS.getArgIndex(); 7129 if (argIndex < NumDataArgs) { 7130 // The check to see if the argIndex is valid will come later. 7131 // We set the bit here because we may exit early from this 7132 // function if we encounter some other error. 7133 CoveredArgs.set(argIndex); 7134 } 7135 7136 // Check the length modifier is valid with the given conversion specifier. 7137 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 7138 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 7139 diag::warn_format_nonsensical_length); 7140 else if (!FS.hasStandardLengthModifier()) 7141 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 7142 else if (!FS.hasStandardLengthConversionCombination()) 7143 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 7144 diag::warn_format_non_standard_conversion_spec); 7145 7146 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 7147 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 7148 7149 // The remaining checks depend on the data arguments. 7150 if (HasVAListArg) 7151 return true; 7152 7153 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 7154 return false; 7155 7156 // Check that the argument type matches the format specifier. 7157 const Expr *Ex = getDataArg(argIndex); 7158 if (!Ex) 7159 return true; 7160 7161 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 7162 7163 if (!AT.isValid()) { 7164 return true; 7165 } 7166 7167 analyze_format_string::ArgType::MatchKind match = 7168 AT.matchesType(S.Context, Ex->getType()); 7169 if (match == analyze_format_string::ArgType::Match) { 7170 return true; 7171 } 7172 7173 ScanfSpecifier fixedFS = FS; 7174 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 7175 S.getLangOpts(), S.Context); 7176 7177 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 7178 if (match == analyze_format_string::ArgType::NoMatchPedantic) { 7179 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 7180 } 7181 7182 if (success) { 7183 // Get the fix string from the fixed format specifier. 7184 SmallString<128> buf; 7185 llvm::raw_svector_ostream os(buf); 7186 fixedFS.toString(os); 7187 7188 EmitFormatDiagnostic( 7189 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) 7190 << Ex->getType() << false << Ex->getSourceRange(), 7191 Ex->getLocStart(), 7192 /*IsStringLocation*/ false, 7193 getSpecifierRange(startSpecifier, specifierLen), 7194 FixItHint::CreateReplacement( 7195 getSpecifierRange(startSpecifier, specifierLen), os.str())); 7196 } else { 7197 EmitFormatDiagnostic(S.PDiag(diag) 7198 << AT.getRepresentativeTypeName(S.Context) 7199 << Ex->getType() << false << Ex->getSourceRange(), 7200 Ex->getLocStart(), 7201 /*IsStringLocation*/ false, 7202 getSpecifierRange(startSpecifier, specifierLen)); 7203 } 7204 7205 return true; 7206 } 7207 7208 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 7209 const Expr *OrigFormatExpr, 7210 ArrayRef<const Expr *> Args, 7211 bool HasVAListArg, unsigned format_idx, 7212 unsigned firstDataArg, 7213 Sema::FormatStringType Type, 7214 bool inFunctionCall, 7215 Sema::VariadicCallType CallType, 7216 llvm::SmallBitVector &CheckedVarArgs, 7217 UncoveredArgHandler &UncoveredArg) { 7218 // CHECK: is the format string a wide literal? 7219 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 7220 CheckFormatHandler::EmitFormatDiagnostic( 7221 S, inFunctionCall, Args[format_idx], 7222 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(), 7223 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 7224 return; 7225 } 7226 7227 // Str - The format string. NOTE: this is NOT null-terminated! 7228 StringRef StrRef = FExpr->getString(); 7229 const char *Str = StrRef.data(); 7230 // Account for cases where the string literal is truncated in a declaration. 7231 const ConstantArrayType *T = 7232 S.Context.getAsConstantArrayType(FExpr->getType()); 7233 assert(T && "String literal not of constant array type!"); 7234 size_t TypeSize = T->getSize().getZExtValue(); 7235 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 7236 const unsigned numDataArgs = Args.size() - firstDataArg; 7237 7238 // Emit a warning if the string literal is truncated and does not contain an 7239 // embedded null character. 7240 if (TypeSize <= StrRef.size() && 7241 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 7242 CheckFormatHandler::EmitFormatDiagnostic( 7243 S, inFunctionCall, Args[format_idx], 7244 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 7245 FExpr->getLocStart(), 7246 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 7247 return; 7248 } 7249 7250 // CHECK: empty format string? 7251 if (StrLen == 0 && numDataArgs > 0) { 7252 CheckFormatHandler::EmitFormatDiagnostic( 7253 S, inFunctionCall, Args[format_idx], 7254 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(), 7255 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 7256 return; 7257 } 7258 7259 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 7260 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 7261 Type == Sema::FST_OSTrace) { 7262 CheckPrintfHandler H( 7263 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 7264 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 7265 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 7266 CheckedVarArgs, UncoveredArg); 7267 7268 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 7269 S.getLangOpts(), 7270 S.Context.getTargetInfo(), 7271 Type == Sema::FST_FreeBSDKPrintf)) 7272 H.DoneProcessing(); 7273 } else if (Type == Sema::FST_Scanf) { 7274 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 7275 numDataArgs, Str, HasVAListArg, Args, format_idx, 7276 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 7277 7278 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 7279 S.getLangOpts(), 7280 S.Context.getTargetInfo())) 7281 H.DoneProcessing(); 7282 } // TODO: handle other formats 7283 } 7284 7285 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 7286 // Str - The format string. NOTE: this is NOT null-terminated! 7287 StringRef StrRef = FExpr->getString(); 7288 const char *Str = StrRef.data(); 7289 // Account for cases where the string literal is truncated in a declaration. 7290 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 7291 assert(T && "String literal not of constant array type!"); 7292 size_t TypeSize = T->getSize().getZExtValue(); 7293 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 7294 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 7295 getLangOpts(), 7296 Context.getTargetInfo()); 7297 } 7298 7299 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 7300 7301 // Returns the related absolute value function that is larger, of 0 if one 7302 // does not exist. 7303 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 7304 switch (AbsFunction) { 7305 default: 7306 return 0; 7307 7308 case Builtin::BI__builtin_abs: 7309 return Builtin::BI__builtin_labs; 7310 case Builtin::BI__builtin_labs: 7311 return Builtin::BI__builtin_llabs; 7312 case Builtin::BI__builtin_llabs: 7313 return 0; 7314 7315 case Builtin::BI__builtin_fabsf: 7316 return Builtin::BI__builtin_fabs; 7317 case Builtin::BI__builtin_fabs: 7318 return Builtin::BI__builtin_fabsl; 7319 case Builtin::BI__builtin_fabsl: 7320 return 0; 7321 7322 case Builtin::BI__builtin_cabsf: 7323 return Builtin::BI__builtin_cabs; 7324 case Builtin::BI__builtin_cabs: 7325 return Builtin::BI__builtin_cabsl; 7326 case Builtin::BI__builtin_cabsl: 7327 return 0; 7328 7329 case Builtin::BIabs: 7330 return Builtin::BIlabs; 7331 case Builtin::BIlabs: 7332 return Builtin::BIllabs; 7333 case Builtin::BIllabs: 7334 return 0; 7335 7336 case Builtin::BIfabsf: 7337 return Builtin::BIfabs; 7338 case Builtin::BIfabs: 7339 return Builtin::BIfabsl; 7340 case Builtin::BIfabsl: 7341 return 0; 7342 7343 case Builtin::BIcabsf: 7344 return Builtin::BIcabs; 7345 case Builtin::BIcabs: 7346 return Builtin::BIcabsl; 7347 case Builtin::BIcabsl: 7348 return 0; 7349 } 7350 } 7351 7352 // Returns the argument type of the absolute value function. 7353 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 7354 unsigned AbsType) { 7355 if (AbsType == 0) 7356 return QualType(); 7357 7358 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 7359 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 7360 if (Error != ASTContext::GE_None) 7361 return QualType(); 7362 7363 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 7364 if (!FT) 7365 return QualType(); 7366 7367 if (FT->getNumParams() != 1) 7368 return QualType(); 7369 7370 return FT->getParamType(0); 7371 } 7372 7373 // Returns the best absolute value function, or zero, based on type and 7374 // current absolute value function. 7375 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 7376 unsigned AbsFunctionKind) { 7377 unsigned BestKind = 0; 7378 uint64_t ArgSize = Context.getTypeSize(ArgType); 7379 for (unsigned Kind = AbsFunctionKind; Kind != 0; 7380 Kind = getLargerAbsoluteValueFunction(Kind)) { 7381 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 7382 if (Context.getTypeSize(ParamType) >= ArgSize) { 7383 if (BestKind == 0) 7384 BestKind = Kind; 7385 else if (Context.hasSameType(ParamType, ArgType)) { 7386 BestKind = Kind; 7387 break; 7388 } 7389 } 7390 } 7391 return BestKind; 7392 } 7393 7394 enum AbsoluteValueKind { 7395 AVK_Integer, 7396 AVK_Floating, 7397 AVK_Complex 7398 }; 7399 7400 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 7401 if (T->isIntegralOrEnumerationType()) 7402 return AVK_Integer; 7403 if (T->isRealFloatingType()) 7404 return AVK_Floating; 7405 if (T->isAnyComplexType()) 7406 return AVK_Complex; 7407 7408 llvm_unreachable("Type not integer, floating, or complex"); 7409 } 7410 7411 // Changes the absolute value function to a different type. Preserves whether 7412 // the function is a builtin. 7413 static unsigned changeAbsFunction(unsigned AbsKind, 7414 AbsoluteValueKind ValueKind) { 7415 switch (ValueKind) { 7416 case AVK_Integer: 7417 switch (AbsKind) { 7418 default: 7419 return 0; 7420 case Builtin::BI__builtin_fabsf: 7421 case Builtin::BI__builtin_fabs: 7422 case Builtin::BI__builtin_fabsl: 7423 case Builtin::BI__builtin_cabsf: 7424 case Builtin::BI__builtin_cabs: 7425 case Builtin::BI__builtin_cabsl: 7426 return Builtin::BI__builtin_abs; 7427 case Builtin::BIfabsf: 7428 case Builtin::BIfabs: 7429 case Builtin::BIfabsl: 7430 case Builtin::BIcabsf: 7431 case Builtin::BIcabs: 7432 case Builtin::BIcabsl: 7433 return Builtin::BIabs; 7434 } 7435 case AVK_Floating: 7436 switch (AbsKind) { 7437 default: 7438 return 0; 7439 case Builtin::BI__builtin_abs: 7440 case Builtin::BI__builtin_labs: 7441 case Builtin::BI__builtin_llabs: 7442 case Builtin::BI__builtin_cabsf: 7443 case Builtin::BI__builtin_cabs: 7444 case Builtin::BI__builtin_cabsl: 7445 return Builtin::BI__builtin_fabsf; 7446 case Builtin::BIabs: 7447 case Builtin::BIlabs: 7448 case Builtin::BIllabs: 7449 case Builtin::BIcabsf: 7450 case Builtin::BIcabs: 7451 case Builtin::BIcabsl: 7452 return Builtin::BIfabsf; 7453 } 7454 case AVK_Complex: 7455 switch (AbsKind) { 7456 default: 7457 return 0; 7458 case Builtin::BI__builtin_abs: 7459 case Builtin::BI__builtin_labs: 7460 case Builtin::BI__builtin_llabs: 7461 case Builtin::BI__builtin_fabsf: 7462 case Builtin::BI__builtin_fabs: 7463 case Builtin::BI__builtin_fabsl: 7464 return Builtin::BI__builtin_cabsf; 7465 case Builtin::BIabs: 7466 case Builtin::BIlabs: 7467 case Builtin::BIllabs: 7468 case Builtin::BIfabsf: 7469 case Builtin::BIfabs: 7470 case Builtin::BIfabsl: 7471 return Builtin::BIcabsf; 7472 } 7473 } 7474 llvm_unreachable("Unable to convert function"); 7475 } 7476 7477 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 7478 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 7479 if (!FnInfo) 7480 return 0; 7481 7482 switch (FDecl->getBuiltinID()) { 7483 default: 7484 return 0; 7485 case Builtin::BI__builtin_abs: 7486 case Builtin::BI__builtin_fabs: 7487 case Builtin::BI__builtin_fabsf: 7488 case Builtin::BI__builtin_fabsl: 7489 case Builtin::BI__builtin_labs: 7490 case Builtin::BI__builtin_llabs: 7491 case Builtin::BI__builtin_cabs: 7492 case Builtin::BI__builtin_cabsf: 7493 case Builtin::BI__builtin_cabsl: 7494 case Builtin::BIabs: 7495 case Builtin::BIlabs: 7496 case Builtin::BIllabs: 7497 case Builtin::BIfabs: 7498 case Builtin::BIfabsf: 7499 case Builtin::BIfabsl: 7500 case Builtin::BIcabs: 7501 case Builtin::BIcabsf: 7502 case Builtin::BIcabsl: 7503 return FDecl->getBuiltinID(); 7504 } 7505 llvm_unreachable("Unknown Builtin type"); 7506 } 7507 7508 // If the replacement is valid, emit a note with replacement function. 7509 // Additionally, suggest including the proper header if not already included. 7510 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 7511 unsigned AbsKind, QualType ArgType) { 7512 bool EmitHeaderHint = true; 7513 const char *HeaderName = nullptr; 7514 const char *FunctionName = nullptr; 7515 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 7516 FunctionName = "std::abs"; 7517 if (ArgType->isIntegralOrEnumerationType()) { 7518 HeaderName = "cstdlib"; 7519 } else if (ArgType->isRealFloatingType()) { 7520 HeaderName = "cmath"; 7521 } else { 7522 llvm_unreachable("Invalid Type"); 7523 } 7524 7525 // Lookup all std::abs 7526 if (NamespaceDecl *Std = S.getStdNamespace()) { 7527 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 7528 R.suppressDiagnostics(); 7529 S.LookupQualifiedName(R, Std); 7530 7531 for (const auto *I : R) { 7532 const FunctionDecl *FDecl = nullptr; 7533 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 7534 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 7535 } else { 7536 FDecl = dyn_cast<FunctionDecl>(I); 7537 } 7538 if (!FDecl) 7539 continue; 7540 7541 // Found std::abs(), check that they are the right ones. 7542 if (FDecl->getNumParams() != 1) 7543 continue; 7544 7545 // Check that the parameter type can handle the argument. 7546 QualType ParamType = FDecl->getParamDecl(0)->getType(); 7547 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 7548 S.Context.getTypeSize(ArgType) <= 7549 S.Context.getTypeSize(ParamType)) { 7550 // Found a function, don't need the header hint. 7551 EmitHeaderHint = false; 7552 break; 7553 } 7554 } 7555 } 7556 } else { 7557 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 7558 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 7559 7560 if (HeaderName) { 7561 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 7562 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 7563 R.suppressDiagnostics(); 7564 S.LookupName(R, S.getCurScope()); 7565 7566 if (R.isSingleResult()) { 7567 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 7568 if (FD && FD->getBuiltinID() == AbsKind) { 7569 EmitHeaderHint = false; 7570 } else { 7571 return; 7572 } 7573 } else if (!R.empty()) { 7574 return; 7575 } 7576 } 7577 } 7578 7579 S.Diag(Loc, diag::note_replace_abs_function) 7580 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 7581 7582 if (!HeaderName) 7583 return; 7584 7585 if (!EmitHeaderHint) 7586 return; 7587 7588 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 7589 << FunctionName; 7590 } 7591 7592 template <std::size_t StrLen> 7593 static bool IsStdFunction(const FunctionDecl *FDecl, 7594 const char (&Str)[StrLen]) { 7595 if (!FDecl) 7596 return false; 7597 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 7598 return false; 7599 if (!FDecl->isInStdNamespace()) 7600 return false; 7601 7602 return true; 7603 } 7604 7605 // Warn when using the wrong abs() function. 7606 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 7607 const FunctionDecl *FDecl) { 7608 if (Call->getNumArgs() != 1) 7609 return; 7610 7611 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 7612 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 7613 if (AbsKind == 0 && !IsStdAbs) 7614 return; 7615 7616 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 7617 QualType ParamType = Call->getArg(0)->getType(); 7618 7619 // Unsigned types cannot be negative. Suggest removing the absolute value 7620 // function call. 7621 if (ArgType->isUnsignedIntegerType()) { 7622 const char *FunctionName = 7623 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 7624 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 7625 Diag(Call->getExprLoc(), diag::note_remove_abs) 7626 << FunctionName 7627 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 7628 return; 7629 } 7630 7631 // Taking the absolute value of a pointer is very suspicious, they probably 7632 // wanted to index into an array, dereference a pointer, call a function, etc. 7633 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 7634 unsigned DiagType = 0; 7635 if (ArgType->isFunctionType()) 7636 DiagType = 1; 7637 else if (ArgType->isArrayType()) 7638 DiagType = 2; 7639 7640 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 7641 return; 7642 } 7643 7644 // std::abs has overloads which prevent most of the absolute value problems 7645 // from occurring. 7646 if (IsStdAbs) 7647 return; 7648 7649 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 7650 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 7651 7652 // The argument and parameter are the same kind. Check if they are the right 7653 // size. 7654 if (ArgValueKind == ParamValueKind) { 7655 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 7656 return; 7657 7658 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 7659 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 7660 << FDecl << ArgType << ParamType; 7661 7662 if (NewAbsKind == 0) 7663 return; 7664 7665 emitReplacement(*this, Call->getExprLoc(), 7666 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 7667 return; 7668 } 7669 7670 // ArgValueKind != ParamValueKind 7671 // The wrong type of absolute value function was used. Attempt to find the 7672 // proper one. 7673 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 7674 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 7675 if (NewAbsKind == 0) 7676 return; 7677 7678 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 7679 << FDecl << ParamValueKind << ArgValueKind; 7680 7681 emitReplacement(*this, Call->getExprLoc(), 7682 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 7683 } 7684 7685 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 7686 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 7687 const FunctionDecl *FDecl) { 7688 if (!Call || !FDecl) return; 7689 7690 // Ignore template specializations and macros. 7691 if (inTemplateInstantiation()) return; 7692 if (Call->getExprLoc().isMacroID()) return; 7693 7694 // Only care about the one template argument, two function parameter std::max 7695 if (Call->getNumArgs() != 2) return; 7696 if (!IsStdFunction(FDecl, "max")) return; 7697 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 7698 if (!ArgList) return; 7699 if (ArgList->size() != 1) return; 7700 7701 // Check that template type argument is unsigned integer. 7702 const auto& TA = ArgList->get(0); 7703 if (TA.getKind() != TemplateArgument::Type) return; 7704 QualType ArgType = TA.getAsType(); 7705 if (!ArgType->isUnsignedIntegerType()) return; 7706 7707 // See if either argument is a literal zero. 7708 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 7709 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 7710 if (!MTE) return false; 7711 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr()); 7712 if (!Num) return false; 7713 if (Num->getValue() != 0) return false; 7714 return true; 7715 }; 7716 7717 const Expr *FirstArg = Call->getArg(0); 7718 const Expr *SecondArg = Call->getArg(1); 7719 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 7720 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 7721 7722 // Only warn when exactly one argument is zero. 7723 if (IsFirstArgZero == IsSecondArgZero) return; 7724 7725 SourceRange FirstRange = FirstArg->getSourceRange(); 7726 SourceRange SecondRange = SecondArg->getSourceRange(); 7727 7728 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 7729 7730 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 7731 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 7732 7733 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 7734 SourceRange RemovalRange; 7735 if (IsFirstArgZero) { 7736 RemovalRange = SourceRange(FirstRange.getBegin(), 7737 SecondRange.getBegin().getLocWithOffset(-1)); 7738 } else { 7739 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 7740 SecondRange.getEnd()); 7741 } 7742 7743 Diag(Call->getExprLoc(), diag::note_remove_max_call) 7744 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 7745 << FixItHint::CreateRemoval(RemovalRange); 7746 } 7747 7748 //===--- CHECK: Standard memory functions ---------------------------------===// 7749 7750 /// Takes the expression passed to the size_t parameter of functions 7751 /// such as memcmp, strncat, etc and warns if it's a comparison. 7752 /// 7753 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 7754 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 7755 IdentifierInfo *FnName, 7756 SourceLocation FnLoc, 7757 SourceLocation RParenLoc) { 7758 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 7759 if (!Size) 7760 return false; 7761 7762 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 7763 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 7764 return false; 7765 7766 SourceRange SizeRange = Size->getSourceRange(); 7767 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 7768 << SizeRange << FnName; 7769 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 7770 << FnName << FixItHint::CreateInsertion( 7771 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")") 7772 << FixItHint::CreateRemoval(RParenLoc); 7773 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 7774 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 7775 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 7776 ")"); 7777 7778 return true; 7779 } 7780 7781 /// Determine whether the given type is or contains a dynamic class type 7782 /// (e.g., whether it has a vtable). 7783 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 7784 bool &IsContained) { 7785 // Look through array types while ignoring qualifiers. 7786 const Type *Ty = T->getBaseElementTypeUnsafe(); 7787 IsContained = false; 7788 7789 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 7790 RD = RD ? RD->getDefinition() : nullptr; 7791 if (!RD || RD->isInvalidDecl()) 7792 return nullptr; 7793 7794 if (RD->isDynamicClass()) 7795 return RD; 7796 7797 // Check all the fields. If any bases were dynamic, the class is dynamic. 7798 // It's impossible for a class to transitively contain itself by value, so 7799 // infinite recursion is impossible. 7800 for (auto *FD : RD->fields()) { 7801 bool SubContained; 7802 if (const CXXRecordDecl *ContainedRD = 7803 getContainedDynamicClass(FD->getType(), SubContained)) { 7804 IsContained = true; 7805 return ContainedRD; 7806 } 7807 } 7808 7809 return nullptr; 7810 } 7811 7812 /// If E is a sizeof expression, returns its argument expression, 7813 /// otherwise returns NULL. 7814 static const Expr *getSizeOfExprArg(const Expr *E) { 7815 if (const UnaryExprOrTypeTraitExpr *SizeOf = 7816 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 7817 if (SizeOf->getKind() == UETT_SizeOf && !SizeOf->isArgumentType()) 7818 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 7819 7820 return nullptr; 7821 } 7822 7823 /// If E is a sizeof expression, returns its argument type. 7824 static QualType getSizeOfArgType(const Expr *E) { 7825 if (const UnaryExprOrTypeTraitExpr *SizeOf = 7826 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 7827 if (SizeOf->getKind() == UETT_SizeOf) 7828 return SizeOf->getTypeOfArgument(); 7829 7830 return QualType(); 7831 } 7832 7833 namespace { 7834 7835 struct SearchNonTrivialToInitializeField 7836 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 7837 using Super = 7838 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 7839 7840 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 7841 7842 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 7843 SourceLocation SL) { 7844 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 7845 asDerived().visitArray(PDIK, AT, SL); 7846 return; 7847 } 7848 7849 Super::visitWithKind(PDIK, FT, SL); 7850 } 7851 7852 void visitARCStrong(QualType FT, SourceLocation SL) { 7853 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 7854 } 7855 void visitARCWeak(QualType FT, SourceLocation SL) { 7856 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 7857 } 7858 void visitStruct(QualType FT, SourceLocation SL) { 7859 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 7860 visit(FD->getType(), FD->getLocation()); 7861 } 7862 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 7863 const ArrayType *AT, SourceLocation SL) { 7864 visit(getContext().getBaseElementType(AT), SL); 7865 } 7866 void visitTrivial(QualType FT, SourceLocation SL) {} 7867 7868 static void diag(QualType RT, const Expr *E, Sema &S) { 7869 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 7870 } 7871 7872 ASTContext &getContext() { return S.getASTContext(); } 7873 7874 const Expr *E; 7875 Sema &S; 7876 }; 7877 7878 struct SearchNonTrivialToCopyField 7879 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 7880 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 7881 7882 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 7883 7884 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 7885 SourceLocation SL) { 7886 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 7887 asDerived().visitArray(PCK, AT, SL); 7888 return; 7889 } 7890 7891 Super::visitWithKind(PCK, FT, SL); 7892 } 7893 7894 void visitARCStrong(QualType FT, SourceLocation SL) { 7895 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 7896 } 7897 void visitARCWeak(QualType FT, SourceLocation SL) { 7898 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 7899 } 7900 void visitStruct(QualType FT, SourceLocation SL) { 7901 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 7902 visit(FD->getType(), FD->getLocation()); 7903 } 7904 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 7905 SourceLocation SL) { 7906 visit(getContext().getBaseElementType(AT), SL); 7907 } 7908 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 7909 SourceLocation SL) {} 7910 void visitTrivial(QualType FT, SourceLocation SL) {} 7911 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 7912 7913 static void diag(QualType RT, const Expr *E, Sema &S) { 7914 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 7915 } 7916 7917 ASTContext &getContext() { return S.getASTContext(); } 7918 7919 const Expr *E; 7920 Sema &S; 7921 }; 7922 7923 } 7924 7925 /// Check for dangerous or invalid arguments to memset(). 7926 /// 7927 /// This issues warnings on known problematic, dangerous or unspecified 7928 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 7929 /// function calls. 7930 /// 7931 /// \param Call The call expression to diagnose. 7932 void Sema::CheckMemaccessArguments(const CallExpr *Call, 7933 unsigned BId, 7934 IdentifierInfo *FnName) { 7935 assert(BId != 0); 7936 7937 // It is possible to have a non-standard definition of memset. Validate 7938 // we have enough arguments, and if not, abort further checking. 7939 unsigned ExpectedNumArgs = 7940 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 7941 if (Call->getNumArgs() < ExpectedNumArgs) 7942 return; 7943 7944 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 7945 BId == Builtin::BIstrndup ? 1 : 2); 7946 unsigned LenArg = 7947 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 7948 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 7949 7950 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 7951 Call->getLocStart(), Call->getRParenLoc())) 7952 return; 7953 7954 // We have special checking when the length is a sizeof expression. 7955 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 7956 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 7957 llvm::FoldingSetNodeID SizeOfArgID; 7958 7959 // Although widely used, 'bzero' is not a standard function. Be more strict 7960 // with the argument types before allowing diagnostics and only allow the 7961 // form bzero(ptr, sizeof(...)). 7962 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 7963 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 7964 return; 7965 7966 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 7967 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 7968 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 7969 7970 QualType DestTy = Dest->getType(); 7971 QualType PointeeTy; 7972 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 7973 PointeeTy = DestPtrTy->getPointeeType(); 7974 7975 // Never warn about void type pointers. This can be used to suppress 7976 // false positives. 7977 if (PointeeTy->isVoidType()) 7978 continue; 7979 7980 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 7981 // actually comparing the expressions for equality. Because computing the 7982 // expression IDs can be expensive, we only do this if the diagnostic is 7983 // enabled. 7984 if (SizeOfArg && 7985 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 7986 SizeOfArg->getExprLoc())) { 7987 // We only compute IDs for expressions if the warning is enabled, and 7988 // cache the sizeof arg's ID. 7989 if (SizeOfArgID == llvm::FoldingSetNodeID()) 7990 SizeOfArg->Profile(SizeOfArgID, Context, true); 7991 llvm::FoldingSetNodeID DestID; 7992 Dest->Profile(DestID, Context, true); 7993 if (DestID == SizeOfArgID) { 7994 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 7995 // over sizeof(src) as well. 7996 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 7997 StringRef ReadableName = FnName->getName(); 7998 7999 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 8000 if (UnaryOp->getOpcode() == UO_AddrOf) 8001 ActionIdx = 1; // If its an address-of operator, just remove it. 8002 if (!PointeeTy->isIncompleteType() && 8003 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 8004 ActionIdx = 2; // If the pointee's size is sizeof(char), 8005 // suggest an explicit length. 8006 8007 // If the function is defined as a builtin macro, do not show macro 8008 // expansion. 8009 SourceLocation SL = SizeOfArg->getExprLoc(); 8010 SourceRange DSR = Dest->getSourceRange(); 8011 SourceRange SSR = SizeOfArg->getSourceRange(); 8012 SourceManager &SM = getSourceManager(); 8013 8014 if (SM.isMacroArgExpansion(SL)) { 8015 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 8016 SL = SM.getSpellingLoc(SL); 8017 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 8018 SM.getSpellingLoc(DSR.getEnd())); 8019 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 8020 SM.getSpellingLoc(SSR.getEnd())); 8021 } 8022 8023 DiagRuntimeBehavior(SL, SizeOfArg, 8024 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 8025 << ReadableName 8026 << PointeeTy 8027 << DestTy 8028 << DSR 8029 << SSR); 8030 DiagRuntimeBehavior(SL, SizeOfArg, 8031 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 8032 << ActionIdx 8033 << SSR); 8034 8035 break; 8036 } 8037 } 8038 8039 // Also check for cases where the sizeof argument is the exact same 8040 // type as the memory argument, and where it points to a user-defined 8041 // record type. 8042 if (SizeOfArgTy != QualType()) { 8043 if (PointeeTy->isRecordType() && 8044 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 8045 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 8046 PDiag(diag::warn_sizeof_pointer_type_memaccess) 8047 << FnName << SizeOfArgTy << ArgIdx 8048 << PointeeTy << Dest->getSourceRange() 8049 << LenExpr->getSourceRange()); 8050 break; 8051 } 8052 } 8053 } else if (DestTy->isArrayType()) { 8054 PointeeTy = DestTy; 8055 } 8056 8057 if (PointeeTy == QualType()) 8058 continue; 8059 8060 // Always complain about dynamic classes. 8061 bool IsContained; 8062 if (const CXXRecordDecl *ContainedRD = 8063 getContainedDynamicClass(PointeeTy, IsContained)) { 8064 8065 unsigned OperationType = 0; 8066 // "overwritten" if we're warning about the destination for any call 8067 // but memcmp; otherwise a verb appropriate to the call. 8068 if (ArgIdx != 0 || BId == Builtin::BImemcmp) { 8069 if (BId == Builtin::BImemcpy) 8070 OperationType = 1; 8071 else if(BId == Builtin::BImemmove) 8072 OperationType = 2; 8073 else if (BId == Builtin::BImemcmp) 8074 OperationType = 3; 8075 } 8076 8077 DiagRuntimeBehavior( 8078 Dest->getExprLoc(), Dest, 8079 PDiag(diag::warn_dyn_class_memaccess) 8080 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx) 8081 << FnName << IsContained << ContainedRD << OperationType 8082 << Call->getCallee()->getSourceRange()); 8083 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 8084 BId != Builtin::BImemset) 8085 DiagRuntimeBehavior( 8086 Dest->getExprLoc(), Dest, 8087 PDiag(diag::warn_arc_object_memaccess) 8088 << ArgIdx << FnName << PointeeTy 8089 << Call->getCallee()->getSourceRange()); 8090 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 8091 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 8092 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 8093 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 8094 PDiag(diag::warn_cstruct_memaccess) 8095 << ArgIdx << FnName << PointeeTy << 0); 8096 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 8097 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 8098 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 8099 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 8100 PDiag(diag::warn_cstruct_memaccess) 8101 << ArgIdx << FnName << PointeeTy << 1); 8102 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 8103 } else { 8104 continue; 8105 } 8106 } else 8107 continue; 8108 8109 DiagRuntimeBehavior( 8110 Dest->getExprLoc(), Dest, 8111 PDiag(diag::note_bad_memaccess_silence) 8112 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 8113 break; 8114 } 8115 } 8116 8117 // A little helper routine: ignore addition and subtraction of integer literals. 8118 // This intentionally does not ignore all integer constant expressions because 8119 // we don't want to remove sizeof(). 8120 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 8121 Ex = Ex->IgnoreParenCasts(); 8122 8123 while (true) { 8124 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 8125 if (!BO || !BO->isAdditiveOp()) 8126 break; 8127 8128 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 8129 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 8130 8131 if (isa<IntegerLiteral>(RHS)) 8132 Ex = LHS; 8133 else if (isa<IntegerLiteral>(LHS)) 8134 Ex = RHS; 8135 else 8136 break; 8137 } 8138 8139 return Ex; 8140 } 8141 8142 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 8143 ASTContext &Context) { 8144 // Only handle constant-sized or VLAs, but not flexible members. 8145 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 8146 // Only issue the FIXIT for arrays of size > 1. 8147 if (CAT->getSize().getSExtValue() <= 1) 8148 return false; 8149 } else if (!Ty->isVariableArrayType()) { 8150 return false; 8151 } 8152 return true; 8153 } 8154 8155 // Warn if the user has made the 'size' argument to strlcpy or strlcat 8156 // be the size of the source, instead of the destination. 8157 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 8158 IdentifierInfo *FnName) { 8159 8160 // Don't crash if the user has the wrong number of arguments 8161 unsigned NumArgs = Call->getNumArgs(); 8162 if ((NumArgs != 3) && (NumArgs != 4)) 8163 return; 8164 8165 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 8166 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 8167 const Expr *CompareWithSrc = nullptr; 8168 8169 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 8170 Call->getLocStart(), Call->getRParenLoc())) 8171 return; 8172 8173 // Look for 'strlcpy(dst, x, sizeof(x))' 8174 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 8175 CompareWithSrc = Ex; 8176 else { 8177 // Look for 'strlcpy(dst, x, strlen(x))' 8178 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 8179 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 8180 SizeCall->getNumArgs() == 1) 8181 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 8182 } 8183 } 8184 8185 if (!CompareWithSrc) 8186 return; 8187 8188 // Determine if the argument to sizeof/strlen is equal to the source 8189 // argument. In principle there's all kinds of things you could do 8190 // here, for instance creating an == expression and evaluating it with 8191 // EvaluateAsBooleanCondition, but this uses a more direct technique: 8192 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 8193 if (!SrcArgDRE) 8194 return; 8195 8196 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 8197 if (!CompareWithSrcDRE || 8198 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 8199 return; 8200 8201 const Expr *OriginalSizeArg = Call->getArg(2); 8202 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size) 8203 << OriginalSizeArg->getSourceRange() << FnName; 8204 8205 // Output a FIXIT hint if the destination is an array (rather than a 8206 // pointer to an array). This could be enhanced to handle some 8207 // pointers if we know the actual size, like if DstArg is 'array+2' 8208 // we could say 'sizeof(array)-2'. 8209 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 8210 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 8211 return; 8212 8213 SmallString<128> sizeString; 8214 llvm::raw_svector_ostream OS(sizeString); 8215 OS << "sizeof("; 8216 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 8217 OS << ")"; 8218 8219 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size) 8220 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 8221 OS.str()); 8222 } 8223 8224 /// Check if two expressions refer to the same declaration. 8225 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 8226 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 8227 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 8228 return D1->getDecl() == D2->getDecl(); 8229 return false; 8230 } 8231 8232 static const Expr *getStrlenExprArg(const Expr *E) { 8233 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 8234 const FunctionDecl *FD = CE->getDirectCallee(); 8235 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 8236 return nullptr; 8237 return CE->getArg(0)->IgnoreParenCasts(); 8238 } 8239 return nullptr; 8240 } 8241 8242 // Warn on anti-patterns as the 'size' argument to strncat. 8243 // The correct size argument should look like following: 8244 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 8245 void Sema::CheckStrncatArguments(const CallExpr *CE, 8246 IdentifierInfo *FnName) { 8247 // Don't crash if the user has the wrong number of arguments. 8248 if (CE->getNumArgs() < 3) 8249 return; 8250 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 8251 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 8252 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 8253 8254 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(), 8255 CE->getRParenLoc())) 8256 return; 8257 8258 // Identify common expressions, which are wrongly used as the size argument 8259 // to strncat and may lead to buffer overflows. 8260 unsigned PatternType = 0; 8261 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 8262 // - sizeof(dst) 8263 if (referToTheSameDecl(SizeOfArg, DstArg)) 8264 PatternType = 1; 8265 // - sizeof(src) 8266 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 8267 PatternType = 2; 8268 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 8269 if (BE->getOpcode() == BO_Sub) { 8270 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 8271 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 8272 // - sizeof(dst) - strlen(dst) 8273 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 8274 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 8275 PatternType = 1; 8276 // - sizeof(src) - (anything) 8277 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 8278 PatternType = 2; 8279 } 8280 } 8281 8282 if (PatternType == 0) 8283 return; 8284 8285 // Generate the diagnostic. 8286 SourceLocation SL = LenArg->getLocStart(); 8287 SourceRange SR = LenArg->getSourceRange(); 8288 SourceManager &SM = getSourceManager(); 8289 8290 // If the function is defined as a builtin macro, do not show macro expansion. 8291 if (SM.isMacroArgExpansion(SL)) { 8292 SL = SM.getSpellingLoc(SL); 8293 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 8294 SM.getSpellingLoc(SR.getEnd())); 8295 } 8296 8297 // Check if the destination is an array (rather than a pointer to an array). 8298 QualType DstTy = DstArg->getType(); 8299 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 8300 Context); 8301 if (!isKnownSizeArray) { 8302 if (PatternType == 1) 8303 Diag(SL, diag::warn_strncat_wrong_size) << SR; 8304 else 8305 Diag(SL, diag::warn_strncat_src_size) << SR; 8306 return; 8307 } 8308 8309 if (PatternType == 1) 8310 Diag(SL, diag::warn_strncat_large_size) << SR; 8311 else 8312 Diag(SL, diag::warn_strncat_src_size) << SR; 8313 8314 SmallString<128> sizeString; 8315 llvm::raw_svector_ostream OS(sizeString); 8316 OS << "sizeof("; 8317 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 8318 OS << ") - "; 8319 OS << "strlen("; 8320 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 8321 OS << ") - 1"; 8322 8323 Diag(SL, diag::note_strncat_wrong_size) 8324 << FixItHint::CreateReplacement(SR, OS.str()); 8325 } 8326 8327 //===--- CHECK: Return Address of Stack Variable --------------------------===// 8328 8329 static const Expr *EvalVal(const Expr *E, 8330 SmallVectorImpl<const DeclRefExpr *> &refVars, 8331 const Decl *ParentDecl); 8332 static const Expr *EvalAddr(const Expr *E, 8333 SmallVectorImpl<const DeclRefExpr *> &refVars, 8334 const Decl *ParentDecl); 8335 8336 /// CheckReturnStackAddr - Check if a return statement returns the address 8337 /// of a stack variable. 8338 static void 8339 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType, 8340 SourceLocation ReturnLoc) { 8341 const Expr *stackE = nullptr; 8342 SmallVector<const DeclRefExpr *, 8> refVars; 8343 8344 // Perform checking for returned stack addresses, local blocks, 8345 // label addresses or references to temporaries. 8346 if (lhsType->isPointerType() || 8347 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) { 8348 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr); 8349 } else if (lhsType->isReferenceType()) { 8350 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr); 8351 } 8352 8353 if (!stackE) 8354 return; // Nothing suspicious was found. 8355 8356 // Parameters are initialized in the calling scope, so taking the address 8357 // of a parameter reference doesn't need a warning. 8358 for (auto *DRE : refVars) 8359 if (isa<ParmVarDecl>(DRE->getDecl())) 8360 return; 8361 8362 SourceLocation diagLoc; 8363 SourceRange diagRange; 8364 if (refVars.empty()) { 8365 diagLoc = stackE->getLocStart(); 8366 diagRange = stackE->getSourceRange(); 8367 } else { 8368 // We followed through a reference variable. 'stackE' contains the 8369 // problematic expression but we will warn at the return statement pointing 8370 // at the reference variable. We will later display the "trail" of 8371 // reference variables using notes. 8372 diagLoc = refVars[0]->getLocStart(); 8373 diagRange = refVars[0]->getSourceRange(); 8374 } 8375 8376 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { 8377 // address of local var 8378 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType() 8379 << DR->getDecl()->getDeclName() << diagRange; 8380 } else if (isa<BlockExpr>(stackE)) { // local block. 8381 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange; 8382 } else if (isa<AddrLabelExpr>(stackE)) { // address of label. 8383 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange; 8384 } else { // local temporary. 8385 // If there is an LValue->RValue conversion, then the value of the 8386 // reference type is used, not the reference. 8387 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) { 8388 if (ICE->getCastKind() == CK_LValueToRValue) { 8389 return; 8390 } 8391 } 8392 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref) 8393 << lhsType->isReferenceType() << diagRange; 8394 } 8395 8396 // Display the "trail" of reference variables that we followed until we 8397 // found the problematic expression using notes. 8398 for (unsigned i = 0, e = refVars.size(); i != e; ++i) { 8399 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl()); 8400 // If this var binds to another reference var, show the range of the next 8401 // var, otherwise the var binds to the problematic expression, in which case 8402 // show the range of the expression. 8403 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange() 8404 : stackE->getSourceRange(); 8405 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind) 8406 << VD->getDeclName() << range; 8407 } 8408 } 8409 8410 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that 8411 /// check if the expression in a return statement evaluates to an address 8412 /// to a location on the stack, a local block, an address of a label, or a 8413 /// reference to local temporary. The recursion is used to traverse the 8414 /// AST of the return expression, with recursion backtracking when we 8415 /// encounter a subexpression that (1) clearly does not lead to one of the 8416 /// above problematic expressions (2) is something we cannot determine leads to 8417 /// a problematic expression based on such local checking. 8418 /// 8419 /// Both EvalAddr and EvalVal follow through reference variables to evaluate 8420 /// the expression that they point to. Such variables are added to the 8421 /// 'refVars' vector so that we know what the reference variable "trail" was. 8422 /// 8423 /// EvalAddr processes expressions that are pointers that are used as 8424 /// references (and not L-values). EvalVal handles all other values. 8425 /// At the base case of the recursion is a check for the above problematic 8426 /// expressions. 8427 /// 8428 /// This implementation handles: 8429 /// 8430 /// * pointer-to-pointer casts 8431 /// * implicit conversions from array references to pointers 8432 /// * taking the address of fields 8433 /// * arbitrary interplay between "&" and "*" operators 8434 /// * pointer arithmetic from an address of a stack variable 8435 /// * taking the address of an array element where the array is on the stack 8436 static const Expr *EvalAddr(const Expr *E, 8437 SmallVectorImpl<const DeclRefExpr *> &refVars, 8438 const Decl *ParentDecl) { 8439 if (E->isTypeDependent()) 8440 return nullptr; 8441 8442 // We should only be called for evaluating pointer expressions. 8443 assert((E->getType()->isAnyPointerType() || 8444 E->getType()->isBlockPointerType() || 8445 E->getType()->isObjCQualifiedIdType()) && 8446 "EvalAddr only works on pointers"); 8447 8448 E = E->IgnoreParens(); 8449 8450 // Our "symbolic interpreter" is just a dispatch off the currently 8451 // viewed AST node. We then recursively traverse the AST by calling 8452 // EvalAddr and EvalVal appropriately. 8453 switch (E->getStmtClass()) { 8454 case Stmt::DeclRefExprClass: { 8455 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 8456 8457 // If we leave the immediate function, the lifetime isn't about to end. 8458 if (DR->refersToEnclosingVariableOrCapture()) 8459 return nullptr; 8460 8461 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) 8462 // If this is a reference variable, follow through to the expression that 8463 // it points to. 8464 if (V->hasLocalStorage() && 8465 V->getType()->isReferenceType() && V->hasInit()) { 8466 // Add the reference variable to the "trail". 8467 refVars.push_back(DR); 8468 return EvalAddr(V->getInit(), refVars, ParentDecl); 8469 } 8470 8471 return nullptr; 8472 } 8473 8474 case Stmt::UnaryOperatorClass: { 8475 // The only unary operator that make sense to handle here 8476 // is AddrOf. All others don't make sense as pointers. 8477 const UnaryOperator *U = cast<UnaryOperator>(E); 8478 8479 if (U->getOpcode() == UO_AddrOf) 8480 return EvalVal(U->getSubExpr(), refVars, ParentDecl); 8481 return nullptr; 8482 } 8483 8484 case Stmt::BinaryOperatorClass: { 8485 // Handle pointer arithmetic. All other binary operators are not valid 8486 // in this context. 8487 const BinaryOperator *B = cast<BinaryOperator>(E); 8488 BinaryOperatorKind op = B->getOpcode(); 8489 8490 if (op != BO_Add && op != BO_Sub) 8491 return nullptr; 8492 8493 const Expr *Base = B->getLHS(); 8494 8495 // Determine which argument is the real pointer base. It could be 8496 // the RHS argument instead of the LHS. 8497 if (!Base->getType()->isPointerType()) 8498 Base = B->getRHS(); 8499 8500 assert(Base->getType()->isPointerType()); 8501 return EvalAddr(Base, refVars, ParentDecl); 8502 } 8503 8504 // For conditional operators we need to see if either the LHS or RHS are 8505 // valid DeclRefExpr*s. If one of them is valid, we return it. 8506 case Stmt::ConditionalOperatorClass: { 8507 const ConditionalOperator *C = cast<ConditionalOperator>(E); 8508 8509 // Handle the GNU extension for missing LHS. 8510 // FIXME: That isn't a ConditionalOperator, so doesn't get here. 8511 if (const Expr *LHSExpr = C->getLHS()) { 8512 // In C++, we can have a throw-expression, which has 'void' type. 8513 if (!LHSExpr->getType()->isVoidType()) 8514 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl)) 8515 return LHS; 8516 } 8517 8518 // In C++, we can have a throw-expression, which has 'void' type. 8519 if (C->getRHS()->getType()->isVoidType()) 8520 return nullptr; 8521 8522 return EvalAddr(C->getRHS(), refVars, ParentDecl); 8523 } 8524 8525 case Stmt::BlockExprClass: 8526 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures()) 8527 return E; // local block. 8528 return nullptr; 8529 8530 case Stmt::AddrLabelExprClass: 8531 return E; // address of label. 8532 8533 case Stmt::ExprWithCleanupsClass: 8534 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars, 8535 ParentDecl); 8536 8537 // For casts, we need to handle conversions from arrays to 8538 // pointer values, and pointer-to-pointer conversions. 8539 case Stmt::ImplicitCastExprClass: 8540 case Stmt::CStyleCastExprClass: 8541 case Stmt::CXXFunctionalCastExprClass: 8542 case Stmt::ObjCBridgedCastExprClass: 8543 case Stmt::CXXStaticCastExprClass: 8544 case Stmt::CXXDynamicCastExprClass: 8545 case Stmt::CXXConstCastExprClass: 8546 case Stmt::CXXReinterpretCastExprClass: { 8547 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr(); 8548 switch (cast<CastExpr>(E)->getCastKind()) { 8549 case CK_LValueToRValue: 8550 case CK_NoOp: 8551 case CK_BaseToDerived: 8552 case CK_DerivedToBase: 8553 case CK_UncheckedDerivedToBase: 8554 case CK_Dynamic: 8555 case CK_CPointerToObjCPointerCast: 8556 case CK_BlockPointerToObjCPointerCast: 8557 case CK_AnyPointerToBlockPointerCast: 8558 return EvalAddr(SubExpr, refVars, ParentDecl); 8559 8560 case CK_ArrayToPointerDecay: 8561 return EvalVal(SubExpr, refVars, ParentDecl); 8562 8563 case CK_BitCast: 8564 if (SubExpr->getType()->isAnyPointerType() || 8565 SubExpr->getType()->isBlockPointerType() || 8566 SubExpr->getType()->isObjCQualifiedIdType()) 8567 return EvalAddr(SubExpr, refVars, ParentDecl); 8568 else 8569 return nullptr; 8570 8571 default: 8572 return nullptr; 8573 } 8574 } 8575 8576 case Stmt::MaterializeTemporaryExprClass: 8577 if (const Expr *Result = 8578 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 8579 refVars, ParentDecl)) 8580 return Result; 8581 return E; 8582 8583 // Everything else: we simply don't reason about them. 8584 default: 8585 return nullptr; 8586 } 8587 } 8588 8589 /// EvalVal - This function is complements EvalAddr in the mutual recursion. 8590 /// See the comments for EvalAddr for more details. 8591 static const Expr *EvalVal(const Expr *E, 8592 SmallVectorImpl<const DeclRefExpr *> &refVars, 8593 const Decl *ParentDecl) { 8594 do { 8595 // We should only be called for evaluating non-pointer expressions, or 8596 // expressions with a pointer type that are not used as references but 8597 // instead 8598 // are l-values (e.g., DeclRefExpr with a pointer type). 8599 8600 // Our "symbolic interpreter" is just a dispatch off the currently 8601 // viewed AST node. We then recursively traverse the AST by calling 8602 // EvalAddr and EvalVal appropriately. 8603 8604 E = E->IgnoreParens(); 8605 switch (E->getStmtClass()) { 8606 case Stmt::ImplicitCastExprClass: { 8607 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E); 8608 if (IE->getValueKind() == VK_LValue) { 8609 E = IE->getSubExpr(); 8610 continue; 8611 } 8612 return nullptr; 8613 } 8614 8615 case Stmt::ExprWithCleanupsClass: 8616 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars, 8617 ParentDecl); 8618 8619 case Stmt::DeclRefExprClass: { 8620 // When we hit a DeclRefExpr we are looking at code that refers to a 8621 // variable's name. If it's not a reference variable we check if it has 8622 // local storage within the function, and if so, return the expression. 8623 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 8624 8625 // If we leave the immediate function, the lifetime isn't about to end. 8626 if (DR->refersToEnclosingVariableOrCapture()) 8627 return nullptr; 8628 8629 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) { 8630 // Check if it refers to itself, e.g. "int& i = i;". 8631 if (V == ParentDecl) 8632 return DR; 8633 8634 if (V->hasLocalStorage()) { 8635 if (!V->getType()->isReferenceType()) 8636 return DR; 8637 8638 // Reference variable, follow through to the expression that 8639 // it points to. 8640 if (V->hasInit()) { 8641 // Add the reference variable to the "trail". 8642 refVars.push_back(DR); 8643 return EvalVal(V->getInit(), refVars, V); 8644 } 8645 } 8646 } 8647 8648 return nullptr; 8649 } 8650 8651 case Stmt::UnaryOperatorClass: { 8652 // The only unary operator that make sense to handle here 8653 // is Deref. All others don't resolve to a "name." This includes 8654 // handling all sorts of rvalues passed to a unary operator. 8655 const UnaryOperator *U = cast<UnaryOperator>(E); 8656 8657 if (U->getOpcode() == UO_Deref) 8658 return EvalAddr(U->getSubExpr(), refVars, ParentDecl); 8659 8660 return nullptr; 8661 } 8662 8663 case Stmt::ArraySubscriptExprClass: { 8664 // Array subscripts are potential references to data on the stack. We 8665 // retrieve the DeclRefExpr* for the array variable if it indeed 8666 // has local storage. 8667 const auto *ASE = cast<ArraySubscriptExpr>(E); 8668 if (ASE->isTypeDependent()) 8669 return nullptr; 8670 return EvalAddr(ASE->getBase(), refVars, ParentDecl); 8671 } 8672 8673 case Stmt::OMPArraySectionExprClass: { 8674 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars, 8675 ParentDecl); 8676 } 8677 8678 case Stmt::ConditionalOperatorClass: { 8679 // For conditional operators we need to see if either the LHS or RHS are 8680 // non-NULL Expr's. If one is non-NULL, we return it. 8681 const ConditionalOperator *C = cast<ConditionalOperator>(E); 8682 8683 // Handle the GNU extension for missing LHS. 8684 if (const Expr *LHSExpr = C->getLHS()) { 8685 // In C++, we can have a throw-expression, which has 'void' type. 8686 if (!LHSExpr->getType()->isVoidType()) 8687 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl)) 8688 return LHS; 8689 } 8690 8691 // In C++, we can have a throw-expression, which has 'void' type. 8692 if (C->getRHS()->getType()->isVoidType()) 8693 return nullptr; 8694 8695 return EvalVal(C->getRHS(), refVars, ParentDecl); 8696 } 8697 8698 // Accesses to members are potential references to data on the stack. 8699 case Stmt::MemberExprClass: { 8700 const MemberExpr *M = cast<MemberExpr>(E); 8701 8702 // Check for indirect access. We only want direct field accesses. 8703 if (M->isArrow()) 8704 return nullptr; 8705 8706 // Check whether the member type is itself a reference, in which case 8707 // we're not going to refer to the member, but to what the member refers 8708 // to. 8709 if (M->getMemberDecl()->getType()->isReferenceType()) 8710 return nullptr; 8711 8712 return EvalVal(M->getBase(), refVars, ParentDecl); 8713 } 8714 8715 case Stmt::MaterializeTemporaryExprClass: 8716 if (const Expr *Result = 8717 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 8718 refVars, ParentDecl)) 8719 return Result; 8720 return E; 8721 8722 default: 8723 // Check that we don't return or take the address of a reference to a 8724 // temporary. This is only useful in C++. 8725 if (!E->isTypeDependent() && E->isRValue()) 8726 return E; 8727 8728 // Everything else: we simply don't reason about them. 8729 return nullptr; 8730 } 8731 } while (true); 8732 } 8733 8734 void 8735 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 8736 SourceLocation ReturnLoc, 8737 bool isObjCMethod, 8738 const AttrVec *Attrs, 8739 const FunctionDecl *FD) { 8740 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc); 8741 8742 // Check if the return value is null but should not be. 8743 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 8744 (!isObjCMethod && isNonNullType(Context, lhsType))) && 8745 CheckNonNullExpr(*this, RetValExp)) 8746 Diag(ReturnLoc, diag::warn_null_ret) 8747 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 8748 8749 // C++11 [basic.stc.dynamic.allocation]p4: 8750 // If an allocation function declared with a non-throwing 8751 // exception-specification fails to allocate storage, it shall return 8752 // a null pointer. Any other allocation function that fails to allocate 8753 // storage shall indicate failure only by throwing an exception [...] 8754 if (FD) { 8755 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 8756 if (Op == OO_New || Op == OO_Array_New) { 8757 const FunctionProtoType *Proto 8758 = FD->getType()->castAs<FunctionProtoType>(); 8759 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 8760 CheckNonNullExpr(*this, RetValExp)) 8761 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 8762 << FD << getLangOpts().CPlusPlus11; 8763 } 8764 } 8765 } 8766 8767 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 8768 8769 /// Check for comparisons of floating point operands using != and ==. 8770 /// Issue a warning if these are no self-comparisons, as they are not likely 8771 /// to do what the programmer intended. 8772 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 8773 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 8774 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 8775 8776 // Special case: check for x == x (which is OK). 8777 // Do not emit warnings for such cases. 8778 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 8779 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 8780 if (DRL->getDecl() == DRR->getDecl()) 8781 return; 8782 8783 // Special case: check for comparisons against literals that can be exactly 8784 // represented by APFloat. In such cases, do not emit a warning. This 8785 // is a heuristic: often comparison against such literals are used to 8786 // detect if a value in a variable has not changed. This clearly can 8787 // lead to false negatives. 8788 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 8789 if (FLL->isExact()) 8790 return; 8791 } else 8792 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 8793 if (FLR->isExact()) 8794 return; 8795 8796 // Check for comparisons with builtin types. 8797 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 8798 if (CL->getBuiltinCallee()) 8799 return; 8800 8801 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 8802 if (CR->getBuiltinCallee()) 8803 return; 8804 8805 // Emit the diagnostic. 8806 Diag(Loc, diag::warn_floatingpoint_eq) 8807 << LHS->getSourceRange() << RHS->getSourceRange(); 8808 } 8809 8810 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 8811 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 8812 8813 namespace { 8814 8815 /// Structure recording the 'active' range of an integer-valued 8816 /// expression. 8817 struct IntRange { 8818 /// The number of bits active in the int. 8819 unsigned Width; 8820 8821 /// True if the int is known not to have negative values. 8822 bool NonNegative; 8823 8824 IntRange(unsigned Width, bool NonNegative) 8825 : Width(Width), NonNegative(NonNegative) {} 8826 8827 /// Returns the range of the bool type. 8828 static IntRange forBoolType() { 8829 return IntRange(1, true); 8830 } 8831 8832 /// Returns the range of an opaque value of the given integral type. 8833 static IntRange forValueOfType(ASTContext &C, QualType T) { 8834 return forValueOfCanonicalType(C, 8835 T->getCanonicalTypeInternal().getTypePtr()); 8836 } 8837 8838 /// Returns the range of an opaque value of a canonical integral type. 8839 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 8840 assert(T->isCanonicalUnqualified()); 8841 8842 if (const VectorType *VT = dyn_cast<VectorType>(T)) 8843 T = VT->getElementType().getTypePtr(); 8844 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 8845 T = CT->getElementType().getTypePtr(); 8846 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 8847 T = AT->getValueType().getTypePtr(); 8848 8849 if (!C.getLangOpts().CPlusPlus) { 8850 // For enum types in C code, use the underlying datatype. 8851 if (const EnumType *ET = dyn_cast<EnumType>(T)) 8852 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 8853 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 8854 // For enum types in C++, use the known bit width of the enumerators. 8855 EnumDecl *Enum = ET->getDecl(); 8856 // In C++11, enums can have a fixed underlying type. Use this type to 8857 // compute the range. 8858 if (Enum->isFixed()) { 8859 return IntRange(C.getIntWidth(QualType(T, 0)), 8860 !ET->isSignedIntegerOrEnumerationType()); 8861 } 8862 8863 unsigned NumPositive = Enum->getNumPositiveBits(); 8864 unsigned NumNegative = Enum->getNumNegativeBits(); 8865 8866 if (NumNegative == 0) 8867 return IntRange(NumPositive, true/*NonNegative*/); 8868 else 8869 return IntRange(std::max(NumPositive + 1, NumNegative), 8870 false/*NonNegative*/); 8871 } 8872 8873 const BuiltinType *BT = cast<BuiltinType>(T); 8874 assert(BT->isInteger()); 8875 8876 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 8877 } 8878 8879 /// Returns the "target" range of a canonical integral type, i.e. 8880 /// the range of values expressible in the type. 8881 /// 8882 /// This matches forValueOfCanonicalType except that enums have the 8883 /// full range of their type, not the range of their enumerators. 8884 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 8885 assert(T->isCanonicalUnqualified()); 8886 8887 if (const VectorType *VT = dyn_cast<VectorType>(T)) 8888 T = VT->getElementType().getTypePtr(); 8889 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 8890 T = CT->getElementType().getTypePtr(); 8891 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 8892 T = AT->getValueType().getTypePtr(); 8893 if (const EnumType *ET = dyn_cast<EnumType>(T)) 8894 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 8895 8896 const BuiltinType *BT = cast<BuiltinType>(T); 8897 assert(BT->isInteger()); 8898 8899 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 8900 } 8901 8902 /// Returns the supremum of two ranges: i.e. their conservative merge. 8903 static IntRange join(IntRange L, IntRange R) { 8904 return IntRange(std::max(L.Width, R.Width), 8905 L.NonNegative && R.NonNegative); 8906 } 8907 8908 /// Returns the infinum of two ranges: i.e. their aggressive merge. 8909 static IntRange meet(IntRange L, IntRange R) { 8910 return IntRange(std::min(L.Width, R.Width), 8911 L.NonNegative || R.NonNegative); 8912 } 8913 }; 8914 8915 } // namespace 8916 8917 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 8918 unsigned MaxWidth) { 8919 if (value.isSigned() && value.isNegative()) 8920 return IntRange(value.getMinSignedBits(), false); 8921 8922 if (value.getBitWidth() > MaxWidth) 8923 value = value.trunc(MaxWidth); 8924 8925 // isNonNegative() just checks the sign bit without considering 8926 // signedness. 8927 return IntRange(value.getActiveBits(), true); 8928 } 8929 8930 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 8931 unsigned MaxWidth) { 8932 if (result.isInt()) 8933 return GetValueRange(C, result.getInt(), MaxWidth); 8934 8935 if (result.isVector()) { 8936 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 8937 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 8938 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 8939 R = IntRange::join(R, El); 8940 } 8941 return R; 8942 } 8943 8944 if (result.isComplexInt()) { 8945 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 8946 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 8947 return IntRange::join(R, I); 8948 } 8949 8950 // This can happen with lossless casts to intptr_t of "based" lvalues. 8951 // Assume it might use arbitrary bits. 8952 // FIXME: The only reason we need to pass the type in here is to get 8953 // the sign right on this one case. It would be nice if APValue 8954 // preserved this. 8955 assert(result.isLValue() || result.isAddrLabelDiff()); 8956 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 8957 } 8958 8959 static QualType GetExprType(const Expr *E) { 8960 QualType Ty = E->getType(); 8961 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 8962 Ty = AtomicRHS->getValueType(); 8963 return Ty; 8964 } 8965 8966 /// Pseudo-evaluate the given integer expression, estimating the 8967 /// range of values it might take. 8968 /// 8969 /// \param MaxWidth - the width to which the value will be truncated 8970 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) { 8971 E = E->IgnoreParens(); 8972 8973 // Try a full evaluation first. 8974 Expr::EvalResult result; 8975 if (E->EvaluateAsRValue(result, C)) 8976 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 8977 8978 // I think we only want to look through implicit casts here; if the 8979 // user has an explicit widening cast, we should treat the value as 8980 // being of the new, wider type. 8981 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 8982 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 8983 return GetExprRange(C, CE->getSubExpr(), MaxWidth); 8984 8985 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 8986 8987 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 8988 CE->getCastKind() == CK_BooleanToSignedIntegral; 8989 8990 // Assume that non-integer casts can span the full range of the type. 8991 if (!isIntegerCast) 8992 return OutputTypeRange; 8993 8994 IntRange SubRange 8995 = GetExprRange(C, CE->getSubExpr(), 8996 std::min(MaxWidth, OutputTypeRange.Width)); 8997 8998 // Bail out if the subexpr's range is as wide as the cast type. 8999 if (SubRange.Width >= OutputTypeRange.Width) 9000 return OutputTypeRange; 9001 9002 // Otherwise, we take the smaller width, and we're non-negative if 9003 // either the output type or the subexpr is. 9004 return IntRange(SubRange.Width, 9005 SubRange.NonNegative || OutputTypeRange.NonNegative); 9006 } 9007 9008 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 9009 // If we can fold the condition, just take that operand. 9010 bool CondResult; 9011 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 9012 return GetExprRange(C, CondResult ? CO->getTrueExpr() 9013 : CO->getFalseExpr(), 9014 MaxWidth); 9015 9016 // Otherwise, conservatively merge. 9017 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth); 9018 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth); 9019 return IntRange::join(L, R); 9020 } 9021 9022 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 9023 switch (BO->getOpcode()) { 9024 case BO_Cmp: 9025 llvm_unreachable("builtin <=> should have class type"); 9026 9027 // Boolean-valued operations are single-bit and positive. 9028 case BO_LAnd: 9029 case BO_LOr: 9030 case BO_LT: 9031 case BO_GT: 9032 case BO_LE: 9033 case BO_GE: 9034 case BO_EQ: 9035 case BO_NE: 9036 return IntRange::forBoolType(); 9037 9038 // The type of the assignments is the type of the LHS, so the RHS 9039 // is not necessarily the same type. 9040 case BO_MulAssign: 9041 case BO_DivAssign: 9042 case BO_RemAssign: 9043 case BO_AddAssign: 9044 case BO_SubAssign: 9045 case BO_XorAssign: 9046 case BO_OrAssign: 9047 // TODO: bitfields? 9048 return IntRange::forValueOfType(C, GetExprType(E)); 9049 9050 // Simple assignments just pass through the RHS, which will have 9051 // been coerced to the LHS type. 9052 case BO_Assign: 9053 // TODO: bitfields? 9054 return GetExprRange(C, BO->getRHS(), MaxWidth); 9055 9056 // Operations with opaque sources are black-listed. 9057 case BO_PtrMemD: 9058 case BO_PtrMemI: 9059 return IntRange::forValueOfType(C, GetExprType(E)); 9060 9061 // Bitwise-and uses the *infinum* of the two source ranges. 9062 case BO_And: 9063 case BO_AndAssign: 9064 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth), 9065 GetExprRange(C, BO->getRHS(), MaxWidth)); 9066 9067 // Left shift gets black-listed based on a judgement call. 9068 case BO_Shl: 9069 // ...except that we want to treat '1 << (blah)' as logically 9070 // positive. It's an important idiom. 9071 if (IntegerLiteral *I 9072 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 9073 if (I->getValue() == 1) { 9074 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 9075 return IntRange(R.Width, /*NonNegative*/ true); 9076 } 9077 } 9078 LLVM_FALLTHROUGH; 9079 9080 case BO_ShlAssign: 9081 return IntRange::forValueOfType(C, GetExprType(E)); 9082 9083 // Right shift by a constant can narrow its left argument. 9084 case BO_Shr: 9085 case BO_ShrAssign: { 9086 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 9087 9088 // If the shift amount is a positive constant, drop the width by 9089 // that much. 9090 llvm::APSInt shift; 9091 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 9092 shift.isNonNegative()) { 9093 unsigned zext = shift.getZExtValue(); 9094 if (zext >= L.Width) 9095 L.Width = (L.NonNegative ? 0 : 1); 9096 else 9097 L.Width -= zext; 9098 } 9099 9100 return L; 9101 } 9102 9103 // Comma acts as its right operand. 9104 case BO_Comma: 9105 return GetExprRange(C, BO->getRHS(), MaxWidth); 9106 9107 // Black-list pointer subtractions. 9108 case BO_Sub: 9109 if (BO->getLHS()->getType()->isPointerType()) 9110 return IntRange::forValueOfType(C, GetExprType(E)); 9111 break; 9112 9113 // The width of a division result is mostly determined by the size 9114 // of the LHS. 9115 case BO_Div: { 9116 // Don't 'pre-truncate' the operands. 9117 unsigned opWidth = C.getIntWidth(GetExprType(E)); 9118 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 9119 9120 // If the divisor is constant, use that. 9121 llvm::APSInt divisor; 9122 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 9123 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 9124 if (log2 >= L.Width) 9125 L.Width = (L.NonNegative ? 0 : 1); 9126 else 9127 L.Width = std::min(L.Width - log2, MaxWidth); 9128 return L; 9129 } 9130 9131 // Otherwise, just use the LHS's width. 9132 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 9133 return IntRange(L.Width, L.NonNegative && R.NonNegative); 9134 } 9135 9136 // The result of a remainder can't be larger than the result of 9137 // either side. 9138 case BO_Rem: { 9139 // Don't 'pre-truncate' the operands. 9140 unsigned opWidth = C.getIntWidth(GetExprType(E)); 9141 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 9142 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 9143 9144 IntRange meet = IntRange::meet(L, R); 9145 meet.Width = std::min(meet.Width, MaxWidth); 9146 return meet; 9147 } 9148 9149 // The default behavior is okay for these. 9150 case BO_Mul: 9151 case BO_Add: 9152 case BO_Xor: 9153 case BO_Or: 9154 break; 9155 } 9156 9157 // The default case is to treat the operation as if it were closed 9158 // on the narrowest type that encompasses both operands. 9159 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 9160 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth); 9161 return IntRange::join(L, R); 9162 } 9163 9164 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 9165 switch (UO->getOpcode()) { 9166 // Boolean-valued operations are white-listed. 9167 case UO_LNot: 9168 return IntRange::forBoolType(); 9169 9170 // Operations with opaque sources are black-listed. 9171 case UO_Deref: 9172 case UO_AddrOf: // should be impossible 9173 return IntRange::forValueOfType(C, GetExprType(E)); 9174 9175 default: 9176 return GetExprRange(C, UO->getSubExpr(), MaxWidth); 9177 } 9178 } 9179 9180 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 9181 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth); 9182 9183 if (const auto *BitField = E->getSourceBitField()) 9184 return IntRange(BitField->getBitWidthValue(C), 9185 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 9186 9187 return IntRange::forValueOfType(C, GetExprType(E)); 9188 } 9189 9190 static IntRange GetExprRange(ASTContext &C, const Expr *E) { 9191 return GetExprRange(C, E, C.getIntWidth(GetExprType(E))); 9192 } 9193 9194 /// Checks whether the given value, which currently has the given 9195 /// source semantics, has the same value when coerced through the 9196 /// target semantics. 9197 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 9198 const llvm::fltSemantics &Src, 9199 const llvm::fltSemantics &Tgt) { 9200 llvm::APFloat truncated = value; 9201 9202 bool ignored; 9203 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 9204 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 9205 9206 return truncated.bitwiseIsEqual(value); 9207 } 9208 9209 /// Checks whether the given value, which currently has the given 9210 /// source semantics, has the same value when coerced through the 9211 /// target semantics. 9212 /// 9213 /// The value might be a vector of floats (or a complex number). 9214 static bool IsSameFloatAfterCast(const APValue &value, 9215 const llvm::fltSemantics &Src, 9216 const llvm::fltSemantics &Tgt) { 9217 if (value.isFloat()) 9218 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 9219 9220 if (value.isVector()) { 9221 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 9222 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 9223 return false; 9224 return true; 9225 } 9226 9227 assert(value.isComplexFloat()); 9228 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 9229 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 9230 } 9231 9232 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC); 9233 9234 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 9235 // Suppress cases where we are comparing against an enum constant. 9236 if (const DeclRefExpr *DR = 9237 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 9238 if (isa<EnumConstantDecl>(DR->getDecl())) 9239 return true; 9240 9241 // Suppress cases where the '0' value is expanded from a macro. 9242 if (E->getLocStart().isMacroID()) 9243 return true; 9244 9245 return false; 9246 } 9247 9248 static bool isKnownToHaveUnsignedValue(Expr *E) { 9249 return E->getType()->isIntegerType() && 9250 (!E->getType()->isSignedIntegerType() || 9251 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 9252 } 9253 9254 namespace { 9255 /// The promoted range of values of a type. In general this has the 9256 /// following structure: 9257 /// 9258 /// |-----------| . . . |-----------| 9259 /// ^ ^ ^ ^ 9260 /// Min HoleMin HoleMax Max 9261 /// 9262 /// ... where there is only a hole if a signed type is promoted to unsigned 9263 /// (in which case Min and Max are the smallest and largest representable 9264 /// values). 9265 struct PromotedRange { 9266 // Min, or HoleMax if there is a hole. 9267 llvm::APSInt PromotedMin; 9268 // Max, or HoleMin if there is a hole. 9269 llvm::APSInt PromotedMax; 9270 9271 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 9272 if (R.Width == 0) 9273 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 9274 else if (R.Width >= BitWidth && !Unsigned) { 9275 // Promotion made the type *narrower*. This happens when promoting 9276 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 9277 // Treat all values of 'signed int' as being in range for now. 9278 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 9279 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 9280 } else { 9281 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 9282 .extOrTrunc(BitWidth); 9283 PromotedMin.setIsUnsigned(Unsigned); 9284 9285 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 9286 .extOrTrunc(BitWidth); 9287 PromotedMax.setIsUnsigned(Unsigned); 9288 } 9289 } 9290 9291 // Determine whether this range is contiguous (has no hole). 9292 bool isContiguous() const { return PromotedMin <= PromotedMax; } 9293 9294 // Where a constant value is within the range. 9295 enum ComparisonResult { 9296 LT = 0x1, 9297 LE = 0x2, 9298 GT = 0x4, 9299 GE = 0x8, 9300 EQ = 0x10, 9301 NE = 0x20, 9302 InRangeFlag = 0x40, 9303 9304 Less = LE | LT | NE, 9305 Min = LE | InRangeFlag, 9306 InRange = InRangeFlag, 9307 Max = GE | InRangeFlag, 9308 Greater = GE | GT | NE, 9309 9310 OnlyValue = LE | GE | EQ | InRangeFlag, 9311 InHole = NE 9312 }; 9313 9314 ComparisonResult compare(const llvm::APSInt &Value) const { 9315 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 9316 Value.isUnsigned() == PromotedMin.isUnsigned()); 9317 if (!isContiguous()) { 9318 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 9319 if (Value.isMinValue()) return Min; 9320 if (Value.isMaxValue()) return Max; 9321 if (Value >= PromotedMin) return InRange; 9322 if (Value <= PromotedMax) return InRange; 9323 return InHole; 9324 } 9325 9326 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 9327 case -1: return Less; 9328 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 9329 case 1: 9330 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 9331 case -1: return InRange; 9332 case 0: return Max; 9333 case 1: return Greater; 9334 } 9335 } 9336 9337 llvm_unreachable("impossible compare result"); 9338 } 9339 9340 static llvm::Optional<StringRef> 9341 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 9342 if (Op == BO_Cmp) { 9343 ComparisonResult LTFlag = LT, GTFlag = GT; 9344 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 9345 9346 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 9347 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 9348 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 9349 return llvm::None; 9350 } 9351 9352 ComparisonResult TrueFlag, FalseFlag; 9353 if (Op == BO_EQ) { 9354 TrueFlag = EQ; 9355 FalseFlag = NE; 9356 } else if (Op == BO_NE) { 9357 TrueFlag = NE; 9358 FalseFlag = EQ; 9359 } else { 9360 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 9361 TrueFlag = LT; 9362 FalseFlag = GE; 9363 } else { 9364 TrueFlag = GT; 9365 FalseFlag = LE; 9366 } 9367 if (Op == BO_GE || Op == BO_LE) 9368 std::swap(TrueFlag, FalseFlag); 9369 } 9370 if (R & TrueFlag) 9371 return StringRef("true"); 9372 if (R & FalseFlag) 9373 return StringRef("false"); 9374 return llvm::None; 9375 } 9376 }; 9377 } 9378 9379 static bool HasEnumType(Expr *E) { 9380 // Strip off implicit integral promotions. 9381 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 9382 if (ICE->getCastKind() != CK_IntegralCast && 9383 ICE->getCastKind() != CK_NoOp) 9384 break; 9385 E = ICE->getSubExpr(); 9386 } 9387 9388 return E->getType()->isEnumeralType(); 9389 } 9390 9391 static int classifyConstantValue(Expr *Constant) { 9392 // The values of this enumeration are used in the diagnostics 9393 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 9394 enum ConstantValueKind { 9395 Miscellaneous = 0, 9396 LiteralTrue, 9397 LiteralFalse 9398 }; 9399 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 9400 return BL->getValue() ? ConstantValueKind::LiteralTrue 9401 : ConstantValueKind::LiteralFalse; 9402 return ConstantValueKind::Miscellaneous; 9403 } 9404 9405 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 9406 Expr *Constant, Expr *Other, 9407 const llvm::APSInt &Value, 9408 bool RhsConstant) { 9409 if (S.inTemplateInstantiation()) 9410 return false; 9411 9412 Expr *OriginalOther = Other; 9413 9414 Constant = Constant->IgnoreParenImpCasts(); 9415 Other = Other->IgnoreParenImpCasts(); 9416 9417 // Suppress warnings on tautological comparisons between values of the same 9418 // enumeration type. There are only two ways we could warn on this: 9419 // - If the constant is outside the range of representable values of 9420 // the enumeration. In such a case, we should warn about the cast 9421 // to enumeration type, not about the comparison. 9422 // - If the constant is the maximum / minimum in-range value. For an 9423 // enumeratin type, such comparisons can be meaningful and useful. 9424 if (Constant->getType()->isEnumeralType() && 9425 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 9426 return false; 9427 9428 // TODO: Investigate using GetExprRange() to get tighter bounds 9429 // on the bit ranges. 9430 QualType OtherT = Other->getType(); 9431 if (const auto *AT = OtherT->getAs<AtomicType>()) 9432 OtherT = AT->getValueType(); 9433 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); 9434 9435 // Whether we're treating Other as being a bool because of the form of 9436 // expression despite it having another type (typically 'int' in C). 9437 bool OtherIsBooleanDespiteType = 9438 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 9439 if (OtherIsBooleanDespiteType) 9440 OtherRange = IntRange::forBoolType(); 9441 9442 // Determine the promoted range of the other type and see if a comparison of 9443 // the constant against that range is tautological. 9444 PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(), 9445 Value.isUnsigned()); 9446 auto Cmp = OtherPromotedRange.compare(Value); 9447 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 9448 if (!Result) 9449 return false; 9450 9451 // Suppress the diagnostic for an in-range comparison if the constant comes 9452 // from a macro or enumerator. We don't want to diagnose 9453 // 9454 // some_long_value <= INT_MAX 9455 // 9456 // when sizeof(int) == sizeof(long). 9457 bool InRange = Cmp & PromotedRange::InRangeFlag; 9458 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 9459 return false; 9460 9461 // If this is a comparison to an enum constant, include that 9462 // constant in the diagnostic. 9463 const EnumConstantDecl *ED = nullptr; 9464 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 9465 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 9466 9467 // Should be enough for uint128 (39 decimal digits) 9468 SmallString<64> PrettySourceValue; 9469 llvm::raw_svector_ostream OS(PrettySourceValue); 9470 if (ED) 9471 OS << '\'' << *ED << "' (" << Value << ")"; 9472 else 9473 OS << Value; 9474 9475 // FIXME: We use a somewhat different formatting for the in-range cases and 9476 // cases involving boolean values for historical reasons. We should pick a 9477 // consistent way of presenting these diagnostics. 9478 if (!InRange || Other->isKnownToHaveBooleanValue()) { 9479 S.DiagRuntimeBehavior( 9480 E->getOperatorLoc(), E, 9481 S.PDiag(!InRange ? diag::warn_out_of_range_compare 9482 : diag::warn_tautological_bool_compare) 9483 << OS.str() << classifyConstantValue(Constant) 9484 << OtherT << OtherIsBooleanDespiteType << *Result 9485 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 9486 } else { 9487 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 9488 ? (HasEnumType(OriginalOther) 9489 ? diag::warn_unsigned_enum_always_true_comparison 9490 : diag::warn_unsigned_always_true_comparison) 9491 : diag::warn_tautological_constant_compare; 9492 9493 S.Diag(E->getOperatorLoc(), Diag) 9494 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 9495 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 9496 } 9497 9498 return true; 9499 } 9500 9501 /// Analyze the operands of the given comparison. Implements the 9502 /// fallback case from AnalyzeComparison. 9503 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 9504 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 9505 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 9506 } 9507 9508 /// Implements -Wsign-compare. 9509 /// 9510 /// \param E the binary operator to check for warnings 9511 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 9512 // The type the comparison is being performed in. 9513 QualType T = E->getLHS()->getType(); 9514 9515 // Only analyze comparison operators where both sides have been converted to 9516 // the same type. 9517 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 9518 return AnalyzeImpConvsInComparison(S, E); 9519 9520 // Don't analyze value-dependent comparisons directly. 9521 if (E->isValueDependent()) 9522 return AnalyzeImpConvsInComparison(S, E); 9523 9524 Expr *LHS = E->getLHS(); 9525 Expr *RHS = E->getRHS(); 9526 9527 if (T->isIntegralType(S.Context)) { 9528 llvm::APSInt RHSValue; 9529 llvm::APSInt LHSValue; 9530 9531 bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context); 9532 bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context); 9533 9534 // We don't care about expressions whose result is a constant. 9535 if (IsRHSIntegralLiteral && IsLHSIntegralLiteral) 9536 return AnalyzeImpConvsInComparison(S, E); 9537 9538 // We only care about expressions where just one side is literal 9539 if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) { 9540 // Is the constant on the RHS or LHS? 9541 const bool RhsConstant = IsRHSIntegralLiteral; 9542 Expr *Const = RhsConstant ? RHS : LHS; 9543 Expr *Other = RhsConstant ? LHS : RHS; 9544 const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue; 9545 9546 // Check whether an integer constant comparison results in a value 9547 // of 'true' or 'false'. 9548 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 9549 return AnalyzeImpConvsInComparison(S, E); 9550 } 9551 } 9552 9553 if (!T->hasUnsignedIntegerRepresentation()) { 9554 // We don't do anything special if this isn't an unsigned integral 9555 // comparison: we're only interested in integral comparisons, and 9556 // signed comparisons only happen in cases we don't care to warn about. 9557 return AnalyzeImpConvsInComparison(S, E); 9558 } 9559 9560 LHS = LHS->IgnoreParenImpCasts(); 9561 RHS = RHS->IgnoreParenImpCasts(); 9562 9563 if (!S.getLangOpts().CPlusPlus) { 9564 // Avoid warning about comparison of integers with different signs when 9565 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 9566 // the type of `E`. 9567 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 9568 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 9569 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 9570 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 9571 } 9572 9573 // Check to see if one of the (unmodified) operands is of different 9574 // signedness. 9575 Expr *signedOperand, *unsignedOperand; 9576 if (LHS->getType()->hasSignedIntegerRepresentation()) { 9577 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 9578 "unsigned comparison between two signed integer expressions?"); 9579 signedOperand = LHS; 9580 unsignedOperand = RHS; 9581 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 9582 signedOperand = RHS; 9583 unsignedOperand = LHS; 9584 } else { 9585 return AnalyzeImpConvsInComparison(S, E); 9586 } 9587 9588 // Otherwise, calculate the effective range of the signed operand. 9589 IntRange signedRange = GetExprRange(S.Context, signedOperand); 9590 9591 // Go ahead and analyze implicit conversions in the operands. Note 9592 // that we skip the implicit conversions on both sides. 9593 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 9594 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 9595 9596 // If the signed range is non-negative, -Wsign-compare won't fire. 9597 if (signedRange.NonNegative) 9598 return; 9599 9600 // For (in)equality comparisons, if the unsigned operand is a 9601 // constant which cannot collide with a overflowed signed operand, 9602 // then reinterpreting the signed operand as unsigned will not 9603 // change the result of the comparison. 9604 if (E->isEqualityOp()) { 9605 unsigned comparisonWidth = S.Context.getIntWidth(T); 9606 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand); 9607 9608 // We should never be unable to prove that the unsigned operand is 9609 // non-negative. 9610 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 9611 9612 if (unsignedRange.Width < comparisonWidth) 9613 return; 9614 } 9615 9616 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 9617 S.PDiag(diag::warn_mixed_sign_comparison) 9618 << LHS->getType() << RHS->getType() 9619 << LHS->getSourceRange() << RHS->getSourceRange()); 9620 } 9621 9622 /// Analyzes an attempt to assign the given value to a bitfield. 9623 /// 9624 /// Returns true if there was something fishy about the attempt. 9625 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 9626 SourceLocation InitLoc) { 9627 assert(Bitfield->isBitField()); 9628 if (Bitfield->isInvalidDecl()) 9629 return false; 9630 9631 // White-list bool bitfields. 9632 QualType BitfieldType = Bitfield->getType(); 9633 if (BitfieldType->isBooleanType()) 9634 return false; 9635 9636 if (BitfieldType->isEnumeralType()) { 9637 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl(); 9638 // If the underlying enum type was not explicitly specified as an unsigned 9639 // type and the enum contain only positive values, MSVC++ will cause an 9640 // inconsistency by storing this as a signed type. 9641 if (S.getLangOpts().CPlusPlus11 && 9642 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 9643 BitfieldEnumDecl->getNumPositiveBits() > 0 && 9644 BitfieldEnumDecl->getNumNegativeBits() == 0) { 9645 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 9646 << BitfieldEnumDecl->getNameAsString(); 9647 } 9648 } 9649 9650 if (Bitfield->getType()->isBooleanType()) 9651 return false; 9652 9653 // Ignore value- or type-dependent expressions. 9654 if (Bitfield->getBitWidth()->isValueDependent() || 9655 Bitfield->getBitWidth()->isTypeDependent() || 9656 Init->isValueDependent() || 9657 Init->isTypeDependent()) 9658 return false; 9659 9660 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 9661 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 9662 9663 llvm::APSInt Value; 9664 if (!OriginalInit->EvaluateAsInt(Value, S.Context, 9665 Expr::SE_AllowSideEffects)) { 9666 // The RHS is not constant. If the RHS has an enum type, make sure the 9667 // bitfield is wide enough to hold all the values of the enum without 9668 // truncation. 9669 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 9670 EnumDecl *ED = EnumTy->getDecl(); 9671 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 9672 9673 // Enum types are implicitly signed on Windows, so check if there are any 9674 // negative enumerators to see if the enum was intended to be signed or 9675 // not. 9676 bool SignedEnum = ED->getNumNegativeBits() > 0; 9677 9678 // Check for surprising sign changes when assigning enum values to a 9679 // bitfield of different signedness. If the bitfield is signed and we 9680 // have exactly the right number of bits to store this unsigned enum, 9681 // suggest changing the enum to an unsigned type. This typically happens 9682 // on Windows where unfixed enums always use an underlying type of 'int'. 9683 unsigned DiagID = 0; 9684 if (SignedEnum && !SignedBitfield) { 9685 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 9686 } else if (SignedBitfield && !SignedEnum && 9687 ED->getNumPositiveBits() == FieldWidth) { 9688 DiagID = diag::warn_signed_bitfield_enum_conversion; 9689 } 9690 9691 if (DiagID) { 9692 S.Diag(InitLoc, DiagID) << Bitfield << ED; 9693 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 9694 SourceRange TypeRange = 9695 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 9696 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 9697 << SignedEnum << TypeRange; 9698 } 9699 9700 // Compute the required bitwidth. If the enum has negative values, we need 9701 // one more bit than the normal number of positive bits to represent the 9702 // sign bit. 9703 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 9704 ED->getNumNegativeBits()) 9705 : ED->getNumPositiveBits(); 9706 9707 // Check the bitwidth. 9708 if (BitsNeeded > FieldWidth) { 9709 Expr *WidthExpr = Bitfield->getBitWidth(); 9710 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 9711 << Bitfield << ED; 9712 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 9713 << BitsNeeded << ED << WidthExpr->getSourceRange(); 9714 } 9715 } 9716 9717 return false; 9718 } 9719 9720 unsigned OriginalWidth = Value.getBitWidth(); 9721 9722 if (!Value.isSigned() || Value.isNegative()) 9723 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 9724 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 9725 OriginalWidth = Value.getMinSignedBits(); 9726 9727 if (OriginalWidth <= FieldWidth) 9728 return false; 9729 9730 // Compute the value which the bitfield will contain. 9731 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 9732 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 9733 9734 // Check whether the stored value is equal to the original value. 9735 TruncatedValue = TruncatedValue.extend(OriginalWidth); 9736 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 9737 return false; 9738 9739 // Special-case bitfields of width 1: booleans are naturally 0/1, and 9740 // therefore don't strictly fit into a signed bitfield of width 1. 9741 if (FieldWidth == 1 && Value == 1) 9742 return false; 9743 9744 std::string PrettyValue = Value.toString(10); 9745 std::string PrettyTrunc = TruncatedValue.toString(10); 9746 9747 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 9748 << PrettyValue << PrettyTrunc << OriginalInit->getType() 9749 << Init->getSourceRange(); 9750 9751 return true; 9752 } 9753 9754 /// Analyze the given simple or compound assignment for warning-worthy 9755 /// operations. 9756 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 9757 // Just recurse on the LHS. 9758 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 9759 9760 // We want to recurse on the RHS as normal unless we're assigning to 9761 // a bitfield. 9762 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 9763 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 9764 E->getOperatorLoc())) { 9765 // Recurse, ignoring any implicit conversions on the RHS. 9766 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 9767 E->getOperatorLoc()); 9768 } 9769 } 9770 9771 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 9772 } 9773 9774 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 9775 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 9776 SourceLocation CContext, unsigned diag, 9777 bool pruneControlFlow = false) { 9778 if (pruneControlFlow) { 9779 S.DiagRuntimeBehavior(E->getExprLoc(), E, 9780 S.PDiag(diag) 9781 << SourceType << T << E->getSourceRange() 9782 << SourceRange(CContext)); 9783 return; 9784 } 9785 S.Diag(E->getExprLoc(), diag) 9786 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 9787 } 9788 9789 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 9790 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 9791 SourceLocation CContext, 9792 unsigned diag, bool pruneControlFlow = false) { 9793 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 9794 } 9795 9796 /// Analyze the given compound assignment for the possible losing of 9797 /// floating-point precision. 9798 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 9799 assert(isa<CompoundAssignOperator>(E) && 9800 "Must be compound assignment operation"); 9801 // Recurse on the LHS and RHS in here 9802 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 9803 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 9804 9805 // Now check the outermost expression 9806 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 9807 const auto *RBT = cast<CompoundAssignOperator>(E) 9808 ->getComputationResultType() 9809 ->getAs<BuiltinType>(); 9810 9811 // If both source and target are floating points. 9812 if (ResultBT && ResultBT->isFloatingPoint() && RBT && RBT->isFloatingPoint()) 9813 // Builtin FP kinds are ordered by increasing FP rank. 9814 if (ResultBT->getKind() < RBT->getKind()) 9815 // We don't want to warn for system macro. 9816 if (!S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 9817 // warn about dropping FP rank. 9818 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), 9819 E->getOperatorLoc(), 9820 diag::warn_impcast_float_result_precision); 9821 } 9822 9823 /// Diagnose an implicit cast from a floating point value to an integer value. 9824 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 9825 SourceLocation CContext) { 9826 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 9827 const bool PruneWarnings = S.inTemplateInstantiation(); 9828 9829 Expr *InnerE = E->IgnoreParenImpCasts(); 9830 // We also want to warn on, e.g., "int i = -1.234" 9831 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 9832 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 9833 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 9834 9835 const bool IsLiteral = 9836 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 9837 9838 llvm::APFloat Value(0.0); 9839 bool IsConstant = 9840 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 9841 if (!IsConstant) { 9842 return DiagnoseImpCast(S, E, T, CContext, 9843 diag::warn_impcast_float_integer, PruneWarnings); 9844 } 9845 9846 bool isExact = false; 9847 9848 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 9849 T->hasUnsignedIntegerRepresentation()); 9850 llvm::APFloat::opStatus Result = Value.convertToInteger( 9851 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 9852 9853 if (Result == llvm::APFloat::opOK && isExact) { 9854 if (IsLiteral) return; 9855 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 9856 PruneWarnings); 9857 } 9858 9859 // Conversion of a floating-point value to a non-bool integer where the 9860 // integral part cannot be represented by the integer type is undefined. 9861 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 9862 return DiagnoseImpCast( 9863 S, E, T, CContext, 9864 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 9865 : diag::warn_impcast_float_to_integer_out_of_range, 9866 PruneWarnings); 9867 9868 unsigned DiagID = 0; 9869 if (IsLiteral) { 9870 // Warn on floating point literal to integer. 9871 DiagID = diag::warn_impcast_literal_float_to_integer; 9872 } else if (IntegerValue == 0) { 9873 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 9874 return DiagnoseImpCast(S, E, T, CContext, 9875 diag::warn_impcast_float_integer, PruneWarnings); 9876 } 9877 // Warn on non-zero to zero conversion. 9878 DiagID = diag::warn_impcast_float_to_integer_zero; 9879 } else { 9880 if (IntegerValue.isUnsigned()) { 9881 if (!IntegerValue.isMaxValue()) { 9882 return DiagnoseImpCast(S, E, T, CContext, 9883 diag::warn_impcast_float_integer, PruneWarnings); 9884 } 9885 } else { // IntegerValue.isSigned() 9886 if (!IntegerValue.isMaxSignedValue() && 9887 !IntegerValue.isMinSignedValue()) { 9888 return DiagnoseImpCast(S, E, T, CContext, 9889 diag::warn_impcast_float_integer, PruneWarnings); 9890 } 9891 } 9892 // Warn on evaluatable floating point expression to integer conversion. 9893 DiagID = diag::warn_impcast_float_to_integer; 9894 } 9895 9896 // FIXME: Force the precision of the source value down so we don't print 9897 // digits which are usually useless (we don't really care here if we 9898 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 9899 // would automatically print the shortest representation, but it's a bit 9900 // tricky to implement. 9901 SmallString<16> PrettySourceValue; 9902 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 9903 precision = (precision * 59 + 195) / 196; 9904 Value.toString(PrettySourceValue, precision); 9905 9906 SmallString<16> PrettyTargetValue; 9907 if (IsBool) 9908 PrettyTargetValue = Value.isZero() ? "false" : "true"; 9909 else 9910 IntegerValue.toString(PrettyTargetValue); 9911 9912 if (PruneWarnings) { 9913 S.DiagRuntimeBehavior(E->getExprLoc(), E, 9914 S.PDiag(DiagID) 9915 << E->getType() << T.getUnqualifiedType() 9916 << PrettySourceValue << PrettyTargetValue 9917 << E->getSourceRange() << SourceRange(CContext)); 9918 } else { 9919 S.Diag(E->getExprLoc(), DiagID) 9920 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 9921 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 9922 } 9923 } 9924 9925 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 9926 IntRange Range) { 9927 if (!Range.Width) return "0"; 9928 9929 llvm::APSInt ValueInRange = Value; 9930 ValueInRange.setIsSigned(!Range.NonNegative); 9931 ValueInRange = ValueInRange.trunc(Range.Width); 9932 return ValueInRange.toString(10); 9933 } 9934 9935 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 9936 if (!isa<ImplicitCastExpr>(Ex)) 9937 return false; 9938 9939 Expr *InnerE = Ex->IgnoreParenImpCasts(); 9940 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 9941 const Type *Source = 9942 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 9943 if (Target->isDependentType()) 9944 return false; 9945 9946 const BuiltinType *FloatCandidateBT = 9947 dyn_cast<BuiltinType>(ToBool ? Source : Target); 9948 const Type *BoolCandidateType = ToBool ? Target : Source; 9949 9950 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 9951 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 9952 } 9953 9954 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 9955 SourceLocation CC) { 9956 unsigned NumArgs = TheCall->getNumArgs(); 9957 for (unsigned i = 0; i < NumArgs; ++i) { 9958 Expr *CurrA = TheCall->getArg(i); 9959 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 9960 continue; 9961 9962 bool IsSwapped = ((i > 0) && 9963 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 9964 IsSwapped |= ((i < (NumArgs - 1)) && 9965 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 9966 if (IsSwapped) { 9967 // Warn on this floating-point to bool conversion. 9968 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 9969 CurrA->getType(), CC, 9970 diag::warn_impcast_floating_point_to_bool); 9971 } 9972 } 9973 } 9974 9975 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 9976 SourceLocation CC) { 9977 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 9978 E->getExprLoc())) 9979 return; 9980 9981 // Don't warn on functions which have return type nullptr_t. 9982 if (isa<CallExpr>(E)) 9983 return; 9984 9985 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 9986 const Expr::NullPointerConstantKind NullKind = 9987 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 9988 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 9989 return; 9990 9991 // Return if target type is a safe conversion. 9992 if (T->isAnyPointerType() || T->isBlockPointerType() || 9993 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 9994 return; 9995 9996 SourceLocation Loc = E->getSourceRange().getBegin(); 9997 9998 // Venture through the macro stacks to get to the source of macro arguments. 9999 // The new location is a better location than the complete location that was 10000 // passed in. 10001 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 10002 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 10003 10004 // __null is usually wrapped in a macro. Go up a macro if that is the case. 10005 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 10006 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 10007 Loc, S.SourceMgr, S.getLangOpts()); 10008 if (MacroName == "NULL") 10009 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 10010 } 10011 10012 // Only warn if the null and context location are in the same macro expansion. 10013 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 10014 return; 10015 10016 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 10017 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 10018 << FixItHint::CreateReplacement(Loc, 10019 S.getFixItZeroLiteralForType(T, Loc)); 10020 } 10021 10022 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 10023 ObjCArrayLiteral *ArrayLiteral); 10024 10025 static void 10026 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 10027 ObjCDictionaryLiteral *DictionaryLiteral); 10028 10029 /// Check a single element within a collection literal against the 10030 /// target element type. 10031 static void checkObjCCollectionLiteralElement(Sema &S, 10032 QualType TargetElementType, 10033 Expr *Element, 10034 unsigned ElementKind) { 10035 // Skip a bitcast to 'id' or qualified 'id'. 10036 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 10037 if (ICE->getCastKind() == CK_BitCast && 10038 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 10039 Element = ICE->getSubExpr(); 10040 } 10041 10042 QualType ElementType = Element->getType(); 10043 ExprResult ElementResult(Element); 10044 if (ElementType->getAs<ObjCObjectPointerType>() && 10045 S.CheckSingleAssignmentConstraints(TargetElementType, 10046 ElementResult, 10047 false, false) 10048 != Sema::Compatible) { 10049 S.Diag(Element->getLocStart(), 10050 diag::warn_objc_collection_literal_element) 10051 << ElementType << ElementKind << TargetElementType 10052 << Element->getSourceRange(); 10053 } 10054 10055 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 10056 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 10057 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 10058 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 10059 } 10060 10061 /// Check an Objective-C array literal being converted to the given 10062 /// target type. 10063 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 10064 ObjCArrayLiteral *ArrayLiteral) { 10065 if (!S.NSArrayDecl) 10066 return; 10067 10068 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 10069 if (!TargetObjCPtr) 10070 return; 10071 10072 if (TargetObjCPtr->isUnspecialized() || 10073 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 10074 != S.NSArrayDecl->getCanonicalDecl()) 10075 return; 10076 10077 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 10078 if (TypeArgs.size() != 1) 10079 return; 10080 10081 QualType TargetElementType = TypeArgs[0]; 10082 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 10083 checkObjCCollectionLiteralElement(S, TargetElementType, 10084 ArrayLiteral->getElement(I), 10085 0); 10086 } 10087 } 10088 10089 /// Check an Objective-C dictionary literal being converted to the given 10090 /// target type. 10091 static void 10092 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 10093 ObjCDictionaryLiteral *DictionaryLiteral) { 10094 if (!S.NSDictionaryDecl) 10095 return; 10096 10097 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 10098 if (!TargetObjCPtr) 10099 return; 10100 10101 if (TargetObjCPtr->isUnspecialized() || 10102 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 10103 != S.NSDictionaryDecl->getCanonicalDecl()) 10104 return; 10105 10106 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 10107 if (TypeArgs.size() != 2) 10108 return; 10109 10110 QualType TargetKeyType = TypeArgs[0]; 10111 QualType TargetObjectType = TypeArgs[1]; 10112 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 10113 auto Element = DictionaryLiteral->getKeyValueElement(I); 10114 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 10115 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 10116 } 10117 } 10118 10119 // Helper function to filter out cases for constant width constant conversion. 10120 // Don't warn on char array initialization or for non-decimal values. 10121 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 10122 SourceLocation CC) { 10123 // If initializing from a constant, and the constant starts with '0', 10124 // then it is a binary, octal, or hexadecimal. Allow these constants 10125 // to fill all the bits, even if there is a sign change. 10126 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 10127 const char FirstLiteralCharacter = 10128 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0]; 10129 if (FirstLiteralCharacter == '0') 10130 return false; 10131 } 10132 10133 // If the CC location points to a '{', and the type is char, then assume 10134 // assume it is an array initialization. 10135 if (CC.isValid() && T->isCharType()) { 10136 const char FirstContextCharacter = 10137 S.getSourceManager().getCharacterData(CC)[0]; 10138 if (FirstContextCharacter == '{') 10139 return false; 10140 } 10141 10142 return true; 10143 } 10144 10145 static void 10146 CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC, 10147 bool *ICContext = nullptr) { 10148 if (E->isTypeDependent() || E->isValueDependent()) return; 10149 10150 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 10151 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 10152 if (Source == Target) return; 10153 if (Target->isDependentType()) return; 10154 10155 // If the conversion context location is invalid don't complain. We also 10156 // don't want to emit a warning if the issue occurs from the expansion of 10157 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 10158 // delay this check as long as possible. Once we detect we are in that 10159 // scenario, we just return. 10160 if (CC.isInvalid()) 10161 return; 10162 10163 // Diagnose implicit casts to bool. 10164 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 10165 if (isa<StringLiteral>(E)) 10166 // Warn on string literal to bool. Checks for string literals in logical 10167 // and expressions, for instance, assert(0 && "error here"), are 10168 // prevented by a check in AnalyzeImplicitConversions(). 10169 return DiagnoseImpCast(S, E, T, CC, 10170 diag::warn_impcast_string_literal_to_bool); 10171 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 10172 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 10173 // This covers the literal expressions that evaluate to Objective-C 10174 // objects. 10175 return DiagnoseImpCast(S, E, T, CC, 10176 diag::warn_impcast_objective_c_literal_to_bool); 10177 } 10178 if (Source->isPointerType() || Source->canDecayToPointerType()) { 10179 // Warn on pointer to bool conversion that is always true. 10180 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 10181 SourceRange(CC)); 10182 } 10183 } 10184 10185 // Check implicit casts from Objective-C collection literals to specialized 10186 // collection types, e.g., NSArray<NSString *> *. 10187 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 10188 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 10189 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 10190 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 10191 10192 // Strip vector types. 10193 if (isa<VectorType>(Source)) { 10194 if (!isa<VectorType>(Target)) { 10195 if (S.SourceMgr.isInSystemMacro(CC)) 10196 return; 10197 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 10198 } 10199 10200 // If the vector cast is cast between two vectors of the same size, it is 10201 // a bitcast, not a conversion. 10202 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 10203 return; 10204 10205 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 10206 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 10207 } 10208 if (auto VecTy = dyn_cast<VectorType>(Target)) 10209 Target = VecTy->getElementType().getTypePtr(); 10210 10211 // Strip complex types. 10212 if (isa<ComplexType>(Source)) { 10213 if (!isa<ComplexType>(Target)) { 10214 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 10215 return; 10216 10217 return DiagnoseImpCast(S, E, T, CC, 10218 S.getLangOpts().CPlusPlus 10219 ? diag::err_impcast_complex_scalar 10220 : diag::warn_impcast_complex_scalar); 10221 } 10222 10223 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 10224 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 10225 } 10226 10227 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 10228 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 10229 10230 // If the source is floating point... 10231 if (SourceBT && SourceBT->isFloatingPoint()) { 10232 // ...and the target is floating point... 10233 if (TargetBT && TargetBT->isFloatingPoint()) { 10234 // ...then warn if we're dropping FP rank. 10235 10236 // Builtin FP kinds are ordered by increasing FP rank. 10237 if (SourceBT->getKind() > TargetBT->getKind()) { 10238 // Don't warn about float constants that are precisely 10239 // representable in the target type. 10240 Expr::EvalResult result; 10241 if (E->EvaluateAsRValue(result, S.Context)) { 10242 // Value might be a float, a float vector, or a float complex. 10243 if (IsSameFloatAfterCast(result.Val, 10244 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 10245 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 10246 return; 10247 } 10248 10249 if (S.SourceMgr.isInSystemMacro(CC)) 10250 return; 10251 10252 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 10253 } 10254 // ... or possibly if we're increasing rank, too 10255 else if (TargetBT->getKind() > SourceBT->getKind()) { 10256 if (S.SourceMgr.isInSystemMacro(CC)) 10257 return; 10258 10259 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 10260 } 10261 return; 10262 } 10263 10264 // If the target is integral, always warn. 10265 if (TargetBT && TargetBT->isInteger()) { 10266 if (S.SourceMgr.isInSystemMacro(CC)) 10267 return; 10268 10269 DiagnoseFloatingImpCast(S, E, T, CC); 10270 } 10271 10272 // Detect the case where a call result is converted from floating-point to 10273 // to bool, and the final argument to the call is converted from bool, to 10274 // discover this typo: 10275 // 10276 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 10277 // 10278 // FIXME: This is an incredibly special case; is there some more general 10279 // way to detect this class of misplaced-parentheses bug? 10280 if (Target->isBooleanType() && isa<CallExpr>(E)) { 10281 // Check last argument of function call to see if it is an 10282 // implicit cast from a type matching the type the result 10283 // is being cast to. 10284 CallExpr *CEx = cast<CallExpr>(E); 10285 if (unsigned NumArgs = CEx->getNumArgs()) { 10286 Expr *LastA = CEx->getArg(NumArgs - 1); 10287 Expr *InnerE = LastA->IgnoreParenImpCasts(); 10288 if (isa<ImplicitCastExpr>(LastA) && 10289 InnerE->getType()->isBooleanType()) { 10290 // Warn on this floating-point to bool conversion 10291 DiagnoseImpCast(S, E, T, CC, 10292 diag::warn_impcast_floating_point_to_bool); 10293 } 10294 } 10295 } 10296 return; 10297 } 10298 10299 DiagnoseNullConversion(S, E, T, CC); 10300 10301 S.DiscardMisalignedMemberAddress(Target, E); 10302 10303 if (!Source->isIntegerType() || !Target->isIntegerType()) 10304 return; 10305 10306 // TODO: remove this early return once the false positives for constant->bool 10307 // in templates, macros, etc, are reduced or removed. 10308 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 10309 return; 10310 10311 IntRange SourceRange = GetExprRange(S.Context, E); 10312 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 10313 10314 if (SourceRange.Width > TargetRange.Width) { 10315 // If the source is a constant, use a default-on diagnostic. 10316 // TODO: this should happen for bitfield stores, too. 10317 llvm::APSInt Value(32); 10318 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) { 10319 if (S.SourceMgr.isInSystemMacro(CC)) 10320 return; 10321 10322 std::string PrettySourceValue = Value.toString(10); 10323 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 10324 10325 S.DiagRuntimeBehavior(E->getExprLoc(), E, 10326 S.PDiag(diag::warn_impcast_integer_precision_constant) 10327 << PrettySourceValue << PrettyTargetValue 10328 << E->getType() << T << E->getSourceRange() 10329 << clang::SourceRange(CC)); 10330 return; 10331 } 10332 10333 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 10334 if (S.SourceMgr.isInSystemMacro(CC)) 10335 return; 10336 10337 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 10338 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 10339 /* pruneControlFlow */ true); 10340 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 10341 } 10342 10343 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative && 10344 SourceRange.NonNegative && Source->isSignedIntegerType()) { 10345 // Warn when doing a signed to signed conversion, warn if the positive 10346 // source value is exactly the width of the target type, which will 10347 // cause a negative value to be stored. 10348 10349 llvm::APSInt Value; 10350 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) && 10351 !S.SourceMgr.isInSystemMacro(CC)) { 10352 if (isSameWidthConstantConversion(S, E, T, CC)) { 10353 std::string PrettySourceValue = Value.toString(10); 10354 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 10355 10356 S.DiagRuntimeBehavior( 10357 E->getExprLoc(), E, 10358 S.PDiag(diag::warn_impcast_integer_precision_constant) 10359 << PrettySourceValue << PrettyTargetValue << E->getType() << T 10360 << E->getSourceRange() << clang::SourceRange(CC)); 10361 return; 10362 } 10363 } 10364 10365 // Fall through for non-constants to give a sign conversion warning. 10366 } 10367 10368 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 10369 (!TargetRange.NonNegative && SourceRange.NonNegative && 10370 SourceRange.Width == TargetRange.Width)) { 10371 if (S.SourceMgr.isInSystemMacro(CC)) 10372 return; 10373 10374 unsigned DiagID = diag::warn_impcast_integer_sign; 10375 10376 // Traditionally, gcc has warned about this under -Wsign-compare. 10377 // We also want to warn about it in -Wconversion. 10378 // So if -Wconversion is off, use a completely identical diagnostic 10379 // in the sign-compare group. 10380 // The conditional-checking code will 10381 if (ICContext) { 10382 DiagID = diag::warn_impcast_integer_sign_conditional; 10383 *ICContext = true; 10384 } 10385 10386 return DiagnoseImpCast(S, E, T, CC, DiagID); 10387 } 10388 10389 // Diagnose conversions between different enumeration types. 10390 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 10391 // type, to give us better diagnostics. 10392 QualType SourceType = E->getType(); 10393 if (!S.getLangOpts().CPlusPlus) { 10394 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 10395 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 10396 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 10397 SourceType = S.Context.getTypeDeclType(Enum); 10398 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 10399 } 10400 } 10401 10402 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 10403 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 10404 if (SourceEnum->getDecl()->hasNameForLinkage() && 10405 TargetEnum->getDecl()->hasNameForLinkage() && 10406 SourceEnum != TargetEnum) { 10407 if (S.SourceMgr.isInSystemMacro(CC)) 10408 return; 10409 10410 return DiagnoseImpCast(S, E, SourceType, T, CC, 10411 diag::warn_impcast_different_enum_types); 10412 } 10413 } 10414 10415 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 10416 SourceLocation CC, QualType T); 10417 10418 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 10419 SourceLocation CC, bool &ICContext) { 10420 E = E->IgnoreParenImpCasts(); 10421 10422 if (isa<ConditionalOperator>(E)) 10423 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T); 10424 10425 AnalyzeImplicitConversions(S, E, CC); 10426 if (E->getType() != T) 10427 return CheckImplicitConversion(S, E, T, CC, &ICContext); 10428 } 10429 10430 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 10431 SourceLocation CC, QualType T) { 10432 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 10433 10434 bool Suspicious = false; 10435 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 10436 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 10437 10438 // If -Wconversion would have warned about either of the candidates 10439 // for a signedness conversion to the context type... 10440 if (!Suspicious) return; 10441 10442 // ...but it's currently ignored... 10443 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 10444 return; 10445 10446 // ...then check whether it would have warned about either of the 10447 // candidates for a signedness conversion to the condition type. 10448 if (E->getType() == T) return; 10449 10450 Suspicious = false; 10451 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 10452 E->getType(), CC, &Suspicious); 10453 if (!Suspicious) 10454 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 10455 E->getType(), CC, &Suspicious); 10456 } 10457 10458 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 10459 /// Input argument E is a logical expression. 10460 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 10461 if (S.getLangOpts().Bool) 10462 return; 10463 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 10464 } 10465 10466 /// AnalyzeImplicitConversions - Find and report any interesting 10467 /// implicit conversions in the given expression. There are a couple 10468 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 10469 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, 10470 SourceLocation CC) { 10471 QualType T = OrigE->getType(); 10472 Expr *E = OrigE->IgnoreParenImpCasts(); 10473 10474 if (E->isTypeDependent() || E->isValueDependent()) 10475 return; 10476 10477 // For conditional operators, we analyze the arguments as if they 10478 // were being fed directly into the output. 10479 if (isa<ConditionalOperator>(E)) { 10480 ConditionalOperator *CO = cast<ConditionalOperator>(E); 10481 CheckConditionalOperator(S, CO, CC, T); 10482 return; 10483 } 10484 10485 // Check implicit argument conversions for function calls. 10486 if (CallExpr *Call = dyn_cast<CallExpr>(E)) 10487 CheckImplicitArgumentConversions(S, Call, CC); 10488 10489 // Go ahead and check any implicit conversions we might have skipped. 10490 // The non-canonical typecheck is just an optimization; 10491 // CheckImplicitConversion will filter out dead implicit conversions. 10492 if (E->getType() != T) 10493 CheckImplicitConversion(S, E, T, CC); 10494 10495 // Now continue drilling into this expression. 10496 10497 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 10498 // The bound subexpressions in a PseudoObjectExpr are not reachable 10499 // as transitive children. 10500 // FIXME: Use a more uniform representation for this. 10501 for (auto *SE : POE->semantics()) 10502 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 10503 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC); 10504 } 10505 10506 // Skip past explicit casts. 10507 if (isa<ExplicitCastExpr>(E)) { 10508 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts(); 10509 return AnalyzeImplicitConversions(S, E, CC); 10510 } 10511 10512 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 10513 // Do a somewhat different check with comparison operators. 10514 if (BO->isComparisonOp()) 10515 return AnalyzeComparison(S, BO); 10516 10517 // And with simple assignments. 10518 if (BO->getOpcode() == BO_Assign) 10519 return AnalyzeAssignment(S, BO); 10520 // And with compound assignments. 10521 if (BO->isAssignmentOp()) 10522 return AnalyzeCompoundAssignment(S, BO); 10523 } 10524 10525 // These break the otherwise-useful invariant below. Fortunately, 10526 // we don't really need to recurse into them, because any internal 10527 // expressions should have been analyzed already when they were 10528 // built into statements. 10529 if (isa<StmtExpr>(E)) return; 10530 10531 // Don't descend into unevaluated contexts. 10532 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 10533 10534 // Now just recurse over the expression's children. 10535 CC = E->getExprLoc(); 10536 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 10537 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 10538 for (Stmt *SubStmt : E->children()) { 10539 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 10540 if (!ChildExpr) 10541 continue; 10542 10543 if (IsLogicalAndOperator && 10544 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 10545 // Ignore checking string literals that are in logical and operators. 10546 // This is a common pattern for asserts. 10547 continue; 10548 AnalyzeImplicitConversions(S, ChildExpr, CC); 10549 } 10550 10551 if (BO && BO->isLogicalOp()) { 10552 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 10553 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 10554 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 10555 10556 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 10557 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 10558 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 10559 } 10560 10561 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) 10562 if (U->getOpcode() == UO_LNot) 10563 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 10564 } 10565 10566 /// Diagnose integer type and any valid implicit conversion to it. 10567 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 10568 // Taking into account implicit conversions, 10569 // allow any integer. 10570 if (!E->getType()->isIntegerType()) { 10571 S.Diag(E->getLocStart(), 10572 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 10573 return true; 10574 } 10575 // Potentially emit standard warnings for implicit conversions if enabled 10576 // using -Wconversion. 10577 CheckImplicitConversion(S, E, IntT, E->getLocStart()); 10578 return false; 10579 } 10580 10581 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 10582 // Returns true when emitting a warning about taking the address of a reference. 10583 static bool CheckForReference(Sema &SemaRef, const Expr *E, 10584 const PartialDiagnostic &PD) { 10585 E = E->IgnoreParenImpCasts(); 10586 10587 const FunctionDecl *FD = nullptr; 10588 10589 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 10590 if (!DRE->getDecl()->getType()->isReferenceType()) 10591 return false; 10592 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 10593 if (!M->getMemberDecl()->getType()->isReferenceType()) 10594 return false; 10595 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 10596 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 10597 return false; 10598 FD = Call->getDirectCallee(); 10599 } else { 10600 return false; 10601 } 10602 10603 SemaRef.Diag(E->getExprLoc(), PD); 10604 10605 // If possible, point to location of function. 10606 if (FD) { 10607 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 10608 } 10609 10610 return true; 10611 } 10612 10613 // Returns true if the SourceLocation is expanded from any macro body. 10614 // Returns false if the SourceLocation is invalid, is from not in a macro 10615 // expansion, or is from expanded from a top-level macro argument. 10616 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 10617 if (Loc.isInvalid()) 10618 return false; 10619 10620 while (Loc.isMacroID()) { 10621 if (SM.isMacroBodyExpansion(Loc)) 10622 return true; 10623 Loc = SM.getImmediateMacroCallerLoc(Loc); 10624 } 10625 10626 return false; 10627 } 10628 10629 /// Diagnose pointers that are always non-null. 10630 /// \param E the expression containing the pointer 10631 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 10632 /// compared to a null pointer 10633 /// \param IsEqual True when the comparison is equal to a null pointer 10634 /// \param Range Extra SourceRange to highlight in the diagnostic 10635 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 10636 Expr::NullPointerConstantKind NullKind, 10637 bool IsEqual, SourceRange Range) { 10638 if (!E) 10639 return; 10640 10641 // Don't warn inside macros. 10642 if (E->getExprLoc().isMacroID()) { 10643 const SourceManager &SM = getSourceManager(); 10644 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 10645 IsInAnyMacroBody(SM, Range.getBegin())) 10646 return; 10647 } 10648 E = E->IgnoreImpCasts(); 10649 10650 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 10651 10652 if (isa<CXXThisExpr>(E)) { 10653 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 10654 : diag::warn_this_bool_conversion; 10655 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 10656 return; 10657 } 10658 10659 bool IsAddressOf = false; 10660 10661 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 10662 if (UO->getOpcode() != UO_AddrOf) 10663 return; 10664 IsAddressOf = true; 10665 E = UO->getSubExpr(); 10666 } 10667 10668 if (IsAddressOf) { 10669 unsigned DiagID = IsCompare 10670 ? diag::warn_address_of_reference_null_compare 10671 : diag::warn_address_of_reference_bool_conversion; 10672 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 10673 << IsEqual; 10674 if (CheckForReference(*this, E, PD)) { 10675 return; 10676 } 10677 } 10678 10679 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 10680 bool IsParam = isa<NonNullAttr>(NonnullAttr); 10681 std::string Str; 10682 llvm::raw_string_ostream S(Str); 10683 E->printPretty(S, nullptr, getPrintingPolicy()); 10684 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 10685 : diag::warn_cast_nonnull_to_bool; 10686 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 10687 << E->getSourceRange() << Range << IsEqual; 10688 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 10689 }; 10690 10691 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 10692 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 10693 if (auto *Callee = Call->getDirectCallee()) { 10694 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 10695 ComplainAboutNonnullParamOrCall(A); 10696 return; 10697 } 10698 } 10699 } 10700 10701 // Expect to find a single Decl. Skip anything more complicated. 10702 ValueDecl *D = nullptr; 10703 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 10704 D = R->getDecl(); 10705 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 10706 D = M->getMemberDecl(); 10707 } 10708 10709 // Weak Decls can be null. 10710 if (!D || D->isWeak()) 10711 return; 10712 10713 // Check for parameter decl with nonnull attribute 10714 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 10715 if (getCurFunction() && 10716 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 10717 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 10718 ComplainAboutNonnullParamOrCall(A); 10719 return; 10720 } 10721 10722 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 10723 auto ParamIter = llvm::find(FD->parameters(), PV); 10724 assert(ParamIter != FD->param_end()); 10725 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 10726 10727 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 10728 if (!NonNull->args_size()) { 10729 ComplainAboutNonnullParamOrCall(NonNull); 10730 return; 10731 } 10732 10733 for (const ParamIdx &ArgNo : NonNull->args()) { 10734 if (ArgNo.getASTIndex() == ParamNo) { 10735 ComplainAboutNonnullParamOrCall(NonNull); 10736 return; 10737 } 10738 } 10739 } 10740 } 10741 } 10742 } 10743 10744 QualType T = D->getType(); 10745 const bool IsArray = T->isArrayType(); 10746 const bool IsFunction = T->isFunctionType(); 10747 10748 // Address of function is used to silence the function warning. 10749 if (IsAddressOf && IsFunction) { 10750 return; 10751 } 10752 10753 // Found nothing. 10754 if (!IsAddressOf && !IsFunction && !IsArray) 10755 return; 10756 10757 // Pretty print the expression for the diagnostic. 10758 std::string Str; 10759 llvm::raw_string_ostream S(Str); 10760 E->printPretty(S, nullptr, getPrintingPolicy()); 10761 10762 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 10763 : diag::warn_impcast_pointer_to_bool; 10764 enum { 10765 AddressOf, 10766 FunctionPointer, 10767 ArrayPointer 10768 } DiagType; 10769 if (IsAddressOf) 10770 DiagType = AddressOf; 10771 else if (IsFunction) 10772 DiagType = FunctionPointer; 10773 else if (IsArray) 10774 DiagType = ArrayPointer; 10775 else 10776 llvm_unreachable("Could not determine diagnostic."); 10777 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 10778 << Range << IsEqual; 10779 10780 if (!IsFunction) 10781 return; 10782 10783 // Suggest '&' to silence the function warning. 10784 Diag(E->getExprLoc(), diag::note_function_warning_silence) 10785 << FixItHint::CreateInsertion(E->getLocStart(), "&"); 10786 10787 // Check to see if '()' fixit should be emitted. 10788 QualType ReturnType; 10789 UnresolvedSet<4> NonTemplateOverloads; 10790 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 10791 if (ReturnType.isNull()) 10792 return; 10793 10794 if (IsCompare) { 10795 // There are two cases here. If there is null constant, the only suggest 10796 // for a pointer return type. If the null is 0, then suggest if the return 10797 // type is a pointer or an integer type. 10798 if (!ReturnType->isPointerType()) { 10799 if (NullKind == Expr::NPCK_ZeroExpression || 10800 NullKind == Expr::NPCK_ZeroLiteral) { 10801 if (!ReturnType->isIntegerType()) 10802 return; 10803 } else { 10804 return; 10805 } 10806 } 10807 } else { // !IsCompare 10808 // For function to bool, only suggest if the function pointer has bool 10809 // return type. 10810 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 10811 return; 10812 } 10813 Diag(E->getExprLoc(), diag::note_function_to_function_call) 10814 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()"); 10815 } 10816 10817 /// Diagnoses "dangerous" implicit conversions within the given 10818 /// expression (which is a full expression). Implements -Wconversion 10819 /// and -Wsign-compare. 10820 /// 10821 /// \param CC the "context" location of the implicit conversion, i.e. 10822 /// the most location of the syntactic entity requiring the implicit 10823 /// conversion 10824 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 10825 // Don't diagnose in unevaluated contexts. 10826 if (isUnevaluatedContext()) 10827 return; 10828 10829 // Don't diagnose for value- or type-dependent expressions. 10830 if (E->isTypeDependent() || E->isValueDependent()) 10831 return; 10832 10833 // Check for array bounds violations in cases where the check isn't triggered 10834 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 10835 // ArraySubscriptExpr is on the RHS of a variable initialization. 10836 CheckArrayAccess(E); 10837 10838 // This is not the right CC for (e.g.) a variable initialization. 10839 AnalyzeImplicitConversions(*this, E, CC); 10840 } 10841 10842 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 10843 /// Input argument E is a logical expression. 10844 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 10845 ::CheckBoolLikeConversion(*this, E, CC); 10846 } 10847 10848 /// Diagnose when expression is an integer constant expression and its evaluation 10849 /// results in integer overflow 10850 void Sema::CheckForIntOverflow (Expr *E) { 10851 // Use a work list to deal with nested struct initializers. 10852 SmallVector<Expr *, 2> Exprs(1, E); 10853 10854 do { 10855 Expr *OriginalE = Exprs.pop_back_val(); 10856 Expr *E = OriginalE->IgnoreParenCasts(); 10857 10858 if (isa<BinaryOperator>(E)) { 10859 E->EvaluateForOverflow(Context); 10860 continue; 10861 } 10862 10863 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 10864 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 10865 else if (isa<ObjCBoxedExpr>(OriginalE)) 10866 E->EvaluateForOverflow(Context); 10867 else if (auto Call = dyn_cast<CallExpr>(E)) 10868 Exprs.append(Call->arg_begin(), Call->arg_end()); 10869 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 10870 Exprs.append(Message->arg_begin(), Message->arg_end()); 10871 } while (!Exprs.empty()); 10872 } 10873 10874 namespace { 10875 10876 /// Visitor for expressions which looks for unsequenced operations on the 10877 /// same object. 10878 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> { 10879 using Base = EvaluatedExprVisitor<SequenceChecker>; 10880 10881 /// A tree of sequenced regions within an expression. Two regions are 10882 /// unsequenced if one is an ancestor or a descendent of the other. When we 10883 /// finish processing an expression with sequencing, such as a comma 10884 /// expression, we fold its tree nodes into its parent, since they are 10885 /// unsequenced with respect to nodes we will visit later. 10886 class SequenceTree { 10887 struct Value { 10888 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 10889 unsigned Parent : 31; 10890 unsigned Merged : 1; 10891 }; 10892 SmallVector<Value, 8> Values; 10893 10894 public: 10895 /// A region within an expression which may be sequenced with respect 10896 /// to some other region. 10897 class Seq { 10898 friend class SequenceTree; 10899 10900 unsigned Index = 0; 10901 10902 explicit Seq(unsigned N) : Index(N) {} 10903 10904 public: 10905 Seq() = default; 10906 }; 10907 10908 SequenceTree() { Values.push_back(Value(0)); } 10909 Seq root() const { return Seq(0); } 10910 10911 /// Create a new sequence of operations, which is an unsequenced 10912 /// subset of \p Parent. This sequence of operations is sequenced with 10913 /// respect to other children of \p Parent. 10914 Seq allocate(Seq Parent) { 10915 Values.push_back(Value(Parent.Index)); 10916 return Seq(Values.size() - 1); 10917 } 10918 10919 /// Merge a sequence of operations into its parent. 10920 void merge(Seq S) { 10921 Values[S.Index].Merged = true; 10922 } 10923 10924 /// Determine whether two operations are unsequenced. This operation 10925 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 10926 /// should have been merged into its parent as appropriate. 10927 bool isUnsequenced(Seq Cur, Seq Old) { 10928 unsigned C = representative(Cur.Index); 10929 unsigned Target = representative(Old.Index); 10930 while (C >= Target) { 10931 if (C == Target) 10932 return true; 10933 C = Values[C].Parent; 10934 } 10935 return false; 10936 } 10937 10938 private: 10939 /// Pick a representative for a sequence. 10940 unsigned representative(unsigned K) { 10941 if (Values[K].Merged) 10942 // Perform path compression as we go. 10943 return Values[K].Parent = representative(Values[K].Parent); 10944 return K; 10945 } 10946 }; 10947 10948 /// An object for which we can track unsequenced uses. 10949 using Object = NamedDecl *; 10950 10951 /// Different flavors of object usage which we track. We only track the 10952 /// least-sequenced usage of each kind. 10953 enum UsageKind { 10954 /// A read of an object. Multiple unsequenced reads are OK. 10955 UK_Use, 10956 10957 /// A modification of an object which is sequenced before the value 10958 /// computation of the expression, such as ++n in C++. 10959 UK_ModAsValue, 10960 10961 /// A modification of an object which is not sequenced before the value 10962 /// computation of the expression, such as n++. 10963 UK_ModAsSideEffect, 10964 10965 UK_Count = UK_ModAsSideEffect + 1 10966 }; 10967 10968 struct Usage { 10969 Expr *Use = nullptr; 10970 SequenceTree::Seq Seq; 10971 10972 Usage() = default; 10973 }; 10974 10975 struct UsageInfo { 10976 Usage Uses[UK_Count]; 10977 10978 /// Have we issued a diagnostic for this variable already? 10979 bool Diagnosed = false; 10980 10981 UsageInfo() = default; 10982 }; 10983 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 10984 10985 Sema &SemaRef; 10986 10987 /// Sequenced regions within the expression. 10988 SequenceTree Tree; 10989 10990 /// Declaration modifications and references which we have seen. 10991 UsageInfoMap UsageMap; 10992 10993 /// The region we are currently within. 10994 SequenceTree::Seq Region; 10995 10996 /// Filled in with declarations which were modified as a side-effect 10997 /// (that is, post-increment operations). 10998 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 10999 11000 /// Expressions to check later. We defer checking these to reduce 11001 /// stack usage. 11002 SmallVectorImpl<Expr *> &WorkList; 11003 11004 /// RAII object wrapping the visitation of a sequenced subexpression of an 11005 /// expression. At the end of this process, the side-effects of the evaluation 11006 /// become sequenced with respect to the value computation of the result, so 11007 /// we downgrade any UK_ModAsSideEffect within the evaluation to 11008 /// UK_ModAsValue. 11009 struct SequencedSubexpression { 11010 SequencedSubexpression(SequenceChecker &Self) 11011 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 11012 Self.ModAsSideEffect = &ModAsSideEffect; 11013 } 11014 11015 ~SequencedSubexpression() { 11016 for (auto &M : llvm::reverse(ModAsSideEffect)) { 11017 UsageInfo &U = Self.UsageMap[M.first]; 11018 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect]; 11019 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue); 11020 SideEffectUsage = M.second; 11021 } 11022 Self.ModAsSideEffect = OldModAsSideEffect; 11023 } 11024 11025 SequenceChecker &Self; 11026 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 11027 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 11028 }; 11029 11030 /// RAII object wrapping the visitation of a subexpression which we might 11031 /// choose to evaluate as a constant. If any subexpression is evaluated and 11032 /// found to be non-constant, this allows us to suppress the evaluation of 11033 /// the outer expression. 11034 class EvaluationTracker { 11035 public: 11036 EvaluationTracker(SequenceChecker &Self) 11037 : Self(Self), Prev(Self.EvalTracker) { 11038 Self.EvalTracker = this; 11039 } 11040 11041 ~EvaluationTracker() { 11042 Self.EvalTracker = Prev; 11043 if (Prev) 11044 Prev->EvalOK &= EvalOK; 11045 } 11046 11047 bool evaluate(const Expr *E, bool &Result) { 11048 if (!EvalOK || E->isValueDependent()) 11049 return false; 11050 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context); 11051 return EvalOK; 11052 } 11053 11054 private: 11055 SequenceChecker &Self; 11056 EvaluationTracker *Prev; 11057 bool EvalOK = true; 11058 } *EvalTracker = nullptr; 11059 11060 /// Find the object which is produced by the specified expression, 11061 /// if any. 11062 Object getObject(Expr *E, bool Mod) const { 11063 E = E->IgnoreParenCasts(); 11064 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 11065 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 11066 return getObject(UO->getSubExpr(), Mod); 11067 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11068 if (BO->getOpcode() == BO_Comma) 11069 return getObject(BO->getRHS(), Mod); 11070 if (Mod && BO->isAssignmentOp()) 11071 return getObject(BO->getLHS(), Mod); 11072 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 11073 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 11074 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 11075 return ME->getMemberDecl(); 11076 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 11077 // FIXME: If this is a reference, map through to its value. 11078 return DRE->getDecl(); 11079 return nullptr; 11080 } 11081 11082 /// Note that an object was modified or used by an expression. 11083 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) { 11084 Usage &U = UI.Uses[UK]; 11085 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) { 11086 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 11087 ModAsSideEffect->push_back(std::make_pair(O, U)); 11088 U.Use = Ref; 11089 U.Seq = Region; 11090 } 11091 } 11092 11093 /// Check whether a modification or use conflicts with a prior usage. 11094 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind, 11095 bool IsModMod) { 11096 if (UI.Diagnosed) 11097 return; 11098 11099 const Usage &U = UI.Uses[OtherKind]; 11100 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) 11101 return; 11102 11103 Expr *Mod = U.Use; 11104 Expr *ModOrUse = Ref; 11105 if (OtherKind == UK_Use) 11106 std::swap(Mod, ModOrUse); 11107 11108 SemaRef.Diag(Mod->getExprLoc(), 11109 IsModMod ? diag::warn_unsequenced_mod_mod 11110 : diag::warn_unsequenced_mod_use) 11111 << O << SourceRange(ModOrUse->getExprLoc()); 11112 UI.Diagnosed = true; 11113 } 11114 11115 void notePreUse(Object O, Expr *Use) { 11116 UsageInfo &U = UsageMap[O]; 11117 // Uses conflict with other modifications. 11118 checkUsage(O, U, Use, UK_ModAsValue, false); 11119 } 11120 11121 void notePostUse(Object O, Expr *Use) { 11122 UsageInfo &U = UsageMap[O]; 11123 checkUsage(O, U, Use, UK_ModAsSideEffect, false); 11124 addUsage(U, O, Use, UK_Use); 11125 } 11126 11127 void notePreMod(Object O, Expr *Mod) { 11128 UsageInfo &U = UsageMap[O]; 11129 // Modifications conflict with other modifications and with uses. 11130 checkUsage(O, U, Mod, UK_ModAsValue, true); 11131 checkUsage(O, U, Mod, UK_Use, false); 11132 } 11133 11134 void notePostMod(Object O, Expr *Use, UsageKind UK) { 11135 UsageInfo &U = UsageMap[O]; 11136 checkUsage(O, U, Use, UK_ModAsSideEffect, true); 11137 addUsage(U, O, Use, UK); 11138 } 11139 11140 public: 11141 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList) 11142 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 11143 Visit(E); 11144 } 11145 11146 void VisitStmt(Stmt *S) { 11147 // Skip all statements which aren't expressions for now. 11148 } 11149 11150 void VisitExpr(Expr *E) { 11151 // By default, just recurse to evaluated subexpressions. 11152 Base::VisitStmt(E); 11153 } 11154 11155 void VisitCastExpr(CastExpr *E) { 11156 Object O = Object(); 11157 if (E->getCastKind() == CK_LValueToRValue) 11158 O = getObject(E->getSubExpr(), false); 11159 11160 if (O) 11161 notePreUse(O, E); 11162 VisitExpr(E); 11163 if (O) 11164 notePostUse(O, E); 11165 } 11166 11167 void VisitBinComma(BinaryOperator *BO) { 11168 // C++11 [expr.comma]p1: 11169 // Every value computation and side effect associated with the left 11170 // expression is sequenced before every value computation and side 11171 // effect associated with the right expression. 11172 SequenceTree::Seq LHS = Tree.allocate(Region); 11173 SequenceTree::Seq RHS = Tree.allocate(Region); 11174 SequenceTree::Seq OldRegion = Region; 11175 11176 { 11177 SequencedSubexpression SeqLHS(*this); 11178 Region = LHS; 11179 Visit(BO->getLHS()); 11180 } 11181 11182 Region = RHS; 11183 Visit(BO->getRHS()); 11184 11185 Region = OldRegion; 11186 11187 // Forget that LHS and RHS are sequenced. They are both unsequenced 11188 // with respect to other stuff. 11189 Tree.merge(LHS); 11190 Tree.merge(RHS); 11191 } 11192 11193 void VisitBinAssign(BinaryOperator *BO) { 11194 // The modification is sequenced after the value computation of the LHS 11195 // and RHS, so check it before inspecting the operands and update the 11196 // map afterwards. 11197 Object O = getObject(BO->getLHS(), true); 11198 if (!O) 11199 return VisitExpr(BO); 11200 11201 notePreMod(O, BO); 11202 11203 // C++11 [expr.ass]p7: 11204 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated 11205 // only once. 11206 // 11207 // Therefore, for a compound assignment operator, O is considered used 11208 // everywhere except within the evaluation of E1 itself. 11209 if (isa<CompoundAssignOperator>(BO)) 11210 notePreUse(O, BO); 11211 11212 Visit(BO->getLHS()); 11213 11214 if (isa<CompoundAssignOperator>(BO)) 11215 notePostUse(O, BO); 11216 11217 Visit(BO->getRHS()); 11218 11219 // C++11 [expr.ass]p1: 11220 // the assignment is sequenced [...] before the value computation of the 11221 // assignment expression. 11222 // C11 6.5.16/3 has no such rule. 11223 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 11224 : UK_ModAsSideEffect); 11225 } 11226 11227 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) { 11228 VisitBinAssign(CAO); 11229 } 11230 11231 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 11232 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 11233 void VisitUnaryPreIncDec(UnaryOperator *UO) { 11234 Object O = getObject(UO->getSubExpr(), true); 11235 if (!O) 11236 return VisitExpr(UO); 11237 11238 notePreMod(O, UO); 11239 Visit(UO->getSubExpr()); 11240 // C++11 [expr.pre.incr]p1: 11241 // the expression ++x is equivalent to x+=1 11242 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 11243 : UK_ModAsSideEffect); 11244 } 11245 11246 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 11247 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 11248 void VisitUnaryPostIncDec(UnaryOperator *UO) { 11249 Object O = getObject(UO->getSubExpr(), true); 11250 if (!O) 11251 return VisitExpr(UO); 11252 11253 notePreMod(O, UO); 11254 Visit(UO->getSubExpr()); 11255 notePostMod(O, UO, UK_ModAsSideEffect); 11256 } 11257 11258 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated. 11259 void VisitBinLOr(BinaryOperator *BO) { 11260 // The side-effects of the LHS of an '&&' are sequenced before the 11261 // value computation of the RHS, and hence before the value computation 11262 // of the '&&' itself, unless the LHS evaluates to zero. We treat them 11263 // as if they were unconditionally sequenced. 11264 EvaluationTracker Eval(*this); 11265 { 11266 SequencedSubexpression Sequenced(*this); 11267 Visit(BO->getLHS()); 11268 } 11269 11270 bool Result; 11271 if (Eval.evaluate(BO->getLHS(), Result)) { 11272 if (!Result) 11273 Visit(BO->getRHS()); 11274 } else { 11275 // Check for unsequenced operations in the RHS, treating it as an 11276 // entirely separate evaluation. 11277 // 11278 // FIXME: If there are operations in the RHS which are unsequenced 11279 // with respect to operations outside the RHS, and those operations 11280 // are unconditionally evaluated, diagnose them. 11281 WorkList.push_back(BO->getRHS()); 11282 } 11283 } 11284 void VisitBinLAnd(BinaryOperator *BO) { 11285 EvaluationTracker Eval(*this); 11286 { 11287 SequencedSubexpression Sequenced(*this); 11288 Visit(BO->getLHS()); 11289 } 11290 11291 bool Result; 11292 if (Eval.evaluate(BO->getLHS(), Result)) { 11293 if (Result) 11294 Visit(BO->getRHS()); 11295 } else { 11296 WorkList.push_back(BO->getRHS()); 11297 } 11298 } 11299 11300 // Only visit the condition, unless we can be sure which subexpression will 11301 // be chosen. 11302 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) { 11303 EvaluationTracker Eval(*this); 11304 { 11305 SequencedSubexpression Sequenced(*this); 11306 Visit(CO->getCond()); 11307 } 11308 11309 bool Result; 11310 if (Eval.evaluate(CO->getCond(), Result)) 11311 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr()); 11312 else { 11313 WorkList.push_back(CO->getTrueExpr()); 11314 WorkList.push_back(CO->getFalseExpr()); 11315 } 11316 } 11317 11318 void VisitCallExpr(CallExpr *CE) { 11319 // C++11 [intro.execution]p15: 11320 // When calling a function [...], every value computation and side effect 11321 // associated with any argument expression, or with the postfix expression 11322 // designating the called function, is sequenced before execution of every 11323 // expression or statement in the body of the function [and thus before 11324 // the value computation of its result]. 11325 SequencedSubexpression Sequenced(*this); 11326 Base::VisitCallExpr(CE); 11327 11328 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 11329 } 11330 11331 void VisitCXXConstructExpr(CXXConstructExpr *CCE) { 11332 // This is a call, so all subexpressions are sequenced before the result. 11333 SequencedSubexpression Sequenced(*this); 11334 11335 if (!CCE->isListInitialization()) 11336 return VisitExpr(CCE); 11337 11338 // In C++11, list initializations are sequenced. 11339 SmallVector<SequenceTree::Seq, 32> Elts; 11340 SequenceTree::Seq Parent = Region; 11341 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(), 11342 E = CCE->arg_end(); 11343 I != E; ++I) { 11344 Region = Tree.allocate(Parent); 11345 Elts.push_back(Region); 11346 Visit(*I); 11347 } 11348 11349 // Forget that the initializers are sequenced. 11350 Region = Parent; 11351 for (unsigned I = 0; I < Elts.size(); ++I) 11352 Tree.merge(Elts[I]); 11353 } 11354 11355 void VisitInitListExpr(InitListExpr *ILE) { 11356 if (!SemaRef.getLangOpts().CPlusPlus11) 11357 return VisitExpr(ILE); 11358 11359 // In C++11, list initializations are sequenced. 11360 SmallVector<SequenceTree::Seq, 32> Elts; 11361 SequenceTree::Seq Parent = Region; 11362 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 11363 Expr *E = ILE->getInit(I); 11364 if (!E) continue; 11365 Region = Tree.allocate(Parent); 11366 Elts.push_back(Region); 11367 Visit(E); 11368 } 11369 11370 // Forget that the initializers are sequenced. 11371 Region = Parent; 11372 for (unsigned I = 0; I < Elts.size(); ++I) 11373 Tree.merge(Elts[I]); 11374 } 11375 }; 11376 11377 } // namespace 11378 11379 void Sema::CheckUnsequencedOperations(Expr *E) { 11380 SmallVector<Expr *, 8> WorkList; 11381 WorkList.push_back(E); 11382 while (!WorkList.empty()) { 11383 Expr *Item = WorkList.pop_back_val(); 11384 SequenceChecker(*this, Item, WorkList); 11385 } 11386 } 11387 11388 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 11389 bool IsConstexpr) { 11390 CheckImplicitConversions(E, CheckLoc); 11391 if (!E->isInstantiationDependent()) 11392 CheckUnsequencedOperations(E); 11393 if (!IsConstexpr && !E->isValueDependent()) 11394 CheckForIntOverflow(E); 11395 DiagnoseMisalignedMembers(); 11396 } 11397 11398 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 11399 FieldDecl *BitField, 11400 Expr *Init) { 11401 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 11402 } 11403 11404 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 11405 SourceLocation Loc) { 11406 if (!PType->isVariablyModifiedType()) 11407 return; 11408 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 11409 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 11410 return; 11411 } 11412 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 11413 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 11414 return; 11415 } 11416 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 11417 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 11418 return; 11419 } 11420 11421 const ArrayType *AT = S.Context.getAsArrayType(PType); 11422 if (!AT) 11423 return; 11424 11425 if (AT->getSizeModifier() != ArrayType::Star) { 11426 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 11427 return; 11428 } 11429 11430 S.Diag(Loc, diag::err_array_star_in_function_definition); 11431 } 11432 11433 /// CheckParmsForFunctionDef - Check that the parameters of the given 11434 /// function are appropriate for the definition of a function. This 11435 /// takes care of any checks that cannot be performed on the 11436 /// declaration itself, e.g., that the types of each of the function 11437 /// parameters are complete. 11438 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 11439 bool CheckParameterNames) { 11440 bool HasInvalidParm = false; 11441 for (ParmVarDecl *Param : Parameters) { 11442 // C99 6.7.5.3p4: the parameters in a parameter type list in a 11443 // function declarator that is part of a function definition of 11444 // that function shall not have incomplete type. 11445 // 11446 // This is also C++ [dcl.fct]p6. 11447 if (!Param->isInvalidDecl() && 11448 RequireCompleteType(Param->getLocation(), Param->getType(), 11449 diag::err_typecheck_decl_incomplete_type)) { 11450 Param->setInvalidDecl(); 11451 HasInvalidParm = true; 11452 } 11453 11454 // C99 6.9.1p5: If the declarator includes a parameter type list, the 11455 // declaration of each parameter shall include an identifier. 11456 if (CheckParameterNames && 11457 Param->getIdentifier() == nullptr && 11458 !Param->isImplicit() && 11459 !getLangOpts().CPlusPlus) 11460 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 11461 11462 // C99 6.7.5.3p12: 11463 // If the function declarator is not part of a definition of that 11464 // function, parameters may have incomplete type and may use the [*] 11465 // notation in their sequences of declarator specifiers to specify 11466 // variable length array types. 11467 QualType PType = Param->getOriginalType(); 11468 // FIXME: This diagnostic should point the '[*]' if source-location 11469 // information is added for it. 11470 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 11471 11472 // If the parameter is a c++ class type and it has to be destructed in the 11473 // callee function, declare the destructor so that it can be called by the 11474 // callee function. Do not perform any direct access check on the dtor here. 11475 if (!Param->isInvalidDecl()) { 11476 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 11477 if (!ClassDecl->isInvalidDecl() && 11478 !ClassDecl->hasIrrelevantDestructor() && 11479 !ClassDecl->isDependentContext() && 11480 ClassDecl->isParamDestroyedInCallee()) { 11481 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 11482 MarkFunctionReferenced(Param->getLocation(), Destructor); 11483 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 11484 } 11485 } 11486 } 11487 11488 // Parameters with the pass_object_size attribute only need to be marked 11489 // constant at function definitions. Because we lack information about 11490 // whether we're on a declaration or definition when we're instantiating the 11491 // attribute, we need to check for constness here. 11492 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 11493 if (!Param->getType().isConstQualified()) 11494 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 11495 << Attr->getSpelling() << 1; 11496 } 11497 11498 return HasInvalidParm; 11499 } 11500 11501 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr 11502 /// or MemberExpr. 11503 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign, 11504 ASTContext &Context) { 11505 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 11506 return Context.getDeclAlign(DRE->getDecl()); 11507 11508 if (const auto *ME = dyn_cast<MemberExpr>(E)) 11509 return Context.getDeclAlign(ME->getMemberDecl()); 11510 11511 return TypeAlign; 11512 } 11513 11514 /// CheckCastAlign - Implements -Wcast-align, which warns when a 11515 /// pointer cast increases the alignment requirements. 11516 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 11517 // This is actually a lot of work to potentially be doing on every 11518 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 11519 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 11520 return; 11521 11522 // Ignore dependent types. 11523 if (T->isDependentType() || Op->getType()->isDependentType()) 11524 return; 11525 11526 // Require that the destination be a pointer type. 11527 const PointerType *DestPtr = T->getAs<PointerType>(); 11528 if (!DestPtr) return; 11529 11530 // If the destination has alignment 1, we're done. 11531 QualType DestPointee = DestPtr->getPointeeType(); 11532 if (DestPointee->isIncompleteType()) return; 11533 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 11534 if (DestAlign.isOne()) return; 11535 11536 // Require that the source be a pointer type. 11537 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 11538 if (!SrcPtr) return; 11539 QualType SrcPointee = SrcPtr->getPointeeType(); 11540 11541 // Whitelist casts from cv void*. We already implicitly 11542 // whitelisted casts to cv void*, since they have alignment 1. 11543 // Also whitelist casts involving incomplete types, which implicitly 11544 // includes 'void'. 11545 if (SrcPointee->isIncompleteType()) return; 11546 11547 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee); 11548 11549 if (auto *CE = dyn_cast<CastExpr>(Op)) { 11550 if (CE->getCastKind() == CK_ArrayToPointerDecay) 11551 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context); 11552 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) { 11553 if (UO->getOpcode() == UO_AddrOf) 11554 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context); 11555 } 11556 11557 if (SrcAlign >= DestAlign) return; 11558 11559 Diag(TRange.getBegin(), diag::warn_cast_align) 11560 << Op->getType() << T 11561 << static_cast<unsigned>(SrcAlign.getQuantity()) 11562 << static_cast<unsigned>(DestAlign.getQuantity()) 11563 << TRange << Op->getSourceRange(); 11564 } 11565 11566 /// Check whether this array fits the idiom of a size-one tail padded 11567 /// array member of a struct. 11568 /// 11569 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 11570 /// commonly used to emulate flexible arrays in C89 code. 11571 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 11572 const NamedDecl *ND) { 11573 if (Size != 1 || !ND) return false; 11574 11575 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 11576 if (!FD) return false; 11577 11578 // Don't consider sizes resulting from macro expansions or template argument 11579 // substitution to form C89 tail-padded arrays. 11580 11581 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 11582 while (TInfo) { 11583 TypeLoc TL = TInfo->getTypeLoc(); 11584 // Look through typedefs. 11585 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 11586 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 11587 TInfo = TDL->getTypeSourceInfo(); 11588 continue; 11589 } 11590 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 11591 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 11592 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 11593 return false; 11594 } 11595 break; 11596 } 11597 11598 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 11599 if (!RD) return false; 11600 if (RD->isUnion()) return false; 11601 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 11602 if (!CRD->isStandardLayout()) return false; 11603 } 11604 11605 // See if this is the last field decl in the record. 11606 const Decl *D = FD; 11607 while ((D = D->getNextDeclInContext())) 11608 if (isa<FieldDecl>(D)) 11609 return false; 11610 return true; 11611 } 11612 11613 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 11614 const ArraySubscriptExpr *ASE, 11615 bool AllowOnePastEnd, bool IndexNegated) { 11616 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 11617 if (IndexExpr->isValueDependent()) 11618 return; 11619 11620 const Type *EffectiveType = 11621 BaseExpr->getType()->getPointeeOrArrayElementType(); 11622 BaseExpr = BaseExpr->IgnoreParenCasts(); 11623 const ConstantArrayType *ArrayTy = 11624 Context.getAsConstantArrayType(BaseExpr->getType()); 11625 if (!ArrayTy) 11626 return; 11627 11628 llvm::APSInt index; 11629 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects)) 11630 return; 11631 if (IndexNegated) 11632 index = -index; 11633 11634 const NamedDecl *ND = nullptr; 11635 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 11636 ND = DRE->getDecl(); 11637 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 11638 ND = ME->getMemberDecl(); 11639 11640 if (index.isUnsigned() || !index.isNegative()) { 11641 llvm::APInt size = ArrayTy->getSize(); 11642 if (!size.isStrictlyPositive()) 11643 return; 11644 11645 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType(); 11646 if (BaseType != EffectiveType) { 11647 // Make sure we're comparing apples to apples when comparing index to size 11648 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 11649 uint64_t array_typesize = Context.getTypeSize(BaseType); 11650 // Handle ptrarith_typesize being zero, such as when casting to void* 11651 if (!ptrarith_typesize) ptrarith_typesize = 1; 11652 if (ptrarith_typesize != array_typesize) { 11653 // There's a cast to a different size type involved 11654 uint64_t ratio = array_typesize / ptrarith_typesize; 11655 // TODO: Be smarter about handling cases where array_typesize is not a 11656 // multiple of ptrarith_typesize 11657 if (ptrarith_typesize * ratio == array_typesize) 11658 size *= llvm::APInt(size.getBitWidth(), ratio); 11659 } 11660 } 11661 11662 if (size.getBitWidth() > index.getBitWidth()) 11663 index = index.zext(size.getBitWidth()); 11664 else if (size.getBitWidth() < index.getBitWidth()) 11665 size = size.zext(index.getBitWidth()); 11666 11667 // For array subscripting the index must be less than size, but for pointer 11668 // arithmetic also allow the index (offset) to be equal to size since 11669 // computing the next address after the end of the array is legal and 11670 // commonly done e.g. in C++ iterators and range-based for loops. 11671 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 11672 return; 11673 11674 // Also don't warn for arrays of size 1 which are members of some 11675 // structure. These are often used to approximate flexible arrays in C89 11676 // code. 11677 if (IsTailPaddedMemberArray(*this, size, ND)) 11678 return; 11679 11680 // Suppress the warning if the subscript expression (as identified by the 11681 // ']' location) and the index expression are both from macro expansions 11682 // within a system header. 11683 if (ASE) { 11684 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 11685 ASE->getRBracketLoc()); 11686 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 11687 SourceLocation IndexLoc = SourceMgr.getSpellingLoc( 11688 IndexExpr->getLocStart()); 11689 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 11690 return; 11691 } 11692 } 11693 11694 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 11695 if (ASE) 11696 DiagID = diag::warn_array_index_exceeds_bounds; 11697 11698 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 11699 PDiag(DiagID) << index.toString(10, true) 11700 << size.toString(10, true) 11701 << (unsigned)size.getLimitedValue(~0U) 11702 << IndexExpr->getSourceRange()); 11703 } else { 11704 unsigned DiagID = diag::warn_array_index_precedes_bounds; 11705 if (!ASE) { 11706 DiagID = diag::warn_ptr_arith_precedes_bounds; 11707 if (index.isNegative()) index = -index; 11708 } 11709 11710 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 11711 PDiag(DiagID) << index.toString(10, true) 11712 << IndexExpr->getSourceRange()); 11713 } 11714 11715 if (!ND) { 11716 // Try harder to find a NamedDecl to point at in the note. 11717 while (const ArraySubscriptExpr *ASE = 11718 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 11719 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 11720 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 11721 ND = DRE->getDecl(); 11722 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 11723 ND = ME->getMemberDecl(); 11724 } 11725 11726 if (ND) 11727 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr, 11728 PDiag(diag::note_array_index_out_of_bounds) 11729 << ND->getDeclName()); 11730 } 11731 11732 void Sema::CheckArrayAccess(const Expr *expr) { 11733 int AllowOnePastEnd = 0; 11734 while (expr) { 11735 expr = expr->IgnoreParenImpCasts(); 11736 switch (expr->getStmtClass()) { 11737 case Stmt::ArraySubscriptExprClass: { 11738 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 11739 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 11740 AllowOnePastEnd > 0); 11741 expr = ASE->getBase(); 11742 break; 11743 } 11744 case Stmt::MemberExprClass: { 11745 expr = cast<MemberExpr>(expr)->getBase(); 11746 break; 11747 } 11748 case Stmt::OMPArraySectionExprClass: { 11749 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 11750 if (ASE->getLowerBound()) 11751 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 11752 /*ASE=*/nullptr, AllowOnePastEnd > 0); 11753 return; 11754 } 11755 case Stmt::UnaryOperatorClass: { 11756 // Only unwrap the * and & unary operators 11757 const UnaryOperator *UO = cast<UnaryOperator>(expr); 11758 expr = UO->getSubExpr(); 11759 switch (UO->getOpcode()) { 11760 case UO_AddrOf: 11761 AllowOnePastEnd++; 11762 break; 11763 case UO_Deref: 11764 AllowOnePastEnd--; 11765 break; 11766 default: 11767 return; 11768 } 11769 break; 11770 } 11771 case Stmt::ConditionalOperatorClass: { 11772 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 11773 if (const Expr *lhs = cond->getLHS()) 11774 CheckArrayAccess(lhs); 11775 if (const Expr *rhs = cond->getRHS()) 11776 CheckArrayAccess(rhs); 11777 return; 11778 } 11779 case Stmt::CXXOperatorCallExprClass: { 11780 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 11781 for (const auto *Arg : OCE->arguments()) 11782 CheckArrayAccess(Arg); 11783 return; 11784 } 11785 default: 11786 return; 11787 } 11788 } 11789 } 11790 11791 //===--- CHECK: Objective-C retain cycles ----------------------------------// 11792 11793 namespace { 11794 11795 struct RetainCycleOwner { 11796 VarDecl *Variable = nullptr; 11797 SourceRange Range; 11798 SourceLocation Loc; 11799 bool Indirect = false; 11800 11801 RetainCycleOwner() = default; 11802 11803 void setLocsFrom(Expr *e) { 11804 Loc = e->getExprLoc(); 11805 Range = e->getSourceRange(); 11806 } 11807 }; 11808 11809 } // namespace 11810 11811 /// Consider whether capturing the given variable can possibly lead to 11812 /// a retain cycle. 11813 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 11814 // In ARC, it's captured strongly iff the variable has __strong 11815 // lifetime. In MRR, it's captured strongly if the variable is 11816 // __block and has an appropriate type. 11817 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 11818 return false; 11819 11820 owner.Variable = var; 11821 if (ref) 11822 owner.setLocsFrom(ref); 11823 return true; 11824 } 11825 11826 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 11827 while (true) { 11828 e = e->IgnoreParens(); 11829 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 11830 switch (cast->getCastKind()) { 11831 case CK_BitCast: 11832 case CK_LValueBitCast: 11833 case CK_LValueToRValue: 11834 case CK_ARCReclaimReturnedObject: 11835 e = cast->getSubExpr(); 11836 continue; 11837 11838 default: 11839 return false; 11840 } 11841 } 11842 11843 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 11844 ObjCIvarDecl *ivar = ref->getDecl(); 11845 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 11846 return false; 11847 11848 // Try to find a retain cycle in the base. 11849 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 11850 return false; 11851 11852 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 11853 owner.Indirect = true; 11854 return true; 11855 } 11856 11857 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 11858 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 11859 if (!var) return false; 11860 return considerVariable(var, ref, owner); 11861 } 11862 11863 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 11864 if (member->isArrow()) return false; 11865 11866 // Don't count this as an indirect ownership. 11867 e = member->getBase(); 11868 continue; 11869 } 11870 11871 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 11872 // Only pay attention to pseudo-objects on property references. 11873 ObjCPropertyRefExpr *pre 11874 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 11875 ->IgnoreParens()); 11876 if (!pre) return false; 11877 if (pre->isImplicitProperty()) return false; 11878 ObjCPropertyDecl *property = pre->getExplicitProperty(); 11879 if (!property->isRetaining() && 11880 !(property->getPropertyIvarDecl() && 11881 property->getPropertyIvarDecl()->getType() 11882 .getObjCLifetime() == Qualifiers::OCL_Strong)) 11883 return false; 11884 11885 owner.Indirect = true; 11886 if (pre->isSuperReceiver()) { 11887 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 11888 if (!owner.Variable) 11889 return false; 11890 owner.Loc = pre->getLocation(); 11891 owner.Range = pre->getSourceRange(); 11892 return true; 11893 } 11894 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 11895 ->getSourceExpr()); 11896 continue; 11897 } 11898 11899 // Array ivars? 11900 11901 return false; 11902 } 11903 } 11904 11905 namespace { 11906 11907 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 11908 ASTContext &Context; 11909 VarDecl *Variable; 11910 Expr *Capturer = nullptr; 11911 bool VarWillBeReased = false; 11912 11913 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 11914 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 11915 Context(Context), Variable(variable) {} 11916 11917 void VisitDeclRefExpr(DeclRefExpr *ref) { 11918 if (ref->getDecl() == Variable && !Capturer) 11919 Capturer = ref; 11920 } 11921 11922 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 11923 if (Capturer) return; 11924 Visit(ref->getBase()); 11925 if (Capturer && ref->isFreeIvar()) 11926 Capturer = ref; 11927 } 11928 11929 void VisitBlockExpr(BlockExpr *block) { 11930 // Look inside nested blocks 11931 if (block->getBlockDecl()->capturesVariable(Variable)) 11932 Visit(block->getBlockDecl()->getBody()); 11933 } 11934 11935 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 11936 if (Capturer) return; 11937 if (OVE->getSourceExpr()) 11938 Visit(OVE->getSourceExpr()); 11939 } 11940 11941 void VisitBinaryOperator(BinaryOperator *BinOp) { 11942 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 11943 return; 11944 Expr *LHS = BinOp->getLHS(); 11945 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 11946 if (DRE->getDecl() != Variable) 11947 return; 11948 if (Expr *RHS = BinOp->getRHS()) { 11949 RHS = RHS->IgnoreParenCasts(); 11950 llvm::APSInt Value; 11951 VarWillBeReased = 11952 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0); 11953 } 11954 } 11955 } 11956 }; 11957 11958 } // namespace 11959 11960 /// Check whether the given argument is a block which captures a 11961 /// variable. 11962 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 11963 assert(owner.Variable && owner.Loc.isValid()); 11964 11965 e = e->IgnoreParenCasts(); 11966 11967 // Look through [^{...} copy] and Block_copy(^{...}). 11968 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 11969 Selector Cmd = ME->getSelector(); 11970 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 11971 e = ME->getInstanceReceiver(); 11972 if (!e) 11973 return nullptr; 11974 e = e->IgnoreParenCasts(); 11975 } 11976 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 11977 if (CE->getNumArgs() == 1) { 11978 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 11979 if (Fn) { 11980 const IdentifierInfo *FnI = Fn->getIdentifier(); 11981 if (FnI && FnI->isStr("_Block_copy")) { 11982 e = CE->getArg(0)->IgnoreParenCasts(); 11983 } 11984 } 11985 } 11986 } 11987 11988 BlockExpr *block = dyn_cast<BlockExpr>(e); 11989 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 11990 return nullptr; 11991 11992 FindCaptureVisitor visitor(S.Context, owner.Variable); 11993 visitor.Visit(block->getBlockDecl()->getBody()); 11994 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 11995 } 11996 11997 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 11998 RetainCycleOwner &owner) { 11999 assert(capturer); 12000 assert(owner.Variable && owner.Loc.isValid()); 12001 12002 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 12003 << owner.Variable << capturer->getSourceRange(); 12004 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 12005 << owner.Indirect << owner.Range; 12006 } 12007 12008 /// Check for a keyword selector that starts with the word 'add' or 12009 /// 'set'. 12010 static bool isSetterLikeSelector(Selector sel) { 12011 if (sel.isUnarySelector()) return false; 12012 12013 StringRef str = sel.getNameForSlot(0); 12014 while (!str.empty() && str.front() == '_') str = str.substr(1); 12015 if (str.startswith("set")) 12016 str = str.substr(3); 12017 else if (str.startswith("add")) { 12018 // Specially whitelist 'addOperationWithBlock:'. 12019 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 12020 return false; 12021 str = str.substr(3); 12022 } 12023 else 12024 return false; 12025 12026 if (str.empty()) return true; 12027 return !isLowercase(str.front()); 12028 } 12029 12030 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 12031 ObjCMessageExpr *Message) { 12032 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 12033 Message->getReceiverInterface(), 12034 NSAPI::ClassId_NSMutableArray); 12035 if (!IsMutableArray) { 12036 return None; 12037 } 12038 12039 Selector Sel = Message->getSelector(); 12040 12041 Optional<NSAPI::NSArrayMethodKind> MKOpt = 12042 S.NSAPIObj->getNSArrayMethodKind(Sel); 12043 if (!MKOpt) { 12044 return None; 12045 } 12046 12047 NSAPI::NSArrayMethodKind MK = *MKOpt; 12048 12049 switch (MK) { 12050 case NSAPI::NSMutableArr_addObject: 12051 case NSAPI::NSMutableArr_insertObjectAtIndex: 12052 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 12053 return 0; 12054 case NSAPI::NSMutableArr_replaceObjectAtIndex: 12055 return 1; 12056 12057 default: 12058 return None; 12059 } 12060 12061 return None; 12062 } 12063 12064 static 12065 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 12066 ObjCMessageExpr *Message) { 12067 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 12068 Message->getReceiverInterface(), 12069 NSAPI::ClassId_NSMutableDictionary); 12070 if (!IsMutableDictionary) { 12071 return None; 12072 } 12073 12074 Selector Sel = Message->getSelector(); 12075 12076 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 12077 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 12078 if (!MKOpt) { 12079 return None; 12080 } 12081 12082 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 12083 12084 switch (MK) { 12085 case NSAPI::NSMutableDict_setObjectForKey: 12086 case NSAPI::NSMutableDict_setValueForKey: 12087 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 12088 return 0; 12089 12090 default: 12091 return None; 12092 } 12093 12094 return None; 12095 } 12096 12097 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 12098 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 12099 Message->getReceiverInterface(), 12100 NSAPI::ClassId_NSMutableSet); 12101 12102 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 12103 Message->getReceiverInterface(), 12104 NSAPI::ClassId_NSMutableOrderedSet); 12105 if (!IsMutableSet && !IsMutableOrderedSet) { 12106 return None; 12107 } 12108 12109 Selector Sel = Message->getSelector(); 12110 12111 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 12112 if (!MKOpt) { 12113 return None; 12114 } 12115 12116 NSAPI::NSSetMethodKind MK = *MKOpt; 12117 12118 switch (MK) { 12119 case NSAPI::NSMutableSet_addObject: 12120 case NSAPI::NSOrderedSet_setObjectAtIndex: 12121 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 12122 case NSAPI::NSOrderedSet_insertObjectAtIndex: 12123 return 0; 12124 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 12125 return 1; 12126 } 12127 12128 return None; 12129 } 12130 12131 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 12132 if (!Message->isInstanceMessage()) { 12133 return; 12134 } 12135 12136 Optional<int> ArgOpt; 12137 12138 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 12139 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 12140 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 12141 return; 12142 } 12143 12144 int ArgIndex = *ArgOpt; 12145 12146 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 12147 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 12148 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 12149 } 12150 12151 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 12152 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 12153 if (ArgRE->isObjCSelfExpr()) { 12154 Diag(Message->getSourceRange().getBegin(), 12155 diag::warn_objc_circular_container) 12156 << ArgRE->getDecl() << StringRef("'super'"); 12157 } 12158 } 12159 } else { 12160 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 12161 12162 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 12163 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 12164 } 12165 12166 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 12167 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 12168 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 12169 ValueDecl *Decl = ReceiverRE->getDecl(); 12170 Diag(Message->getSourceRange().getBegin(), 12171 diag::warn_objc_circular_container) 12172 << Decl << Decl; 12173 if (!ArgRE->isObjCSelfExpr()) { 12174 Diag(Decl->getLocation(), 12175 diag::note_objc_circular_container_declared_here) 12176 << Decl; 12177 } 12178 } 12179 } 12180 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 12181 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 12182 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 12183 ObjCIvarDecl *Decl = IvarRE->getDecl(); 12184 Diag(Message->getSourceRange().getBegin(), 12185 diag::warn_objc_circular_container) 12186 << Decl << Decl; 12187 Diag(Decl->getLocation(), 12188 diag::note_objc_circular_container_declared_here) 12189 << Decl; 12190 } 12191 } 12192 } 12193 } 12194 } 12195 12196 /// Check a message send to see if it's likely to cause a retain cycle. 12197 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 12198 // Only check instance methods whose selector looks like a setter. 12199 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 12200 return; 12201 12202 // Try to find a variable that the receiver is strongly owned by. 12203 RetainCycleOwner owner; 12204 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 12205 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 12206 return; 12207 } else { 12208 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 12209 owner.Variable = getCurMethodDecl()->getSelfDecl(); 12210 owner.Loc = msg->getSuperLoc(); 12211 owner.Range = msg->getSuperLoc(); 12212 } 12213 12214 // Check whether the receiver is captured by any of the arguments. 12215 const ObjCMethodDecl *MD = msg->getMethodDecl(); 12216 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 12217 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 12218 // noescape blocks should not be retained by the method. 12219 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 12220 continue; 12221 return diagnoseRetainCycle(*this, capturer, owner); 12222 } 12223 } 12224 } 12225 12226 /// Check a property assign to see if it's likely to cause a retain cycle. 12227 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 12228 RetainCycleOwner owner; 12229 if (!findRetainCycleOwner(*this, receiver, owner)) 12230 return; 12231 12232 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 12233 diagnoseRetainCycle(*this, capturer, owner); 12234 } 12235 12236 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 12237 RetainCycleOwner Owner; 12238 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 12239 return; 12240 12241 // Because we don't have an expression for the variable, we have to set the 12242 // location explicitly here. 12243 Owner.Loc = Var->getLocation(); 12244 Owner.Range = Var->getSourceRange(); 12245 12246 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 12247 diagnoseRetainCycle(*this, Capturer, Owner); 12248 } 12249 12250 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 12251 Expr *RHS, bool isProperty) { 12252 // Check if RHS is an Objective-C object literal, which also can get 12253 // immediately zapped in a weak reference. Note that we explicitly 12254 // allow ObjCStringLiterals, since those are designed to never really die. 12255 RHS = RHS->IgnoreParenImpCasts(); 12256 12257 // This enum needs to match with the 'select' in 12258 // warn_objc_arc_literal_assign (off-by-1). 12259 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 12260 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 12261 return false; 12262 12263 S.Diag(Loc, diag::warn_arc_literal_assign) 12264 << (unsigned) Kind 12265 << (isProperty ? 0 : 1) 12266 << RHS->getSourceRange(); 12267 12268 return true; 12269 } 12270 12271 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 12272 Qualifiers::ObjCLifetime LT, 12273 Expr *RHS, bool isProperty) { 12274 // Strip off any implicit cast added to get to the one ARC-specific. 12275 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 12276 if (cast->getCastKind() == CK_ARCConsumeObject) { 12277 S.Diag(Loc, diag::warn_arc_retained_assign) 12278 << (LT == Qualifiers::OCL_ExplicitNone) 12279 << (isProperty ? 0 : 1) 12280 << RHS->getSourceRange(); 12281 return true; 12282 } 12283 RHS = cast->getSubExpr(); 12284 } 12285 12286 if (LT == Qualifiers::OCL_Weak && 12287 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 12288 return true; 12289 12290 return false; 12291 } 12292 12293 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 12294 QualType LHS, Expr *RHS) { 12295 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 12296 12297 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 12298 return false; 12299 12300 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 12301 return true; 12302 12303 return false; 12304 } 12305 12306 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 12307 Expr *LHS, Expr *RHS) { 12308 QualType LHSType; 12309 // PropertyRef on LHS type need be directly obtained from 12310 // its declaration as it has a PseudoType. 12311 ObjCPropertyRefExpr *PRE 12312 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 12313 if (PRE && !PRE->isImplicitProperty()) { 12314 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 12315 if (PD) 12316 LHSType = PD->getType(); 12317 } 12318 12319 if (LHSType.isNull()) 12320 LHSType = LHS->getType(); 12321 12322 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 12323 12324 if (LT == Qualifiers::OCL_Weak) { 12325 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 12326 getCurFunction()->markSafeWeakUse(LHS); 12327 } 12328 12329 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 12330 return; 12331 12332 // FIXME. Check for other life times. 12333 if (LT != Qualifiers::OCL_None) 12334 return; 12335 12336 if (PRE) { 12337 if (PRE->isImplicitProperty()) 12338 return; 12339 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 12340 if (!PD) 12341 return; 12342 12343 unsigned Attributes = PD->getPropertyAttributes(); 12344 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) { 12345 // when 'assign' attribute was not explicitly specified 12346 // by user, ignore it and rely on property type itself 12347 // for lifetime info. 12348 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 12349 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) && 12350 LHSType->isObjCRetainableType()) 12351 return; 12352 12353 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 12354 if (cast->getCastKind() == CK_ARCConsumeObject) { 12355 Diag(Loc, diag::warn_arc_retained_property_assign) 12356 << RHS->getSourceRange(); 12357 return; 12358 } 12359 RHS = cast->getSubExpr(); 12360 } 12361 } 12362 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) { 12363 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 12364 return; 12365 } 12366 } 12367 } 12368 12369 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 12370 12371 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 12372 SourceLocation StmtLoc, 12373 const NullStmt *Body) { 12374 // Do not warn if the body is a macro that expands to nothing, e.g: 12375 // 12376 // #define CALL(x) 12377 // if (condition) 12378 // CALL(0); 12379 if (Body->hasLeadingEmptyMacro()) 12380 return false; 12381 12382 // Get line numbers of statement and body. 12383 bool StmtLineInvalid; 12384 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 12385 &StmtLineInvalid); 12386 if (StmtLineInvalid) 12387 return false; 12388 12389 bool BodyLineInvalid; 12390 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 12391 &BodyLineInvalid); 12392 if (BodyLineInvalid) 12393 return false; 12394 12395 // Warn if null statement and body are on the same line. 12396 if (StmtLine != BodyLine) 12397 return false; 12398 12399 return true; 12400 } 12401 12402 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 12403 const Stmt *Body, 12404 unsigned DiagID) { 12405 // Since this is a syntactic check, don't emit diagnostic for template 12406 // instantiations, this just adds noise. 12407 if (CurrentInstantiationScope) 12408 return; 12409 12410 // The body should be a null statement. 12411 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 12412 if (!NBody) 12413 return; 12414 12415 // Do the usual checks. 12416 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 12417 return; 12418 12419 Diag(NBody->getSemiLoc(), DiagID); 12420 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 12421 } 12422 12423 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 12424 const Stmt *PossibleBody) { 12425 assert(!CurrentInstantiationScope); // Ensured by caller 12426 12427 SourceLocation StmtLoc; 12428 const Stmt *Body; 12429 unsigned DiagID; 12430 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 12431 StmtLoc = FS->getRParenLoc(); 12432 Body = FS->getBody(); 12433 DiagID = diag::warn_empty_for_body; 12434 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 12435 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 12436 Body = WS->getBody(); 12437 DiagID = diag::warn_empty_while_body; 12438 } else 12439 return; // Neither `for' nor `while'. 12440 12441 // The body should be a null statement. 12442 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 12443 if (!NBody) 12444 return; 12445 12446 // Skip expensive checks if diagnostic is disabled. 12447 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 12448 return; 12449 12450 // Do the usual checks. 12451 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 12452 return; 12453 12454 // `for(...);' and `while(...);' are popular idioms, so in order to keep 12455 // noise level low, emit diagnostics only if for/while is followed by a 12456 // CompoundStmt, e.g.: 12457 // for (int i = 0; i < n; i++); 12458 // { 12459 // a(i); 12460 // } 12461 // or if for/while is followed by a statement with more indentation 12462 // than for/while itself: 12463 // for (int i = 0; i < n; i++); 12464 // a(i); 12465 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 12466 if (!ProbableTypo) { 12467 bool BodyColInvalid; 12468 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 12469 PossibleBody->getLocStart(), 12470 &BodyColInvalid); 12471 if (BodyColInvalid) 12472 return; 12473 12474 bool StmtColInvalid; 12475 unsigned StmtCol = SourceMgr.getPresumedColumnNumber( 12476 S->getLocStart(), 12477 &StmtColInvalid); 12478 if (StmtColInvalid) 12479 return; 12480 12481 if (BodyCol > StmtCol) 12482 ProbableTypo = true; 12483 } 12484 12485 if (ProbableTypo) { 12486 Diag(NBody->getSemiLoc(), DiagID); 12487 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 12488 } 12489 } 12490 12491 //===--- CHECK: Warn on self move with std::move. -------------------------===// 12492 12493 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 12494 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 12495 SourceLocation OpLoc) { 12496 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 12497 return; 12498 12499 if (inTemplateInstantiation()) 12500 return; 12501 12502 // Strip parens and casts away. 12503 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 12504 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 12505 12506 // Check for a call expression 12507 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 12508 if (!CE || CE->getNumArgs() != 1) 12509 return; 12510 12511 // Check for a call to std::move 12512 if (!CE->isCallToStdMove()) 12513 return; 12514 12515 // Get argument from std::move 12516 RHSExpr = CE->getArg(0); 12517 12518 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 12519 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 12520 12521 // Two DeclRefExpr's, check that the decls are the same. 12522 if (LHSDeclRef && RHSDeclRef) { 12523 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 12524 return; 12525 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 12526 RHSDeclRef->getDecl()->getCanonicalDecl()) 12527 return; 12528 12529 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 12530 << LHSExpr->getSourceRange() 12531 << RHSExpr->getSourceRange(); 12532 return; 12533 } 12534 12535 // Member variables require a different approach to check for self moves. 12536 // MemberExpr's are the same if every nested MemberExpr refers to the same 12537 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 12538 // the base Expr's are CXXThisExpr's. 12539 const Expr *LHSBase = LHSExpr; 12540 const Expr *RHSBase = RHSExpr; 12541 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 12542 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 12543 if (!LHSME || !RHSME) 12544 return; 12545 12546 while (LHSME && RHSME) { 12547 if (LHSME->getMemberDecl()->getCanonicalDecl() != 12548 RHSME->getMemberDecl()->getCanonicalDecl()) 12549 return; 12550 12551 LHSBase = LHSME->getBase(); 12552 RHSBase = RHSME->getBase(); 12553 LHSME = dyn_cast<MemberExpr>(LHSBase); 12554 RHSME = dyn_cast<MemberExpr>(RHSBase); 12555 } 12556 12557 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 12558 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 12559 if (LHSDeclRef && RHSDeclRef) { 12560 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 12561 return; 12562 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 12563 RHSDeclRef->getDecl()->getCanonicalDecl()) 12564 return; 12565 12566 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 12567 << LHSExpr->getSourceRange() 12568 << RHSExpr->getSourceRange(); 12569 return; 12570 } 12571 12572 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 12573 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 12574 << LHSExpr->getSourceRange() 12575 << RHSExpr->getSourceRange(); 12576 } 12577 12578 //===--- Layout compatibility ----------------------------------------------// 12579 12580 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 12581 12582 /// Check if two enumeration types are layout-compatible. 12583 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 12584 // C++11 [dcl.enum] p8: 12585 // Two enumeration types are layout-compatible if they have the same 12586 // underlying type. 12587 return ED1->isComplete() && ED2->isComplete() && 12588 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 12589 } 12590 12591 /// Check if two fields are layout-compatible. 12592 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 12593 FieldDecl *Field2) { 12594 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 12595 return false; 12596 12597 if (Field1->isBitField() != Field2->isBitField()) 12598 return false; 12599 12600 if (Field1->isBitField()) { 12601 // Make sure that the bit-fields are the same length. 12602 unsigned Bits1 = Field1->getBitWidthValue(C); 12603 unsigned Bits2 = Field2->getBitWidthValue(C); 12604 12605 if (Bits1 != Bits2) 12606 return false; 12607 } 12608 12609 return true; 12610 } 12611 12612 /// Check if two standard-layout structs are layout-compatible. 12613 /// (C++11 [class.mem] p17) 12614 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 12615 RecordDecl *RD2) { 12616 // If both records are C++ classes, check that base classes match. 12617 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 12618 // If one of records is a CXXRecordDecl we are in C++ mode, 12619 // thus the other one is a CXXRecordDecl, too. 12620 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 12621 // Check number of base classes. 12622 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 12623 return false; 12624 12625 // Check the base classes. 12626 for (CXXRecordDecl::base_class_const_iterator 12627 Base1 = D1CXX->bases_begin(), 12628 BaseEnd1 = D1CXX->bases_end(), 12629 Base2 = D2CXX->bases_begin(); 12630 Base1 != BaseEnd1; 12631 ++Base1, ++Base2) { 12632 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 12633 return false; 12634 } 12635 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 12636 // If only RD2 is a C++ class, it should have zero base classes. 12637 if (D2CXX->getNumBases() > 0) 12638 return false; 12639 } 12640 12641 // Check the fields. 12642 RecordDecl::field_iterator Field2 = RD2->field_begin(), 12643 Field2End = RD2->field_end(), 12644 Field1 = RD1->field_begin(), 12645 Field1End = RD1->field_end(); 12646 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 12647 if (!isLayoutCompatible(C, *Field1, *Field2)) 12648 return false; 12649 } 12650 if (Field1 != Field1End || Field2 != Field2End) 12651 return false; 12652 12653 return true; 12654 } 12655 12656 /// Check if two standard-layout unions are layout-compatible. 12657 /// (C++11 [class.mem] p18) 12658 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 12659 RecordDecl *RD2) { 12660 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 12661 for (auto *Field2 : RD2->fields()) 12662 UnmatchedFields.insert(Field2); 12663 12664 for (auto *Field1 : RD1->fields()) { 12665 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 12666 I = UnmatchedFields.begin(), 12667 E = UnmatchedFields.end(); 12668 12669 for ( ; I != E; ++I) { 12670 if (isLayoutCompatible(C, Field1, *I)) { 12671 bool Result = UnmatchedFields.erase(*I); 12672 (void) Result; 12673 assert(Result); 12674 break; 12675 } 12676 } 12677 if (I == E) 12678 return false; 12679 } 12680 12681 return UnmatchedFields.empty(); 12682 } 12683 12684 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 12685 RecordDecl *RD2) { 12686 if (RD1->isUnion() != RD2->isUnion()) 12687 return false; 12688 12689 if (RD1->isUnion()) 12690 return isLayoutCompatibleUnion(C, RD1, RD2); 12691 else 12692 return isLayoutCompatibleStruct(C, RD1, RD2); 12693 } 12694 12695 /// Check if two types are layout-compatible in C++11 sense. 12696 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 12697 if (T1.isNull() || T2.isNull()) 12698 return false; 12699 12700 // C++11 [basic.types] p11: 12701 // If two types T1 and T2 are the same type, then T1 and T2 are 12702 // layout-compatible types. 12703 if (C.hasSameType(T1, T2)) 12704 return true; 12705 12706 T1 = T1.getCanonicalType().getUnqualifiedType(); 12707 T2 = T2.getCanonicalType().getUnqualifiedType(); 12708 12709 const Type::TypeClass TC1 = T1->getTypeClass(); 12710 const Type::TypeClass TC2 = T2->getTypeClass(); 12711 12712 if (TC1 != TC2) 12713 return false; 12714 12715 if (TC1 == Type::Enum) { 12716 return isLayoutCompatible(C, 12717 cast<EnumType>(T1)->getDecl(), 12718 cast<EnumType>(T2)->getDecl()); 12719 } else if (TC1 == Type::Record) { 12720 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 12721 return false; 12722 12723 return isLayoutCompatible(C, 12724 cast<RecordType>(T1)->getDecl(), 12725 cast<RecordType>(T2)->getDecl()); 12726 } 12727 12728 return false; 12729 } 12730 12731 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 12732 12733 /// Given a type tag expression find the type tag itself. 12734 /// 12735 /// \param TypeExpr Type tag expression, as it appears in user's code. 12736 /// 12737 /// \param VD Declaration of an identifier that appears in a type tag. 12738 /// 12739 /// \param MagicValue Type tag magic value. 12740 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 12741 const ValueDecl **VD, uint64_t *MagicValue) { 12742 while(true) { 12743 if (!TypeExpr) 12744 return false; 12745 12746 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 12747 12748 switch (TypeExpr->getStmtClass()) { 12749 case Stmt::UnaryOperatorClass: { 12750 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 12751 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 12752 TypeExpr = UO->getSubExpr(); 12753 continue; 12754 } 12755 return false; 12756 } 12757 12758 case Stmt::DeclRefExprClass: { 12759 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 12760 *VD = DRE->getDecl(); 12761 return true; 12762 } 12763 12764 case Stmt::IntegerLiteralClass: { 12765 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 12766 llvm::APInt MagicValueAPInt = IL->getValue(); 12767 if (MagicValueAPInt.getActiveBits() <= 64) { 12768 *MagicValue = MagicValueAPInt.getZExtValue(); 12769 return true; 12770 } else 12771 return false; 12772 } 12773 12774 case Stmt::BinaryConditionalOperatorClass: 12775 case Stmt::ConditionalOperatorClass: { 12776 const AbstractConditionalOperator *ACO = 12777 cast<AbstractConditionalOperator>(TypeExpr); 12778 bool Result; 12779 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) { 12780 if (Result) 12781 TypeExpr = ACO->getTrueExpr(); 12782 else 12783 TypeExpr = ACO->getFalseExpr(); 12784 continue; 12785 } 12786 return false; 12787 } 12788 12789 case Stmt::BinaryOperatorClass: { 12790 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 12791 if (BO->getOpcode() == BO_Comma) { 12792 TypeExpr = BO->getRHS(); 12793 continue; 12794 } 12795 return false; 12796 } 12797 12798 default: 12799 return false; 12800 } 12801 } 12802 } 12803 12804 /// Retrieve the C type corresponding to type tag TypeExpr. 12805 /// 12806 /// \param TypeExpr Expression that specifies a type tag. 12807 /// 12808 /// \param MagicValues Registered magic values. 12809 /// 12810 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 12811 /// kind. 12812 /// 12813 /// \param TypeInfo Information about the corresponding C type. 12814 /// 12815 /// \returns true if the corresponding C type was found. 12816 static bool GetMatchingCType( 12817 const IdentifierInfo *ArgumentKind, 12818 const Expr *TypeExpr, const ASTContext &Ctx, 12819 const llvm::DenseMap<Sema::TypeTagMagicValue, 12820 Sema::TypeTagData> *MagicValues, 12821 bool &FoundWrongKind, 12822 Sema::TypeTagData &TypeInfo) { 12823 FoundWrongKind = false; 12824 12825 // Variable declaration that has type_tag_for_datatype attribute. 12826 const ValueDecl *VD = nullptr; 12827 12828 uint64_t MagicValue; 12829 12830 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue)) 12831 return false; 12832 12833 if (VD) { 12834 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 12835 if (I->getArgumentKind() != ArgumentKind) { 12836 FoundWrongKind = true; 12837 return false; 12838 } 12839 TypeInfo.Type = I->getMatchingCType(); 12840 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 12841 TypeInfo.MustBeNull = I->getMustBeNull(); 12842 return true; 12843 } 12844 return false; 12845 } 12846 12847 if (!MagicValues) 12848 return false; 12849 12850 llvm::DenseMap<Sema::TypeTagMagicValue, 12851 Sema::TypeTagData>::const_iterator I = 12852 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 12853 if (I == MagicValues->end()) 12854 return false; 12855 12856 TypeInfo = I->second; 12857 return true; 12858 } 12859 12860 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 12861 uint64_t MagicValue, QualType Type, 12862 bool LayoutCompatible, 12863 bool MustBeNull) { 12864 if (!TypeTagForDatatypeMagicValues) 12865 TypeTagForDatatypeMagicValues.reset( 12866 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 12867 12868 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 12869 (*TypeTagForDatatypeMagicValues)[Magic] = 12870 TypeTagData(Type, LayoutCompatible, MustBeNull); 12871 } 12872 12873 static bool IsSameCharType(QualType T1, QualType T2) { 12874 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 12875 if (!BT1) 12876 return false; 12877 12878 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 12879 if (!BT2) 12880 return false; 12881 12882 BuiltinType::Kind T1Kind = BT1->getKind(); 12883 BuiltinType::Kind T2Kind = BT2->getKind(); 12884 12885 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 12886 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 12887 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 12888 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 12889 } 12890 12891 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 12892 const ArrayRef<const Expr *> ExprArgs, 12893 SourceLocation CallSiteLoc) { 12894 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 12895 bool IsPointerAttr = Attr->getIsPointer(); 12896 12897 // Retrieve the argument representing the 'type_tag'. 12898 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 12899 if (TypeTagIdxAST >= ExprArgs.size()) { 12900 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 12901 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 12902 return; 12903 } 12904 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 12905 bool FoundWrongKind; 12906 TypeTagData TypeInfo; 12907 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 12908 TypeTagForDatatypeMagicValues.get(), 12909 FoundWrongKind, TypeInfo)) { 12910 if (FoundWrongKind) 12911 Diag(TypeTagExpr->getExprLoc(), 12912 diag::warn_type_tag_for_datatype_wrong_kind) 12913 << TypeTagExpr->getSourceRange(); 12914 return; 12915 } 12916 12917 // Retrieve the argument representing the 'arg_idx'. 12918 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 12919 if (ArgumentIdxAST >= ExprArgs.size()) { 12920 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 12921 << 1 << Attr->getArgumentIdx().getSourceIndex(); 12922 return; 12923 } 12924 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 12925 if (IsPointerAttr) { 12926 // Skip implicit cast of pointer to `void *' (as a function argument). 12927 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 12928 if (ICE->getType()->isVoidPointerType() && 12929 ICE->getCastKind() == CK_BitCast) 12930 ArgumentExpr = ICE->getSubExpr(); 12931 } 12932 QualType ArgumentType = ArgumentExpr->getType(); 12933 12934 // Passing a `void*' pointer shouldn't trigger a warning. 12935 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 12936 return; 12937 12938 if (TypeInfo.MustBeNull) { 12939 // Type tag with matching void type requires a null pointer. 12940 if (!ArgumentExpr->isNullPointerConstant(Context, 12941 Expr::NPC_ValueDependentIsNotNull)) { 12942 Diag(ArgumentExpr->getExprLoc(), 12943 diag::warn_type_safety_null_pointer_required) 12944 << ArgumentKind->getName() 12945 << ArgumentExpr->getSourceRange() 12946 << TypeTagExpr->getSourceRange(); 12947 } 12948 return; 12949 } 12950 12951 QualType RequiredType = TypeInfo.Type; 12952 if (IsPointerAttr) 12953 RequiredType = Context.getPointerType(RequiredType); 12954 12955 bool mismatch = false; 12956 if (!TypeInfo.LayoutCompatible) { 12957 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 12958 12959 // C++11 [basic.fundamental] p1: 12960 // Plain char, signed char, and unsigned char are three distinct types. 12961 // 12962 // But we treat plain `char' as equivalent to `signed char' or `unsigned 12963 // char' depending on the current char signedness mode. 12964 if (mismatch) 12965 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 12966 RequiredType->getPointeeType())) || 12967 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 12968 mismatch = false; 12969 } else 12970 if (IsPointerAttr) 12971 mismatch = !isLayoutCompatible(Context, 12972 ArgumentType->getPointeeType(), 12973 RequiredType->getPointeeType()); 12974 else 12975 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 12976 12977 if (mismatch) 12978 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 12979 << ArgumentType << ArgumentKind 12980 << TypeInfo.LayoutCompatible << RequiredType 12981 << ArgumentExpr->getSourceRange() 12982 << TypeTagExpr->getSourceRange(); 12983 } 12984 12985 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 12986 CharUnits Alignment) { 12987 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 12988 } 12989 12990 void Sema::DiagnoseMisalignedMembers() { 12991 for (MisalignedMember &m : MisalignedMembers) { 12992 const NamedDecl *ND = m.RD; 12993 if (ND->getName().empty()) { 12994 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 12995 ND = TD; 12996 } 12997 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member) 12998 << m.MD << ND << m.E->getSourceRange(); 12999 } 13000 MisalignedMembers.clear(); 13001 } 13002 13003 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 13004 E = E->IgnoreParens(); 13005 if (!T->isPointerType() && !T->isIntegerType()) 13006 return; 13007 if (isa<UnaryOperator>(E) && 13008 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 13009 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 13010 if (isa<MemberExpr>(Op)) { 13011 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(), 13012 MisalignedMember(Op)); 13013 if (MA != MisalignedMembers.end() && 13014 (T->isIntegerType() || 13015 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 13016 Context.getTypeAlignInChars( 13017 T->getPointeeType()) <= MA->Alignment)))) 13018 MisalignedMembers.erase(MA); 13019 } 13020 } 13021 } 13022 13023 void Sema::RefersToMemberWithReducedAlignment( 13024 Expr *E, 13025 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 13026 Action) { 13027 const auto *ME = dyn_cast<MemberExpr>(E); 13028 if (!ME) 13029 return; 13030 13031 // No need to check expressions with an __unaligned-qualified type. 13032 if (E->getType().getQualifiers().hasUnaligned()) 13033 return; 13034 13035 // For a chain of MemberExpr like "a.b.c.d" this list 13036 // will keep FieldDecl's like [d, c, b]. 13037 SmallVector<FieldDecl *, 4> ReverseMemberChain; 13038 const MemberExpr *TopME = nullptr; 13039 bool AnyIsPacked = false; 13040 do { 13041 QualType BaseType = ME->getBase()->getType(); 13042 if (ME->isArrow()) 13043 BaseType = BaseType->getPointeeType(); 13044 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl(); 13045 if (RD->isInvalidDecl()) 13046 return; 13047 13048 ValueDecl *MD = ME->getMemberDecl(); 13049 auto *FD = dyn_cast<FieldDecl>(MD); 13050 // We do not care about non-data members. 13051 if (!FD || FD->isInvalidDecl()) 13052 return; 13053 13054 AnyIsPacked = 13055 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 13056 ReverseMemberChain.push_back(FD); 13057 13058 TopME = ME; 13059 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 13060 } while (ME); 13061 assert(TopME && "We did not compute a topmost MemberExpr!"); 13062 13063 // Not the scope of this diagnostic. 13064 if (!AnyIsPacked) 13065 return; 13066 13067 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 13068 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 13069 // TODO: The innermost base of the member expression may be too complicated. 13070 // For now, just disregard these cases. This is left for future 13071 // improvement. 13072 if (!DRE && !isa<CXXThisExpr>(TopBase)) 13073 return; 13074 13075 // Alignment expected by the whole expression. 13076 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 13077 13078 // No need to do anything else with this case. 13079 if (ExpectedAlignment.isOne()) 13080 return; 13081 13082 // Synthesize offset of the whole access. 13083 CharUnits Offset; 13084 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 13085 I++) { 13086 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 13087 } 13088 13089 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 13090 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 13091 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 13092 13093 // The base expression of the innermost MemberExpr may give 13094 // stronger guarantees than the class containing the member. 13095 if (DRE && !TopME->isArrow()) { 13096 const ValueDecl *VD = DRE->getDecl(); 13097 if (!VD->getType()->isReferenceType()) 13098 CompleteObjectAlignment = 13099 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 13100 } 13101 13102 // Check if the synthesized offset fulfills the alignment. 13103 if (Offset % ExpectedAlignment != 0 || 13104 // It may fulfill the offset it but the effective alignment may still be 13105 // lower than the expected expression alignment. 13106 CompleteObjectAlignment < ExpectedAlignment) { 13107 // If this happens, we want to determine a sensible culprit of this. 13108 // Intuitively, watching the chain of member expressions from right to 13109 // left, we start with the required alignment (as required by the field 13110 // type) but some packed attribute in that chain has reduced the alignment. 13111 // It may happen that another packed structure increases it again. But if 13112 // we are here such increase has not been enough. So pointing the first 13113 // FieldDecl that either is packed or else its RecordDecl is, 13114 // seems reasonable. 13115 FieldDecl *FD = nullptr; 13116 CharUnits Alignment; 13117 for (FieldDecl *FDI : ReverseMemberChain) { 13118 if (FDI->hasAttr<PackedAttr>() || 13119 FDI->getParent()->hasAttr<PackedAttr>()) { 13120 FD = FDI; 13121 Alignment = std::min( 13122 Context.getTypeAlignInChars(FD->getType()), 13123 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 13124 break; 13125 } 13126 } 13127 assert(FD && "We did not find a packed FieldDecl!"); 13128 Action(E, FD->getParent(), FD, Alignment); 13129 } 13130 } 13131 13132 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 13133 using namespace std::placeholders; 13134 13135 RefersToMemberWithReducedAlignment( 13136 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 13137 _2, _3, _4)); 13138 } 13139