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