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/ASTContext.h" 16 #include "clang/AST/CharUnits.h" 17 #include "clang/AST/DeclCXX.h" 18 #include "clang/AST/DeclObjC.h" 19 #include "clang/AST/EvaluatedExprVisitor.h" 20 #include "clang/AST/Expr.h" 21 #include "clang/AST/ExprCXX.h" 22 #include "clang/AST/ExprObjC.h" 23 #include "clang/AST/ExprOpenMP.h" 24 #include "clang/AST/StmtCXX.h" 25 #include "clang/AST/StmtObjC.h" 26 #include "clang/Analysis/Analyses/FormatString.h" 27 #include "clang/Basic/CharInfo.h" 28 #include "clang/Basic/TargetBuiltins.h" 29 #include "clang/Basic/TargetInfo.h" 30 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 31 #include "clang/Sema/Initialization.h" 32 #include "clang/Sema/Lookup.h" 33 #include "clang/Sema/ScopeInfo.h" 34 #include "clang/Sema/Sema.h" 35 #include "clang/Sema/SemaInternal.h" 36 #include "llvm/ADT/STLExtras.h" 37 #include "llvm/ADT/SmallBitVector.h" 38 #include "llvm/ADT/SmallString.h" 39 #include "llvm/Support/ConvertUTF.h" 40 #include "llvm/Support/Format.h" 41 #include "llvm/Support/Locale.h" 42 #include "llvm/Support/raw_ostream.h" 43 44 using namespace clang; 45 using namespace sema; 46 47 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 48 unsigned ByteNo) const { 49 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts, 50 Context.getTargetInfo()); 51 } 52 53 /// Checks that a call expression's argument count is the desired number. 54 /// This is useful when doing custom type-checking. Returns true on error. 55 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { 56 unsigned argCount = call->getNumArgs(); 57 if (argCount == desiredArgCount) return false; 58 59 if (argCount < desiredArgCount) 60 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args) 61 << 0 /*function call*/ << desiredArgCount << argCount 62 << call->getSourceRange(); 63 64 // Highlight all the excess arguments. 65 SourceRange range(call->getArg(desiredArgCount)->getLocStart(), 66 call->getArg(argCount - 1)->getLocEnd()); 67 68 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) 69 << 0 /*function call*/ << desiredArgCount << argCount 70 << call->getArg(1)->getSourceRange(); 71 } 72 73 /// Check that the first argument to __builtin_annotation is an integer 74 /// and the second argument is a non-wide string literal. 75 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) { 76 if (checkArgCount(S, TheCall, 2)) 77 return true; 78 79 // First argument should be an integer. 80 Expr *ValArg = TheCall->getArg(0); 81 QualType Ty = ValArg->getType(); 82 if (!Ty->isIntegerType()) { 83 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg) 84 << ValArg->getSourceRange(); 85 return true; 86 } 87 88 // Second argument should be a constant string. 89 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts(); 90 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg); 91 if (!Literal || !Literal->isAscii()) { 92 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg) 93 << StrArg->getSourceRange(); 94 return true; 95 } 96 97 TheCall->setType(Ty); 98 return false; 99 } 100 101 /// Check that the argument to __builtin_addressof is a glvalue, and set the 102 /// result type to the corresponding pointer type. 103 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) { 104 if (checkArgCount(S, TheCall, 1)) 105 return true; 106 107 ExprResult Arg(TheCall->getArg(0)); 108 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart()); 109 if (ResultType.isNull()) 110 return true; 111 112 TheCall->setArg(0, Arg.get()); 113 TheCall->setType(ResultType); 114 return false; 115 } 116 117 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) { 118 if (checkArgCount(S, TheCall, 3)) 119 return true; 120 121 // First two arguments should be integers. 122 for (unsigned I = 0; I < 2; ++I) { 123 Expr *Arg = TheCall->getArg(I); 124 QualType Ty = Arg->getType(); 125 if (!Ty->isIntegerType()) { 126 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int) 127 << Ty << Arg->getSourceRange(); 128 return true; 129 } 130 } 131 132 // Third argument should be a pointer to a non-const integer. 133 // IRGen correctly handles volatile, restrict, and address spaces, and 134 // the other qualifiers aren't possible. 135 { 136 Expr *Arg = TheCall->getArg(2); 137 QualType Ty = Arg->getType(); 138 const auto *PtrTy = Ty->getAs<PointerType>(); 139 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() && 140 !PtrTy->getPointeeType().isConstQualified())) { 141 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int) 142 << Ty << Arg->getSourceRange(); 143 return true; 144 } 145 } 146 147 return false; 148 } 149 150 static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl, 151 CallExpr *TheCall, unsigned SizeIdx, 152 unsigned DstSizeIdx) { 153 if (TheCall->getNumArgs() <= SizeIdx || 154 TheCall->getNumArgs() <= DstSizeIdx) 155 return; 156 157 const Expr *SizeArg = TheCall->getArg(SizeIdx); 158 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx); 159 160 llvm::APSInt Size, DstSize; 161 162 // find out if both sizes are known at compile time 163 if (!SizeArg->EvaluateAsInt(Size, S.Context) || 164 !DstSizeArg->EvaluateAsInt(DstSize, S.Context)) 165 return; 166 167 if (Size.ule(DstSize)) 168 return; 169 170 // confirmed overflow so generate the diagnostic. 171 IdentifierInfo *FnName = FDecl->getIdentifier(); 172 SourceLocation SL = TheCall->getLocStart(); 173 SourceRange SR = TheCall->getSourceRange(); 174 175 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName; 176 } 177 178 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { 179 if (checkArgCount(S, BuiltinCall, 2)) 180 return true; 181 182 SourceLocation BuiltinLoc = BuiltinCall->getLocStart(); 183 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); 184 Expr *Call = BuiltinCall->getArg(0); 185 Expr *Chain = BuiltinCall->getArg(1); 186 187 if (Call->getStmtClass() != Stmt::CallExprClass) { 188 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) 189 << Call->getSourceRange(); 190 return true; 191 } 192 193 auto CE = cast<CallExpr>(Call); 194 if (CE->getCallee()->getType()->isBlockPointerType()) { 195 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) 196 << Call->getSourceRange(); 197 return true; 198 } 199 200 const Decl *TargetDecl = CE->getCalleeDecl(); 201 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 202 if (FD->getBuiltinID()) { 203 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) 204 << Call->getSourceRange(); 205 return true; 206 } 207 208 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { 209 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) 210 << Call->getSourceRange(); 211 return true; 212 } 213 214 ExprResult ChainResult = S.UsualUnaryConversions(Chain); 215 if (ChainResult.isInvalid()) 216 return true; 217 if (!ChainResult.get()->getType()->isPointerType()) { 218 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) 219 << Chain->getSourceRange(); 220 return true; 221 } 222 223 QualType ReturnTy = CE->getCallReturnType(S.Context); 224 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; 225 QualType BuiltinTy = S.Context.getFunctionType( 226 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); 227 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); 228 229 Builtin = 230 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); 231 232 BuiltinCall->setType(CE->getType()); 233 BuiltinCall->setValueKind(CE->getValueKind()); 234 BuiltinCall->setObjectKind(CE->getObjectKind()); 235 BuiltinCall->setCallee(Builtin); 236 BuiltinCall->setArg(1, ChainResult.get()); 237 238 return false; 239 } 240 241 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 242 Scope::ScopeFlags NeededScopeFlags, 243 unsigned DiagID) { 244 // Scopes aren't available during instantiation. Fortunately, builtin 245 // functions cannot be template args so they cannot be formed through template 246 // instantiation. Therefore checking once during the parse is sufficient. 247 if (!SemaRef.ActiveTemplateInstantiations.empty()) 248 return false; 249 250 Scope *S = SemaRef.getCurScope(); 251 while (S && !S->isSEHExceptScope()) 252 S = S->getParent(); 253 if (!S || !(S->getFlags() & NeededScopeFlags)) { 254 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 255 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 256 << DRE->getDecl()->getIdentifier(); 257 return true; 258 } 259 260 return false; 261 } 262 263 static inline bool isBlockPointer(Expr *Arg) { 264 return Arg->getType()->isBlockPointerType(); 265 } 266 267 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local 268 /// void*, which is a requirement of device side enqueue. 269 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { 270 const BlockPointerType *BPT = 271 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 272 ArrayRef<QualType> Params = 273 BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes(); 274 unsigned ArgCounter = 0; 275 bool IllegalParams = false; 276 // Iterate through the block parameters until either one is found that is not 277 // a local void*, or the block is valid. 278 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); 279 I != E; ++I, ++ArgCounter) { 280 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || 281 (*I)->getPointeeType().getQualifiers().getAddressSpace() != 282 LangAS::opencl_local) { 283 // Get the location of the error. If a block literal has been passed 284 // (BlockExpr) then we can point straight to the offending argument, 285 // else we just point to the variable reference. 286 SourceLocation ErrorLoc; 287 if (isa<BlockExpr>(BlockArg)) { 288 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); 289 ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart(); 290 } else if (isa<DeclRefExpr>(BlockArg)) { 291 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart(); 292 } 293 S.Diag(ErrorLoc, 294 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); 295 IllegalParams = true; 296 } 297 } 298 299 return IllegalParams; 300 } 301 302 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the 303 /// get_kernel_work_group_size 304 /// and get_kernel_preferred_work_group_size_multiple builtin functions. 305 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { 306 if (checkArgCount(S, TheCall, 1)) 307 return true; 308 309 Expr *BlockArg = TheCall->getArg(0); 310 if (!isBlockPointer(BlockArg)) { 311 S.Diag(BlockArg->getLocStart(), 312 diag::err_opencl_enqueue_kernel_expected_type) << "block"; 313 return true; 314 } 315 return checkOpenCLBlockArgs(S, BlockArg); 316 } 317 318 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 319 unsigned Start, unsigned End); 320 321 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 322 /// 'local void*' parameter of passed block. 323 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 324 Expr *BlockArg, 325 unsigned NumNonVarArgs) { 326 const BlockPointerType *BPT = 327 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 328 unsigned NumBlockParams = 329 BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams(); 330 unsigned TotalNumArgs = TheCall->getNumArgs(); 331 332 // For each argument passed to the block, a corresponding uint needs to 333 // be passed to describe the size of the local memory. 334 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 335 S.Diag(TheCall->getLocStart(), 336 diag::err_opencl_enqueue_kernel_local_size_args); 337 return true; 338 } 339 340 // Check that the sizes of the local memory are specified by integers. 341 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 342 TotalNumArgs - 1); 343 } 344 345 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 346 /// overload formats specified in Table 6.13.17.1. 347 /// int enqueue_kernel(queue_t queue, 348 /// kernel_enqueue_flags_t flags, 349 /// const ndrange_t ndrange, 350 /// void (^block)(void)) 351 /// int enqueue_kernel(queue_t queue, 352 /// kernel_enqueue_flags_t flags, 353 /// const ndrange_t ndrange, 354 /// uint num_events_in_wait_list, 355 /// clk_event_t *event_wait_list, 356 /// clk_event_t *event_ret, 357 /// void (^block)(void)) 358 /// int enqueue_kernel(queue_t queue, 359 /// kernel_enqueue_flags_t flags, 360 /// const ndrange_t ndrange, 361 /// void (^block)(local void*, ...), 362 /// uint size0, ...) 363 /// int enqueue_kernel(queue_t queue, 364 /// kernel_enqueue_flags_t flags, 365 /// const ndrange_t ndrange, 366 /// uint num_events_in_wait_list, 367 /// clk_event_t *event_wait_list, 368 /// clk_event_t *event_ret, 369 /// void (^block)(local void*, ...), 370 /// uint size0, ...) 371 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 372 unsigned NumArgs = TheCall->getNumArgs(); 373 374 if (NumArgs < 4) { 375 S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args); 376 return true; 377 } 378 379 Expr *Arg0 = TheCall->getArg(0); 380 Expr *Arg1 = TheCall->getArg(1); 381 Expr *Arg2 = TheCall->getArg(2); 382 Expr *Arg3 = TheCall->getArg(3); 383 384 // First argument always needs to be a queue_t type. 385 if (!Arg0->getType()->isQueueT()) { 386 S.Diag(TheCall->getArg(0)->getLocStart(), 387 diag::err_opencl_enqueue_kernel_expected_type) 388 << S.Context.OCLQueueTy; 389 return true; 390 } 391 392 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 393 if (!Arg1->getType()->isIntegerType()) { 394 S.Diag(TheCall->getArg(1)->getLocStart(), 395 diag::err_opencl_enqueue_kernel_expected_type) 396 << "'kernel_enqueue_flags_t' (i.e. uint)"; 397 return true; 398 } 399 400 // Third argument is always an ndrange_t type. 401 if (!Arg2->getType()->isNDRangeT()) { 402 S.Diag(TheCall->getArg(2)->getLocStart(), 403 diag::err_opencl_enqueue_kernel_expected_type) 404 << S.Context.OCLNDRangeTy; 405 return true; 406 } 407 408 // With four arguments, there is only one form that the function could be 409 // called in: no events and no variable arguments. 410 if (NumArgs == 4) { 411 // check that the last argument is the right block type. 412 if (!isBlockPointer(Arg3)) { 413 S.Diag(Arg3->getLocStart(), diag::err_opencl_enqueue_kernel_expected_type) 414 << "block"; 415 return true; 416 } 417 // we have a block type, check the prototype 418 const BlockPointerType *BPT = 419 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 420 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) { 421 S.Diag(Arg3->getLocStart(), 422 diag::err_opencl_enqueue_kernel_blocks_no_args); 423 return true; 424 } 425 return false; 426 } 427 // we can have block + varargs. 428 if (isBlockPointer(Arg3)) 429 return (checkOpenCLBlockArgs(S, Arg3) || 430 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 431 // last two cases with either exactly 7 args or 7 args and varargs. 432 if (NumArgs >= 7) { 433 // check common block argument. 434 Expr *Arg6 = TheCall->getArg(6); 435 if (!isBlockPointer(Arg6)) { 436 S.Diag(Arg6->getLocStart(), diag::err_opencl_enqueue_kernel_expected_type) 437 << "block"; 438 return true; 439 } 440 if (checkOpenCLBlockArgs(S, Arg6)) 441 return true; 442 443 // Forth argument has to be any integer type. 444 if (!Arg3->getType()->isIntegerType()) { 445 S.Diag(TheCall->getArg(3)->getLocStart(), 446 diag::err_opencl_enqueue_kernel_expected_type) 447 << "integer"; 448 return true; 449 } 450 // check remaining common arguments. 451 Expr *Arg4 = TheCall->getArg(4); 452 Expr *Arg5 = TheCall->getArg(5); 453 454 // Fith argument is always passed as pointers to clk_event_t. 455 if (!Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 456 S.Diag(TheCall->getArg(4)->getLocStart(), 457 diag::err_opencl_enqueue_kernel_expected_type) 458 << S.Context.getPointerType(S.Context.OCLClkEventTy); 459 return true; 460 } 461 462 // Sixth argument is always passed as pointers to clk_event_t. 463 if (!(Arg5->getType()->isPointerType() && 464 Arg5->getType()->getPointeeType()->isClkEventT())) { 465 S.Diag(TheCall->getArg(5)->getLocStart(), 466 diag::err_opencl_enqueue_kernel_expected_type) 467 << S.Context.getPointerType(S.Context.OCLClkEventTy); 468 return true; 469 } 470 471 if (NumArgs == 7) 472 return false; 473 474 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 475 } 476 477 // None of the specific case has been detected, give generic error 478 S.Diag(TheCall->getLocStart(), 479 diag::err_opencl_enqueue_kernel_incorrect_args); 480 return true; 481 } 482 483 /// Returns OpenCL access qual. 484 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 485 return D->getAttr<OpenCLAccessAttr>(); 486 } 487 488 /// Returns true if pipe element type is different from the pointer. 489 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 490 const Expr *Arg0 = Call->getArg(0); 491 // First argument type should always be pipe. 492 if (!Arg0->getType()->isPipeType()) { 493 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg) 494 << Call->getDirectCallee() << Arg0->getSourceRange(); 495 return true; 496 } 497 OpenCLAccessAttr *AccessQual = 498 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 499 // Validates the access qualifier is compatible with the call. 500 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 501 // read_only and write_only, and assumed to be read_only if no qualifier is 502 // specified. 503 switch (Call->getDirectCallee()->getBuiltinID()) { 504 case Builtin::BIread_pipe: 505 case Builtin::BIreserve_read_pipe: 506 case Builtin::BIcommit_read_pipe: 507 case Builtin::BIwork_group_reserve_read_pipe: 508 case Builtin::BIsub_group_reserve_read_pipe: 509 case Builtin::BIwork_group_commit_read_pipe: 510 case Builtin::BIsub_group_commit_read_pipe: 511 if (!(!AccessQual || AccessQual->isReadOnly())) { 512 S.Diag(Arg0->getLocStart(), 513 diag::err_opencl_builtin_pipe_invalid_access_modifier) 514 << "read_only" << Arg0->getSourceRange(); 515 return true; 516 } 517 break; 518 case Builtin::BIwrite_pipe: 519 case Builtin::BIreserve_write_pipe: 520 case Builtin::BIcommit_write_pipe: 521 case Builtin::BIwork_group_reserve_write_pipe: 522 case Builtin::BIsub_group_reserve_write_pipe: 523 case Builtin::BIwork_group_commit_write_pipe: 524 case Builtin::BIsub_group_commit_write_pipe: 525 if (!(AccessQual && AccessQual->isWriteOnly())) { 526 S.Diag(Arg0->getLocStart(), 527 diag::err_opencl_builtin_pipe_invalid_access_modifier) 528 << "write_only" << Arg0->getSourceRange(); 529 return true; 530 } 531 break; 532 default: 533 break; 534 } 535 return false; 536 } 537 538 /// Returns true if pipe element type is different from the pointer. 539 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 540 const Expr *Arg0 = Call->getArg(0); 541 const Expr *ArgIdx = Call->getArg(Idx); 542 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 543 const QualType EltTy = PipeTy->getElementType(); 544 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 545 // The Idx argument should be a pointer and the type of the pointer and 546 // the type of pipe element should also be the same. 547 if (!ArgTy || 548 !S.Context.hasSameType( 549 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 550 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 551 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 552 << ArgIdx->getType() << ArgIdx->getSourceRange(); 553 return true; 554 } 555 return false; 556 } 557 558 // \brief Performs semantic analysis for the read/write_pipe call. 559 // \param S Reference to the semantic analyzer. 560 // \param Call A pointer to the builtin call. 561 // \return True if a semantic error has been found, false otherwise. 562 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 563 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 564 // functions have two forms. 565 switch (Call->getNumArgs()) { 566 case 2: { 567 if (checkOpenCLPipeArg(S, Call)) 568 return true; 569 // The call with 2 arguments should be 570 // read/write_pipe(pipe T, T*). 571 // Check packet type T. 572 if (checkOpenCLPipePacketType(S, Call, 1)) 573 return true; 574 } break; 575 576 case 4: { 577 if (checkOpenCLPipeArg(S, Call)) 578 return true; 579 // The call with 4 arguments should be 580 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 581 // Check reserve_id_t. 582 if (!Call->getArg(1)->getType()->isReserveIDT()) { 583 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 584 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 585 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 586 return true; 587 } 588 589 // Check the index. 590 const Expr *Arg2 = Call->getArg(2); 591 if (!Arg2->getType()->isIntegerType() && 592 !Arg2->getType()->isUnsignedIntegerType()) { 593 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 594 << Call->getDirectCallee() << S.Context.UnsignedIntTy 595 << Arg2->getType() << Arg2->getSourceRange(); 596 return true; 597 } 598 599 // Check packet type T. 600 if (checkOpenCLPipePacketType(S, Call, 3)) 601 return true; 602 } break; 603 default: 604 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num) 605 << Call->getDirectCallee() << Call->getSourceRange(); 606 return true; 607 } 608 609 return false; 610 } 611 612 // \brief Performs a semantic analysis on the {work_group_/sub_group_ 613 // /_}reserve_{read/write}_pipe 614 // \param S Reference to the semantic analyzer. 615 // \param Call The call to the builtin function to be analyzed. 616 // \return True if a semantic error was found, false otherwise. 617 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 618 if (checkArgCount(S, Call, 2)) 619 return true; 620 621 if (checkOpenCLPipeArg(S, Call)) 622 return true; 623 624 // Check the reserve size. 625 if (!Call->getArg(1)->getType()->isIntegerType() && 626 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 627 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 628 << Call->getDirectCallee() << S.Context.UnsignedIntTy 629 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 630 return true; 631 } 632 633 return false; 634 } 635 636 // \brief Performs a semantic analysis on {work_group_/sub_group_ 637 // /_}commit_{read/write}_pipe 638 // \param S Reference to the semantic analyzer. 639 // \param Call The call to the builtin function to be analyzed. 640 // \return True if a semantic error was found, false otherwise. 641 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 642 if (checkArgCount(S, Call, 2)) 643 return true; 644 645 if (checkOpenCLPipeArg(S, Call)) 646 return true; 647 648 // Check reserve_id_t. 649 if (!Call->getArg(1)->getType()->isReserveIDT()) { 650 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 651 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 652 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 653 return true; 654 } 655 656 return false; 657 } 658 659 // \brief Performs a semantic analysis on the call to built-in Pipe 660 // Query Functions. 661 // \param S Reference to the semantic analyzer. 662 // \param Call The call to the builtin function to be analyzed. 663 // \return True if a semantic error was found, false otherwise. 664 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 665 if (checkArgCount(S, Call, 1)) 666 return true; 667 668 if (!Call->getArg(0)->getType()->isPipeType()) { 669 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg) 670 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 671 return true; 672 } 673 674 return false; 675 } 676 // \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions. 677 // \brief Performs semantic analysis for the to_global/local/private call. 678 // \param S Reference to the semantic analyzer. 679 // \param BuiltinID ID of the builtin function. 680 // \param Call A pointer to the builtin call. 681 // \return True if a semantic error has been found, false otherwise. 682 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 683 CallExpr *Call) { 684 if (Call->getNumArgs() != 1) { 685 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num) 686 << Call->getDirectCallee() << Call->getSourceRange(); 687 return true; 688 } 689 690 auto RT = Call->getArg(0)->getType(); 691 if (!RT->isPointerType() || RT->getPointeeType() 692 .getAddressSpace() == LangAS::opencl_constant) { 693 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg) 694 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 695 return true; 696 } 697 698 RT = RT->getPointeeType(); 699 auto Qual = RT.getQualifiers(); 700 switch (BuiltinID) { 701 case Builtin::BIto_global: 702 Qual.setAddressSpace(LangAS::opencl_global); 703 break; 704 case Builtin::BIto_local: 705 Qual.setAddressSpace(LangAS::opencl_local); 706 break; 707 default: 708 Qual.removeAddressSpace(); 709 } 710 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 711 RT.getUnqualifiedType(), Qual))); 712 713 return false; 714 } 715 716 ExprResult 717 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 718 CallExpr *TheCall) { 719 ExprResult TheCallResult(TheCall); 720 721 // Find out if any arguments are required to be integer constant expressions. 722 unsigned ICEArguments = 0; 723 ASTContext::GetBuiltinTypeError Error; 724 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 725 if (Error != ASTContext::GE_None) 726 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 727 728 // If any arguments are required to be ICE's, check and diagnose. 729 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 730 // Skip arguments not required to be ICE's. 731 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 732 733 llvm::APSInt Result; 734 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 735 return true; 736 ICEArguments &= ~(1 << ArgNo); 737 } 738 739 switch (BuiltinID) { 740 case Builtin::BI__builtin___CFStringMakeConstantString: 741 assert(TheCall->getNumArgs() == 1 && 742 "Wrong # arguments to builtin CFStringMakeConstantString"); 743 if (CheckObjCString(TheCall->getArg(0))) 744 return ExprError(); 745 break; 746 case Builtin::BI__builtin_stdarg_start: 747 case Builtin::BI__builtin_va_start: 748 if (SemaBuiltinVAStart(TheCall)) 749 return ExprError(); 750 break; 751 case Builtin::BI__va_start: { 752 switch (Context.getTargetInfo().getTriple().getArch()) { 753 case llvm::Triple::arm: 754 case llvm::Triple::thumb: 755 if (SemaBuiltinVAStartARM(TheCall)) 756 return ExprError(); 757 break; 758 default: 759 if (SemaBuiltinVAStart(TheCall)) 760 return ExprError(); 761 break; 762 } 763 break; 764 } 765 case Builtin::BI__builtin_isgreater: 766 case Builtin::BI__builtin_isgreaterequal: 767 case Builtin::BI__builtin_isless: 768 case Builtin::BI__builtin_islessequal: 769 case Builtin::BI__builtin_islessgreater: 770 case Builtin::BI__builtin_isunordered: 771 if (SemaBuiltinUnorderedCompare(TheCall)) 772 return ExprError(); 773 break; 774 case Builtin::BI__builtin_fpclassify: 775 if (SemaBuiltinFPClassification(TheCall, 6)) 776 return ExprError(); 777 break; 778 case Builtin::BI__builtin_isfinite: 779 case Builtin::BI__builtin_isinf: 780 case Builtin::BI__builtin_isinf_sign: 781 case Builtin::BI__builtin_isnan: 782 case Builtin::BI__builtin_isnormal: 783 if (SemaBuiltinFPClassification(TheCall, 1)) 784 return ExprError(); 785 break; 786 case Builtin::BI__builtin_shufflevector: 787 return SemaBuiltinShuffleVector(TheCall); 788 // TheCall will be freed by the smart pointer here, but that's fine, since 789 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 790 case Builtin::BI__builtin_prefetch: 791 if (SemaBuiltinPrefetch(TheCall)) 792 return ExprError(); 793 break; 794 case Builtin::BI__assume: 795 case Builtin::BI__builtin_assume: 796 if (SemaBuiltinAssume(TheCall)) 797 return ExprError(); 798 break; 799 case Builtin::BI__builtin_assume_aligned: 800 if (SemaBuiltinAssumeAligned(TheCall)) 801 return ExprError(); 802 break; 803 case Builtin::BI__builtin_object_size: 804 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 805 return ExprError(); 806 break; 807 case Builtin::BI__builtin_longjmp: 808 if (SemaBuiltinLongjmp(TheCall)) 809 return ExprError(); 810 break; 811 case Builtin::BI__builtin_setjmp: 812 if (SemaBuiltinSetjmp(TheCall)) 813 return ExprError(); 814 break; 815 case Builtin::BI_setjmp: 816 case Builtin::BI_setjmpex: 817 if (checkArgCount(*this, TheCall, 1)) 818 return true; 819 break; 820 821 case Builtin::BI__builtin_classify_type: 822 if (checkArgCount(*this, TheCall, 1)) return true; 823 TheCall->setType(Context.IntTy); 824 break; 825 case Builtin::BI__builtin_constant_p: 826 if (checkArgCount(*this, TheCall, 1)) return true; 827 TheCall->setType(Context.IntTy); 828 break; 829 case Builtin::BI__sync_fetch_and_add: 830 case Builtin::BI__sync_fetch_and_add_1: 831 case Builtin::BI__sync_fetch_and_add_2: 832 case Builtin::BI__sync_fetch_and_add_4: 833 case Builtin::BI__sync_fetch_and_add_8: 834 case Builtin::BI__sync_fetch_and_add_16: 835 case Builtin::BI__sync_fetch_and_sub: 836 case Builtin::BI__sync_fetch_and_sub_1: 837 case Builtin::BI__sync_fetch_and_sub_2: 838 case Builtin::BI__sync_fetch_and_sub_4: 839 case Builtin::BI__sync_fetch_and_sub_8: 840 case Builtin::BI__sync_fetch_and_sub_16: 841 case Builtin::BI__sync_fetch_and_or: 842 case Builtin::BI__sync_fetch_and_or_1: 843 case Builtin::BI__sync_fetch_and_or_2: 844 case Builtin::BI__sync_fetch_and_or_4: 845 case Builtin::BI__sync_fetch_and_or_8: 846 case Builtin::BI__sync_fetch_and_or_16: 847 case Builtin::BI__sync_fetch_and_and: 848 case Builtin::BI__sync_fetch_and_and_1: 849 case Builtin::BI__sync_fetch_and_and_2: 850 case Builtin::BI__sync_fetch_and_and_4: 851 case Builtin::BI__sync_fetch_and_and_8: 852 case Builtin::BI__sync_fetch_and_and_16: 853 case Builtin::BI__sync_fetch_and_xor: 854 case Builtin::BI__sync_fetch_and_xor_1: 855 case Builtin::BI__sync_fetch_and_xor_2: 856 case Builtin::BI__sync_fetch_and_xor_4: 857 case Builtin::BI__sync_fetch_and_xor_8: 858 case Builtin::BI__sync_fetch_and_xor_16: 859 case Builtin::BI__sync_fetch_and_nand: 860 case Builtin::BI__sync_fetch_and_nand_1: 861 case Builtin::BI__sync_fetch_and_nand_2: 862 case Builtin::BI__sync_fetch_and_nand_4: 863 case Builtin::BI__sync_fetch_and_nand_8: 864 case Builtin::BI__sync_fetch_and_nand_16: 865 case Builtin::BI__sync_add_and_fetch: 866 case Builtin::BI__sync_add_and_fetch_1: 867 case Builtin::BI__sync_add_and_fetch_2: 868 case Builtin::BI__sync_add_and_fetch_4: 869 case Builtin::BI__sync_add_and_fetch_8: 870 case Builtin::BI__sync_add_and_fetch_16: 871 case Builtin::BI__sync_sub_and_fetch: 872 case Builtin::BI__sync_sub_and_fetch_1: 873 case Builtin::BI__sync_sub_and_fetch_2: 874 case Builtin::BI__sync_sub_and_fetch_4: 875 case Builtin::BI__sync_sub_and_fetch_8: 876 case Builtin::BI__sync_sub_and_fetch_16: 877 case Builtin::BI__sync_and_and_fetch: 878 case Builtin::BI__sync_and_and_fetch_1: 879 case Builtin::BI__sync_and_and_fetch_2: 880 case Builtin::BI__sync_and_and_fetch_4: 881 case Builtin::BI__sync_and_and_fetch_8: 882 case Builtin::BI__sync_and_and_fetch_16: 883 case Builtin::BI__sync_or_and_fetch: 884 case Builtin::BI__sync_or_and_fetch_1: 885 case Builtin::BI__sync_or_and_fetch_2: 886 case Builtin::BI__sync_or_and_fetch_4: 887 case Builtin::BI__sync_or_and_fetch_8: 888 case Builtin::BI__sync_or_and_fetch_16: 889 case Builtin::BI__sync_xor_and_fetch: 890 case Builtin::BI__sync_xor_and_fetch_1: 891 case Builtin::BI__sync_xor_and_fetch_2: 892 case Builtin::BI__sync_xor_and_fetch_4: 893 case Builtin::BI__sync_xor_and_fetch_8: 894 case Builtin::BI__sync_xor_and_fetch_16: 895 case Builtin::BI__sync_nand_and_fetch: 896 case Builtin::BI__sync_nand_and_fetch_1: 897 case Builtin::BI__sync_nand_and_fetch_2: 898 case Builtin::BI__sync_nand_and_fetch_4: 899 case Builtin::BI__sync_nand_and_fetch_8: 900 case Builtin::BI__sync_nand_and_fetch_16: 901 case Builtin::BI__sync_val_compare_and_swap: 902 case Builtin::BI__sync_val_compare_and_swap_1: 903 case Builtin::BI__sync_val_compare_and_swap_2: 904 case Builtin::BI__sync_val_compare_and_swap_4: 905 case Builtin::BI__sync_val_compare_and_swap_8: 906 case Builtin::BI__sync_val_compare_and_swap_16: 907 case Builtin::BI__sync_bool_compare_and_swap: 908 case Builtin::BI__sync_bool_compare_and_swap_1: 909 case Builtin::BI__sync_bool_compare_and_swap_2: 910 case Builtin::BI__sync_bool_compare_and_swap_4: 911 case Builtin::BI__sync_bool_compare_and_swap_8: 912 case Builtin::BI__sync_bool_compare_and_swap_16: 913 case Builtin::BI__sync_lock_test_and_set: 914 case Builtin::BI__sync_lock_test_and_set_1: 915 case Builtin::BI__sync_lock_test_and_set_2: 916 case Builtin::BI__sync_lock_test_and_set_4: 917 case Builtin::BI__sync_lock_test_and_set_8: 918 case Builtin::BI__sync_lock_test_and_set_16: 919 case Builtin::BI__sync_lock_release: 920 case Builtin::BI__sync_lock_release_1: 921 case Builtin::BI__sync_lock_release_2: 922 case Builtin::BI__sync_lock_release_4: 923 case Builtin::BI__sync_lock_release_8: 924 case Builtin::BI__sync_lock_release_16: 925 case Builtin::BI__sync_swap: 926 case Builtin::BI__sync_swap_1: 927 case Builtin::BI__sync_swap_2: 928 case Builtin::BI__sync_swap_4: 929 case Builtin::BI__sync_swap_8: 930 case Builtin::BI__sync_swap_16: 931 return SemaBuiltinAtomicOverloaded(TheCallResult); 932 case Builtin::BI__builtin_nontemporal_load: 933 case Builtin::BI__builtin_nontemporal_store: 934 return SemaBuiltinNontemporalOverloaded(TheCallResult); 935 #define BUILTIN(ID, TYPE, ATTRS) 936 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 937 case Builtin::BI##ID: \ 938 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 939 #include "clang/Basic/Builtins.def" 940 case Builtin::BI__builtin_annotation: 941 if (SemaBuiltinAnnotation(*this, TheCall)) 942 return ExprError(); 943 break; 944 case Builtin::BI__builtin_addressof: 945 if (SemaBuiltinAddressof(*this, TheCall)) 946 return ExprError(); 947 break; 948 case Builtin::BI__builtin_add_overflow: 949 case Builtin::BI__builtin_sub_overflow: 950 case Builtin::BI__builtin_mul_overflow: 951 if (SemaBuiltinOverflow(*this, TheCall)) 952 return ExprError(); 953 break; 954 case Builtin::BI__builtin_operator_new: 955 case Builtin::BI__builtin_operator_delete: 956 if (!getLangOpts().CPlusPlus) { 957 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language) 958 << (BuiltinID == Builtin::BI__builtin_operator_new 959 ? "__builtin_operator_new" 960 : "__builtin_operator_delete") 961 << "C++"; 962 return ExprError(); 963 } 964 // CodeGen assumes it can find the global new and delete to call, 965 // so ensure that they are declared. 966 DeclareGlobalNewDelete(); 967 break; 968 969 // check secure string manipulation functions where overflows 970 // are detectable at compile time 971 case Builtin::BI__builtin___memcpy_chk: 972 case Builtin::BI__builtin___memmove_chk: 973 case Builtin::BI__builtin___memset_chk: 974 case Builtin::BI__builtin___strlcat_chk: 975 case Builtin::BI__builtin___strlcpy_chk: 976 case Builtin::BI__builtin___strncat_chk: 977 case Builtin::BI__builtin___strncpy_chk: 978 case Builtin::BI__builtin___stpncpy_chk: 979 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3); 980 break; 981 case Builtin::BI__builtin___memccpy_chk: 982 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4); 983 break; 984 case Builtin::BI__builtin___snprintf_chk: 985 case Builtin::BI__builtin___vsnprintf_chk: 986 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3); 987 break; 988 case Builtin::BI__builtin_call_with_static_chain: 989 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 990 return ExprError(); 991 break; 992 case Builtin::BI__exception_code: 993 case Builtin::BI_exception_code: 994 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 995 diag::err_seh___except_block)) 996 return ExprError(); 997 break; 998 case Builtin::BI__exception_info: 999 case Builtin::BI_exception_info: 1000 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1001 diag::err_seh___except_filter)) 1002 return ExprError(); 1003 break; 1004 case Builtin::BI__GetExceptionInfo: 1005 if (checkArgCount(*this, TheCall, 1)) 1006 return ExprError(); 1007 1008 if (CheckCXXThrowOperand( 1009 TheCall->getLocStart(), 1010 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1011 TheCall)) 1012 return ExprError(); 1013 1014 TheCall->setType(Context.VoidPtrTy); 1015 break; 1016 // OpenCL v2.0, s6.13.16 - Pipe functions 1017 case Builtin::BIread_pipe: 1018 case Builtin::BIwrite_pipe: 1019 // Since those two functions are declared with var args, we need a semantic 1020 // check for the argument. 1021 if (SemaBuiltinRWPipe(*this, TheCall)) 1022 return ExprError(); 1023 TheCall->setType(Context.IntTy); 1024 break; 1025 case Builtin::BIreserve_read_pipe: 1026 case Builtin::BIreserve_write_pipe: 1027 case Builtin::BIwork_group_reserve_read_pipe: 1028 case Builtin::BIwork_group_reserve_write_pipe: 1029 case Builtin::BIsub_group_reserve_read_pipe: 1030 case Builtin::BIsub_group_reserve_write_pipe: 1031 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1032 return ExprError(); 1033 // Since return type of reserve_read/write_pipe built-in function is 1034 // reserve_id_t, which is not defined in the builtin def file , we used int 1035 // as return type and need to override the return type of these functions. 1036 TheCall->setType(Context.OCLReserveIDTy); 1037 break; 1038 case Builtin::BIcommit_read_pipe: 1039 case Builtin::BIcommit_write_pipe: 1040 case Builtin::BIwork_group_commit_read_pipe: 1041 case Builtin::BIwork_group_commit_write_pipe: 1042 case Builtin::BIsub_group_commit_read_pipe: 1043 case Builtin::BIsub_group_commit_write_pipe: 1044 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1045 return ExprError(); 1046 break; 1047 case Builtin::BIget_pipe_num_packets: 1048 case Builtin::BIget_pipe_max_packets: 1049 if (SemaBuiltinPipePackets(*this, TheCall)) 1050 return ExprError(); 1051 TheCall->setType(Context.UnsignedIntTy); 1052 break; 1053 case Builtin::BIto_global: 1054 case Builtin::BIto_local: 1055 case Builtin::BIto_private: 1056 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1057 return ExprError(); 1058 break; 1059 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1060 case Builtin::BIenqueue_kernel: 1061 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1062 return ExprError(); 1063 break; 1064 case Builtin::BIget_kernel_work_group_size: 1065 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1066 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1067 return ExprError(); 1068 break; 1069 case Builtin::BI__builtin_os_log_format: 1070 case Builtin::BI__builtin_os_log_format_buffer_size: 1071 if (SemaBuiltinOSLogFormat(TheCall)) { 1072 return ExprError(); 1073 } 1074 break; 1075 } 1076 1077 // Since the target specific builtins for each arch overlap, only check those 1078 // of the arch we are compiling for. 1079 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 1080 switch (Context.getTargetInfo().getTriple().getArch()) { 1081 case llvm::Triple::arm: 1082 case llvm::Triple::armeb: 1083 case llvm::Triple::thumb: 1084 case llvm::Triple::thumbeb: 1085 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall)) 1086 return ExprError(); 1087 break; 1088 case llvm::Triple::aarch64: 1089 case llvm::Triple::aarch64_be: 1090 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall)) 1091 return ExprError(); 1092 break; 1093 case llvm::Triple::mips: 1094 case llvm::Triple::mipsel: 1095 case llvm::Triple::mips64: 1096 case llvm::Triple::mips64el: 1097 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall)) 1098 return ExprError(); 1099 break; 1100 case llvm::Triple::systemz: 1101 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall)) 1102 return ExprError(); 1103 break; 1104 case llvm::Triple::x86: 1105 case llvm::Triple::x86_64: 1106 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall)) 1107 return ExprError(); 1108 break; 1109 case llvm::Triple::ppc: 1110 case llvm::Triple::ppc64: 1111 case llvm::Triple::ppc64le: 1112 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall)) 1113 return ExprError(); 1114 break; 1115 default: 1116 break; 1117 } 1118 } 1119 1120 return TheCallResult; 1121 } 1122 1123 // Get the valid immediate range for the specified NEON type code. 1124 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 1125 NeonTypeFlags Type(t); 1126 int IsQuad = ForceQuad ? true : Type.isQuad(); 1127 switch (Type.getEltType()) { 1128 case NeonTypeFlags::Int8: 1129 case NeonTypeFlags::Poly8: 1130 return shift ? 7 : (8 << IsQuad) - 1; 1131 case NeonTypeFlags::Int16: 1132 case NeonTypeFlags::Poly16: 1133 return shift ? 15 : (4 << IsQuad) - 1; 1134 case NeonTypeFlags::Int32: 1135 return shift ? 31 : (2 << IsQuad) - 1; 1136 case NeonTypeFlags::Int64: 1137 case NeonTypeFlags::Poly64: 1138 return shift ? 63 : (1 << IsQuad) - 1; 1139 case NeonTypeFlags::Poly128: 1140 return shift ? 127 : (1 << IsQuad) - 1; 1141 case NeonTypeFlags::Float16: 1142 assert(!shift && "cannot shift float types!"); 1143 return (4 << IsQuad) - 1; 1144 case NeonTypeFlags::Float32: 1145 assert(!shift && "cannot shift float types!"); 1146 return (2 << IsQuad) - 1; 1147 case NeonTypeFlags::Float64: 1148 assert(!shift && "cannot shift float types!"); 1149 return (1 << IsQuad) - 1; 1150 } 1151 llvm_unreachable("Invalid NeonTypeFlag!"); 1152 } 1153 1154 /// getNeonEltType - Return the QualType corresponding to the elements of 1155 /// the vector type specified by the NeonTypeFlags. This is used to check 1156 /// the pointer arguments for Neon load/store intrinsics. 1157 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 1158 bool IsPolyUnsigned, bool IsInt64Long) { 1159 switch (Flags.getEltType()) { 1160 case NeonTypeFlags::Int8: 1161 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 1162 case NeonTypeFlags::Int16: 1163 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 1164 case NeonTypeFlags::Int32: 1165 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 1166 case NeonTypeFlags::Int64: 1167 if (IsInt64Long) 1168 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 1169 else 1170 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 1171 : Context.LongLongTy; 1172 case NeonTypeFlags::Poly8: 1173 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 1174 case NeonTypeFlags::Poly16: 1175 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 1176 case NeonTypeFlags::Poly64: 1177 if (IsInt64Long) 1178 return Context.UnsignedLongTy; 1179 else 1180 return Context.UnsignedLongLongTy; 1181 case NeonTypeFlags::Poly128: 1182 break; 1183 case NeonTypeFlags::Float16: 1184 return Context.HalfTy; 1185 case NeonTypeFlags::Float32: 1186 return Context.FloatTy; 1187 case NeonTypeFlags::Float64: 1188 return Context.DoubleTy; 1189 } 1190 llvm_unreachable("Invalid NeonTypeFlag!"); 1191 } 1192 1193 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1194 llvm::APSInt Result; 1195 uint64_t mask = 0; 1196 unsigned TV = 0; 1197 int PtrArgNum = -1; 1198 bool HasConstPtr = false; 1199 switch (BuiltinID) { 1200 #define GET_NEON_OVERLOAD_CHECK 1201 #include "clang/Basic/arm_neon.inc" 1202 #undef GET_NEON_OVERLOAD_CHECK 1203 } 1204 1205 // For NEON intrinsics which are overloaded on vector element type, validate 1206 // the immediate which specifies which variant to emit. 1207 unsigned ImmArg = TheCall->getNumArgs()-1; 1208 if (mask) { 1209 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 1210 return true; 1211 1212 TV = Result.getLimitedValue(64); 1213 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 1214 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code) 1215 << TheCall->getArg(ImmArg)->getSourceRange(); 1216 } 1217 1218 if (PtrArgNum >= 0) { 1219 // Check that pointer arguments have the specified type. 1220 Expr *Arg = TheCall->getArg(PtrArgNum); 1221 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 1222 Arg = ICE->getSubExpr(); 1223 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 1224 QualType RHSTy = RHS.get()->getType(); 1225 1226 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 1227 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64; 1228 bool IsInt64Long = 1229 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong; 1230 QualType EltTy = 1231 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 1232 if (HasConstPtr) 1233 EltTy = EltTy.withConst(); 1234 QualType LHSTy = Context.getPointerType(EltTy); 1235 AssignConvertType ConvTy; 1236 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 1237 if (RHS.isInvalid()) 1238 return true; 1239 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy, 1240 RHS.get(), AA_Assigning)) 1241 return true; 1242 } 1243 1244 // For NEON intrinsics which take an immediate value as part of the 1245 // instruction, range check them here. 1246 unsigned i = 0, l = 0, u = 0; 1247 switch (BuiltinID) { 1248 default: 1249 return false; 1250 #define GET_NEON_IMMEDIATE_CHECK 1251 #include "clang/Basic/arm_neon.inc" 1252 #undef GET_NEON_IMMEDIATE_CHECK 1253 } 1254 1255 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1256 } 1257 1258 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 1259 unsigned MaxWidth) { 1260 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 1261 BuiltinID == ARM::BI__builtin_arm_ldaex || 1262 BuiltinID == ARM::BI__builtin_arm_strex || 1263 BuiltinID == ARM::BI__builtin_arm_stlex || 1264 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1265 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1266 BuiltinID == AArch64::BI__builtin_arm_strex || 1267 BuiltinID == AArch64::BI__builtin_arm_stlex) && 1268 "unexpected ARM builtin"); 1269 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 1270 BuiltinID == ARM::BI__builtin_arm_ldaex || 1271 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1272 BuiltinID == AArch64::BI__builtin_arm_ldaex; 1273 1274 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 1275 1276 // Ensure that we have the proper number of arguments. 1277 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 1278 return true; 1279 1280 // Inspect the pointer argument of the atomic builtin. This should always be 1281 // a pointer type, whose element is an integral scalar or pointer type. 1282 // Because it is a pointer type, we don't have to worry about any implicit 1283 // casts here. 1284 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 1285 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 1286 if (PointerArgRes.isInvalid()) 1287 return true; 1288 PointerArg = PointerArgRes.get(); 1289 1290 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 1291 if (!pointerType) { 1292 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 1293 << PointerArg->getType() << PointerArg->getSourceRange(); 1294 return true; 1295 } 1296 1297 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 1298 // task is to insert the appropriate casts into the AST. First work out just 1299 // what the appropriate type is. 1300 QualType ValType = pointerType->getPointeeType(); 1301 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 1302 if (IsLdrex) 1303 AddrType.addConst(); 1304 1305 // Issue a warning if the cast is dodgy. 1306 CastKind CastNeeded = CK_NoOp; 1307 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 1308 CastNeeded = CK_BitCast; 1309 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers) 1310 << PointerArg->getType() 1311 << Context.getPointerType(AddrType) 1312 << AA_Passing << PointerArg->getSourceRange(); 1313 } 1314 1315 // Finally, do the cast and replace the argument with the corrected version. 1316 AddrType = Context.getPointerType(AddrType); 1317 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 1318 if (PointerArgRes.isInvalid()) 1319 return true; 1320 PointerArg = PointerArgRes.get(); 1321 1322 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 1323 1324 // In general, we allow ints, floats and pointers to be loaded and stored. 1325 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 1326 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 1327 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 1328 << PointerArg->getType() << PointerArg->getSourceRange(); 1329 return true; 1330 } 1331 1332 // But ARM doesn't have instructions to deal with 128-bit versions. 1333 if (Context.getTypeSize(ValType) > MaxWidth) { 1334 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 1335 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size) 1336 << PointerArg->getType() << PointerArg->getSourceRange(); 1337 return true; 1338 } 1339 1340 switch (ValType.getObjCLifetime()) { 1341 case Qualifiers::OCL_None: 1342 case Qualifiers::OCL_ExplicitNone: 1343 // okay 1344 break; 1345 1346 case Qualifiers::OCL_Weak: 1347 case Qualifiers::OCL_Strong: 1348 case Qualifiers::OCL_Autoreleasing: 1349 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 1350 << ValType << PointerArg->getSourceRange(); 1351 return true; 1352 } 1353 1354 if (IsLdrex) { 1355 TheCall->setType(ValType); 1356 return false; 1357 } 1358 1359 // Initialize the argument to be stored. 1360 ExprResult ValArg = TheCall->getArg(0); 1361 InitializedEntity Entity = InitializedEntity::InitializeParameter( 1362 Context, ValType, /*consume*/ false); 1363 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 1364 if (ValArg.isInvalid()) 1365 return true; 1366 TheCall->setArg(0, ValArg.get()); 1367 1368 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 1369 // but the custom checker bypasses all default analysis. 1370 TheCall->setType(Context.IntTy); 1371 return false; 1372 } 1373 1374 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1375 llvm::APSInt Result; 1376 1377 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 1378 BuiltinID == ARM::BI__builtin_arm_ldaex || 1379 BuiltinID == ARM::BI__builtin_arm_strex || 1380 BuiltinID == ARM::BI__builtin_arm_stlex) { 1381 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 1382 } 1383 1384 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 1385 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1386 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 1387 } 1388 1389 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 1390 BuiltinID == ARM::BI__builtin_arm_wsr64) 1391 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 1392 1393 if (BuiltinID == ARM::BI__builtin_arm_rsr || 1394 BuiltinID == ARM::BI__builtin_arm_rsrp || 1395 BuiltinID == ARM::BI__builtin_arm_wsr || 1396 BuiltinID == ARM::BI__builtin_arm_wsrp) 1397 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1398 1399 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1400 return true; 1401 1402 // For intrinsics which take an immediate value as part of the instruction, 1403 // range check them here. 1404 unsigned i = 0, l = 0, u = 0; 1405 switch (BuiltinID) { 1406 default: return false; 1407 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break; 1408 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break; 1409 case ARM::BI__builtin_arm_vcvtr_f: 1410 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break; 1411 case ARM::BI__builtin_arm_dmb: 1412 case ARM::BI__builtin_arm_dsb: 1413 case ARM::BI__builtin_arm_isb: 1414 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break; 1415 } 1416 1417 // FIXME: VFP Intrinsics should error if VFP not present. 1418 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1419 } 1420 1421 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, 1422 CallExpr *TheCall) { 1423 llvm::APSInt Result; 1424 1425 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 1426 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1427 BuiltinID == AArch64::BI__builtin_arm_strex || 1428 BuiltinID == AArch64::BI__builtin_arm_stlex) { 1429 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 1430 } 1431 1432 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 1433 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1434 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 1435 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 1436 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 1437 } 1438 1439 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 1440 BuiltinID == AArch64::BI__builtin_arm_wsr64) 1441 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1442 1443 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 1444 BuiltinID == AArch64::BI__builtin_arm_rsrp || 1445 BuiltinID == AArch64::BI__builtin_arm_wsr || 1446 BuiltinID == AArch64::BI__builtin_arm_wsrp) 1447 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1448 1449 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1450 return true; 1451 1452 // For intrinsics which take an immediate value as part of the instruction, 1453 // range check them here. 1454 unsigned i = 0, l = 0, u = 0; 1455 switch (BuiltinID) { 1456 default: return false; 1457 case AArch64::BI__builtin_arm_dmb: 1458 case AArch64::BI__builtin_arm_dsb: 1459 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 1460 } 1461 1462 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1463 } 1464 1465 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the 1466 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 1467 // ordering for DSP is unspecified. MSA is ordered by the data format used 1468 // by the underlying instruction i.e., df/m, df/n and then by size. 1469 // 1470 // FIXME: The size tests here should instead be tablegen'd along with the 1471 // definitions from include/clang/Basic/BuiltinsMips.def. 1472 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 1473 // be too. 1474 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1475 unsigned i = 0, l = 0, u = 0, m = 0; 1476 switch (BuiltinID) { 1477 default: return false; 1478 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 1479 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 1480 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 1481 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 1482 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 1483 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 1484 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 1485 // MSA instrinsics. Instructions (which the intrinsics maps to) which use the 1486 // df/m field. 1487 // These intrinsics take an unsigned 3 bit immediate. 1488 case Mips::BI__builtin_msa_bclri_b: 1489 case Mips::BI__builtin_msa_bnegi_b: 1490 case Mips::BI__builtin_msa_bseti_b: 1491 case Mips::BI__builtin_msa_sat_s_b: 1492 case Mips::BI__builtin_msa_sat_u_b: 1493 case Mips::BI__builtin_msa_slli_b: 1494 case Mips::BI__builtin_msa_srai_b: 1495 case Mips::BI__builtin_msa_srari_b: 1496 case Mips::BI__builtin_msa_srli_b: 1497 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 1498 case Mips::BI__builtin_msa_binsli_b: 1499 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 1500 // These intrinsics take an unsigned 4 bit immediate. 1501 case Mips::BI__builtin_msa_bclri_h: 1502 case Mips::BI__builtin_msa_bnegi_h: 1503 case Mips::BI__builtin_msa_bseti_h: 1504 case Mips::BI__builtin_msa_sat_s_h: 1505 case Mips::BI__builtin_msa_sat_u_h: 1506 case Mips::BI__builtin_msa_slli_h: 1507 case Mips::BI__builtin_msa_srai_h: 1508 case Mips::BI__builtin_msa_srari_h: 1509 case Mips::BI__builtin_msa_srli_h: 1510 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 1511 case Mips::BI__builtin_msa_binsli_h: 1512 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 1513 // These intrinsics take an unsigned 5 bit immedate. 1514 // The first block of intrinsics actually have an unsigned 5 bit field, 1515 // not a df/n field. 1516 case Mips::BI__builtin_msa_clei_u_b: 1517 case Mips::BI__builtin_msa_clei_u_h: 1518 case Mips::BI__builtin_msa_clei_u_w: 1519 case Mips::BI__builtin_msa_clei_u_d: 1520 case Mips::BI__builtin_msa_clti_u_b: 1521 case Mips::BI__builtin_msa_clti_u_h: 1522 case Mips::BI__builtin_msa_clti_u_w: 1523 case Mips::BI__builtin_msa_clti_u_d: 1524 case Mips::BI__builtin_msa_maxi_u_b: 1525 case Mips::BI__builtin_msa_maxi_u_h: 1526 case Mips::BI__builtin_msa_maxi_u_w: 1527 case Mips::BI__builtin_msa_maxi_u_d: 1528 case Mips::BI__builtin_msa_mini_u_b: 1529 case Mips::BI__builtin_msa_mini_u_h: 1530 case Mips::BI__builtin_msa_mini_u_w: 1531 case Mips::BI__builtin_msa_mini_u_d: 1532 case Mips::BI__builtin_msa_addvi_b: 1533 case Mips::BI__builtin_msa_addvi_h: 1534 case Mips::BI__builtin_msa_addvi_w: 1535 case Mips::BI__builtin_msa_addvi_d: 1536 case Mips::BI__builtin_msa_bclri_w: 1537 case Mips::BI__builtin_msa_bnegi_w: 1538 case Mips::BI__builtin_msa_bseti_w: 1539 case Mips::BI__builtin_msa_sat_s_w: 1540 case Mips::BI__builtin_msa_sat_u_w: 1541 case Mips::BI__builtin_msa_slli_w: 1542 case Mips::BI__builtin_msa_srai_w: 1543 case Mips::BI__builtin_msa_srari_w: 1544 case Mips::BI__builtin_msa_srli_w: 1545 case Mips::BI__builtin_msa_srlri_w: 1546 case Mips::BI__builtin_msa_subvi_b: 1547 case Mips::BI__builtin_msa_subvi_h: 1548 case Mips::BI__builtin_msa_subvi_w: 1549 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 1550 case Mips::BI__builtin_msa_binsli_w: 1551 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 1552 // These intrinsics take an unsigned 6 bit immediate. 1553 case Mips::BI__builtin_msa_bclri_d: 1554 case Mips::BI__builtin_msa_bnegi_d: 1555 case Mips::BI__builtin_msa_bseti_d: 1556 case Mips::BI__builtin_msa_sat_s_d: 1557 case Mips::BI__builtin_msa_sat_u_d: 1558 case Mips::BI__builtin_msa_slli_d: 1559 case Mips::BI__builtin_msa_srai_d: 1560 case Mips::BI__builtin_msa_srari_d: 1561 case Mips::BI__builtin_msa_srli_d: 1562 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 1563 case Mips::BI__builtin_msa_binsli_d: 1564 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 1565 // These intrinsics take a signed 5 bit immediate. 1566 case Mips::BI__builtin_msa_ceqi_b: 1567 case Mips::BI__builtin_msa_ceqi_h: 1568 case Mips::BI__builtin_msa_ceqi_w: 1569 case Mips::BI__builtin_msa_ceqi_d: 1570 case Mips::BI__builtin_msa_clti_s_b: 1571 case Mips::BI__builtin_msa_clti_s_h: 1572 case Mips::BI__builtin_msa_clti_s_w: 1573 case Mips::BI__builtin_msa_clti_s_d: 1574 case Mips::BI__builtin_msa_clei_s_b: 1575 case Mips::BI__builtin_msa_clei_s_h: 1576 case Mips::BI__builtin_msa_clei_s_w: 1577 case Mips::BI__builtin_msa_clei_s_d: 1578 case Mips::BI__builtin_msa_maxi_s_b: 1579 case Mips::BI__builtin_msa_maxi_s_h: 1580 case Mips::BI__builtin_msa_maxi_s_w: 1581 case Mips::BI__builtin_msa_maxi_s_d: 1582 case Mips::BI__builtin_msa_mini_s_b: 1583 case Mips::BI__builtin_msa_mini_s_h: 1584 case Mips::BI__builtin_msa_mini_s_w: 1585 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 1586 // These intrinsics take an unsigned 8 bit immediate. 1587 case Mips::BI__builtin_msa_andi_b: 1588 case Mips::BI__builtin_msa_nori_b: 1589 case Mips::BI__builtin_msa_ori_b: 1590 case Mips::BI__builtin_msa_shf_b: 1591 case Mips::BI__builtin_msa_shf_h: 1592 case Mips::BI__builtin_msa_shf_w: 1593 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 1594 case Mips::BI__builtin_msa_bseli_b: 1595 case Mips::BI__builtin_msa_bmnzi_b: 1596 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 1597 // df/n format 1598 // These intrinsics take an unsigned 4 bit immediate. 1599 case Mips::BI__builtin_msa_copy_s_b: 1600 case Mips::BI__builtin_msa_copy_u_b: 1601 case Mips::BI__builtin_msa_insve_b: 1602 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 1603 case Mips::BI__builtin_msa_sld_b: 1604 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 1605 // These intrinsics take an unsigned 3 bit immediate. 1606 case Mips::BI__builtin_msa_copy_s_h: 1607 case Mips::BI__builtin_msa_copy_u_h: 1608 case Mips::BI__builtin_msa_insve_h: 1609 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 1610 case Mips::BI__builtin_msa_sld_h: 1611 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 1612 // These intrinsics take an unsigned 2 bit immediate. 1613 case Mips::BI__builtin_msa_copy_s_w: 1614 case Mips::BI__builtin_msa_copy_u_w: 1615 case Mips::BI__builtin_msa_insve_w: 1616 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 1617 case Mips::BI__builtin_msa_sld_w: 1618 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 1619 // These intrinsics take an unsigned 1 bit immediate. 1620 case Mips::BI__builtin_msa_copy_s_d: 1621 case Mips::BI__builtin_msa_copy_u_d: 1622 case Mips::BI__builtin_msa_insve_d: 1623 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 1624 case Mips::BI__builtin_msa_sld_d: 1625 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 1626 // Memory offsets and immediate loads. 1627 // These intrinsics take a signed 10 bit immediate. 1628 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 127; break; 1629 case Mips::BI__builtin_msa_ldi_h: 1630 case Mips::BI__builtin_msa_ldi_w: 1631 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 1632 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break; 1633 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break; 1634 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break; 1635 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break; 1636 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break; 1637 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break; 1638 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break; 1639 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break; 1640 } 1641 1642 if (!m) 1643 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 1644 1645 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 1646 SemaBuiltinConstantArgMultiple(TheCall, i, m); 1647 } 1648 1649 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1650 unsigned i = 0, l = 0, u = 0; 1651 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde || 1652 BuiltinID == PPC::BI__builtin_divdeu || 1653 BuiltinID == PPC::BI__builtin_bpermd; 1654 bool IsTarget64Bit = Context.getTargetInfo() 1655 .getTypeWidth(Context 1656 .getTargetInfo() 1657 .getIntPtrType()) == 64; 1658 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe || 1659 BuiltinID == PPC::BI__builtin_divweu || 1660 BuiltinID == PPC::BI__builtin_divde || 1661 BuiltinID == PPC::BI__builtin_divdeu; 1662 1663 if (Is64BitBltin && !IsTarget64Bit) 1664 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt) 1665 << TheCall->getSourceRange(); 1666 1667 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) || 1668 (BuiltinID == PPC::BI__builtin_bpermd && 1669 !Context.getTargetInfo().hasFeature("bpermd"))) 1670 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7) 1671 << TheCall->getSourceRange(); 1672 1673 switch (BuiltinID) { 1674 default: return false; 1675 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 1676 case PPC::BI__builtin_altivec_crypto_vshasigmad: 1677 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1678 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 1679 case PPC::BI__builtin_tbegin: 1680 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 1681 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 1682 case PPC::BI__builtin_tabortwc: 1683 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 1684 case PPC::BI__builtin_tabortwci: 1685 case PPC::BI__builtin_tabortdci: 1686 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 1687 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 1688 } 1689 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 1690 } 1691 1692 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 1693 CallExpr *TheCall) { 1694 if (BuiltinID == SystemZ::BI__builtin_tabort) { 1695 Expr *Arg = TheCall->getArg(0); 1696 llvm::APSInt AbortCode(32); 1697 if (Arg->isIntegerConstantExpr(AbortCode, Context) && 1698 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256) 1699 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code) 1700 << Arg->getSourceRange(); 1701 } 1702 1703 // For intrinsics which take an immediate value as part of the instruction, 1704 // range check them here. 1705 unsigned i = 0, l = 0, u = 0; 1706 switch (BuiltinID) { 1707 default: return false; 1708 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 1709 case SystemZ::BI__builtin_s390_verimb: 1710 case SystemZ::BI__builtin_s390_verimh: 1711 case SystemZ::BI__builtin_s390_verimf: 1712 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 1713 case SystemZ::BI__builtin_s390_vfaeb: 1714 case SystemZ::BI__builtin_s390_vfaeh: 1715 case SystemZ::BI__builtin_s390_vfaef: 1716 case SystemZ::BI__builtin_s390_vfaebs: 1717 case SystemZ::BI__builtin_s390_vfaehs: 1718 case SystemZ::BI__builtin_s390_vfaefs: 1719 case SystemZ::BI__builtin_s390_vfaezb: 1720 case SystemZ::BI__builtin_s390_vfaezh: 1721 case SystemZ::BI__builtin_s390_vfaezf: 1722 case SystemZ::BI__builtin_s390_vfaezbs: 1723 case SystemZ::BI__builtin_s390_vfaezhs: 1724 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 1725 case SystemZ::BI__builtin_s390_vfidb: 1726 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 1727 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 1728 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 1729 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 1730 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 1731 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 1732 case SystemZ::BI__builtin_s390_vstrcb: 1733 case SystemZ::BI__builtin_s390_vstrch: 1734 case SystemZ::BI__builtin_s390_vstrcf: 1735 case SystemZ::BI__builtin_s390_vstrczb: 1736 case SystemZ::BI__builtin_s390_vstrczh: 1737 case SystemZ::BI__builtin_s390_vstrczf: 1738 case SystemZ::BI__builtin_s390_vstrcbs: 1739 case SystemZ::BI__builtin_s390_vstrchs: 1740 case SystemZ::BI__builtin_s390_vstrcfs: 1741 case SystemZ::BI__builtin_s390_vstrczbs: 1742 case SystemZ::BI__builtin_s390_vstrczhs: 1743 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 1744 } 1745 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 1746 } 1747 1748 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 1749 /// This checks that the target supports __builtin_cpu_supports and 1750 /// that the string argument is constant and valid. 1751 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) { 1752 Expr *Arg = TheCall->getArg(0); 1753 1754 // Check if the argument is a string literal. 1755 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 1756 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal) 1757 << Arg->getSourceRange(); 1758 1759 // Check the contents of the string. 1760 StringRef Feature = 1761 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 1762 if (!S.Context.getTargetInfo().validateCpuSupports(Feature)) 1763 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports) 1764 << Arg->getSourceRange(); 1765 return false; 1766 } 1767 1768 // Check if the rounding mode is legal. 1769 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 1770 // Indicates if this instruction has rounding control or just SAE. 1771 bool HasRC = false; 1772 1773 unsigned ArgNum = 0; 1774 switch (BuiltinID) { 1775 default: 1776 return false; 1777 case X86::BI__builtin_ia32_vcvttsd2si32: 1778 case X86::BI__builtin_ia32_vcvttsd2si64: 1779 case X86::BI__builtin_ia32_vcvttsd2usi32: 1780 case X86::BI__builtin_ia32_vcvttsd2usi64: 1781 case X86::BI__builtin_ia32_vcvttss2si32: 1782 case X86::BI__builtin_ia32_vcvttss2si64: 1783 case X86::BI__builtin_ia32_vcvttss2usi32: 1784 case X86::BI__builtin_ia32_vcvttss2usi64: 1785 ArgNum = 1; 1786 break; 1787 case X86::BI__builtin_ia32_cvtps2pd512_mask: 1788 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 1789 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 1790 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 1791 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 1792 case X86::BI__builtin_ia32_cvttps2dq512_mask: 1793 case X86::BI__builtin_ia32_cvttps2qq512_mask: 1794 case X86::BI__builtin_ia32_cvttps2udq512_mask: 1795 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 1796 case X86::BI__builtin_ia32_exp2pd_mask: 1797 case X86::BI__builtin_ia32_exp2ps_mask: 1798 case X86::BI__builtin_ia32_getexppd512_mask: 1799 case X86::BI__builtin_ia32_getexpps512_mask: 1800 case X86::BI__builtin_ia32_rcp28pd_mask: 1801 case X86::BI__builtin_ia32_rcp28ps_mask: 1802 case X86::BI__builtin_ia32_rsqrt28pd_mask: 1803 case X86::BI__builtin_ia32_rsqrt28ps_mask: 1804 case X86::BI__builtin_ia32_vcomisd: 1805 case X86::BI__builtin_ia32_vcomiss: 1806 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 1807 ArgNum = 3; 1808 break; 1809 case X86::BI__builtin_ia32_cmppd512_mask: 1810 case X86::BI__builtin_ia32_cmpps512_mask: 1811 case X86::BI__builtin_ia32_cmpsd_mask: 1812 case X86::BI__builtin_ia32_cmpss_mask: 1813 case X86::BI__builtin_ia32_getexpsd128_round_mask: 1814 case X86::BI__builtin_ia32_getexpss128_round_mask: 1815 case X86::BI__builtin_ia32_rcp28sd_round_mask: 1816 case X86::BI__builtin_ia32_rcp28ss_round_mask: 1817 case X86::BI__builtin_ia32_reducepd512_mask: 1818 case X86::BI__builtin_ia32_reduceps512_mask: 1819 case X86::BI__builtin_ia32_rndscalepd_mask: 1820 case X86::BI__builtin_ia32_rndscaleps_mask: 1821 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 1822 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 1823 ArgNum = 4; 1824 break; 1825 case X86::BI__builtin_ia32_fixupimmpd512_mask: 1826 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 1827 case X86::BI__builtin_ia32_fixupimmps512_mask: 1828 case X86::BI__builtin_ia32_fixupimmps512_maskz: 1829 case X86::BI__builtin_ia32_fixupimmsd_mask: 1830 case X86::BI__builtin_ia32_fixupimmsd_maskz: 1831 case X86::BI__builtin_ia32_fixupimmss_mask: 1832 case X86::BI__builtin_ia32_fixupimmss_maskz: 1833 case X86::BI__builtin_ia32_rangepd512_mask: 1834 case X86::BI__builtin_ia32_rangeps512_mask: 1835 case X86::BI__builtin_ia32_rangesd128_round_mask: 1836 case X86::BI__builtin_ia32_rangess128_round_mask: 1837 case X86::BI__builtin_ia32_reducesd_mask: 1838 case X86::BI__builtin_ia32_reducess_mask: 1839 case X86::BI__builtin_ia32_rndscalesd_round_mask: 1840 case X86::BI__builtin_ia32_rndscaless_round_mask: 1841 ArgNum = 5; 1842 break; 1843 case X86::BI__builtin_ia32_vcvtsd2si64: 1844 case X86::BI__builtin_ia32_vcvtsd2si32: 1845 case X86::BI__builtin_ia32_vcvtsd2usi32: 1846 case X86::BI__builtin_ia32_vcvtsd2usi64: 1847 case X86::BI__builtin_ia32_vcvtss2si32: 1848 case X86::BI__builtin_ia32_vcvtss2si64: 1849 case X86::BI__builtin_ia32_vcvtss2usi32: 1850 case X86::BI__builtin_ia32_vcvtss2usi64: 1851 ArgNum = 1; 1852 HasRC = true; 1853 break; 1854 case X86::BI__builtin_ia32_cvtusi2sd64: 1855 case X86::BI__builtin_ia32_cvtusi2ss32: 1856 case X86::BI__builtin_ia32_cvtusi2ss64: 1857 ArgNum = 2; 1858 HasRC = true; 1859 break; 1860 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 1861 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 1862 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 1863 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 1864 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 1865 case X86::BI__builtin_ia32_cvtps2qq512_mask: 1866 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 1867 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 1868 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 1869 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 1870 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 1871 ArgNum = 3; 1872 HasRC = true; 1873 break; 1874 case X86::BI__builtin_ia32_addpd512_mask: 1875 case X86::BI__builtin_ia32_addps512_mask: 1876 case X86::BI__builtin_ia32_divpd512_mask: 1877 case X86::BI__builtin_ia32_divps512_mask: 1878 case X86::BI__builtin_ia32_mulpd512_mask: 1879 case X86::BI__builtin_ia32_mulps512_mask: 1880 case X86::BI__builtin_ia32_subpd512_mask: 1881 case X86::BI__builtin_ia32_subps512_mask: 1882 case X86::BI__builtin_ia32_addss_round_mask: 1883 case X86::BI__builtin_ia32_addsd_round_mask: 1884 case X86::BI__builtin_ia32_divss_round_mask: 1885 case X86::BI__builtin_ia32_divsd_round_mask: 1886 case X86::BI__builtin_ia32_mulss_round_mask: 1887 case X86::BI__builtin_ia32_mulsd_round_mask: 1888 case X86::BI__builtin_ia32_subss_round_mask: 1889 case X86::BI__builtin_ia32_subsd_round_mask: 1890 case X86::BI__builtin_ia32_scalefpd512_mask: 1891 case X86::BI__builtin_ia32_scalefps512_mask: 1892 case X86::BI__builtin_ia32_scalefsd_round_mask: 1893 case X86::BI__builtin_ia32_scalefss_round_mask: 1894 case X86::BI__builtin_ia32_getmantpd512_mask: 1895 case X86::BI__builtin_ia32_getmantps512_mask: 1896 case X86::BI__builtin_ia32_vfmaddpd512_mask: 1897 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 1898 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 1899 case X86::BI__builtin_ia32_vfmaddps512_mask: 1900 case X86::BI__builtin_ia32_vfmaddps512_mask3: 1901 case X86::BI__builtin_ia32_vfmaddps512_maskz: 1902 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 1903 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 1904 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 1905 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 1906 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 1907 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 1908 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 1909 case X86::BI__builtin_ia32_vfmsubps512_mask3: 1910 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 1911 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 1912 case X86::BI__builtin_ia32_vfnmaddpd512_mask: 1913 case X86::BI__builtin_ia32_vfnmaddps512_mask: 1914 case X86::BI__builtin_ia32_vfnmsubpd512_mask: 1915 case X86::BI__builtin_ia32_vfnmsubpd512_mask3: 1916 case X86::BI__builtin_ia32_vfnmsubps512_mask: 1917 case X86::BI__builtin_ia32_vfnmsubps512_mask3: 1918 case X86::BI__builtin_ia32_vfmaddsd3_mask: 1919 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 1920 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 1921 case X86::BI__builtin_ia32_vfmaddss3_mask: 1922 case X86::BI__builtin_ia32_vfmaddss3_maskz: 1923 case X86::BI__builtin_ia32_vfmaddss3_mask3: 1924 ArgNum = 4; 1925 HasRC = true; 1926 break; 1927 case X86::BI__builtin_ia32_getmantsd_round_mask: 1928 case X86::BI__builtin_ia32_getmantss_round_mask: 1929 ArgNum = 5; 1930 HasRC = true; 1931 break; 1932 } 1933 1934 llvm::APSInt Result; 1935 1936 // We can't check the value of a dependent argument. 1937 Expr *Arg = TheCall->getArg(ArgNum); 1938 if (Arg->isTypeDependent() || Arg->isValueDependent()) 1939 return false; 1940 1941 // Check constant-ness first. 1942 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 1943 return true; 1944 1945 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 1946 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 1947 // combined with ROUND_NO_EXC. 1948 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 1949 Result == 8/*ROUND_NO_EXC*/ || 1950 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 1951 return false; 1952 1953 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding) 1954 << Arg->getSourceRange(); 1955 } 1956 1957 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1958 if (BuiltinID == X86::BI__builtin_cpu_supports) 1959 return SemaBuiltinCpuSupports(*this, TheCall); 1960 1961 if (BuiltinID == X86::BI__builtin_ms_va_start) 1962 return SemaBuiltinMSVAStart(TheCall); 1963 1964 // If the intrinsic has rounding or SAE make sure its valid. 1965 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 1966 return true; 1967 1968 // For intrinsics which take an immediate value as part of the instruction, 1969 // range check them here. 1970 int i = 0, l = 0, u = 0; 1971 switch (BuiltinID) { 1972 default: 1973 return false; 1974 case X86::BI__builtin_ia32_extractf64x4_mask: 1975 case X86::BI__builtin_ia32_extracti64x4_mask: 1976 case X86::BI__builtin_ia32_extractf32x8_mask: 1977 case X86::BI__builtin_ia32_extracti32x8_mask: 1978 case X86::BI__builtin_ia32_extractf64x2_256_mask: 1979 case X86::BI__builtin_ia32_extracti64x2_256_mask: 1980 case X86::BI__builtin_ia32_extractf32x4_256_mask: 1981 case X86::BI__builtin_ia32_extracti32x4_256_mask: 1982 i = 1; l = 0; u = 1; 1983 break; 1984 case X86::BI_mm_prefetch: 1985 case X86::BI__builtin_ia32_extractf32x4_mask: 1986 case X86::BI__builtin_ia32_extracti32x4_mask: 1987 case X86::BI__builtin_ia32_extractf64x2_512_mask: 1988 case X86::BI__builtin_ia32_extracti64x2_512_mask: 1989 i = 1; l = 0; u = 3; 1990 break; 1991 case X86::BI__builtin_ia32_insertf32x8_mask: 1992 case X86::BI__builtin_ia32_inserti32x8_mask: 1993 case X86::BI__builtin_ia32_insertf64x4_mask: 1994 case X86::BI__builtin_ia32_inserti64x4_mask: 1995 case X86::BI__builtin_ia32_insertf64x2_256_mask: 1996 case X86::BI__builtin_ia32_inserti64x2_256_mask: 1997 case X86::BI__builtin_ia32_insertf32x4_256_mask: 1998 case X86::BI__builtin_ia32_inserti32x4_256_mask: 1999 i = 2; l = 0; u = 1; 2000 break; 2001 case X86::BI__builtin_ia32_sha1rnds4: 2002 case X86::BI__builtin_ia32_shuf_f32x4_256_mask: 2003 case X86::BI__builtin_ia32_shuf_f64x2_256_mask: 2004 case X86::BI__builtin_ia32_shuf_i32x4_256_mask: 2005 case X86::BI__builtin_ia32_shuf_i64x2_256_mask: 2006 case X86::BI__builtin_ia32_insertf64x2_512_mask: 2007 case X86::BI__builtin_ia32_inserti64x2_512_mask: 2008 case X86::BI__builtin_ia32_insertf32x4_mask: 2009 case X86::BI__builtin_ia32_inserti32x4_mask: 2010 i = 2; l = 0; u = 3; 2011 break; 2012 case X86::BI__builtin_ia32_vpermil2pd: 2013 case X86::BI__builtin_ia32_vpermil2pd256: 2014 case X86::BI__builtin_ia32_vpermil2ps: 2015 case X86::BI__builtin_ia32_vpermil2ps256: 2016 i = 3; l = 0; u = 3; 2017 break; 2018 case X86::BI__builtin_ia32_cmpb128_mask: 2019 case X86::BI__builtin_ia32_cmpw128_mask: 2020 case X86::BI__builtin_ia32_cmpd128_mask: 2021 case X86::BI__builtin_ia32_cmpq128_mask: 2022 case X86::BI__builtin_ia32_cmpb256_mask: 2023 case X86::BI__builtin_ia32_cmpw256_mask: 2024 case X86::BI__builtin_ia32_cmpd256_mask: 2025 case X86::BI__builtin_ia32_cmpq256_mask: 2026 case X86::BI__builtin_ia32_cmpb512_mask: 2027 case X86::BI__builtin_ia32_cmpw512_mask: 2028 case X86::BI__builtin_ia32_cmpd512_mask: 2029 case X86::BI__builtin_ia32_cmpq512_mask: 2030 case X86::BI__builtin_ia32_ucmpb128_mask: 2031 case X86::BI__builtin_ia32_ucmpw128_mask: 2032 case X86::BI__builtin_ia32_ucmpd128_mask: 2033 case X86::BI__builtin_ia32_ucmpq128_mask: 2034 case X86::BI__builtin_ia32_ucmpb256_mask: 2035 case X86::BI__builtin_ia32_ucmpw256_mask: 2036 case X86::BI__builtin_ia32_ucmpd256_mask: 2037 case X86::BI__builtin_ia32_ucmpq256_mask: 2038 case X86::BI__builtin_ia32_ucmpb512_mask: 2039 case X86::BI__builtin_ia32_ucmpw512_mask: 2040 case X86::BI__builtin_ia32_ucmpd512_mask: 2041 case X86::BI__builtin_ia32_ucmpq512_mask: 2042 case X86::BI__builtin_ia32_vpcomub: 2043 case X86::BI__builtin_ia32_vpcomuw: 2044 case X86::BI__builtin_ia32_vpcomud: 2045 case X86::BI__builtin_ia32_vpcomuq: 2046 case X86::BI__builtin_ia32_vpcomb: 2047 case X86::BI__builtin_ia32_vpcomw: 2048 case X86::BI__builtin_ia32_vpcomd: 2049 case X86::BI__builtin_ia32_vpcomq: 2050 i = 2; l = 0; u = 7; 2051 break; 2052 case X86::BI__builtin_ia32_roundps: 2053 case X86::BI__builtin_ia32_roundpd: 2054 case X86::BI__builtin_ia32_roundps256: 2055 case X86::BI__builtin_ia32_roundpd256: 2056 i = 1; l = 0; u = 15; 2057 break; 2058 case X86::BI__builtin_ia32_roundss: 2059 case X86::BI__builtin_ia32_roundsd: 2060 case X86::BI__builtin_ia32_rangepd128_mask: 2061 case X86::BI__builtin_ia32_rangepd256_mask: 2062 case X86::BI__builtin_ia32_rangepd512_mask: 2063 case X86::BI__builtin_ia32_rangeps128_mask: 2064 case X86::BI__builtin_ia32_rangeps256_mask: 2065 case X86::BI__builtin_ia32_rangeps512_mask: 2066 case X86::BI__builtin_ia32_getmantsd_round_mask: 2067 case X86::BI__builtin_ia32_getmantss_round_mask: 2068 i = 2; l = 0; u = 15; 2069 break; 2070 case X86::BI__builtin_ia32_cmpps: 2071 case X86::BI__builtin_ia32_cmpss: 2072 case X86::BI__builtin_ia32_cmppd: 2073 case X86::BI__builtin_ia32_cmpsd: 2074 case X86::BI__builtin_ia32_cmpps256: 2075 case X86::BI__builtin_ia32_cmppd256: 2076 case X86::BI__builtin_ia32_cmpps128_mask: 2077 case X86::BI__builtin_ia32_cmppd128_mask: 2078 case X86::BI__builtin_ia32_cmpps256_mask: 2079 case X86::BI__builtin_ia32_cmppd256_mask: 2080 case X86::BI__builtin_ia32_cmpps512_mask: 2081 case X86::BI__builtin_ia32_cmppd512_mask: 2082 case X86::BI__builtin_ia32_cmpsd_mask: 2083 case X86::BI__builtin_ia32_cmpss_mask: 2084 i = 2; l = 0; u = 31; 2085 break; 2086 case X86::BI__builtin_ia32_xabort: 2087 i = 0; l = -128; u = 255; 2088 break; 2089 case X86::BI__builtin_ia32_pshufw: 2090 case X86::BI__builtin_ia32_aeskeygenassist128: 2091 i = 1; l = -128; u = 255; 2092 break; 2093 case X86::BI__builtin_ia32_vcvtps2ph: 2094 case X86::BI__builtin_ia32_vcvtps2ph256: 2095 case X86::BI__builtin_ia32_rndscaleps_128_mask: 2096 case X86::BI__builtin_ia32_rndscalepd_128_mask: 2097 case X86::BI__builtin_ia32_rndscaleps_256_mask: 2098 case X86::BI__builtin_ia32_rndscalepd_256_mask: 2099 case X86::BI__builtin_ia32_rndscaleps_mask: 2100 case X86::BI__builtin_ia32_rndscalepd_mask: 2101 case X86::BI__builtin_ia32_reducepd128_mask: 2102 case X86::BI__builtin_ia32_reducepd256_mask: 2103 case X86::BI__builtin_ia32_reducepd512_mask: 2104 case X86::BI__builtin_ia32_reduceps128_mask: 2105 case X86::BI__builtin_ia32_reduceps256_mask: 2106 case X86::BI__builtin_ia32_reduceps512_mask: 2107 case X86::BI__builtin_ia32_prold512_mask: 2108 case X86::BI__builtin_ia32_prolq512_mask: 2109 case X86::BI__builtin_ia32_prold128_mask: 2110 case X86::BI__builtin_ia32_prold256_mask: 2111 case X86::BI__builtin_ia32_prolq128_mask: 2112 case X86::BI__builtin_ia32_prolq256_mask: 2113 case X86::BI__builtin_ia32_prord128_mask: 2114 case X86::BI__builtin_ia32_prord256_mask: 2115 case X86::BI__builtin_ia32_prorq128_mask: 2116 case X86::BI__builtin_ia32_prorq256_mask: 2117 case X86::BI__builtin_ia32_psllwi512_mask: 2118 case X86::BI__builtin_ia32_psllwi128_mask: 2119 case X86::BI__builtin_ia32_psllwi256_mask: 2120 case X86::BI__builtin_ia32_psrldi128_mask: 2121 case X86::BI__builtin_ia32_psrldi256_mask: 2122 case X86::BI__builtin_ia32_psrldi512_mask: 2123 case X86::BI__builtin_ia32_psrlqi128_mask: 2124 case X86::BI__builtin_ia32_psrlqi256_mask: 2125 case X86::BI__builtin_ia32_psrlqi512_mask: 2126 case X86::BI__builtin_ia32_psrawi512_mask: 2127 case X86::BI__builtin_ia32_psrawi128_mask: 2128 case X86::BI__builtin_ia32_psrawi256_mask: 2129 case X86::BI__builtin_ia32_psrlwi512_mask: 2130 case X86::BI__builtin_ia32_psrlwi128_mask: 2131 case X86::BI__builtin_ia32_psrlwi256_mask: 2132 case X86::BI__builtin_ia32_psradi128_mask: 2133 case X86::BI__builtin_ia32_psradi256_mask: 2134 case X86::BI__builtin_ia32_psradi512_mask: 2135 case X86::BI__builtin_ia32_psraqi128_mask: 2136 case X86::BI__builtin_ia32_psraqi256_mask: 2137 case X86::BI__builtin_ia32_psraqi512_mask: 2138 case X86::BI__builtin_ia32_pslldi128_mask: 2139 case X86::BI__builtin_ia32_pslldi256_mask: 2140 case X86::BI__builtin_ia32_pslldi512_mask: 2141 case X86::BI__builtin_ia32_psllqi128_mask: 2142 case X86::BI__builtin_ia32_psllqi256_mask: 2143 case X86::BI__builtin_ia32_psllqi512_mask: 2144 case X86::BI__builtin_ia32_fpclasspd128_mask: 2145 case X86::BI__builtin_ia32_fpclasspd256_mask: 2146 case X86::BI__builtin_ia32_fpclassps128_mask: 2147 case X86::BI__builtin_ia32_fpclassps256_mask: 2148 case X86::BI__builtin_ia32_fpclassps512_mask: 2149 case X86::BI__builtin_ia32_fpclasspd512_mask: 2150 case X86::BI__builtin_ia32_fpclasssd_mask: 2151 case X86::BI__builtin_ia32_fpclassss_mask: 2152 i = 1; l = 0; u = 255; 2153 break; 2154 case X86::BI__builtin_ia32_palignr: 2155 case X86::BI__builtin_ia32_insertps128: 2156 case X86::BI__builtin_ia32_dpps: 2157 case X86::BI__builtin_ia32_dppd: 2158 case X86::BI__builtin_ia32_dpps256: 2159 case X86::BI__builtin_ia32_mpsadbw128: 2160 case X86::BI__builtin_ia32_mpsadbw256: 2161 case X86::BI__builtin_ia32_pcmpistrm128: 2162 case X86::BI__builtin_ia32_pcmpistri128: 2163 case X86::BI__builtin_ia32_pcmpistria128: 2164 case X86::BI__builtin_ia32_pcmpistric128: 2165 case X86::BI__builtin_ia32_pcmpistrio128: 2166 case X86::BI__builtin_ia32_pcmpistris128: 2167 case X86::BI__builtin_ia32_pcmpistriz128: 2168 case X86::BI__builtin_ia32_pclmulqdq128: 2169 case X86::BI__builtin_ia32_vperm2f128_pd256: 2170 case X86::BI__builtin_ia32_vperm2f128_ps256: 2171 case X86::BI__builtin_ia32_vperm2f128_si256: 2172 case X86::BI__builtin_ia32_permti256: 2173 i = 2; l = -128; u = 255; 2174 break; 2175 case X86::BI__builtin_ia32_palignr128: 2176 case X86::BI__builtin_ia32_palignr256: 2177 case X86::BI__builtin_ia32_palignr512_mask: 2178 case X86::BI__builtin_ia32_alignq512_mask: 2179 case X86::BI__builtin_ia32_alignd512_mask: 2180 case X86::BI__builtin_ia32_alignd128_mask: 2181 case X86::BI__builtin_ia32_alignd256_mask: 2182 case X86::BI__builtin_ia32_alignq128_mask: 2183 case X86::BI__builtin_ia32_alignq256_mask: 2184 case X86::BI__builtin_ia32_vcomisd: 2185 case X86::BI__builtin_ia32_vcomiss: 2186 case X86::BI__builtin_ia32_shuf_f32x4_mask: 2187 case X86::BI__builtin_ia32_shuf_f64x2_mask: 2188 case X86::BI__builtin_ia32_shuf_i32x4_mask: 2189 case X86::BI__builtin_ia32_shuf_i64x2_mask: 2190 case X86::BI__builtin_ia32_dbpsadbw128_mask: 2191 case X86::BI__builtin_ia32_dbpsadbw256_mask: 2192 case X86::BI__builtin_ia32_dbpsadbw512_mask: 2193 i = 2; l = 0; u = 255; 2194 break; 2195 case X86::BI__builtin_ia32_fixupimmpd512_mask: 2196 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 2197 case X86::BI__builtin_ia32_fixupimmps512_mask: 2198 case X86::BI__builtin_ia32_fixupimmps512_maskz: 2199 case X86::BI__builtin_ia32_fixupimmsd_mask: 2200 case X86::BI__builtin_ia32_fixupimmsd_maskz: 2201 case X86::BI__builtin_ia32_fixupimmss_mask: 2202 case X86::BI__builtin_ia32_fixupimmss_maskz: 2203 case X86::BI__builtin_ia32_fixupimmpd128_mask: 2204 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 2205 case X86::BI__builtin_ia32_fixupimmpd256_mask: 2206 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 2207 case X86::BI__builtin_ia32_fixupimmps128_mask: 2208 case X86::BI__builtin_ia32_fixupimmps128_maskz: 2209 case X86::BI__builtin_ia32_fixupimmps256_mask: 2210 case X86::BI__builtin_ia32_fixupimmps256_maskz: 2211 case X86::BI__builtin_ia32_pternlogd512_mask: 2212 case X86::BI__builtin_ia32_pternlogd512_maskz: 2213 case X86::BI__builtin_ia32_pternlogq512_mask: 2214 case X86::BI__builtin_ia32_pternlogq512_maskz: 2215 case X86::BI__builtin_ia32_pternlogd128_mask: 2216 case X86::BI__builtin_ia32_pternlogd128_maskz: 2217 case X86::BI__builtin_ia32_pternlogd256_mask: 2218 case X86::BI__builtin_ia32_pternlogd256_maskz: 2219 case X86::BI__builtin_ia32_pternlogq128_mask: 2220 case X86::BI__builtin_ia32_pternlogq128_maskz: 2221 case X86::BI__builtin_ia32_pternlogq256_mask: 2222 case X86::BI__builtin_ia32_pternlogq256_maskz: 2223 i = 3; l = 0; u = 255; 2224 break; 2225 case X86::BI__builtin_ia32_pcmpestrm128: 2226 case X86::BI__builtin_ia32_pcmpestri128: 2227 case X86::BI__builtin_ia32_pcmpestria128: 2228 case X86::BI__builtin_ia32_pcmpestric128: 2229 case X86::BI__builtin_ia32_pcmpestrio128: 2230 case X86::BI__builtin_ia32_pcmpestris128: 2231 case X86::BI__builtin_ia32_pcmpestriz128: 2232 i = 4; l = -128; u = 255; 2233 break; 2234 case X86::BI__builtin_ia32_rndscalesd_round_mask: 2235 case X86::BI__builtin_ia32_rndscaless_round_mask: 2236 i = 4; l = 0; u = 255; 2237 break; 2238 } 2239 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 2240 } 2241 2242 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 2243 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 2244 /// Returns true when the format fits the function and the FormatStringInfo has 2245 /// been populated. 2246 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 2247 FormatStringInfo *FSI) { 2248 FSI->HasVAListArg = Format->getFirstArg() == 0; 2249 FSI->FormatIdx = Format->getFormatIdx() - 1; 2250 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 2251 2252 // The way the format attribute works in GCC, the implicit this argument 2253 // of member functions is counted. However, it doesn't appear in our own 2254 // lists, so decrement format_idx in that case. 2255 if (IsCXXMember) { 2256 if(FSI->FormatIdx == 0) 2257 return false; 2258 --FSI->FormatIdx; 2259 if (FSI->FirstDataArg != 0) 2260 --FSI->FirstDataArg; 2261 } 2262 return true; 2263 } 2264 2265 /// Checks if a the given expression evaluates to null. 2266 /// 2267 /// \brief Returns true if the value evaluates to null. 2268 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 2269 // If the expression has non-null type, it doesn't evaluate to null. 2270 if (auto nullability 2271 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 2272 if (*nullability == NullabilityKind::NonNull) 2273 return false; 2274 } 2275 2276 // As a special case, transparent unions initialized with zero are 2277 // considered null for the purposes of the nonnull attribute. 2278 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 2279 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 2280 if (const CompoundLiteralExpr *CLE = 2281 dyn_cast<CompoundLiteralExpr>(Expr)) 2282 if (const InitListExpr *ILE = 2283 dyn_cast<InitListExpr>(CLE->getInitializer())) 2284 Expr = ILE->getInit(0); 2285 } 2286 2287 bool Result; 2288 return (!Expr->isValueDependent() && 2289 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 2290 !Result); 2291 } 2292 2293 static void CheckNonNullArgument(Sema &S, 2294 const Expr *ArgExpr, 2295 SourceLocation CallSiteLoc) { 2296 if (CheckNonNullExpr(S, ArgExpr)) 2297 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 2298 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange()); 2299 } 2300 2301 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 2302 FormatStringInfo FSI; 2303 if ((GetFormatStringType(Format) == FST_NSString) && 2304 getFormatStringInfo(Format, false, &FSI)) { 2305 Idx = FSI.FormatIdx; 2306 return true; 2307 } 2308 return false; 2309 } 2310 /// \brief Diagnose use of %s directive in an NSString which is being passed 2311 /// as formatting string to formatting method. 2312 static void 2313 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 2314 const NamedDecl *FDecl, 2315 Expr **Args, 2316 unsigned NumArgs) { 2317 unsigned Idx = 0; 2318 bool Format = false; 2319 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 2320 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 2321 Idx = 2; 2322 Format = true; 2323 } 2324 else 2325 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 2326 if (S.GetFormatNSStringIdx(I, Idx)) { 2327 Format = true; 2328 break; 2329 } 2330 } 2331 if (!Format || NumArgs <= Idx) 2332 return; 2333 const Expr *FormatExpr = Args[Idx]; 2334 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 2335 FormatExpr = CSCE->getSubExpr(); 2336 const StringLiteral *FormatString; 2337 if (const ObjCStringLiteral *OSL = 2338 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 2339 FormatString = OSL->getString(); 2340 else 2341 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 2342 if (!FormatString) 2343 return; 2344 if (S.FormatStringHasSArg(FormatString)) { 2345 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 2346 << "%s" << 1 << 1; 2347 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 2348 << FDecl->getDeclName(); 2349 } 2350 } 2351 2352 /// Determine whether the given type has a non-null nullability annotation. 2353 static bool isNonNullType(ASTContext &ctx, QualType type) { 2354 if (auto nullability = type->getNullability(ctx)) 2355 return *nullability == NullabilityKind::NonNull; 2356 2357 return false; 2358 } 2359 2360 static void CheckNonNullArguments(Sema &S, 2361 const NamedDecl *FDecl, 2362 const FunctionProtoType *Proto, 2363 ArrayRef<const Expr *> Args, 2364 SourceLocation CallSiteLoc) { 2365 assert((FDecl || Proto) && "Need a function declaration or prototype"); 2366 2367 // Check the attributes attached to the method/function itself. 2368 llvm::SmallBitVector NonNullArgs; 2369 if (FDecl) { 2370 // Handle the nonnull attribute on the function/method declaration itself. 2371 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 2372 if (!NonNull->args_size()) { 2373 // Easy case: all pointer arguments are nonnull. 2374 for (const auto *Arg : Args) 2375 if (S.isValidPointerAttrType(Arg->getType())) 2376 CheckNonNullArgument(S, Arg, CallSiteLoc); 2377 return; 2378 } 2379 2380 for (unsigned Val : NonNull->args()) { 2381 if (Val >= Args.size()) 2382 continue; 2383 if (NonNullArgs.empty()) 2384 NonNullArgs.resize(Args.size()); 2385 NonNullArgs.set(Val); 2386 } 2387 } 2388 } 2389 2390 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 2391 // Handle the nonnull attribute on the parameters of the 2392 // function/method. 2393 ArrayRef<ParmVarDecl*> parms; 2394 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 2395 parms = FD->parameters(); 2396 else 2397 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 2398 2399 unsigned ParamIndex = 0; 2400 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 2401 I != E; ++I, ++ParamIndex) { 2402 const ParmVarDecl *PVD = *I; 2403 if (PVD->hasAttr<NonNullAttr>() || 2404 isNonNullType(S.Context, PVD->getType())) { 2405 if (NonNullArgs.empty()) 2406 NonNullArgs.resize(Args.size()); 2407 2408 NonNullArgs.set(ParamIndex); 2409 } 2410 } 2411 } else { 2412 // If we have a non-function, non-method declaration but no 2413 // function prototype, try to dig out the function prototype. 2414 if (!Proto) { 2415 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 2416 QualType type = VD->getType().getNonReferenceType(); 2417 if (auto pointerType = type->getAs<PointerType>()) 2418 type = pointerType->getPointeeType(); 2419 else if (auto blockType = type->getAs<BlockPointerType>()) 2420 type = blockType->getPointeeType(); 2421 // FIXME: data member pointers? 2422 2423 // Dig out the function prototype, if there is one. 2424 Proto = type->getAs<FunctionProtoType>(); 2425 } 2426 } 2427 2428 // Fill in non-null argument information from the nullability 2429 // information on the parameter types (if we have them). 2430 if (Proto) { 2431 unsigned Index = 0; 2432 for (auto paramType : Proto->getParamTypes()) { 2433 if (isNonNullType(S.Context, paramType)) { 2434 if (NonNullArgs.empty()) 2435 NonNullArgs.resize(Args.size()); 2436 2437 NonNullArgs.set(Index); 2438 } 2439 2440 ++Index; 2441 } 2442 } 2443 } 2444 2445 // Check for non-null arguments. 2446 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 2447 ArgIndex != ArgIndexEnd; ++ArgIndex) { 2448 if (NonNullArgs[ArgIndex]) 2449 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 2450 } 2451 } 2452 2453 /// Handles the checks for format strings, non-POD arguments to vararg 2454 /// functions, and NULL arguments passed to non-NULL parameters. 2455 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 2456 ArrayRef<const Expr *> Args, bool IsMemberFunction, 2457 SourceLocation Loc, SourceRange Range, 2458 VariadicCallType CallType) { 2459 // FIXME: We should check as much as we can in the template definition. 2460 if (CurContext->isDependentContext()) 2461 return; 2462 2463 // Printf and scanf checking. 2464 llvm::SmallBitVector CheckedVarArgs; 2465 if (FDecl) { 2466 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 2467 // Only create vector if there are format attributes. 2468 CheckedVarArgs.resize(Args.size()); 2469 2470 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 2471 CheckedVarArgs); 2472 } 2473 } 2474 2475 // Refuse POD arguments that weren't caught by the format string 2476 // checks above. 2477 if (CallType != VariadicDoesNotApply) { 2478 unsigned NumParams = Proto ? Proto->getNumParams() 2479 : FDecl && isa<FunctionDecl>(FDecl) 2480 ? cast<FunctionDecl>(FDecl)->getNumParams() 2481 : FDecl && isa<ObjCMethodDecl>(FDecl) 2482 ? cast<ObjCMethodDecl>(FDecl)->param_size() 2483 : 0; 2484 2485 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 2486 // Args[ArgIdx] can be null in malformed code. 2487 if (const Expr *Arg = Args[ArgIdx]) { 2488 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 2489 checkVariadicArgument(Arg, CallType); 2490 } 2491 } 2492 } 2493 2494 if (FDecl || Proto) { 2495 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 2496 2497 // Type safety checking. 2498 if (FDecl) { 2499 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 2500 CheckArgumentWithTypeTag(I, Args.data()); 2501 } 2502 } 2503 } 2504 2505 /// CheckConstructorCall - Check a constructor call for correctness and safety 2506 /// properties not enforced by the C type system. 2507 void Sema::CheckConstructorCall(FunctionDecl *FDecl, 2508 ArrayRef<const Expr *> Args, 2509 const FunctionProtoType *Proto, 2510 SourceLocation Loc) { 2511 VariadicCallType CallType = 2512 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 2513 checkCall(FDecl, Proto, Args, /*IsMemberFunction=*/true, Loc, SourceRange(), 2514 CallType); 2515 } 2516 2517 /// CheckFunctionCall - Check a direct function call for various correctness 2518 /// and safety properties not strictly enforced by the C type system. 2519 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 2520 const FunctionProtoType *Proto) { 2521 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 2522 isa<CXXMethodDecl>(FDecl); 2523 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 2524 IsMemberOperatorCall; 2525 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 2526 TheCall->getCallee()); 2527 Expr** Args = TheCall->getArgs(); 2528 unsigned NumArgs = TheCall->getNumArgs(); 2529 if (IsMemberOperatorCall) { 2530 // If this is a call to a member operator, hide the first argument 2531 // from checkCall. 2532 // FIXME: Our choice of AST representation here is less than ideal. 2533 ++Args; 2534 --NumArgs; 2535 } 2536 checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs), 2537 IsMemberFunction, TheCall->getRParenLoc(), 2538 TheCall->getCallee()->getSourceRange(), CallType); 2539 2540 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 2541 // None of the checks below are needed for functions that don't have 2542 // simple names (e.g., C++ conversion functions). 2543 if (!FnInfo) 2544 return false; 2545 2546 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo); 2547 if (getLangOpts().ObjC1) 2548 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 2549 2550 unsigned CMId = FDecl->getMemoryFunctionKind(); 2551 if (CMId == 0) 2552 return false; 2553 2554 // Handle memory setting and copying functions. 2555 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 2556 CheckStrlcpycatArguments(TheCall, FnInfo); 2557 else if (CMId == Builtin::BIstrncat) 2558 CheckStrncatArguments(TheCall, FnInfo); 2559 else 2560 CheckMemaccessArguments(TheCall, CMId, FnInfo); 2561 2562 return false; 2563 } 2564 2565 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 2566 ArrayRef<const Expr *> Args) { 2567 VariadicCallType CallType = 2568 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 2569 2570 checkCall(Method, nullptr, Args, 2571 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 2572 CallType); 2573 2574 return false; 2575 } 2576 2577 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 2578 const FunctionProtoType *Proto) { 2579 QualType Ty; 2580 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 2581 Ty = V->getType().getNonReferenceType(); 2582 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 2583 Ty = F->getType().getNonReferenceType(); 2584 else 2585 return false; 2586 2587 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 2588 !Ty->isFunctionProtoType()) 2589 return false; 2590 2591 VariadicCallType CallType; 2592 if (!Proto || !Proto->isVariadic()) { 2593 CallType = VariadicDoesNotApply; 2594 } else if (Ty->isBlockPointerType()) { 2595 CallType = VariadicBlock; 2596 } else { // Ty->isFunctionPointerType() 2597 CallType = VariadicFunction; 2598 } 2599 2600 checkCall(NDecl, Proto, 2601 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 2602 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 2603 TheCall->getCallee()->getSourceRange(), CallType); 2604 2605 return false; 2606 } 2607 2608 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 2609 /// such as function pointers returned from functions. 2610 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 2611 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 2612 TheCall->getCallee()); 2613 checkCall(/*FDecl=*/nullptr, Proto, 2614 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 2615 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 2616 TheCall->getCallee()->getSourceRange(), CallType); 2617 2618 return false; 2619 } 2620 2621 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 2622 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 2623 return false; 2624 2625 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 2626 switch (Op) { 2627 case AtomicExpr::AO__c11_atomic_init: 2628 llvm_unreachable("There is no ordering argument for an init"); 2629 2630 case AtomicExpr::AO__c11_atomic_load: 2631 case AtomicExpr::AO__atomic_load_n: 2632 case AtomicExpr::AO__atomic_load: 2633 return OrderingCABI != llvm::AtomicOrderingCABI::release && 2634 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 2635 2636 case AtomicExpr::AO__c11_atomic_store: 2637 case AtomicExpr::AO__atomic_store: 2638 case AtomicExpr::AO__atomic_store_n: 2639 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 2640 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 2641 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 2642 2643 default: 2644 return true; 2645 } 2646 } 2647 2648 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 2649 AtomicExpr::AtomicOp Op) { 2650 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 2651 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 2652 2653 // All these operations take one of the following forms: 2654 enum { 2655 // C __c11_atomic_init(A *, C) 2656 Init, 2657 // C __c11_atomic_load(A *, int) 2658 Load, 2659 // void __atomic_load(A *, CP, int) 2660 LoadCopy, 2661 // void __atomic_store(A *, CP, int) 2662 Copy, 2663 // C __c11_atomic_add(A *, M, int) 2664 Arithmetic, 2665 // C __atomic_exchange_n(A *, CP, int) 2666 Xchg, 2667 // void __atomic_exchange(A *, C *, CP, int) 2668 GNUXchg, 2669 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 2670 C11CmpXchg, 2671 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 2672 GNUCmpXchg 2673 } Form = Init; 2674 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 2675 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 2676 // where: 2677 // C is an appropriate type, 2678 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 2679 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 2680 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 2681 // the int parameters are for orderings. 2682 2683 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 2684 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == 2685 AtomicExpr::AO__atomic_load, 2686 "need to update code for modified C11 atomics"); 2687 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init && 2688 Op <= AtomicExpr::AO__c11_atomic_fetch_xor; 2689 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 2690 Op == AtomicExpr::AO__atomic_store_n || 2691 Op == AtomicExpr::AO__atomic_exchange_n || 2692 Op == AtomicExpr::AO__atomic_compare_exchange_n; 2693 bool IsAddSub = false; 2694 2695 switch (Op) { 2696 case AtomicExpr::AO__c11_atomic_init: 2697 Form = Init; 2698 break; 2699 2700 case AtomicExpr::AO__c11_atomic_load: 2701 case AtomicExpr::AO__atomic_load_n: 2702 Form = Load; 2703 break; 2704 2705 case AtomicExpr::AO__atomic_load: 2706 Form = LoadCopy; 2707 break; 2708 2709 case AtomicExpr::AO__c11_atomic_store: 2710 case AtomicExpr::AO__atomic_store: 2711 case AtomicExpr::AO__atomic_store_n: 2712 Form = Copy; 2713 break; 2714 2715 case AtomicExpr::AO__c11_atomic_fetch_add: 2716 case AtomicExpr::AO__c11_atomic_fetch_sub: 2717 case AtomicExpr::AO__atomic_fetch_add: 2718 case AtomicExpr::AO__atomic_fetch_sub: 2719 case AtomicExpr::AO__atomic_add_fetch: 2720 case AtomicExpr::AO__atomic_sub_fetch: 2721 IsAddSub = true; 2722 // Fall through. 2723 case AtomicExpr::AO__c11_atomic_fetch_and: 2724 case AtomicExpr::AO__c11_atomic_fetch_or: 2725 case AtomicExpr::AO__c11_atomic_fetch_xor: 2726 case AtomicExpr::AO__atomic_fetch_and: 2727 case AtomicExpr::AO__atomic_fetch_or: 2728 case AtomicExpr::AO__atomic_fetch_xor: 2729 case AtomicExpr::AO__atomic_fetch_nand: 2730 case AtomicExpr::AO__atomic_and_fetch: 2731 case AtomicExpr::AO__atomic_or_fetch: 2732 case AtomicExpr::AO__atomic_xor_fetch: 2733 case AtomicExpr::AO__atomic_nand_fetch: 2734 Form = Arithmetic; 2735 break; 2736 2737 case AtomicExpr::AO__c11_atomic_exchange: 2738 case AtomicExpr::AO__atomic_exchange_n: 2739 Form = Xchg; 2740 break; 2741 2742 case AtomicExpr::AO__atomic_exchange: 2743 Form = GNUXchg; 2744 break; 2745 2746 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 2747 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 2748 Form = C11CmpXchg; 2749 break; 2750 2751 case AtomicExpr::AO__atomic_compare_exchange: 2752 case AtomicExpr::AO__atomic_compare_exchange_n: 2753 Form = GNUCmpXchg; 2754 break; 2755 } 2756 2757 // Check we have the right number of arguments. 2758 if (TheCall->getNumArgs() < NumArgs[Form]) { 2759 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 2760 << 0 << NumArgs[Form] << TheCall->getNumArgs() 2761 << TheCall->getCallee()->getSourceRange(); 2762 return ExprError(); 2763 } else if (TheCall->getNumArgs() > NumArgs[Form]) { 2764 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(), 2765 diag::err_typecheck_call_too_many_args) 2766 << 0 << NumArgs[Form] << TheCall->getNumArgs() 2767 << TheCall->getCallee()->getSourceRange(); 2768 return ExprError(); 2769 } 2770 2771 // Inspect the first argument of the atomic operation. 2772 Expr *Ptr = TheCall->getArg(0); 2773 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 2774 if (ConvertedPtr.isInvalid()) 2775 return ExprError(); 2776 2777 Ptr = ConvertedPtr.get(); 2778 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 2779 if (!pointerType) { 2780 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 2781 << Ptr->getType() << Ptr->getSourceRange(); 2782 return ExprError(); 2783 } 2784 2785 // For a __c11 builtin, this should be a pointer to an _Atomic type. 2786 QualType AtomTy = pointerType->getPointeeType(); // 'A' 2787 QualType ValType = AtomTy; // 'C' 2788 if (IsC11) { 2789 if (!AtomTy->isAtomicType()) { 2790 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic) 2791 << Ptr->getType() << Ptr->getSourceRange(); 2792 return ExprError(); 2793 } 2794 if (AtomTy.isConstQualified()) { 2795 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic) 2796 << Ptr->getType() << Ptr->getSourceRange(); 2797 return ExprError(); 2798 } 2799 ValType = AtomTy->getAs<AtomicType>()->getValueType(); 2800 } else if (Form != Load && Form != LoadCopy) { 2801 if (ValType.isConstQualified()) { 2802 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer) 2803 << Ptr->getType() << Ptr->getSourceRange(); 2804 return ExprError(); 2805 } 2806 } 2807 2808 // For an arithmetic operation, the implied arithmetic must be well-formed. 2809 if (Form == Arithmetic) { 2810 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 2811 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) { 2812 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 2813 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 2814 return ExprError(); 2815 } 2816 if (!IsAddSub && !ValType->isIntegerType()) { 2817 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int) 2818 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 2819 return ExprError(); 2820 } 2821 if (IsC11 && ValType->isPointerType() && 2822 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(), 2823 diag::err_incomplete_type)) { 2824 return ExprError(); 2825 } 2826 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 2827 // For __atomic_*_n operations, the value type must be a scalar integral or 2828 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 2829 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 2830 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 2831 return ExprError(); 2832 } 2833 2834 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 2835 !AtomTy->isScalarType()) { 2836 // For GNU atomics, require a trivially-copyable type. This is not part of 2837 // the GNU atomics specification, but we enforce it for sanity. 2838 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy) 2839 << Ptr->getType() << Ptr->getSourceRange(); 2840 return ExprError(); 2841 } 2842 2843 switch (ValType.getObjCLifetime()) { 2844 case Qualifiers::OCL_None: 2845 case Qualifiers::OCL_ExplicitNone: 2846 // okay 2847 break; 2848 2849 case Qualifiers::OCL_Weak: 2850 case Qualifiers::OCL_Strong: 2851 case Qualifiers::OCL_Autoreleasing: 2852 // FIXME: Can this happen? By this point, ValType should be known 2853 // to be trivially copyable. 2854 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 2855 << ValType << Ptr->getSourceRange(); 2856 return ExprError(); 2857 } 2858 2859 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the 2860 // volatile-ness of the pointee-type inject itself into the result or the 2861 // other operands. Similarly atomic_load can take a pointer to a const 'A'. 2862 ValType.removeLocalVolatile(); 2863 ValType.removeLocalConst(); 2864 QualType ResultType = ValType; 2865 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init) 2866 ResultType = Context.VoidTy; 2867 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 2868 ResultType = Context.BoolTy; 2869 2870 // The type of a parameter passed 'by value'. In the GNU atomics, such 2871 // arguments are actually passed as pointers. 2872 QualType ByValType = ValType; // 'CP' 2873 if (!IsC11 && !IsN) 2874 ByValType = Ptr->getType(); 2875 2876 // The first argument --- the pointer --- has a fixed type; we 2877 // deduce the types of the rest of the arguments accordingly. Walk 2878 // the remaining arguments, converting them to the deduced value type. 2879 for (unsigned i = 1; i != NumArgs[Form]; ++i) { 2880 QualType Ty; 2881 if (i < NumVals[Form] + 1) { 2882 switch (i) { 2883 case 1: 2884 // The second argument is the non-atomic operand. For arithmetic, this 2885 // is always passed by value, and for a compare_exchange it is always 2886 // passed by address. For the rest, GNU uses by-address and C11 uses 2887 // by-value. 2888 assert(Form != Load); 2889 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 2890 Ty = ValType; 2891 else if (Form == Copy || Form == Xchg) 2892 Ty = ByValType; 2893 else if (Form == Arithmetic) 2894 Ty = Context.getPointerDiffType(); 2895 else { 2896 Expr *ValArg = TheCall->getArg(i); 2897 unsigned AS = 0; 2898 // Keep address space of non-atomic pointer type. 2899 if (const PointerType *PtrTy = 2900 ValArg->getType()->getAs<PointerType>()) { 2901 AS = PtrTy->getPointeeType().getAddressSpace(); 2902 } 2903 Ty = Context.getPointerType( 2904 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 2905 } 2906 break; 2907 case 2: 2908 // The third argument to compare_exchange / GNU exchange is a 2909 // (pointer to a) desired value. 2910 Ty = ByValType; 2911 break; 2912 case 3: 2913 // The fourth argument to GNU compare_exchange is a 'weak' flag. 2914 Ty = Context.BoolTy; 2915 break; 2916 } 2917 } else { 2918 // The order(s) are always converted to int. 2919 Ty = Context.IntTy; 2920 } 2921 2922 InitializedEntity Entity = 2923 InitializedEntity::InitializeParameter(Context, Ty, false); 2924 ExprResult Arg = TheCall->getArg(i); 2925 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 2926 if (Arg.isInvalid()) 2927 return true; 2928 TheCall->setArg(i, Arg.get()); 2929 } 2930 2931 // Permute the arguments into a 'consistent' order. 2932 SmallVector<Expr*, 5> SubExprs; 2933 SubExprs.push_back(Ptr); 2934 switch (Form) { 2935 case Init: 2936 // Note, AtomicExpr::getVal1() has a special case for this atomic. 2937 SubExprs.push_back(TheCall->getArg(1)); // Val1 2938 break; 2939 case Load: 2940 SubExprs.push_back(TheCall->getArg(1)); // Order 2941 break; 2942 case LoadCopy: 2943 case Copy: 2944 case Arithmetic: 2945 case Xchg: 2946 SubExprs.push_back(TheCall->getArg(2)); // Order 2947 SubExprs.push_back(TheCall->getArg(1)); // Val1 2948 break; 2949 case GNUXchg: 2950 // Note, AtomicExpr::getVal2() has a special case for this atomic. 2951 SubExprs.push_back(TheCall->getArg(3)); // Order 2952 SubExprs.push_back(TheCall->getArg(1)); // Val1 2953 SubExprs.push_back(TheCall->getArg(2)); // Val2 2954 break; 2955 case C11CmpXchg: 2956 SubExprs.push_back(TheCall->getArg(3)); // Order 2957 SubExprs.push_back(TheCall->getArg(1)); // Val1 2958 SubExprs.push_back(TheCall->getArg(4)); // OrderFail 2959 SubExprs.push_back(TheCall->getArg(2)); // Val2 2960 break; 2961 case GNUCmpXchg: 2962 SubExprs.push_back(TheCall->getArg(4)); // Order 2963 SubExprs.push_back(TheCall->getArg(1)); // Val1 2964 SubExprs.push_back(TheCall->getArg(5)); // OrderFail 2965 SubExprs.push_back(TheCall->getArg(2)); // Val2 2966 SubExprs.push_back(TheCall->getArg(3)); // Weak 2967 break; 2968 } 2969 2970 if (SubExprs.size() >= 2 && Form != Init) { 2971 llvm::APSInt Result(32); 2972 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) && 2973 !isValidOrderingForOp(Result.getSExtValue(), Op)) 2974 Diag(SubExprs[1]->getLocStart(), 2975 diag::warn_atomic_op_has_invalid_memory_order) 2976 << SubExprs[1]->getSourceRange(); 2977 } 2978 2979 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(), 2980 SubExprs, ResultType, Op, 2981 TheCall->getRParenLoc()); 2982 2983 if ((Op == AtomicExpr::AO__c11_atomic_load || 2984 (Op == AtomicExpr::AO__c11_atomic_store)) && 2985 Context.AtomicUsesUnsupportedLibcall(AE)) 2986 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) << 2987 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1); 2988 2989 return AE; 2990 } 2991 2992 /// checkBuiltinArgument - Given a call to a builtin function, perform 2993 /// normal type-checking on the given argument, updating the call in 2994 /// place. This is useful when a builtin function requires custom 2995 /// type-checking for some of its arguments but not necessarily all of 2996 /// them. 2997 /// 2998 /// Returns true on error. 2999 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 3000 FunctionDecl *Fn = E->getDirectCallee(); 3001 assert(Fn && "builtin call without direct callee!"); 3002 3003 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 3004 InitializedEntity Entity = 3005 InitializedEntity::InitializeParameter(S.Context, Param); 3006 3007 ExprResult Arg = E->getArg(0); 3008 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 3009 if (Arg.isInvalid()) 3010 return true; 3011 3012 E->setArg(ArgIndex, Arg.get()); 3013 return false; 3014 } 3015 3016 /// SemaBuiltinAtomicOverloaded - We have a call to a function like 3017 /// __sync_fetch_and_add, which is an overloaded function based on the pointer 3018 /// type of its first argument. The main ActOnCallExpr routines have already 3019 /// promoted the types of arguments because all of these calls are prototyped as 3020 /// void(...). 3021 /// 3022 /// This function goes through and does final semantic checking for these 3023 /// builtins, 3024 ExprResult 3025 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 3026 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 3027 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 3028 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 3029 3030 // Ensure that we have at least one argument to do type inference from. 3031 if (TheCall->getNumArgs() < 1) { 3032 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 3033 << 0 << 1 << TheCall->getNumArgs() 3034 << TheCall->getCallee()->getSourceRange(); 3035 return ExprError(); 3036 } 3037 3038 // Inspect the first argument of the atomic builtin. This should always be 3039 // a pointer type, whose element is an integral scalar or pointer type. 3040 // Because it is a pointer type, we don't have to worry about any implicit 3041 // casts here. 3042 // FIXME: We don't allow floating point scalars as input. 3043 Expr *FirstArg = TheCall->getArg(0); 3044 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 3045 if (FirstArgResult.isInvalid()) 3046 return ExprError(); 3047 FirstArg = FirstArgResult.get(); 3048 TheCall->setArg(0, FirstArg); 3049 3050 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 3051 if (!pointerType) { 3052 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 3053 << FirstArg->getType() << FirstArg->getSourceRange(); 3054 return ExprError(); 3055 } 3056 3057 QualType ValType = pointerType->getPointeeType(); 3058 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 3059 !ValType->isBlockPointerType()) { 3060 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr) 3061 << FirstArg->getType() << FirstArg->getSourceRange(); 3062 return ExprError(); 3063 } 3064 3065 switch (ValType.getObjCLifetime()) { 3066 case Qualifiers::OCL_None: 3067 case Qualifiers::OCL_ExplicitNone: 3068 // okay 3069 break; 3070 3071 case Qualifiers::OCL_Weak: 3072 case Qualifiers::OCL_Strong: 3073 case Qualifiers::OCL_Autoreleasing: 3074 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 3075 << ValType << FirstArg->getSourceRange(); 3076 return ExprError(); 3077 } 3078 3079 // Strip any qualifiers off ValType. 3080 ValType = ValType.getUnqualifiedType(); 3081 3082 // The majority of builtins return a value, but a few have special return 3083 // types, so allow them to override appropriately below. 3084 QualType ResultType = ValType; 3085 3086 // We need to figure out which concrete builtin this maps onto. For example, 3087 // __sync_fetch_and_add with a 2 byte object turns into 3088 // __sync_fetch_and_add_2. 3089 #define BUILTIN_ROW(x) \ 3090 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 3091 Builtin::BI##x##_8, Builtin::BI##x##_16 } 3092 3093 static const unsigned BuiltinIndices[][5] = { 3094 BUILTIN_ROW(__sync_fetch_and_add), 3095 BUILTIN_ROW(__sync_fetch_and_sub), 3096 BUILTIN_ROW(__sync_fetch_and_or), 3097 BUILTIN_ROW(__sync_fetch_and_and), 3098 BUILTIN_ROW(__sync_fetch_and_xor), 3099 BUILTIN_ROW(__sync_fetch_and_nand), 3100 3101 BUILTIN_ROW(__sync_add_and_fetch), 3102 BUILTIN_ROW(__sync_sub_and_fetch), 3103 BUILTIN_ROW(__sync_and_and_fetch), 3104 BUILTIN_ROW(__sync_or_and_fetch), 3105 BUILTIN_ROW(__sync_xor_and_fetch), 3106 BUILTIN_ROW(__sync_nand_and_fetch), 3107 3108 BUILTIN_ROW(__sync_val_compare_and_swap), 3109 BUILTIN_ROW(__sync_bool_compare_and_swap), 3110 BUILTIN_ROW(__sync_lock_test_and_set), 3111 BUILTIN_ROW(__sync_lock_release), 3112 BUILTIN_ROW(__sync_swap) 3113 }; 3114 #undef BUILTIN_ROW 3115 3116 // Determine the index of the size. 3117 unsigned SizeIndex; 3118 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 3119 case 1: SizeIndex = 0; break; 3120 case 2: SizeIndex = 1; break; 3121 case 4: SizeIndex = 2; break; 3122 case 8: SizeIndex = 3; break; 3123 case 16: SizeIndex = 4; break; 3124 default: 3125 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size) 3126 << FirstArg->getType() << FirstArg->getSourceRange(); 3127 return ExprError(); 3128 } 3129 3130 // Each of these builtins has one pointer argument, followed by some number of 3131 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 3132 // that we ignore. Find out which row of BuiltinIndices to read from as well 3133 // as the number of fixed args. 3134 unsigned BuiltinID = FDecl->getBuiltinID(); 3135 unsigned BuiltinIndex, NumFixed = 1; 3136 bool WarnAboutSemanticsChange = false; 3137 switch (BuiltinID) { 3138 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 3139 case Builtin::BI__sync_fetch_and_add: 3140 case Builtin::BI__sync_fetch_and_add_1: 3141 case Builtin::BI__sync_fetch_and_add_2: 3142 case Builtin::BI__sync_fetch_and_add_4: 3143 case Builtin::BI__sync_fetch_and_add_8: 3144 case Builtin::BI__sync_fetch_and_add_16: 3145 BuiltinIndex = 0; 3146 break; 3147 3148 case Builtin::BI__sync_fetch_and_sub: 3149 case Builtin::BI__sync_fetch_and_sub_1: 3150 case Builtin::BI__sync_fetch_and_sub_2: 3151 case Builtin::BI__sync_fetch_and_sub_4: 3152 case Builtin::BI__sync_fetch_and_sub_8: 3153 case Builtin::BI__sync_fetch_and_sub_16: 3154 BuiltinIndex = 1; 3155 break; 3156 3157 case Builtin::BI__sync_fetch_and_or: 3158 case Builtin::BI__sync_fetch_and_or_1: 3159 case Builtin::BI__sync_fetch_and_or_2: 3160 case Builtin::BI__sync_fetch_and_or_4: 3161 case Builtin::BI__sync_fetch_and_or_8: 3162 case Builtin::BI__sync_fetch_and_or_16: 3163 BuiltinIndex = 2; 3164 break; 3165 3166 case Builtin::BI__sync_fetch_and_and: 3167 case Builtin::BI__sync_fetch_and_and_1: 3168 case Builtin::BI__sync_fetch_and_and_2: 3169 case Builtin::BI__sync_fetch_and_and_4: 3170 case Builtin::BI__sync_fetch_and_and_8: 3171 case Builtin::BI__sync_fetch_and_and_16: 3172 BuiltinIndex = 3; 3173 break; 3174 3175 case Builtin::BI__sync_fetch_and_xor: 3176 case Builtin::BI__sync_fetch_and_xor_1: 3177 case Builtin::BI__sync_fetch_and_xor_2: 3178 case Builtin::BI__sync_fetch_and_xor_4: 3179 case Builtin::BI__sync_fetch_and_xor_8: 3180 case Builtin::BI__sync_fetch_and_xor_16: 3181 BuiltinIndex = 4; 3182 break; 3183 3184 case Builtin::BI__sync_fetch_and_nand: 3185 case Builtin::BI__sync_fetch_and_nand_1: 3186 case Builtin::BI__sync_fetch_and_nand_2: 3187 case Builtin::BI__sync_fetch_and_nand_4: 3188 case Builtin::BI__sync_fetch_and_nand_8: 3189 case Builtin::BI__sync_fetch_and_nand_16: 3190 BuiltinIndex = 5; 3191 WarnAboutSemanticsChange = true; 3192 break; 3193 3194 case Builtin::BI__sync_add_and_fetch: 3195 case Builtin::BI__sync_add_and_fetch_1: 3196 case Builtin::BI__sync_add_and_fetch_2: 3197 case Builtin::BI__sync_add_and_fetch_4: 3198 case Builtin::BI__sync_add_and_fetch_8: 3199 case Builtin::BI__sync_add_and_fetch_16: 3200 BuiltinIndex = 6; 3201 break; 3202 3203 case Builtin::BI__sync_sub_and_fetch: 3204 case Builtin::BI__sync_sub_and_fetch_1: 3205 case Builtin::BI__sync_sub_and_fetch_2: 3206 case Builtin::BI__sync_sub_and_fetch_4: 3207 case Builtin::BI__sync_sub_and_fetch_8: 3208 case Builtin::BI__sync_sub_and_fetch_16: 3209 BuiltinIndex = 7; 3210 break; 3211 3212 case Builtin::BI__sync_and_and_fetch: 3213 case Builtin::BI__sync_and_and_fetch_1: 3214 case Builtin::BI__sync_and_and_fetch_2: 3215 case Builtin::BI__sync_and_and_fetch_4: 3216 case Builtin::BI__sync_and_and_fetch_8: 3217 case Builtin::BI__sync_and_and_fetch_16: 3218 BuiltinIndex = 8; 3219 break; 3220 3221 case Builtin::BI__sync_or_and_fetch: 3222 case Builtin::BI__sync_or_and_fetch_1: 3223 case Builtin::BI__sync_or_and_fetch_2: 3224 case Builtin::BI__sync_or_and_fetch_4: 3225 case Builtin::BI__sync_or_and_fetch_8: 3226 case Builtin::BI__sync_or_and_fetch_16: 3227 BuiltinIndex = 9; 3228 break; 3229 3230 case Builtin::BI__sync_xor_and_fetch: 3231 case Builtin::BI__sync_xor_and_fetch_1: 3232 case Builtin::BI__sync_xor_and_fetch_2: 3233 case Builtin::BI__sync_xor_and_fetch_4: 3234 case Builtin::BI__sync_xor_and_fetch_8: 3235 case Builtin::BI__sync_xor_and_fetch_16: 3236 BuiltinIndex = 10; 3237 break; 3238 3239 case Builtin::BI__sync_nand_and_fetch: 3240 case Builtin::BI__sync_nand_and_fetch_1: 3241 case Builtin::BI__sync_nand_and_fetch_2: 3242 case Builtin::BI__sync_nand_and_fetch_4: 3243 case Builtin::BI__sync_nand_and_fetch_8: 3244 case Builtin::BI__sync_nand_and_fetch_16: 3245 BuiltinIndex = 11; 3246 WarnAboutSemanticsChange = true; 3247 break; 3248 3249 case Builtin::BI__sync_val_compare_and_swap: 3250 case Builtin::BI__sync_val_compare_and_swap_1: 3251 case Builtin::BI__sync_val_compare_and_swap_2: 3252 case Builtin::BI__sync_val_compare_and_swap_4: 3253 case Builtin::BI__sync_val_compare_and_swap_8: 3254 case Builtin::BI__sync_val_compare_and_swap_16: 3255 BuiltinIndex = 12; 3256 NumFixed = 2; 3257 break; 3258 3259 case Builtin::BI__sync_bool_compare_and_swap: 3260 case Builtin::BI__sync_bool_compare_and_swap_1: 3261 case Builtin::BI__sync_bool_compare_and_swap_2: 3262 case Builtin::BI__sync_bool_compare_and_swap_4: 3263 case Builtin::BI__sync_bool_compare_and_swap_8: 3264 case Builtin::BI__sync_bool_compare_and_swap_16: 3265 BuiltinIndex = 13; 3266 NumFixed = 2; 3267 ResultType = Context.BoolTy; 3268 break; 3269 3270 case Builtin::BI__sync_lock_test_and_set: 3271 case Builtin::BI__sync_lock_test_and_set_1: 3272 case Builtin::BI__sync_lock_test_and_set_2: 3273 case Builtin::BI__sync_lock_test_and_set_4: 3274 case Builtin::BI__sync_lock_test_and_set_8: 3275 case Builtin::BI__sync_lock_test_and_set_16: 3276 BuiltinIndex = 14; 3277 break; 3278 3279 case Builtin::BI__sync_lock_release: 3280 case Builtin::BI__sync_lock_release_1: 3281 case Builtin::BI__sync_lock_release_2: 3282 case Builtin::BI__sync_lock_release_4: 3283 case Builtin::BI__sync_lock_release_8: 3284 case Builtin::BI__sync_lock_release_16: 3285 BuiltinIndex = 15; 3286 NumFixed = 0; 3287 ResultType = Context.VoidTy; 3288 break; 3289 3290 case Builtin::BI__sync_swap: 3291 case Builtin::BI__sync_swap_1: 3292 case Builtin::BI__sync_swap_2: 3293 case Builtin::BI__sync_swap_4: 3294 case Builtin::BI__sync_swap_8: 3295 case Builtin::BI__sync_swap_16: 3296 BuiltinIndex = 16; 3297 break; 3298 } 3299 3300 // Now that we know how many fixed arguments we expect, first check that we 3301 // have at least that many. 3302 if (TheCall->getNumArgs() < 1+NumFixed) { 3303 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 3304 << 0 << 1+NumFixed << TheCall->getNumArgs() 3305 << TheCall->getCallee()->getSourceRange(); 3306 return ExprError(); 3307 } 3308 3309 if (WarnAboutSemanticsChange) { 3310 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change) 3311 << TheCall->getCallee()->getSourceRange(); 3312 } 3313 3314 // Get the decl for the concrete builtin from this, we can tell what the 3315 // concrete integer type we should convert to is. 3316 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 3317 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 3318 FunctionDecl *NewBuiltinDecl; 3319 if (NewBuiltinID == BuiltinID) 3320 NewBuiltinDecl = FDecl; 3321 else { 3322 // Perform builtin lookup to avoid redeclaring it. 3323 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 3324 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName); 3325 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 3326 assert(Res.getFoundDecl()); 3327 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 3328 if (!NewBuiltinDecl) 3329 return ExprError(); 3330 } 3331 3332 // The first argument --- the pointer --- has a fixed type; we 3333 // deduce the types of the rest of the arguments accordingly. Walk 3334 // the remaining arguments, converting them to the deduced value type. 3335 for (unsigned i = 0; i != NumFixed; ++i) { 3336 ExprResult Arg = TheCall->getArg(i+1); 3337 3338 // GCC does an implicit conversion to the pointer or integer ValType. This 3339 // can fail in some cases (1i -> int**), check for this error case now. 3340 // Initialize the argument. 3341 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 3342 ValType, /*consume*/ false); 3343 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 3344 if (Arg.isInvalid()) 3345 return ExprError(); 3346 3347 // Okay, we have something that *can* be converted to the right type. Check 3348 // to see if there is a potentially weird extension going on here. This can 3349 // happen when you do an atomic operation on something like an char* and 3350 // pass in 42. The 42 gets converted to char. This is even more strange 3351 // for things like 45.123 -> char, etc. 3352 // FIXME: Do this check. 3353 TheCall->setArg(i+1, Arg.get()); 3354 } 3355 3356 ASTContext& Context = this->getASTContext(); 3357 3358 // Create a new DeclRefExpr to refer to the new decl. 3359 DeclRefExpr* NewDRE = DeclRefExpr::Create( 3360 Context, 3361 DRE->getQualifierLoc(), 3362 SourceLocation(), 3363 NewBuiltinDecl, 3364 /*enclosing*/ false, 3365 DRE->getLocation(), 3366 Context.BuiltinFnTy, 3367 DRE->getValueKind()); 3368 3369 // Set the callee in the CallExpr. 3370 // FIXME: This loses syntactic information. 3371 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 3372 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 3373 CK_BuiltinFnToFnPtr); 3374 TheCall->setCallee(PromotedCall.get()); 3375 3376 // Change the result type of the call to match the original value type. This 3377 // is arbitrary, but the codegen for these builtins ins design to handle it 3378 // gracefully. 3379 TheCall->setType(ResultType); 3380 3381 return TheCallResult; 3382 } 3383 3384 /// SemaBuiltinNontemporalOverloaded - We have a call to 3385 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 3386 /// overloaded function based on the pointer type of its last argument. 3387 /// 3388 /// This function goes through and does final semantic checking for these 3389 /// builtins. 3390 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 3391 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 3392 DeclRefExpr *DRE = 3393 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 3394 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 3395 unsigned BuiltinID = FDecl->getBuiltinID(); 3396 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 3397 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 3398 "Unexpected nontemporal load/store builtin!"); 3399 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 3400 unsigned numArgs = isStore ? 2 : 1; 3401 3402 // Ensure that we have the proper number of arguments. 3403 if (checkArgCount(*this, TheCall, numArgs)) 3404 return ExprError(); 3405 3406 // Inspect the last argument of the nontemporal builtin. This should always 3407 // be a pointer type, from which we imply the type of the memory access. 3408 // Because it is a pointer type, we don't have to worry about any implicit 3409 // casts here. 3410 Expr *PointerArg = TheCall->getArg(numArgs - 1); 3411 ExprResult PointerArgResult = 3412 DefaultFunctionArrayLvalueConversion(PointerArg); 3413 3414 if (PointerArgResult.isInvalid()) 3415 return ExprError(); 3416 PointerArg = PointerArgResult.get(); 3417 TheCall->setArg(numArgs - 1, PointerArg); 3418 3419 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 3420 if (!pointerType) { 3421 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer) 3422 << PointerArg->getType() << PointerArg->getSourceRange(); 3423 return ExprError(); 3424 } 3425 3426 QualType ValType = pointerType->getPointeeType(); 3427 3428 // Strip any qualifiers off ValType. 3429 ValType = ValType.getUnqualifiedType(); 3430 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 3431 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 3432 !ValType->isVectorType()) { 3433 Diag(DRE->getLocStart(), 3434 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 3435 << PointerArg->getType() << PointerArg->getSourceRange(); 3436 return ExprError(); 3437 } 3438 3439 if (!isStore) { 3440 TheCall->setType(ValType); 3441 return TheCallResult; 3442 } 3443 3444 ExprResult ValArg = TheCall->getArg(0); 3445 InitializedEntity Entity = InitializedEntity::InitializeParameter( 3446 Context, ValType, /*consume*/ false); 3447 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 3448 if (ValArg.isInvalid()) 3449 return ExprError(); 3450 3451 TheCall->setArg(0, ValArg.get()); 3452 TheCall->setType(Context.VoidTy); 3453 return TheCallResult; 3454 } 3455 3456 /// CheckObjCString - Checks that the argument to the builtin 3457 /// CFString constructor is correct 3458 /// Note: It might also make sense to do the UTF-16 conversion here (would 3459 /// simplify the backend). 3460 bool Sema::CheckObjCString(Expr *Arg) { 3461 Arg = Arg->IgnoreParenCasts(); 3462 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 3463 3464 if (!Literal || !Literal->isAscii()) { 3465 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant) 3466 << Arg->getSourceRange(); 3467 return true; 3468 } 3469 3470 if (Literal->containsNonAsciiOrNull()) { 3471 StringRef String = Literal->getString(); 3472 unsigned NumBytes = String.size(); 3473 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 3474 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 3475 llvm::UTF16 *ToPtr = &ToBuf[0]; 3476 3477 llvm::ConversionResult Result = 3478 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 3479 ToPtr + NumBytes, llvm::strictConversion); 3480 // Check for conversion failure. 3481 if (Result != llvm::conversionOK) 3482 Diag(Arg->getLocStart(), 3483 diag::warn_cfstring_truncated) << Arg->getSourceRange(); 3484 } 3485 return false; 3486 } 3487 3488 /// CheckObjCString - Checks that the format string argument to the os_log() 3489 /// and os_trace() functions is correct, and converts it to const char *. 3490 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 3491 Arg = Arg->IgnoreParenCasts(); 3492 auto *Literal = dyn_cast<StringLiteral>(Arg); 3493 if (!Literal) { 3494 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 3495 Literal = ObjcLiteral->getString(); 3496 } 3497 } 3498 3499 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 3500 return ExprError( 3501 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant) 3502 << Arg->getSourceRange()); 3503 } 3504 3505 ExprResult Result(Literal); 3506 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 3507 InitializedEntity Entity = 3508 InitializedEntity::InitializeParameter(Context, ResultTy, false); 3509 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 3510 return Result; 3511 } 3512 3513 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 3514 /// for validity. Emit an error and return true on failure; return false 3515 /// on success. 3516 bool Sema::SemaBuiltinVAStartImpl(CallExpr *TheCall) { 3517 Expr *Fn = TheCall->getCallee(); 3518 if (TheCall->getNumArgs() > 2) { 3519 Diag(TheCall->getArg(2)->getLocStart(), 3520 diag::err_typecheck_call_too_many_args) 3521 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 3522 << Fn->getSourceRange() 3523 << SourceRange(TheCall->getArg(2)->getLocStart(), 3524 (*(TheCall->arg_end()-1))->getLocEnd()); 3525 return true; 3526 } 3527 3528 if (TheCall->getNumArgs() < 2) { 3529 return Diag(TheCall->getLocEnd(), 3530 diag::err_typecheck_call_too_few_args_at_least) 3531 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 3532 } 3533 3534 // Type-check the first argument normally. 3535 if (checkBuiltinArgument(*this, TheCall, 0)) 3536 return true; 3537 3538 // Determine whether the current function is variadic or not. 3539 BlockScopeInfo *CurBlock = getCurBlock(); 3540 bool isVariadic; 3541 if (CurBlock) 3542 isVariadic = CurBlock->TheDecl->isVariadic(); 3543 else if (FunctionDecl *FD = getCurFunctionDecl()) 3544 isVariadic = FD->isVariadic(); 3545 else 3546 isVariadic = getCurMethodDecl()->isVariadic(); 3547 3548 if (!isVariadic) { 3549 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function); 3550 return true; 3551 } 3552 3553 // Verify that the second argument to the builtin is the last argument of the 3554 // current function or method. 3555 bool SecondArgIsLastNamedArgument = false; 3556 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 3557 3558 // These are valid if SecondArgIsLastNamedArgument is false after the next 3559 // block. 3560 QualType Type; 3561 SourceLocation ParamLoc; 3562 bool IsCRegister = false; 3563 3564 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 3565 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 3566 // FIXME: This isn't correct for methods (results in bogus warning). 3567 // Get the last formal in the current function. 3568 const ParmVarDecl *LastArg; 3569 if (CurBlock) 3570 LastArg = CurBlock->TheDecl->parameters().back(); 3571 else if (FunctionDecl *FD = getCurFunctionDecl()) 3572 LastArg = FD->parameters().back(); 3573 else 3574 LastArg = getCurMethodDecl()->parameters().back(); 3575 SecondArgIsLastNamedArgument = PV == LastArg; 3576 3577 Type = PV->getType(); 3578 ParamLoc = PV->getLocation(); 3579 IsCRegister = 3580 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 3581 } 3582 } 3583 3584 if (!SecondArgIsLastNamedArgument) 3585 Diag(TheCall->getArg(1)->getLocStart(), 3586 diag::warn_second_arg_of_va_start_not_last_named_param); 3587 else if (IsCRegister || Type->isReferenceType() || 3588 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 3589 // Promotable integers are UB, but enumerations need a bit of 3590 // extra checking to see what their promotable type actually is. 3591 if (!Type->isPromotableIntegerType()) 3592 return false; 3593 if (!Type->isEnumeralType()) 3594 return true; 3595 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl(); 3596 return !(ED && 3597 Context.typesAreCompatible(ED->getPromotionType(), Type)); 3598 }()) { 3599 unsigned Reason = 0; 3600 if (Type->isReferenceType()) Reason = 1; 3601 else if (IsCRegister) Reason = 2; 3602 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason; 3603 Diag(ParamLoc, diag::note_parameter_type) << Type; 3604 } 3605 3606 TheCall->setType(Context.VoidTy); 3607 return false; 3608 } 3609 3610 /// Check the arguments to '__builtin_va_start' for validity, and that 3611 /// it was called from a function of the native ABI. 3612 /// Emit an error and return true on failure; return false on success. 3613 bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) { 3614 // On x86-64 Unix, don't allow this in Win64 ABI functions. 3615 // On x64 Windows, don't allow this in System V ABI functions. 3616 // (Yes, that means there's no corresponding way to support variadic 3617 // System V ABI functions on Windows.) 3618 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) { 3619 unsigned OS = Context.getTargetInfo().getTriple().getOS(); 3620 clang::CallingConv CC = CC_C; 3621 if (const FunctionDecl *FD = getCurFunctionDecl()) 3622 CC = FD->getType()->getAs<FunctionType>()->getCallConv(); 3623 if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) || 3624 (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64)) 3625 return Diag(TheCall->getCallee()->getLocStart(), 3626 diag::err_va_start_used_in_wrong_abi_function) 3627 << (OS != llvm::Triple::Win32); 3628 } 3629 return SemaBuiltinVAStartImpl(TheCall); 3630 } 3631 3632 /// Check the arguments to '__builtin_ms_va_start' for validity, and that 3633 /// it was called from a Win64 ABI function. 3634 /// Emit an error and return true on failure; return false on success. 3635 bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) { 3636 // This only makes sense for x86-64. 3637 const llvm::Triple &TT = Context.getTargetInfo().getTriple(); 3638 Expr *Callee = TheCall->getCallee(); 3639 if (TT.getArch() != llvm::Triple::x86_64) 3640 return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt); 3641 // Don't allow this in System V ABI functions. 3642 clang::CallingConv CC = CC_C; 3643 if (const FunctionDecl *FD = getCurFunctionDecl()) 3644 CC = FD->getType()->getAs<FunctionType>()->getCallConv(); 3645 if (CC == CC_X86_64SysV || 3646 (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64)) 3647 return Diag(Callee->getLocStart(), 3648 diag::err_ms_va_start_used_in_sysv_function); 3649 return SemaBuiltinVAStartImpl(TheCall); 3650 } 3651 3652 bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) { 3653 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 3654 // const char *named_addr); 3655 3656 Expr *Func = Call->getCallee(); 3657 3658 if (Call->getNumArgs() < 3) 3659 return Diag(Call->getLocEnd(), 3660 diag::err_typecheck_call_too_few_args_at_least) 3661 << 0 /*function call*/ << 3 << Call->getNumArgs(); 3662 3663 // Determine whether the current function is variadic or not. 3664 bool IsVariadic; 3665 if (BlockScopeInfo *CurBlock = getCurBlock()) 3666 IsVariadic = CurBlock->TheDecl->isVariadic(); 3667 else if (FunctionDecl *FD = getCurFunctionDecl()) 3668 IsVariadic = FD->isVariadic(); 3669 else if (ObjCMethodDecl *MD = getCurMethodDecl()) 3670 IsVariadic = MD->isVariadic(); 3671 else 3672 llvm_unreachable("unexpected statement type"); 3673 3674 if (!IsVariadic) { 3675 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function); 3676 return true; 3677 } 3678 3679 // Type-check the first argument normally. 3680 if (checkBuiltinArgument(*this, Call, 0)) 3681 return true; 3682 3683 const struct { 3684 unsigned ArgNo; 3685 QualType Type; 3686 } ArgumentTypes[] = { 3687 { 1, Context.getPointerType(Context.CharTy.withConst()) }, 3688 { 2, Context.getSizeType() }, 3689 }; 3690 3691 for (const auto &AT : ArgumentTypes) { 3692 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens(); 3693 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType()) 3694 continue; 3695 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible) 3696 << Arg->getType() << AT.Type << 1 /* different class */ 3697 << 0 /* qualifier difference */ << 3 /* parameter mismatch */ 3698 << AT.ArgNo + 1 << Arg->getType() << AT.Type; 3699 } 3700 3701 return false; 3702 } 3703 3704 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 3705 /// friends. This is declared to take (...), so we have to check everything. 3706 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 3707 if (TheCall->getNumArgs() < 2) 3708 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 3709 << 0 << 2 << TheCall->getNumArgs()/*function call*/; 3710 if (TheCall->getNumArgs() > 2) 3711 return Diag(TheCall->getArg(2)->getLocStart(), 3712 diag::err_typecheck_call_too_many_args) 3713 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 3714 << SourceRange(TheCall->getArg(2)->getLocStart(), 3715 (*(TheCall->arg_end()-1))->getLocEnd()); 3716 3717 ExprResult OrigArg0 = TheCall->getArg(0); 3718 ExprResult OrigArg1 = TheCall->getArg(1); 3719 3720 // Do standard promotions between the two arguments, returning their common 3721 // type. 3722 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false); 3723 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 3724 return true; 3725 3726 // Make sure any conversions are pushed back into the call; this is 3727 // type safe since unordered compare builtins are declared as "_Bool 3728 // foo(...)". 3729 TheCall->setArg(0, OrigArg0.get()); 3730 TheCall->setArg(1, OrigArg1.get()); 3731 3732 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 3733 return false; 3734 3735 // If the common type isn't a real floating type, then the arguments were 3736 // invalid for this operation. 3737 if (Res.isNull() || !Res->isRealFloatingType()) 3738 return Diag(OrigArg0.get()->getLocStart(), 3739 diag::err_typecheck_call_invalid_ordered_compare) 3740 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 3741 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd()); 3742 3743 return false; 3744 } 3745 3746 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 3747 /// __builtin_isnan and friends. This is declared to take (...), so we have 3748 /// to check everything. We expect the last argument to be a floating point 3749 /// value. 3750 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 3751 if (TheCall->getNumArgs() < NumArgs) 3752 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 3753 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/; 3754 if (TheCall->getNumArgs() > NumArgs) 3755 return Diag(TheCall->getArg(NumArgs)->getLocStart(), 3756 diag::err_typecheck_call_too_many_args) 3757 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 3758 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(), 3759 (*(TheCall->arg_end()-1))->getLocEnd()); 3760 3761 Expr *OrigArg = TheCall->getArg(NumArgs-1); 3762 3763 if (OrigArg->isTypeDependent()) 3764 return false; 3765 3766 // This operation requires a non-_Complex floating-point number. 3767 if (!OrigArg->getType()->isRealFloatingType()) 3768 return Diag(OrigArg->getLocStart(), 3769 diag::err_typecheck_call_invalid_unary_fp) 3770 << OrigArg->getType() << OrigArg->getSourceRange(); 3771 3772 // If this is an implicit conversion from float -> double, remove it. 3773 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) { 3774 Expr *CastArg = Cast->getSubExpr(); 3775 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) { 3776 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) && 3777 "promotion from float to double is the only expected cast here"); 3778 Cast->setSubExpr(nullptr); 3779 TheCall->setArg(NumArgs-1, CastArg); 3780 } 3781 } 3782 3783 return false; 3784 } 3785 3786 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 3787 // This is declared to take (...), so we have to check everything. 3788 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 3789 if (TheCall->getNumArgs() < 2) 3790 return ExprError(Diag(TheCall->getLocEnd(), 3791 diag::err_typecheck_call_too_few_args_at_least) 3792 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 3793 << TheCall->getSourceRange()); 3794 3795 // Determine which of the following types of shufflevector we're checking: 3796 // 1) unary, vector mask: (lhs, mask) 3797 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 3798 QualType resType = TheCall->getArg(0)->getType(); 3799 unsigned numElements = 0; 3800 3801 if (!TheCall->getArg(0)->isTypeDependent() && 3802 !TheCall->getArg(1)->isTypeDependent()) { 3803 QualType LHSType = TheCall->getArg(0)->getType(); 3804 QualType RHSType = TheCall->getArg(1)->getType(); 3805 3806 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 3807 return ExprError(Diag(TheCall->getLocStart(), 3808 diag::err_shufflevector_non_vector) 3809 << SourceRange(TheCall->getArg(0)->getLocStart(), 3810 TheCall->getArg(1)->getLocEnd())); 3811 3812 numElements = LHSType->getAs<VectorType>()->getNumElements(); 3813 unsigned numResElements = TheCall->getNumArgs() - 2; 3814 3815 // Check to see if we have a call with 2 vector arguments, the unary shuffle 3816 // with mask. If so, verify that RHS is an integer vector type with the 3817 // same number of elts as lhs. 3818 if (TheCall->getNumArgs() == 2) { 3819 if (!RHSType->hasIntegerRepresentation() || 3820 RHSType->getAs<VectorType>()->getNumElements() != numElements) 3821 return ExprError(Diag(TheCall->getLocStart(), 3822 diag::err_shufflevector_incompatible_vector) 3823 << SourceRange(TheCall->getArg(1)->getLocStart(), 3824 TheCall->getArg(1)->getLocEnd())); 3825 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 3826 return ExprError(Diag(TheCall->getLocStart(), 3827 diag::err_shufflevector_incompatible_vector) 3828 << SourceRange(TheCall->getArg(0)->getLocStart(), 3829 TheCall->getArg(1)->getLocEnd())); 3830 } else if (numElements != numResElements) { 3831 QualType eltType = LHSType->getAs<VectorType>()->getElementType(); 3832 resType = Context.getVectorType(eltType, numResElements, 3833 VectorType::GenericVector); 3834 } 3835 } 3836 3837 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 3838 if (TheCall->getArg(i)->isTypeDependent() || 3839 TheCall->getArg(i)->isValueDependent()) 3840 continue; 3841 3842 llvm::APSInt Result(32); 3843 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 3844 return ExprError(Diag(TheCall->getLocStart(), 3845 diag::err_shufflevector_nonconstant_argument) 3846 << TheCall->getArg(i)->getSourceRange()); 3847 3848 // Allow -1 which will be translated to undef in the IR. 3849 if (Result.isSigned() && Result.isAllOnesValue()) 3850 continue; 3851 3852 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 3853 return ExprError(Diag(TheCall->getLocStart(), 3854 diag::err_shufflevector_argument_too_large) 3855 << TheCall->getArg(i)->getSourceRange()); 3856 } 3857 3858 SmallVector<Expr*, 32> exprs; 3859 3860 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 3861 exprs.push_back(TheCall->getArg(i)); 3862 TheCall->setArg(i, nullptr); 3863 } 3864 3865 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 3866 TheCall->getCallee()->getLocStart(), 3867 TheCall->getRParenLoc()); 3868 } 3869 3870 /// SemaConvertVectorExpr - Handle __builtin_convertvector 3871 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 3872 SourceLocation BuiltinLoc, 3873 SourceLocation RParenLoc) { 3874 ExprValueKind VK = VK_RValue; 3875 ExprObjectKind OK = OK_Ordinary; 3876 QualType DstTy = TInfo->getType(); 3877 QualType SrcTy = E->getType(); 3878 3879 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 3880 return ExprError(Diag(BuiltinLoc, 3881 diag::err_convertvector_non_vector) 3882 << E->getSourceRange()); 3883 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 3884 return ExprError(Diag(BuiltinLoc, 3885 diag::err_convertvector_non_vector_type)); 3886 3887 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 3888 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements(); 3889 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements(); 3890 if (SrcElts != DstElts) 3891 return ExprError(Diag(BuiltinLoc, 3892 diag::err_convertvector_incompatible_vector) 3893 << E->getSourceRange()); 3894 } 3895 3896 return new (Context) 3897 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 3898 } 3899 3900 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 3901 // This is declared to take (const void*, ...) and can take two 3902 // optional constant int args. 3903 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 3904 unsigned NumArgs = TheCall->getNumArgs(); 3905 3906 if (NumArgs > 3) 3907 return Diag(TheCall->getLocEnd(), 3908 diag::err_typecheck_call_too_many_args_at_most) 3909 << 0 /*function call*/ << 3 << NumArgs 3910 << TheCall->getSourceRange(); 3911 3912 // Argument 0 is checked for us and the remaining arguments must be 3913 // constant integers. 3914 for (unsigned i = 1; i != NumArgs; ++i) 3915 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 3916 return true; 3917 3918 return false; 3919 } 3920 3921 /// SemaBuiltinAssume - Handle __assume (MS Extension). 3922 // __assume does not evaluate its arguments, and should warn if its argument 3923 // has side effects. 3924 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 3925 Expr *Arg = TheCall->getArg(0); 3926 if (Arg->isInstantiationDependent()) return false; 3927 3928 if (Arg->HasSideEffects(Context)) 3929 Diag(Arg->getLocStart(), diag::warn_assume_side_effects) 3930 << Arg->getSourceRange() 3931 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 3932 3933 return false; 3934 } 3935 3936 /// Handle __builtin_assume_aligned. This is declared 3937 /// as (const void*, size_t, ...) and can take one optional constant int arg. 3938 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 3939 unsigned NumArgs = TheCall->getNumArgs(); 3940 3941 if (NumArgs > 3) 3942 return Diag(TheCall->getLocEnd(), 3943 diag::err_typecheck_call_too_many_args_at_most) 3944 << 0 /*function call*/ << 3 << NumArgs 3945 << TheCall->getSourceRange(); 3946 3947 // The alignment must be a constant integer. 3948 Expr *Arg = TheCall->getArg(1); 3949 3950 // We can't check the value of a dependent argument. 3951 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 3952 llvm::APSInt Result; 3953 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 3954 return true; 3955 3956 if (!Result.isPowerOf2()) 3957 return Diag(TheCall->getLocStart(), 3958 diag::err_alignment_not_power_of_two) 3959 << Arg->getSourceRange(); 3960 } 3961 3962 if (NumArgs > 2) { 3963 ExprResult Arg(TheCall->getArg(2)); 3964 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 3965 Context.getSizeType(), false); 3966 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 3967 if (Arg.isInvalid()) return true; 3968 TheCall->setArg(2, Arg.get()); 3969 } 3970 3971 return false; 3972 } 3973 3974 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 3975 unsigned BuiltinID = 3976 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 3977 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 3978 3979 unsigned NumArgs = TheCall->getNumArgs(); 3980 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 3981 if (NumArgs < NumRequiredArgs) { 3982 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 3983 << 0 /* function call */ << NumRequiredArgs << NumArgs 3984 << TheCall->getSourceRange(); 3985 } 3986 if (NumArgs >= NumRequiredArgs + 0x100) { 3987 return Diag(TheCall->getLocEnd(), 3988 diag::err_typecheck_call_too_many_args_at_most) 3989 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 3990 << TheCall->getSourceRange(); 3991 } 3992 unsigned i = 0; 3993 3994 // For formatting call, check buffer arg. 3995 if (!IsSizeCall) { 3996 ExprResult Arg(TheCall->getArg(i)); 3997 InitializedEntity Entity = InitializedEntity::InitializeParameter( 3998 Context, Context.VoidPtrTy, false); 3999 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4000 if (Arg.isInvalid()) 4001 return true; 4002 TheCall->setArg(i, Arg.get()); 4003 i++; 4004 } 4005 4006 // Check string literal arg. 4007 unsigned FormatIdx = i; 4008 { 4009 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 4010 if (Arg.isInvalid()) 4011 return true; 4012 TheCall->setArg(i, Arg.get()); 4013 i++; 4014 } 4015 4016 // Make sure variadic args are scalar. 4017 unsigned FirstDataArg = i; 4018 while (i < NumArgs) { 4019 ExprResult Arg = DefaultVariadicArgumentPromotion( 4020 TheCall->getArg(i), VariadicFunction, nullptr); 4021 if (Arg.isInvalid()) 4022 return true; 4023 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 4024 if (ArgSize.getQuantity() >= 0x100) { 4025 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big) 4026 << i << (int)ArgSize.getQuantity() << 0xff 4027 << TheCall->getSourceRange(); 4028 } 4029 TheCall->setArg(i, Arg.get()); 4030 i++; 4031 } 4032 4033 // Check formatting specifiers. NOTE: We're only doing this for the non-size 4034 // call to avoid duplicate diagnostics. 4035 if (!IsSizeCall) { 4036 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 4037 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 4038 bool Success = CheckFormatArguments( 4039 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 4040 VariadicFunction, TheCall->getLocStart(), SourceRange(), 4041 CheckedVarArgs); 4042 if (!Success) 4043 return true; 4044 } 4045 4046 if (IsSizeCall) { 4047 TheCall->setType(Context.getSizeType()); 4048 } else { 4049 TheCall->setType(Context.VoidPtrTy); 4050 } 4051 return false; 4052 } 4053 4054 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 4055 /// TheCall is a constant expression. 4056 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 4057 llvm::APSInt &Result) { 4058 Expr *Arg = TheCall->getArg(ArgNum); 4059 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4060 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 4061 4062 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 4063 4064 if (!Arg->isIntegerConstantExpr(Result, Context)) 4065 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type) 4066 << FDecl->getDeclName() << Arg->getSourceRange(); 4067 4068 return false; 4069 } 4070 4071 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 4072 /// TheCall is a constant expression in the range [Low, High]. 4073 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 4074 int Low, int High) { 4075 llvm::APSInt Result; 4076 4077 // We can't check the value of a dependent argument. 4078 Expr *Arg = TheCall->getArg(ArgNum); 4079 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4080 return false; 4081 4082 // Check constant-ness first. 4083 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4084 return true; 4085 4086 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) 4087 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 4088 << Low << High << Arg->getSourceRange(); 4089 4090 return false; 4091 } 4092 4093 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 4094 /// TheCall is a constant expression is a multiple of Num.. 4095 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 4096 unsigned Num) { 4097 llvm::APSInt Result; 4098 4099 // We can't check the value of a dependent argument. 4100 Expr *Arg = TheCall->getArg(ArgNum); 4101 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4102 return false; 4103 4104 // Check constant-ness first. 4105 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4106 return true; 4107 4108 if (Result.getSExtValue() % Num != 0) 4109 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple) 4110 << Num << Arg->getSourceRange(); 4111 4112 return false; 4113 } 4114 4115 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 4116 /// TheCall is an ARM/AArch64 special register string literal. 4117 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 4118 int ArgNum, unsigned ExpectedFieldNum, 4119 bool AllowName) { 4120 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 4121 BuiltinID == ARM::BI__builtin_arm_wsr64 || 4122 BuiltinID == ARM::BI__builtin_arm_rsr || 4123 BuiltinID == ARM::BI__builtin_arm_rsrp || 4124 BuiltinID == ARM::BI__builtin_arm_wsr || 4125 BuiltinID == ARM::BI__builtin_arm_wsrp; 4126 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 4127 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 4128 BuiltinID == AArch64::BI__builtin_arm_rsr || 4129 BuiltinID == AArch64::BI__builtin_arm_rsrp || 4130 BuiltinID == AArch64::BI__builtin_arm_wsr || 4131 BuiltinID == AArch64::BI__builtin_arm_wsrp; 4132 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 4133 4134 // We can't check the value of a dependent argument. 4135 Expr *Arg = TheCall->getArg(ArgNum); 4136 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4137 return false; 4138 4139 // Check if the argument is a string literal. 4140 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 4141 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal) 4142 << Arg->getSourceRange(); 4143 4144 // Check the type of special register given. 4145 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 4146 SmallVector<StringRef, 6> Fields; 4147 Reg.split(Fields, ":"); 4148 4149 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 4150 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg) 4151 << Arg->getSourceRange(); 4152 4153 // If the string is the name of a register then we cannot check that it is 4154 // valid here but if the string is of one the forms described in ACLE then we 4155 // can check that the supplied fields are integers and within the valid 4156 // ranges. 4157 if (Fields.size() > 1) { 4158 bool FiveFields = Fields.size() == 5; 4159 4160 bool ValidString = true; 4161 if (IsARMBuiltin) { 4162 ValidString &= Fields[0].startswith_lower("cp") || 4163 Fields[0].startswith_lower("p"); 4164 if (ValidString) 4165 Fields[0] = 4166 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 4167 4168 ValidString &= Fields[2].startswith_lower("c"); 4169 if (ValidString) 4170 Fields[2] = Fields[2].drop_front(1); 4171 4172 if (FiveFields) { 4173 ValidString &= Fields[3].startswith_lower("c"); 4174 if (ValidString) 4175 Fields[3] = Fields[3].drop_front(1); 4176 } 4177 } 4178 4179 SmallVector<int, 5> Ranges; 4180 if (FiveFields) 4181 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 7, 15, 15}); 4182 else 4183 Ranges.append({15, 7, 15}); 4184 4185 for (unsigned i=0; i<Fields.size(); ++i) { 4186 int IntField; 4187 ValidString &= !Fields[i].getAsInteger(10, IntField); 4188 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 4189 } 4190 4191 if (!ValidString) 4192 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg) 4193 << Arg->getSourceRange(); 4194 4195 } else if (IsAArch64Builtin && Fields.size() == 1) { 4196 // If the register name is one of those that appear in the condition below 4197 // and the special register builtin being used is one of the write builtins, 4198 // then we require that the argument provided for writing to the register 4199 // is an integer constant expression. This is because it will be lowered to 4200 // an MSR (immediate) instruction, so we need to know the immediate at 4201 // compile time. 4202 if (TheCall->getNumArgs() != 2) 4203 return false; 4204 4205 std::string RegLower = Reg.lower(); 4206 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 4207 RegLower != "pan" && RegLower != "uao") 4208 return false; 4209 4210 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 4211 } 4212 4213 return false; 4214 } 4215 4216 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 4217 /// This checks that the target supports __builtin_longjmp and 4218 /// that val is a constant 1. 4219 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 4220 if (!Context.getTargetInfo().hasSjLjLowering()) 4221 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported) 4222 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd()); 4223 4224 Expr *Arg = TheCall->getArg(1); 4225 llvm::APSInt Result; 4226 4227 // TODO: This is less than ideal. Overload this to take a value. 4228 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 4229 return true; 4230 4231 if (Result != 1) 4232 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val) 4233 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 4234 4235 return false; 4236 } 4237 4238 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 4239 /// This checks that the target supports __builtin_setjmp. 4240 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 4241 if (!Context.getTargetInfo().hasSjLjLowering()) 4242 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported) 4243 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd()); 4244 return false; 4245 } 4246 4247 namespace { 4248 class UncoveredArgHandler { 4249 enum { Unknown = -1, AllCovered = -2 }; 4250 signed FirstUncoveredArg; 4251 SmallVector<const Expr *, 4> DiagnosticExprs; 4252 4253 public: 4254 UncoveredArgHandler() : FirstUncoveredArg(Unknown) { } 4255 4256 bool hasUncoveredArg() const { 4257 return (FirstUncoveredArg >= 0); 4258 } 4259 4260 unsigned getUncoveredArg() const { 4261 assert(hasUncoveredArg() && "no uncovered argument"); 4262 return FirstUncoveredArg; 4263 } 4264 4265 void setAllCovered() { 4266 // A string has been found with all arguments covered, so clear out 4267 // the diagnostics. 4268 DiagnosticExprs.clear(); 4269 FirstUncoveredArg = AllCovered; 4270 } 4271 4272 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 4273 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 4274 4275 // Don't update if a previous string covers all arguments. 4276 if (FirstUncoveredArg == AllCovered) 4277 return; 4278 4279 // UncoveredArgHandler tracks the highest uncovered argument index 4280 // and with it all the strings that match this index. 4281 if (NewFirstUncoveredArg == FirstUncoveredArg) 4282 DiagnosticExprs.push_back(StrExpr); 4283 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 4284 DiagnosticExprs.clear(); 4285 DiagnosticExprs.push_back(StrExpr); 4286 FirstUncoveredArg = NewFirstUncoveredArg; 4287 } 4288 } 4289 4290 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 4291 }; 4292 4293 enum StringLiteralCheckType { 4294 SLCT_NotALiteral, 4295 SLCT_UncheckedLiteral, 4296 SLCT_CheckedLiteral 4297 }; 4298 } // end anonymous namespace 4299 4300 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 4301 BinaryOperatorKind BinOpKind, 4302 bool AddendIsRight) { 4303 unsigned BitWidth = Offset.getBitWidth(); 4304 unsigned AddendBitWidth = Addend.getBitWidth(); 4305 // There might be negative interim results. 4306 if (Addend.isUnsigned()) { 4307 Addend = Addend.zext(++AddendBitWidth); 4308 Addend.setIsSigned(true); 4309 } 4310 // Adjust the bit width of the APSInts. 4311 if (AddendBitWidth > BitWidth) { 4312 Offset = Offset.sext(AddendBitWidth); 4313 BitWidth = AddendBitWidth; 4314 } else if (BitWidth > AddendBitWidth) { 4315 Addend = Addend.sext(BitWidth); 4316 } 4317 4318 bool Ov = false; 4319 llvm::APSInt ResOffset = Offset; 4320 if (BinOpKind == BO_Add) 4321 ResOffset = Offset.sadd_ov(Addend, Ov); 4322 else { 4323 assert(AddendIsRight && BinOpKind == BO_Sub && 4324 "operator must be add or sub with addend on the right"); 4325 ResOffset = Offset.ssub_ov(Addend, Ov); 4326 } 4327 4328 // We add an offset to a pointer here so we should support an offset as big as 4329 // possible. 4330 if (Ov) { 4331 assert(BitWidth <= UINT_MAX / 2 && "index (intermediate) result too big"); 4332 Offset = Offset.sext(2 * BitWidth); 4333 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 4334 return; 4335 } 4336 4337 Offset = ResOffset; 4338 } 4339 4340 namespace { 4341 // This is a wrapper class around StringLiteral to support offsetted string 4342 // literals as format strings. It takes the offset into account when returning 4343 // the string and its length or the source locations to display notes correctly. 4344 class FormatStringLiteral { 4345 const StringLiteral *FExpr; 4346 int64_t Offset; 4347 4348 public: 4349 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 4350 : FExpr(fexpr), Offset(Offset) {} 4351 4352 StringRef getString() const { 4353 return FExpr->getString().drop_front(Offset); 4354 } 4355 4356 unsigned getByteLength() const { 4357 return FExpr->getByteLength() - getCharByteWidth() * Offset; 4358 } 4359 unsigned getLength() const { return FExpr->getLength() - Offset; } 4360 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 4361 4362 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 4363 4364 QualType getType() const { return FExpr->getType(); } 4365 4366 bool isAscii() const { return FExpr->isAscii(); } 4367 bool isWide() const { return FExpr->isWide(); } 4368 bool isUTF8() const { return FExpr->isUTF8(); } 4369 bool isUTF16() const { return FExpr->isUTF16(); } 4370 bool isUTF32() const { return FExpr->isUTF32(); } 4371 bool isPascal() const { return FExpr->isPascal(); } 4372 4373 SourceLocation getLocationOfByte( 4374 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 4375 const TargetInfo &Target, unsigned *StartToken = nullptr, 4376 unsigned *StartTokenByteOffset = nullptr) const { 4377 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 4378 StartToken, StartTokenByteOffset); 4379 } 4380 4381 SourceLocation getLocStart() const LLVM_READONLY { 4382 return FExpr->getLocStart().getLocWithOffset(Offset); 4383 } 4384 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); } 4385 }; 4386 } // end anonymous namespace 4387 4388 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 4389 const Expr *OrigFormatExpr, 4390 ArrayRef<const Expr *> Args, 4391 bool HasVAListArg, unsigned format_idx, 4392 unsigned firstDataArg, 4393 Sema::FormatStringType Type, 4394 bool inFunctionCall, 4395 Sema::VariadicCallType CallType, 4396 llvm::SmallBitVector &CheckedVarArgs, 4397 UncoveredArgHandler &UncoveredArg); 4398 4399 // Determine if an expression is a string literal or constant string. 4400 // If this function returns false on the arguments to a function expecting a 4401 // format string, we will usually need to emit a warning. 4402 // True string literals are then checked by CheckFormatString. 4403 static StringLiteralCheckType 4404 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 4405 bool HasVAListArg, unsigned format_idx, 4406 unsigned firstDataArg, Sema::FormatStringType Type, 4407 Sema::VariadicCallType CallType, bool InFunctionCall, 4408 llvm::SmallBitVector &CheckedVarArgs, 4409 UncoveredArgHandler &UncoveredArg, 4410 llvm::APSInt Offset) { 4411 tryAgain: 4412 assert(Offset.isSigned() && "invalid offset"); 4413 4414 if (E->isTypeDependent() || E->isValueDependent()) 4415 return SLCT_NotALiteral; 4416 4417 E = E->IgnoreParenCasts(); 4418 4419 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 4420 // Technically -Wformat-nonliteral does not warn about this case. 4421 // The behavior of printf and friends in this case is implementation 4422 // dependent. Ideally if the format string cannot be null then 4423 // it should have a 'nonnull' attribute in the function prototype. 4424 return SLCT_UncheckedLiteral; 4425 4426 switch (E->getStmtClass()) { 4427 case Stmt::BinaryConditionalOperatorClass: 4428 case Stmt::ConditionalOperatorClass: { 4429 // The expression is a literal if both sub-expressions were, and it was 4430 // completely checked only if both sub-expressions were checked. 4431 const AbstractConditionalOperator *C = 4432 cast<AbstractConditionalOperator>(E); 4433 4434 // Determine whether it is necessary to check both sub-expressions, for 4435 // example, because the condition expression is a constant that can be 4436 // evaluated at compile time. 4437 bool CheckLeft = true, CheckRight = true; 4438 4439 bool Cond; 4440 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) { 4441 if (Cond) 4442 CheckRight = false; 4443 else 4444 CheckLeft = false; 4445 } 4446 4447 // We need to maintain the offsets for the right and the left hand side 4448 // separately to check if every possible indexed expression is a valid 4449 // string literal. They might have different offsets for different string 4450 // literals in the end. 4451 StringLiteralCheckType Left; 4452 if (!CheckLeft) 4453 Left = SLCT_UncheckedLiteral; 4454 else { 4455 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 4456 HasVAListArg, format_idx, firstDataArg, 4457 Type, CallType, InFunctionCall, 4458 CheckedVarArgs, UncoveredArg, Offset); 4459 if (Left == SLCT_NotALiteral || !CheckRight) { 4460 return Left; 4461 } 4462 } 4463 4464 StringLiteralCheckType Right = 4465 checkFormatStringExpr(S, C->getFalseExpr(), Args, 4466 HasVAListArg, format_idx, firstDataArg, 4467 Type, CallType, InFunctionCall, CheckedVarArgs, 4468 UncoveredArg, Offset); 4469 4470 return (CheckLeft && Left < Right) ? Left : Right; 4471 } 4472 4473 case Stmt::ImplicitCastExprClass: { 4474 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 4475 goto tryAgain; 4476 } 4477 4478 case Stmt::OpaqueValueExprClass: 4479 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 4480 E = src; 4481 goto tryAgain; 4482 } 4483 return SLCT_NotALiteral; 4484 4485 case Stmt::PredefinedExprClass: 4486 // While __func__, etc., are technically not string literals, they 4487 // cannot contain format specifiers and thus are not a security 4488 // liability. 4489 return SLCT_UncheckedLiteral; 4490 4491 case Stmt::DeclRefExprClass: { 4492 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 4493 4494 // As an exception, do not flag errors for variables binding to 4495 // const string literals. 4496 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 4497 bool isConstant = false; 4498 QualType T = DR->getType(); 4499 4500 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 4501 isConstant = AT->getElementType().isConstant(S.Context); 4502 } else if (const PointerType *PT = T->getAs<PointerType>()) { 4503 isConstant = T.isConstant(S.Context) && 4504 PT->getPointeeType().isConstant(S.Context); 4505 } else if (T->isObjCObjectPointerType()) { 4506 // In ObjC, there is usually no "const ObjectPointer" type, 4507 // so don't check if the pointee type is constant. 4508 isConstant = T.isConstant(S.Context); 4509 } 4510 4511 if (isConstant) { 4512 if (const Expr *Init = VD->getAnyInitializer()) { 4513 // Look through initializers like const char c[] = { "foo" } 4514 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 4515 if (InitList->isStringLiteralInit()) 4516 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 4517 } 4518 return checkFormatStringExpr(S, Init, Args, 4519 HasVAListArg, format_idx, 4520 firstDataArg, Type, CallType, 4521 /*InFunctionCall*/ false, CheckedVarArgs, 4522 UncoveredArg, Offset); 4523 } 4524 } 4525 4526 // For vprintf* functions (i.e., HasVAListArg==true), we add a 4527 // special check to see if the format string is a function parameter 4528 // of the function calling the printf function. If the function 4529 // has an attribute indicating it is a printf-like function, then we 4530 // should suppress warnings concerning non-literals being used in a call 4531 // to a vprintf function. For example: 4532 // 4533 // void 4534 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 4535 // va_list ap; 4536 // va_start(ap, fmt); 4537 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 4538 // ... 4539 // } 4540 if (HasVAListArg) { 4541 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 4542 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 4543 int PVIndex = PV->getFunctionScopeIndex() + 1; 4544 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 4545 // adjust for implicit parameter 4546 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 4547 if (MD->isInstance()) 4548 ++PVIndex; 4549 // We also check if the formats are compatible. 4550 // We can't pass a 'scanf' string to a 'printf' function. 4551 if (PVIndex == PVFormat->getFormatIdx() && 4552 Type == S.GetFormatStringType(PVFormat)) 4553 return SLCT_UncheckedLiteral; 4554 } 4555 } 4556 } 4557 } 4558 } 4559 4560 return SLCT_NotALiteral; 4561 } 4562 4563 case Stmt::CallExprClass: 4564 case Stmt::CXXMemberCallExprClass: { 4565 const CallExpr *CE = cast<CallExpr>(E); 4566 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 4567 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) { 4568 unsigned ArgIndex = FA->getFormatIdx(); 4569 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 4570 if (MD->isInstance()) 4571 --ArgIndex; 4572 const Expr *Arg = CE->getArg(ArgIndex - 1); 4573 4574 return checkFormatStringExpr(S, Arg, Args, 4575 HasVAListArg, format_idx, firstDataArg, 4576 Type, CallType, InFunctionCall, 4577 CheckedVarArgs, UncoveredArg, Offset); 4578 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) { 4579 unsigned BuiltinID = FD->getBuiltinID(); 4580 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 4581 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 4582 const Expr *Arg = CE->getArg(0); 4583 return checkFormatStringExpr(S, Arg, Args, 4584 HasVAListArg, format_idx, 4585 firstDataArg, Type, CallType, 4586 InFunctionCall, CheckedVarArgs, 4587 UncoveredArg, Offset); 4588 } 4589 } 4590 } 4591 4592 return SLCT_NotALiteral; 4593 } 4594 case Stmt::ObjCMessageExprClass: { 4595 const auto *ME = cast<ObjCMessageExpr>(E); 4596 if (const auto *ND = ME->getMethodDecl()) { 4597 if (const auto *FA = ND->getAttr<FormatArgAttr>()) { 4598 unsigned ArgIndex = FA->getFormatIdx(); 4599 const Expr *Arg = ME->getArg(ArgIndex - 1); 4600 return checkFormatStringExpr( 4601 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 4602 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset); 4603 } 4604 } 4605 4606 return SLCT_NotALiteral; 4607 } 4608 case Stmt::ObjCStringLiteralClass: 4609 case Stmt::StringLiteralClass: { 4610 const StringLiteral *StrE = nullptr; 4611 4612 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 4613 StrE = ObjCFExpr->getString(); 4614 else 4615 StrE = cast<StringLiteral>(E); 4616 4617 if (StrE) { 4618 if (Offset.isNegative() || Offset > StrE->getLength()) { 4619 // TODO: It would be better to have an explicit warning for out of 4620 // bounds literals. 4621 return SLCT_NotALiteral; 4622 } 4623 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 4624 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 4625 firstDataArg, Type, InFunctionCall, CallType, 4626 CheckedVarArgs, UncoveredArg); 4627 return SLCT_CheckedLiteral; 4628 } 4629 4630 return SLCT_NotALiteral; 4631 } 4632 case Stmt::BinaryOperatorClass: { 4633 llvm::APSInt LResult; 4634 llvm::APSInt RResult; 4635 4636 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 4637 4638 // A string literal + an int offset is still a string literal. 4639 if (BinOp->isAdditiveOp()) { 4640 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context); 4641 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context); 4642 4643 if (LIsInt != RIsInt) { 4644 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 4645 4646 if (LIsInt) { 4647 if (BinOpKind == BO_Add) { 4648 sumOffsets(Offset, LResult, BinOpKind, RIsInt); 4649 E = BinOp->getRHS(); 4650 goto tryAgain; 4651 } 4652 } else { 4653 sumOffsets(Offset, RResult, BinOpKind, RIsInt); 4654 E = BinOp->getLHS(); 4655 goto tryAgain; 4656 } 4657 } 4658 } 4659 4660 return SLCT_NotALiteral; 4661 } 4662 case Stmt::UnaryOperatorClass: { 4663 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 4664 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 4665 if (UnaOp->getOpcode() == clang::UO_AddrOf && ASE) { 4666 llvm::APSInt IndexResult; 4667 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) { 4668 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true); 4669 E = ASE->getBase(); 4670 goto tryAgain; 4671 } 4672 } 4673 4674 return SLCT_NotALiteral; 4675 } 4676 4677 default: 4678 return SLCT_NotALiteral; 4679 } 4680 } 4681 4682 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 4683 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 4684 .Case("scanf", FST_Scanf) 4685 .Cases("printf", "printf0", FST_Printf) 4686 .Cases("NSString", "CFString", FST_NSString) 4687 .Case("strftime", FST_Strftime) 4688 .Case("strfmon", FST_Strfmon) 4689 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 4690 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 4691 .Case("os_trace", FST_OSLog) 4692 .Case("os_log", FST_OSLog) 4693 .Default(FST_Unknown); 4694 } 4695 4696 /// CheckFormatArguments - Check calls to printf and scanf (and similar 4697 /// functions) for correct use of format strings. 4698 /// Returns true if a format string has been fully checked. 4699 bool Sema::CheckFormatArguments(const FormatAttr *Format, 4700 ArrayRef<const Expr *> Args, 4701 bool IsCXXMember, 4702 VariadicCallType CallType, 4703 SourceLocation Loc, SourceRange Range, 4704 llvm::SmallBitVector &CheckedVarArgs) { 4705 FormatStringInfo FSI; 4706 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 4707 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 4708 FSI.FirstDataArg, GetFormatStringType(Format), 4709 CallType, Loc, Range, CheckedVarArgs); 4710 return false; 4711 } 4712 4713 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 4714 bool HasVAListArg, unsigned format_idx, 4715 unsigned firstDataArg, FormatStringType Type, 4716 VariadicCallType CallType, 4717 SourceLocation Loc, SourceRange Range, 4718 llvm::SmallBitVector &CheckedVarArgs) { 4719 // CHECK: printf/scanf-like function is called with no format string. 4720 if (format_idx >= Args.size()) { 4721 Diag(Loc, diag::warn_missing_format_string) << Range; 4722 return false; 4723 } 4724 4725 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 4726 4727 // CHECK: format string is not a string literal. 4728 // 4729 // Dynamically generated format strings are difficult to 4730 // automatically vet at compile time. Requiring that format strings 4731 // are string literals: (1) permits the checking of format strings by 4732 // the compiler and thereby (2) can practically remove the source of 4733 // many format string exploits. 4734 4735 // Format string can be either ObjC string (e.g. @"%d") or 4736 // C string (e.g. "%d") 4737 // ObjC string uses the same format specifiers as C string, so we can use 4738 // the same format string checking logic for both ObjC and C strings. 4739 UncoveredArgHandler UncoveredArg; 4740 StringLiteralCheckType CT = 4741 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 4742 format_idx, firstDataArg, Type, CallType, 4743 /*IsFunctionCall*/ true, CheckedVarArgs, 4744 UncoveredArg, 4745 /*no string offset*/ llvm::APSInt(64, false) = 0); 4746 4747 // Generate a diagnostic where an uncovered argument is detected. 4748 if (UncoveredArg.hasUncoveredArg()) { 4749 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 4750 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 4751 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 4752 } 4753 4754 if (CT != SLCT_NotALiteral) 4755 // Literal format string found, check done! 4756 return CT == SLCT_CheckedLiteral; 4757 4758 // Strftime is particular as it always uses a single 'time' argument, 4759 // so it is safe to pass a non-literal string. 4760 if (Type == FST_Strftime) 4761 return false; 4762 4763 // Do not emit diag when the string param is a macro expansion and the 4764 // format is either NSString or CFString. This is a hack to prevent 4765 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 4766 // which are usually used in place of NS and CF string literals. 4767 SourceLocation FormatLoc = Args[format_idx]->getLocStart(); 4768 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 4769 return false; 4770 4771 // If there are no arguments specified, warn with -Wformat-security, otherwise 4772 // warn only with -Wformat-nonliteral. 4773 if (Args.size() == firstDataArg) { 4774 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 4775 << OrigFormatExpr->getSourceRange(); 4776 switch (Type) { 4777 default: 4778 break; 4779 case FST_Kprintf: 4780 case FST_FreeBSDKPrintf: 4781 case FST_Printf: 4782 Diag(FormatLoc, diag::note_format_security_fixit) 4783 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 4784 break; 4785 case FST_NSString: 4786 Diag(FormatLoc, diag::note_format_security_fixit) 4787 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 4788 break; 4789 } 4790 } else { 4791 Diag(FormatLoc, diag::warn_format_nonliteral) 4792 << OrigFormatExpr->getSourceRange(); 4793 } 4794 return false; 4795 } 4796 4797 namespace { 4798 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 4799 protected: 4800 Sema &S; 4801 const FormatStringLiteral *FExpr; 4802 const Expr *OrigFormatExpr; 4803 const Sema::FormatStringType FSType; 4804 const unsigned FirstDataArg; 4805 const unsigned NumDataArgs; 4806 const char *Beg; // Start of format string. 4807 const bool HasVAListArg; 4808 ArrayRef<const Expr *> Args; 4809 unsigned FormatIdx; 4810 llvm::SmallBitVector CoveredArgs; 4811 bool usesPositionalArgs; 4812 bool atFirstArg; 4813 bool inFunctionCall; 4814 Sema::VariadicCallType CallType; 4815 llvm::SmallBitVector &CheckedVarArgs; 4816 UncoveredArgHandler &UncoveredArg; 4817 4818 public: 4819 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 4820 const Expr *origFormatExpr, 4821 const Sema::FormatStringType type, unsigned firstDataArg, 4822 unsigned numDataArgs, const char *beg, bool hasVAListArg, 4823 ArrayRef<const Expr *> Args, unsigned formatIdx, 4824 bool inFunctionCall, Sema::VariadicCallType callType, 4825 llvm::SmallBitVector &CheckedVarArgs, 4826 UncoveredArgHandler &UncoveredArg) 4827 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 4828 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 4829 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 4830 usesPositionalArgs(false), atFirstArg(true), 4831 inFunctionCall(inFunctionCall), CallType(callType), 4832 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 4833 CoveredArgs.resize(numDataArgs); 4834 CoveredArgs.reset(); 4835 } 4836 4837 void DoneProcessing(); 4838 4839 void HandleIncompleteSpecifier(const char *startSpecifier, 4840 unsigned specifierLen) override; 4841 4842 void HandleInvalidLengthModifier( 4843 const analyze_format_string::FormatSpecifier &FS, 4844 const analyze_format_string::ConversionSpecifier &CS, 4845 const char *startSpecifier, unsigned specifierLen, 4846 unsigned DiagID); 4847 4848 void HandleNonStandardLengthModifier( 4849 const analyze_format_string::FormatSpecifier &FS, 4850 const char *startSpecifier, unsigned specifierLen); 4851 4852 void HandleNonStandardConversionSpecifier( 4853 const analyze_format_string::ConversionSpecifier &CS, 4854 const char *startSpecifier, unsigned specifierLen); 4855 4856 void HandlePosition(const char *startPos, unsigned posLen) override; 4857 4858 void HandleInvalidPosition(const char *startSpecifier, 4859 unsigned specifierLen, 4860 analyze_format_string::PositionContext p) override; 4861 4862 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 4863 4864 void HandleNullChar(const char *nullCharacter) override; 4865 4866 template <typename Range> 4867 static void 4868 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 4869 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 4870 bool IsStringLocation, Range StringRange, 4871 ArrayRef<FixItHint> Fixit = None); 4872 4873 protected: 4874 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 4875 const char *startSpec, 4876 unsigned specifierLen, 4877 const char *csStart, unsigned csLen); 4878 4879 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 4880 const char *startSpec, 4881 unsigned specifierLen); 4882 4883 SourceRange getFormatStringRange(); 4884 CharSourceRange getSpecifierRange(const char *startSpecifier, 4885 unsigned specifierLen); 4886 SourceLocation getLocationOfByte(const char *x); 4887 4888 const Expr *getDataArg(unsigned i) const; 4889 4890 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 4891 const analyze_format_string::ConversionSpecifier &CS, 4892 const char *startSpecifier, unsigned specifierLen, 4893 unsigned argIndex); 4894 4895 template <typename Range> 4896 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 4897 bool IsStringLocation, Range StringRange, 4898 ArrayRef<FixItHint> Fixit = None); 4899 }; 4900 } // end anonymous namespace 4901 4902 SourceRange CheckFormatHandler::getFormatStringRange() { 4903 return OrigFormatExpr->getSourceRange(); 4904 } 4905 4906 CharSourceRange CheckFormatHandler:: 4907 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 4908 SourceLocation Start = getLocationOfByte(startSpecifier); 4909 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 4910 4911 // Advance the end SourceLocation by one due to half-open ranges. 4912 End = End.getLocWithOffset(1); 4913 4914 return CharSourceRange::getCharRange(Start, End); 4915 } 4916 4917 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 4918 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 4919 S.getLangOpts(), S.Context.getTargetInfo()); 4920 } 4921 4922 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 4923 unsigned specifierLen){ 4924 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 4925 getLocationOfByte(startSpecifier), 4926 /*IsStringLocation*/true, 4927 getSpecifierRange(startSpecifier, specifierLen)); 4928 } 4929 4930 void CheckFormatHandler::HandleInvalidLengthModifier( 4931 const analyze_format_string::FormatSpecifier &FS, 4932 const analyze_format_string::ConversionSpecifier &CS, 4933 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 4934 using namespace analyze_format_string; 4935 4936 const LengthModifier &LM = FS.getLengthModifier(); 4937 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 4938 4939 // See if we know how to fix this length modifier. 4940 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 4941 if (FixedLM) { 4942 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 4943 getLocationOfByte(LM.getStart()), 4944 /*IsStringLocation*/true, 4945 getSpecifierRange(startSpecifier, specifierLen)); 4946 4947 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 4948 << FixedLM->toString() 4949 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 4950 4951 } else { 4952 FixItHint Hint; 4953 if (DiagID == diag::warn_format_nonsensical_length) 4954 Hint = FixItHint::CreateRemoval(LMRange); 4955 4956 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 4957 getLocationOfByte(LM.getStart()), 4958 /*IsStringLocation*/true, 4959 getSpecifierRange(startSpecifier, specifierLen), 4960 Hint); 4961 } 4962 } 4963 4964 void CheckFormatHandler::HandleNonStandardLengthModifier( 4965 const analyze_format_string::FormatSpecifier &FS, 4966 const char *startSpecifier, unsigned specifierLen) { 4967 using namespace analyze_format_string; 4968 4969 const LengthModifier &LM = FS.getLengthModifier(); 4970 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 4971 4972 // See if we know how to fix this length modifier. 4973 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 4974 if (FixedLM) { 4975 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 4976 << LM.toString() << 0, 4977 getLocationOfByte(LM.getStart()), 4978 /*IsStringLocation*/true, 4979 getSpecifierRange(startSpecifier, specifierLen)); 4980 4981 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 4982 << FixedLM->toString() 4983 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 4984 4985 } else { 4986 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 4987 << LM.toString() << 0, 4988 getLocationOfByte(LM.getStart()), 4989 /*IsStringLocation*/true, 4990 getSpecifierRange(startSpecifier, specifierLen)); 4991 } 4992 } 4993 4994 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 4995 const analyze_format_string::ConversionSpecifier &CS, 4996 const char *startSpecifier, unsigned specifierLen) { 4997 using namespace analyze_format_string; 4998 4999 // See if we know how to fix this conversion specifier. 5000 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 5001 if (FixedCS) { 5002 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5003 << CS.toString() << /*conversion specifier*/1, 5004 getLocationOfByte(CS.getStart()), 5005 /*IsStringLocation*/true, 5006 getSpecifierRange(startSpecifier, specifierLen)); 5007 5008 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 5009 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 5010 << FixedCS->toString() 5011 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 5012 } else { 5013 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5014 << CS.toString() << /*conversion specifier*/1, 5015 getLocationOfByte(CS.getStart()), 5016 /*IsStringLocation*/true, 5017 getSpecifierRange(startSpecifier, specifierLen)); 5018 } 5019 } 5020 5021 void CheckFormatHandler::HandlePosition(const char *startPos, 5022 unsigned posLen) { 5023 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 5024 getLocationOfByte(startPos), 5025 /*IsStringLocation*/true, 5026 getSpecifierRange(startPos, posLen)); 5027 } 5028 5029 void 5030 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 5031 analyze_format_string::PositionContext p) { 5032 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 5033 << (unsigned) p, 5034 getLocationOfByte(startPos), /*IsStringLocation*/true, 5035 getSpecifierRange(startPos, posLen)); 5036 } 5037 5038 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 5039 unsigned posLen) { 5040 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 5041 getLocationOfByte(startPos), 5042 /*IsStringLocation*/true, 5043 getSpecifierRange(startPos, posLen)); 5044 } 5045 5046 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 5047 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 5048 // The presence of a null character is likely an error. 5049 EmitFormatDiagnostic( 5050 S.PDiag(diag::warn_printf_format_string_contains_null_char), 5051 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 5052 getFormatStringRange()); 5053 } 5054 } 5055 5056 // Note that this may return NULL if there was an error parsing or building 5057 // one of the argument expressions. 5058 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 5059 return Args[FirstDataArg + i]; 5060 } 5061 5062 void CheckFormatHandler::DoneProcessing() { 5063 // Does the number of data arguments exceed the number of 5064 // format conversions in the format string? 5065 if (!HasVAListArg) { 5066 // Find any arguments that weren't covered. 5067 CoveredArgs.flip(); 5068 signed notCoveredArg = CoveredArgs.find_first(); 5069 if (notCoveredArg >= 0) { 5070 assert((unsigned)notCoveredArg < NumDataArgs); 5071 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 5072 } else { 5073 UncoveredArg.setAllCovered(); 5074 } 5075 } 5076 } 5077 5078 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 5079 const Expr *ArgExpr) { 5080 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 5081 "Invalid state"); 5082 5083 if (!ArgExpr) 5084 return; 5085 5086 SourceLocation Loc = ArgExpr->getLocStart(); 5087 5088 if (S.getSourceManager().isInSystemMacro(Loc)) 5089 return; 5090 5091 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 5092 for (auto E : DiagnosticExprs) 5093 PDiag << E->getSourceRange(); 5094 5095 CheckFormatHandler::EmitFormatDiagnostic( 5096 S, IsFunctionCall, DiagnosticExprs[0], 5097 PDiag, Loc, /*IsStringLocation*/false, 5098 DiagnosticExprs[0]->getSourceRange()); 5099 } 5100 5101 bool 5102 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 5103 SourceLocation Loc, 5104 const char *startSpec, 5105 unsigned specifierLen, 5106 const char *csStart, 5107 unsigned csLen) { 5108 bool keepGoing = true; 5109 if (argIndex < NumDataArgs) { 5110 // Consider the argument coverered, even though the specifier doesn't 5111 // make sense. 5112 CoveredArgs.set(argIndex); 5113 } 5114 else { 5115 // If argIndex exceeds the number of data arguments we 5116 // don't issue a warning because that is just a cascade of warnings (and 5117 // they may have intended '%%' anyway). We don't want to continue processing 5118 // the format string after this point, however, as we will like just get 5119 // gibberish when trying to match arguments. 5120 keepGoing = false; 5121 } 5122 5123 StringRef Specifier(csStart, csLen); 5124 5125 // If the specifier in non-printable, it could be the first byte of a UTF-8 5126 // sequence. In that case, print the UTF-8 code point. If not, print the byte 5127 // hex value. 5128 std::string CodePointStr; 5129 if (!llvm::sys::locale::isPrint(*csStart)) { 5130 llvm::UTF32 CodePoint; 5131 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 5132 const llvm::UTF8 *E = 5133 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 5134 llvm::ConversionResult Result = 5135 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 5136 5137 if (Result != llvm::conversionOK) { 5138 unsigned char FirstChar = *csStart; 5139 CodePoint = (llvm::UTF32)FirstChar; 5140 } 5141 5142 llvm::raw_string_ostream OS(CodePointStr); 5143 if (CodePoint < 256) 5144 OS << "\\x" << llvm::format("%02x", CodePoint); 5145 else if (CodePoint <= 0xFFFF) 5146 OS << "\\u" << llvm::format("%04x", CodePoint); 5147 else 5148 OS << "\\U" << llvm::format("%08x", CodePoint); 5149 OS.flush(); 5150 Specifier = CodePointStr; 5151 } 5152 5153 EmitFormatDiagnostic( 5154 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 5155 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 5156 5157 return keepGoing; 5158 } 5159 5160 void 5161 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 5162 const char *startSpec, 5163 unsigned specifierLen) { 5164 EmitFormatDiagnostic( 5165 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 5166 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 5167 } 5168 5169 bool 5170 CheckFormatHandler::CheckNumArgs( 5171 const analyze_format_string::FormatSpecifier &FS, 5172 const analyze_format_string::ConversionSpecifier &CS, 5173 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 5174 5175 if (argIndex >= NumDataArgs) { 5176 PartialDiagnostic PDiag = FS.usesPositionalArg() 5177 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 5178 << (argIndex+1) << NumDataArgs) 5179 : S.PDiag(diag::warn_printf_insufficient_data_args); 5180 EmitFormatDiagnostic( 5181 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 5182 getSpecifierRange(startSpecifier, specifierLen)); 5183 5184 // Since more arguments than conversion tokens are given, by extension 5185 // all arguments are covered, so mark this as so. 5186 UncoveredArg.setAllCovered(); 5187 return false; 5188 } 5189 return true; 5190 } 5191 5192 template<typename Range> 5193 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 5194 SourceLocation Loc, 5195 bool IsStringLocation, 5196 Range StringRange, 5197 ArrayRef<FixItHint> FixIt) { 5198 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 5199 Loc, IsStringLocation, StringRange, FixIt); 5200 } 5201 5202 /// \brief If the format string is not within the funcion call, emit a note 5203 /// so that the function call and string are in diagnostic messages. 5204 /// 5205 /// \param InFunctionCall if true, the format string is within the function 5206 /// call and only one diagnostic message will be produced. Otherwise, an 5207 /// extra note will be emitted pointing to location of the format string. 5208 /// 5209 /// \param ArgumentExpr the expression that is passed as the format string 5210 /// argument in the function call. Used for getting locations when two 5211 /// diagnostics are emitted. 5212 /// 5213 /// \param PDiag the callee should already have provided any strings for the 5214 /// diagnostic message. This function only adds locations and fixits 5215 /// to diagnostics. 5216 /// 5217 /// \param Loc primary location for diagnostic. If two diagnostics are 5218 /// required, one will be at Loc and a new SourceLocation will be created for 5219 /// the other one. 5220 /// 5221 /// \param IsStringLocation if true, Loc points to the format string should be 5222 /// used for the note. Otherwise, Loc points to the argument list and will 5223 /// be used with PDiag. 5224 /// 5225 /// \param StringRange some or all of the string to highlight. This is 5226 /// templated so it can accept either a CharSourceRange or a SourceRange. 5227 /// 5228 /// \param FixIt optional fix it hint for the format string. 5229 template <typename Range> 5230 void CheckFormatHandler::EmitFormatDiagnostic( 5231 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 5232 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 5233 Range StringRange, ArrayRef<FixItHint> FixIt) { 5234 if (InFunctionCall) { 5235 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 5236 D << StringRange; 5237 D << FixIt; 5238 } else { 5239 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 5240 << ArgumentExpr->getSourceRange(); 5241 5242 const Sema::SemaDiagnosticBuilder &Note = 5243 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 5244 diag::note_format_string_defined); 5245 5246 Note << StringRange; 5247 Note << FixIt; 5248 } 5249 } 5250 5251 //===--- CHECK: Printf format string checking ------------------------------===// 5252 5253 namespace { 5254 class CheckPrintfHandler : public CheckFormatHandler { 5255 public: 5256 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 5257 const Expr *origFormatExpr, 5258 const Sema::FormatStringType type, unsigned firstDataArg, 5259 unsigned numDataArgs, bool isObjC, const char *beg, 5260 bool hasVAListArg, ArrayRef<const Expr *> Args, 5261 unsigned formatIdx, bool inFunctionCall, 5262 Sema::VariadicCallType CallType, 5263 llvm::SmallBitVector &CheckedVarArgs, 5264 UncoveredArgHandler &UncoveredArg) 5265 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 5266 numDataArgs, beg, hasVAListArg, Args, formatIdx, 5267 inFunctionCall, CallType, CheckedVarArgs, 5268 UncoveredArg) {} 5269 5270 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 5271 5272 /// Returns true if '%@' specifiers are allowed in the format string. 5273 bool allowsObjCArg() const { 5274 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 5275 FSType == Sema::FST_OSTrace; 5276 } 5277 5278 bool HandleInvalidPrintfConversionSpecifier( 5279 const analyze_printf::PrintfSpecifier &FS, 5280 const char *startSpecifier, 5281 unsigned specifierLen) override; 5282 5283 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 5284 const char *startSpecifier, 5285 unsigned specifierLen) override; 5286 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 5287 const char *StartSpecifier, 5288 unsigned SpecifierLen, 5289 const Expr *E); 5290 5291 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 5292 const char *startSpecifier, unsigned specifierLen); 5293 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 5294 const analyze_printf::OptionalAmount &Amt, 5295 unsigned type, 5296 const char *startSpecifier, unsigned specifierLen); 5297 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 5298 const analyze_printf::OptionalFlag &flag, 5299 const char *startSpecifier, unsigned specifierLen); 5300 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 5301 const analyze_printf::OptionalFlag &ignoredFlag, 5302 const analyze_printf::OptionalFlag &flag, 5303 const char *startSpecifier, unsigned specifierLen); 5304 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 5305 const Expr *E); 5306 5307 void HandleEmptyObjCModifierFlag(const char *startFlag, 5308 unsigned flagLen) override; 5309 5310 void HandleInvalidObjCModifierFlag(const char *startFlag, 5311 unsigned flagLen) override; 5312 5313 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 5314 const char *flagsEnd, 5315 const char *conversionPosition) 5316 override; 5317 }; 5318 } // end anonymous namespace 5319 5320 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 5321 const analyze_printf::PrintfSpecifier &FS, 5322 const char *startSpecifier, 5323 unsigned specifierLen) { 5324 const analyze_printf::PrintfConversionSpecifier &CS = 5325 FS.getConversionSpecifier(); 5326 5327 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 5328 getLocationOfByte(CS.getStart()), 5329 startSpecifier, specifierLen, 5330 CS.getStart(), CS.getLength()); 5331 } 5332 5333 bool CheckPrintfHandler::HandleAmount( 5334 const analyze_format_string::OptionalAmount &Amt, 5335 unsigned k, const char *startSpecifier, 5336 unsigned specifierLen) { 5337 if (Amt.hasDataArgument()) { 5338 if (!HasVAListArg) { 5339 unsigned argIndex = Amt.getArgIndex(); 5340 if (argIndex >= NumDataArgs) { 5341 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 5342 << k, 5343 getLocationOfByte(Amt.getStart()), 5344 /*IsStringLocation*/true, 5345 getSpecifierRange(startSpecifier, specifierLen)); 5346 // Don't do any more checking. We will just emit 5347 // spurious errors. 5348 return false; 5349 } 5350 5351 // Type check the data argument. It should be an 'int'. 5352 // Although not in conformance with C99, we also allow the argument to be 5353 // an 'unsigned int' as that is a reasonably safe case. GCC also 5354 // doesn't emit a warning for that case. 5355 CoveredArgs.set(argIndex); 5356 const Expr *Arg = getDataArg(argIndex); 5357 if (!Arg) 5358 return false; 5359 5360 QualType T = Arg->getType(); 5361 5362 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 5363 assert(AT.isValid()); 5364 5365 if (!AT.matchesType(S.Context, T)) { 5366 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 5367 << k << AT.getRepresentativeTypeName(S.Context) 5368 << T << Arg->getSourceRange(), 5369 getLocationOfByte(Amt.getStart()), 5370 /*IsStringLocation*/true, 5371 getSpecifierRange(startSpecifier, specifierLen)); 5372 // Don't do any more checking. We will just emit 5373 // spurious errors. 5374 return false; 5375 } 5376 } 5377 } 5378 return true; 5379 } 5380 5381 void CheckPrintfHandler::HandleInvalidAmount( 5382 const analyze_printf::PrintfSpecifier &FS, 5383 const analyze_printf::OptionalAmount &Amt, 5384 unsigned type, 5385 const char *startSpecifier, 5386 unsigned specifierLen) { 5387 const analyze_printf::PrintfConversionSpecifier &CS = 5388 FS.getConversionSpecifier(); 5389 5390 FixItHint fixit = 5391 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 5392 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 5393 Amt.getConstantLength())) 5394 : FixItHint(); 5395 5396 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 5397 << type << CS.toString(), 5398 getLocationOfByte(Amt.getStart()), 5399 /*IsStringLocation*/true, 5400 getSpecifierRange(startSpecifier, specifierLen), 5401 fixit); 5402 } 5403 5404 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 5405 const analyze_printf::OptionalFlag &flag, 5406 const char *startSpecifier, 5407 unsigned specifierLen) { 5408 // Warn about pointless flag with a fixit removal. 5409 const analyze_printf::PrintfConversionSpecifier &CS = 5410 FS.getConversionSpecifier(); 5411 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 5412 << flag.toString() << CS.toString(), 5413 getLocationOfByte(flag.getPosition()), 5414 /*IsStringLocation*/true, 5415 getSpecifierRange(startSpecifier, specifierLen), 5416 FixItHint::CreateRemoval( 5417 getSpecifierRange(flag.getPosition(), 1))); 5418 } 5419 5420 void CheckPrintfHandler::HandleIgnoredFlag( 5421 const analyze_printf::PrintfSpecifier &FS, 5422 const analyze_printf::OptionalFlag &ignoredFlag, 5423 const analyze_printf::OptionalFlag &flag, 5424 const char *startSpecifier, 5425 unsigned specifierLen) { 5426 // Warn about ignored flag with a fixit removal. 5427 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 5428 << ignoredFlag.toString() << flag.toString(), 5429 getLocationOfByte(ignoredFlag.getPosition()), 5430 /*IsStringLocation*/true, 5431 getSpecifierRange(startSpecifier, specifierLen), 5432 FixItHint::CreateRemoval( 5433 getSpecifierRange(ignoredFlag.getPosition(), 1))); 5434 } 5435 5436 // void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 5437 // bool IsStringLocation, Range StringRange, 5438 // ArrayRef<FixItHint> Fixit = None); 5439 5440 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 5441 unsigned flagLen) { 5442 // Warn about an empty flag. 5443 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 5444 getLocationOfByte(startFlag), 5445 /*IsStringLocation*/true, 5446 getSpecifierRange(startFlag, flagLen)); 5447 } 5448 5449 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 5450 unsigned flagLen) { 5451 // Warn about an invalid flag. 5452 auto Range = getSpecifierRange(startFlag, flagLen); 5453 StringRef flag(startFlag, flagLen); 5454 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 5455 getLocationOfByte(startFlag), 5456 /*IsStringLocation*/true, 5457 Range, FixItHint::CreateRemoval(Range)); 5458 } 5459 5460 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 5461 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 5462 // Warn about using '[...]' without a '@' conversion. 5463 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 5464 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 5465 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 5466 getLocationOfByte(conversionPosition), 5467 /*IsStringLocation*/true, 5468 Range, FixItHint::CreateRemoval(Range)); 5469 } 5470 5471 // Determines if the specified is a C++ class or struct containing 5472 // a member with the specified name and kind (e.g. a CXXMethodDecl named 5473 // "c_str()"). 5474 template<typename MemberKind> 5475 static llvm::SmallPtrSet<MemberKind*, 1> 5476 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 5477 const RecordType *RT = Ty->getAs<RecordType>(); 5478 llvm::SmallPtrSet<MemberKind*, 1> Results; 5479 5480 if (!RT) 5481 return Results; 5482 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 5483 if (!RD || !RD->getDefinition()) 5484 return Results; 5485 5486 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 5487 Sema::LookupMemberName); 5488 R.suppressDiagnostics(); 5489 5490 // We just need to include all members of the right kind turned up by the 5491 // filter, at this point. 5492 if (S.LookupQualifiedName(R, RT->getDecl())) 5493 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 5494 NamedDecl *decl = (*I)->getUnderlyingDecl(); 5495 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 5496 Results.insert(FK); 5497 } 5498 return Results; 5499 } 5500 5501 /// Check if we could call '.c_str()' on an object. 5502 /// 5503 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 5504 /// allow the call, or if it would be ambiguous). 5505 bool Sema::hasCStrMethod(const Expr *E) { 5506 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet; 5507 MethodSet Results = 5508 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 5509 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 5510 MI != ME; ++MI) 5511 if ((*MI)->getMinRequiredArguments() == 0) 5512 return true; 5513 return false; 5514 } 5515 5516 // Check if a (w)string was passed when a (w)char* was needed, and offer a 5517 // better diagnostic if so. AT is assumed to be valid. 5518 // Returns true when a c_str() conversion method is found. 5519 bool CheckPrintfHandler::checkForCStrMembers( 5520 const analyze_printf::ArgType &AT, const Expr *E) { 5521 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet; 5522 5523 MethodSet Results = 5524 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 5525 5526 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 5527 MI != ME; ++MI) { 5528 const CXXMethodDecl *Method = *MI; 5529 if (Method->getMinRequiredArguments() == 0 && 5530 AT.matchesType(S.Context, Method->getReturnType())) { 5531 // FIXME: Suggest parens if the expression needs them. 5532 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd()); 5533 S.Diag(E->getLocStart(), diag::note_printf_c_str) 5534 << "c_str()" 5535 << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 5536 return true; 5537 } 5538 } 5539 5540 return false; 5541 } 5542 5543 bool 5544 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 5545 &FS, 5546 const char *startSpecifier, 5547 unsigned specifierLen) { 5548 using namespace analyze_format_string; 5549 using namespace analyze_printf; 5550 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 5551 5552 if (FS.consumesDataArgument()) { 5553 if (atFirstArg) { 5554 atFirstArg = false; 5555 usesPositionalArgs = FS.usesPositionalArg(); 5556 } 5557 else if (usesPositionalArgs != FS.usesPositionalArg()) { 5558 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 5559 startSpecifier, specifierLen); 5560 return false; 5561 } 5562 } 5563 5564 // First check if the field width, precision, and conversion specifier 5565 // have matching data arguments. 5566 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 5567 startSpecifier, specifierLen)) { 5568 return false; 5569 } 5570 5571 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 5572 startSpecifier, specifierLen)) { 5573 return false; 5574 } 5575 5576 if (!CS.consumesDataArgument()) { 5577 // FIXME: Technically specifying a precision or field width here 5578 // makes no sense. Worth issuing a warning at some point. 5579 return true; 5580 } 5581 5582 // Consume the argument. 5583 unsigned argIndex = FS.getArgIndex(); 5584 if (argIndex < NumDataArgs) { 5585 // The check to see if the argIndex is valid will come later. 5586 // We set the bit here because we may exit early from this 5587 // function if we encounter some other error. 5588 CoveredArgs.set(argIndex); 5589 } 5590 5591 // FreeBSD kernel extensions. 5592 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 5593 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 5594 // We need at least two arguments. 5595 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 5596 return false; 5597 5598 // Claim the second argument. 5599 CoveredArgs.set(argIndex + 1); 5600 5601 // Type check the first argument (int for %b, pointer for %D) 5602 const Expr *Ex = getDataArg(argIndex); 5603 const analyze_printf::ArgType &AT = 5604 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 5605 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 5606 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 5607 EmitFormatDiagnostic( 5608 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 5609 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 5610 << false << Ex->getSourceRange(), 5611 Ex->getLocStart(), /*IsStringLocation*/false, 5612 getSpecifierRange(startSpecifier, specifierLen)); 5613 5614 // Type check the second argument (char * for both %b and %D) 5615 Ex = getDataArg(argIndex + 1); 5616 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 5617 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 5618 EmitFormatDiagnostic( 5619 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 5620 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 5621 << false << Ex->getSourceRange(), 5622 Ex->getLocStart(), /*IsStringLocation*/false, 5623 getSpecifierRange(startSpecifier, specifierLen)); 5624 5625 return true; 5626 } 5627 5628 // Check for using an Objective-C specific conversion specifier 5629 // in a non-ObjC literal. 5630 if (!allowsObjCArg() && CS.isObjCArg()) { 5631 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 5632 specifierLen); 5633 } 5634 5635 // %P can only be used with os_log. 5636 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 5637 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 5638 specifierLen); 5639 } 5640 5641 // %n is not allowed with os_log. 5642 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 5643 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 5644 getLocationOfByte(CS.getStart()), 5645 /*IsStringLocation*/ false, 5646 getSpecifierRange(startSpecifier, specifierLen)); 5647 5648 return true; 5649 } 5650 5651 // Only scalars are allowed for os_trace. 5652 if (FSType == Sema::FST_OSTrace && 5653 (CS.getKind() == ConversionSpecifier::PArg || 5654 CS.getKind() == ConversionSpecifier::sArg || 5655 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 5656 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 5657 specifierLen); 5658 } 5659 5660 // Check for use of public/private annotation outside of os_log(). 5661 if (FSType != Sema::FST_OSLog) { 5662 if (FS.isPublic().isSet()) { 5663 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 5664 << "public", 5665 getLocationOfByte(FS.isPublic().getPosition()), 5666 /*IsStringLocation*/ false, 5667 getSpecifierRange(startSpecifier, specifierLen)); 5668 } 5669 if (FS.isPrivate().isSet()) { 5670 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 5671 << "private", 5672 getLocationOfByte(FS.isPrivate().getPosition()), 5673 /*IsStringLocation*/ false, 5674 getSpecifierRange(startSpecifier, specifierLen)); 5675 } 5676 } 5677 5678 // Check for invalid use of field width 5679 if (!FS.hasValidFieldWidth()) { 5680 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 5681 startSpecifier, specifierLen); 5682 } 5683 5684 // Check for invalid use of precision 5685 if (!FS.hasValidPrecision()) { 5686 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 5687 startSpecifier, specifierLen); 5688 } 5689 5690 // Precision is mandatory for %P specifier. 5691 if (CS.getKind() == ConversionSpecifier::PArg && 5692 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 5693 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 5694 getLocationOfByte(startSpecifier), 5695 /*IsStringLocation*/ false, 5696 getSpecifierRange(startSpecifier, specifierLen)); 5697 } 5698 5699 // Check each flag does not conflict with any other component. 5700 if (!FS.hasValidThousandsGroupingPrefix()) 5701 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 5702 if (!FS.hasValidLeadingZeros()) 5703 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 5704 if (!FS.hasValidPlusPrefix()) 5705 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 5706 if (!FS.hasValidSpacePrefix()) 5707 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 5708 if (!FS.hasValidAlternativeForm()) 5709 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 5710 if (!FS.hasValidLeftJustified()) 5711 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 5712 5713 // Check that flags are not ignored by another flag 5714 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 5715 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 5716 startSpecifier, specifierLen); 5717 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 5718 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 5719 startSpecifier, specifierLen); 5720 5721 // Check the length modifier is valid with the given conversion specifier. 5722 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 5723 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 5724 diag::warn_format_nonsensical_length); 5725 else if (!FS.hasStandardLengthModifier()) 5726 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 5727 else if (!FS.hasStandardLengthConversionCombination()) 5728 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 5729 diag::warn_format_non_standard_conversion_spec); 5730 5731 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 5732 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 5733 5734 // The remaining checks depend on the data arguments. 5735 if (HasVAListArg) 5736 return true; 5737 5738 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 5739 return false; 5740 5741 const Expr *Arg = getDataArg(argIndex); 5742 if (!Arg) 5743 return true; 5744 5745 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 5746 } 5747 5748 static bool requiresParensToAddCast(const Expr *E) { 5749 // FIXME: We should have a general way to reason about operator 5750 // precedence and whether parens are actually needed here. 5751 // Take care of a few common cases where they aren't. 5752 const Expr *Inside = E->IgnoreImpCasts(); 5753 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 5754 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 5755 5756 switch (Inside->getStmtClass()) { 5757 case Stmt::ArraySubscriptExprClass: 5758 case Stmt::CallExprClass: 5759 case Stmt::CharacterLiteralClass: 5760 case Stmt::CXXBoolLiteralExprClass: 5761 case Stmt::DeclRefExprClass: 5762 case Stmt::FloatingLiteralClass: 5763 case Stmt::IntegerLiteralClass: 5764 case Stmt::MemberExprClass: 5765 case Stmt::ObjCArrayLiteralClass: 5766 case Stmt::ObjCBoolLiteralExprClass: 5767 case Stmt::ObjCBoxedExprClass: 5768 case Stmt::ObjCDictionaryLiteralClass: 5769 case Stmt::ObjCEncodeExprClass: 5770 case Stmt::ObjCIvarRefExprClass: 5771 case Stmt::ObjCMessageExprClass: 5772 case Stmt::ObjCPropertyRefExprClass: 5773 case Stmt::ObjCStringLiteralClass: 5774 case Stmt::ObjCSubscriptRefExprClass: 5775 case Stmt::ParenExprClass: 5776 case Stmt::StringLiteralClass: 5777 case Stmt::UnaryOperatorClass: 5778 return false; 5779 default: 5780 return true; 5781 } 5782 } 5783 5784 static std::pair<QualType, StringRef> 5785 shouldNotPrintDirectly(const ASTContext &Context, 5786 QualType IntendedTy, 5787 const Expr *E) { 5788 // Use a 'while' to peel off layers of typedefs. 5789 QualType TyTy = IntendedTy; 5790 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 5791 StringRef Name = UserTy->getDecl()->getName(); 5792 QualType CastTy = llvm::StringSwitch<QualType>(Name) 5793 .Case("NSInteger", Context.LongTy) 5794 .Case("NSUInteger", Context.UnsignedLongTy) 5795 .Case("SInt32", Context.IntTy) 5796 .Case("UInt32", Context.UnsignedIntTy) 5797 .Default(QualType()); 5798 5799 if (!CastTy.isNull()) 5800 return std::make_pair(CastTy, Name); 5801 5802 TyTy = UserTy->desugar(); 5803 } 5804 5805 // Strip parens if necessary. 5806 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 5807 return shouldNotPrintDirectly(Context, 5808 PE->getSubExpr()->getType(), 5809 PE->getSubExpr()); 5810 5811 // If this is a conditional expression, then its result type is constructed 5812 // via usual arithmetic conversions and thus there might be no necessary 5813 // typedef sugar there. Recurse to operands to check for NSInteger & 5814 // Co. usage condition. 5815 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 5816 QualType TrueTy, FalseTy; 5817 StringRef TrueName, FalseName; 5818 5819 std::tie(TrueTy, TrueName) = 5820 shouldNotPrintDirectly(Context, 5821 CO->getTrueExpr()->getType(), 5822 CO->getTrueExpr()); 5823 std::tie(FalseTy, FalseName) = 5824 shouldNotPrintDirectly(Context, 5825 CO->getFalseExpr()->getType(), 5826 CO->getFalseExpr()); 5827 5828 if (TrueTy == FalseTy) 5829 return std::make_pair(TrueTy, TrueName); 5830 else if (TrueTy.isNull()) 5831 return std::make_pair(FalseTy, FalseName); 5832 else if (FalseTy.isNull()) 5833 return std::make_pair(TrueTy, TrueName); 5834 } 5835 5836 return std::make_pair(QualType(), StringRef()); 5837 } 5838 5839 bool 5840 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 5841 const char *StartSpecifier, 5842 unsigned SpecifierLen, 5843 const Expr *E) { 5844 using namespace analyze_format_string; 5845 using namespace analyze_printf; 5846 // Now type check the data expression that matches the 5847 // format specifier. 5848 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 5849 if (!AT.isValid()) 5850 return true; 5851 5852 QualType ExprTy = E->getType(); 5853 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 5854 ExprTy = TET->getUnderlyingExpr()->getType(); 5855 } 5856 5857 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy); 5858 5859 if (match == analyze_printf::ArgType::Match) { 5860 return true; 5861 } 5862 5863 // Look through argument promotions for our error message's reported type. 5864 // This includes the integral and floating promotions, but excludes array 5865 // and function pointer decay; seeing that an argument intended to be a 5866 // string has type 'char [6]' is probably more confusing than 'char *'. 5867 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 5868 if (ICE->getCastKind() == CK_IntegralCast || 5869 ICE->getCastKind() == CK_FloatingCast) { 5870 E = ICE->getSubExpr(); 5871 ExprTy = E->getType(); 5872 5873 // Check if we didn't match because of an implicit cast from a 'char' 5874 // or 'short' to an 'int'. This is done because printf is a varargs 5875 // function. 5876 if (ICE->getType() == S.Context.IntTy || 5877 ICE->getType() == S.Context.UnsignedIntTy) { 5878 // All further checking is done on the subexpression. 5879 if (AT.matchesType(S.Context, ExprTy)) 5880 return true; 5881 } 5882 } 5883 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 5884 // Special case for 'a', which has type 'int' in C. 5885 // Note, however, that we do /not/ want to treat multibyte constants like 5886 // 'MooV' as characters! This form is deprecated but still exists. 5887 if (ExprTy == S.Context.IntTy) 5888 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 5889 ExprTy = S.Context.CharTy; 5890 } 5891 5892 // Look through enums to their underlying type. 5893 bool IsEnum = false; 5894 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 5895 ExprTy = EnumTy->getDecl()->getIntegerType(); 5896 IsEnum = true; 5897 } 5898 5899 // %C in an Objective-C context prints a unichar, not a wchar_t. 5900 // If the argument is an integer of some kind, believe the %C and suggest 5901 // a cast instead of changing the conversion specifier. 5902 QualType IntendedTy = ExprTy; 5903 if (isObjCContext() && 5904 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 5905 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 5906 !ExprTy->isCharType()) { 5907 // 'unichar' is defined as a typedef of unsigned short, but we should 5908 // prefer using the typedef if it is visible. 5909 IntendedTy = S.Context.UnsignedShortTy; 5910 5911 // While we are here, check if the value is an IntegerLiteral that happens 5912 // to be within the valid range. 5913 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 5914 const llvm::APInt &V = IL->getValue(); 5915 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 5916 return true; 5917 } 5918 5919 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(), 5920 Sema::LookupOrdinaryName); 5921 if (S.LookupName(Result, S.getCurScope())) { 5922 NamedDecl *ND = Result.getFoundDecl(); 5923 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 5924 if (TD->getUnderlyingType() == IntendedTy) 5925 IntendedTy = S.Context.getTypedefType(TD); 5926 } 5927 } 5928 } 5929 5930 // Special-case some of Darwin's platform-independence types by suggesting 5931 // casts to primitive types that are known to be large enough. 5932 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 5933 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 5934 QualType CastTy; 5935 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 5936 if (!CastTy.isNull()) { 5937 IntendedTy = CastTy; 5938 ShouldNotPrintDirectly = true; 5939 } 5940 } 5941 5942 // We may be able to offer a FixItHint if it is a supported type. 5943 PrintfSpecifier fixedFS = FS; 5944 bool success = 5945 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 5946 5947 if (success) { 5948 // Get the fix string from the fixed format specifier 5949 SmallString<16> buf; 5950 llvm::raw_svector_ostream os(buf); 5951 fixedFS.toString(os); 5952 5953 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 5954 5955 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 5956 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 5957 if (match == analyze_format_string::ArgType::NoMatchPedantic) { 5958 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 5959 } 5960 // In this case, the specifier is wrong and should be changed to match 5961 // the argument. 5962 EmitFormatDiagnostic(S.PDiag(diag) 5963 << AT.getRepresentativeTypeName(S.Context) 5964 << IntendedTy << IsEnum << E->getSourceRange(), 5965 E->getLocStart(), 5966 /*IsStringLocation*/ false, SpecRange, 5967 FixItHint::CreateReplacement(SpecRange, os.str())); 5968 } else { 5969 // The canonical type for formatting this value is different from the 5970 // actual type of the expression. (This occurs, for example, with Darwin's 5971 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 5972 // should be printed as 'long' for 64-bit compatibility.) 5973 // Rather than emitting a normal format/argument mismatch, we want to 5974 // add a cast to the recommended type (and correct the format string 5975 // if necessary). 5976 SmallString<16> CastBuf; 5977 llvm::raw_svector_ostream CastFix(CastBuf); 5978 CastFix << "("; 5979 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 5980 CastFix << ")"; 5981 5982 SmallVector<FixItHint,4> Hints; 5983 if (!AT.matchesType(S.Context, IntendedTy)) 5984 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 5985 5986 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 5987 // If there's already a cast present, just replace it. 5988 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 5989 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 5990 5991 } else if (!requiresParensToAddCast(E)) { 5992 // If the expression has high enough precedence, 5993 // just write the C-style cast. 5994 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(), 5995 CastFix.str())); 5996 } else { 5997 // Otherwise, add parens around the expression as well as the cast. 5998 CastFix << "("; 5999 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(), 6000 CastFix.str())); 6001 6002 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd()); 6003 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 6004 } 6005 6006 if (ShouldNotPrintDirectly) { 6007 // The expression has a type that should not be printed directly. 6008 // We extract the name from the typedef because we don't want to show 6009 // the underlying type in the diagnostic. 6010 StringRef Name; 6011 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 6012 Name = TypedefTy->getDecl()->getName(); 6013 else 6014 Name = CastTyName; 6015 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast) 6016 << Name << IntendedTy << IsEnum 6017 << E->getSourceRange(), 6018 E->getLocStart(), /*IsStringLocation=*/false, 6019 SpecRange, Hints); 6020 } else { 6021 // In this case, the expression could be printed using a different 6022 // specifier, but we've decided that the specifier is probably correct 6023 // and we should cast instead. Just use the normal warning message. 6024 EmitFormatDiagnostic( 6025 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 6026 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 6027 << E->getSourceRange(), 6028 E->getLocStart(), /*IsStringLocation*/false, 6029 SpecRange, Hints); 6030 } 6031 } 6032 } else { 6033 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 6034 SpecifierLen); 6035 // Since the warning for passing non-POD types to variadic functions 6036 // was deferred until now, we emit a warning for non-POD 6037 // arguments here. 6038 switch (S.isValidVarArgType(ExprTy)) { 6039 case Sema::VAK_Valid: 6040 case Sema::VAK_ValidInCXX11: { 6041 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 6042 if (match == analyze_printf::ArgType::NoMatchPedantic) { 6043 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 6044 } 6045 6046 EmitFormatDiagnostic( 6047 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 6048 << IsEnum << CSR << E->getSourceRange(), 6049 E->getLocStart(), /*IsStringLocation*/ false, CSR); 6050 break; 6051 } 6052 case Sema::VAK_Undefined: 6053 case Sema::VAK_MSVCUndefined: 6054 EmitFormatDiagnostic( 6055 S.PDiag(diag::warn_non_pod_vararg_with_format_string) 6056 << S.getLangOpts().CPlusPlus11 6057 << ExprTy 6058 << CallType 6059 << AT.getRepresentativeTypeName(S.Context) 6060 << CSR 6061 << E->getSourceRange(), 6062 E->getLocStart(), /*IsStringLocation*/false, CSR); 6063 checkForCStrMembers(AT, E); 6064 break; 6065 6066 case Sema::VAK_Invalid: 6067 if (ExprTy->isObjCObjectType()) 6068 EmitFormatDiagnostic( 6069 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 6070 << S.getLangOpts().CPlusPlus11 6071 << ExprTy 6072 << CallType 6073 << AT.getRepresentativeTypeName(S.Context) 6074 << CSR 6075 << E->getSourceRange(), 6076 E->getLocStart(), /*IsStringLocation*/false, CSR); 6077 else 6078 // FIXME: If this is an initializer list, suggest removing the braces 6079 // or inserting a cast to the target type. 6080 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format) 6081 << isa<InitListExpr>(E) << ExprTy << CallType 6082 << AT.getRepresentativeTypeName(S.Context) 6083 << E->getSourceRange(); 6084 break; 6085 } 6086 6087 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 6088 "format string specifier index out of range"); 6089 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 6090 } 6091 6092 return true; 6093 } 6094 6095 //===--- CHECK: Scanf format string checking ------------------------------===// 6096 6097 namespace { 6098 class CheckScanfHandler : public CheckFormatHandler { 6099 public: 6100 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 6101 const Expr *origFormatExpr, Sema::FormatStringType type, 6102 unsigned firstDataArg, unsigned numDataArgs, 6103 const char *beg, bool hasVAListArg, 6104 ArrayRef<const Expr *> Args, unsigned formatIdx, 6105 bool inFunctionCall, Sema::VariadicCallType CallType, 6106 llvm::SmallBitVector &CheckedVarArgs, 6107 UncoveredArgHandler &UncoveredArg) 6108 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 6109 numDataArgs, beg, hasVAListArg, Args, formatIdx, 6110 inFunctionCall, CallType, CheckedVarArgs, 6111 UncoveredArg) {} 6112 6113 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 6114 const char *startSpecifier, 6115 unsigned specifierLen) override; 6116 6117 bool HandleInvalidScanfConversionSpecifier( 6118 const analyze_scanf::ScanfSpecifier &FS, 6119 const char *startSpecifier, 6120 unsigned specifierLen) override; 6121 6122 void HandleIncompleteScanList(const char *start, const char *end) override; 6123 }; 6124 } // end anonymous namespace 6125 6126 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 6127 const char *end) { 6128 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 6129 getLocationOfByte(end), /*IsStringLocation*/true, 6130 getSpecifierRange(start, end - start)); 6131 } 6132 6133 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 6134 const analyze_scanf::ScanfSpecifier &FS, 6135 const char *startSpecifier, 6136 unsigned specifierLen) { 6137 6138 const analyze_scanf::ScanfConversionSpecifier &CS = 6139 FS.getConversionSpecifier(); 6140 6141 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 6142 getLocationOfByte(CS.getStart()), 6143 startSpecifier, specifierLen, 6144 CS.getStart(), CS.getLength()); 6145 } 6146 6147 bool CheckScanfHandler::HandleScanfSpecifier( 6148 const analyze_scanf::ScanfSpecifier &FS, 6149 const char *startSpecifier, 6150 unsigned specifierLen) { 6151 using namespace analyze_scanf; 6152 using namespace analyze_format_string; 6153 6154 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 6155 6156 // Handle case where '%' and '*' don't consume an argument. These shouldn't 6157 // be used to decide if we are using positional arguments consistently. 6158 if (FS.consumesDataArgument()) { 6159 if (atFirstArg) { 6160 atFirstArg = false; 6161 usesPositionalArgs = FS.usesPositionalArg(); 6162 } 6163 else if (usesPositionalArgs != FS.usesPositionalArg()) { 6164 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 6165 startSpecifier, specifierLen); 6166 return false; 6167 } 6168 } 6169 6170 // Check if the field with is non-zero. 6171 const OptionalAmount &Amt = FS.getFieldWidth(); 6172 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 6173 if (Amt.getConstantAmount() == 0) { 6174 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 6175 Amt.getConstantLength()); 6176 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 6177 getLocationOfByte(Amt.getStart()), 6178 /*IsStringLocation*/true, R, 6179 FixItHint::CreateRemoval(R)); 6180 } 6181 } 6182 6183 if (!FS.consumesDataArgument()) { 6184 // FIXME: Technically specifying a precision or field width here 6185 // makes no sense. Worth issuing a warning at some point. 6186 return true; 6187 } 6188 6189 // Consume the argument. 6190 unsigned argIndex = FS.getArgIndex(); 6191 if (argIndex < NumDataArgs) { 6192 // The check to see if the argIndex is valid will come later. 6193 // We set the bit here because we may exit early from this 6194 // function if we encounter some other error. 6195 CoveredArgs.set(argIndex); 6196 } 6197 6198 // Check the length modifier is valid with the given conversion specifier. 6199 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 6200 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6201 diag::warn_format_nonsensical_length); 6202 else if (!FS.hasStandardLengthModifier()) 6203 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 6204 else if (!FS.hasStandardLengthConversionCombination()) 6205 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6206 diag::warn_format_non_standard_conversion_spec); 6207 6208 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 6209 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 6210 6211 // The remaining checks depend on the data arguments. 6212 if (HasVAListArg) 6213 return true; 6214 6215 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 6216 return false; 6217 6218 // Check that the argument type matches the format specifier. 6219 const Expr *Ex = getDataArg(argIndex); 6220 if (!Ex) 6221 return true; 6222 6223 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 6224 6225 if (!AT.isValid()) { 6226 return true; 6227 } 6228 6229 analyze_format_string::ArgType::MatchKind match = 6230 AT.matchesType(S.Context, Ex->getType()); 6231 if (match == analyze_format_string::ArgType::Match) { 6232 return true; 6233 } 6234 6235 ScanfSpecifier fixedFS = FS; 6236 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 6237 S.getLangOpts(), S.Context); 6238 6239 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 6240 if (match == analyze_format_string::ArgType::NoMatchPedantic) { 6241 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 6242 } 6243 6244 if (success) { 6245 // Get the fix string from the fixed format specifier. 6246 SmallString<128> buf; 6247 llvm::raw_svector_ostream os(buf); 6248 fixedFS.toString(os); 6249 6250 EmitFormatDiagnostic( 6251 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) 6252 << Ex->getType() << false << Ex->getSourceRange(), 6253 Ex->getLocStart(), 6254 /*IsStringLocation*/ false, 6255 getSpecifierRange(startSpecifier, specifierLen), 6256 FixItHint::CreateReplacement( 6257 getSpecifierRange(startSpecifier, specifierLen), os.str())); 6258 } else { 6259 EmitFormatDiagnostic(S.PDiag(diag) 6260 << AT.getRepresentativeTypeName(S.Context) 6261 << Ex->getType() << false << Ex->getSourceRange(), 6262 Ex->getLocStart(), 6263 /*IsStringLocation*/ false, 6264 getSpecifierRange(startSpecifier, specifierLen)); 6265 } 6266 6267 return true; 6268 } 6269 6270 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 6271 const Expr *OrigFormatExpr, 6272 ArrayRef<const Expr *> Args, 6273 bool HasVAListArg, unsigned format_idx, 6274 unsigned firstDataArg, 6275 Sema::FormatStringType Type, 6276 bool inFunctionCall, 6277 Sema::VariadicCallType CallType, 6278 llvm::SmallBitVector &CheckedVarArgs, 6279 UncoveredArgHandler &UncoveredArg) { 6280 // CHECK: is the format string a wide literal? 6281 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 6282 CheckFormatHandler::EmitFormatDiagnostic( 6283 S, inFunctionCall, Args[format_idx], 6284 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(), 6285 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 6286 return; 6287 } 6288 6289 // Str - The format string. NOTE: this is NOT null-terminated! 6290 StringRef StrRef = FExpr->getString(); 6291 const char *Str = StrRef.data(); 6292 // Account for cases where the string literal is truncated in a declaration. 6293 const ConstantArrayType *T = 6294 S.Context.getAsConstantArrayType(FExpr->getType()); 6295 assert(T && "String literal not of constant array type!"); 6296 size_t TypeSize = T->getSize().getZExtValue(); 6297 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 6298 const unsigned numDataArgs = Args.size() - firstDataArg; 6299 6300 // Emit a warning if the string literal is truncated and does not contain an 6301 // embedded null character. 6302 if (TypeSize <= StrRef.size() && 6303 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 6304 CheckFormatHandler::EmitFormatDiagnostic( 6305 S, inFunctionCall, Args[format_idx], 6306 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 6307 FExpr->getLocStart(), 6308 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 6309 return; 6310 } 6311 6312 // CHECK: empty format string? 6313 if (StrLen == 0 && numDataArgs > 0) { 6314 CheckFormatHandler::EmitFormatDiagnostic( 6315 S, inFunctionCall, Args[format_idx], 6316 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(), 6317 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 6318 return; 6319 } 6320 6321 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 6322 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 6323 Type == Sema::FST_OSTrace) { 6324 CheckPrintfHandler H( 6325 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 6326 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 6327 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 6328 CheckedVarArgs, UncoveredArg); 6329 6330 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 6331 S.getLangOpts(), 6332 S.Context.getTargetInfo(), 6333 Type == Sema::FST_FreeBSDKPrintf)) 6334 H.DoneProcessing(); 6335 } else if (Type == Sema::FST_Scanf) { 6336 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 6337 numDataArgs, Str, HasVAListArg, Args, format_idx, 6338 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 6339 6340 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 6341 S.getLangOpts(), 6342 S.Context.getTargetInfo())) 6343 H.DoneProcessing(); 6344 } // TODO: handle other formats 6345 } 6346 6347 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 6348 // Str - The format string. NOTE: this is NOT null-terminated! 6349 StringRef StrRef = FExpr->getString(); 6350 const char *Str = StrRef.data(); 6351 // Account for cases where the string literal is truncated in a declaration. 6352 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 6353 assert(T && "String literal not of constant array type!"); 6354 size_t TypeSize = T->getSize().getZExtValue(); 6355 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 6356 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 6357 getLangOpts(), 6358 Context.getTargetInfo()); 6359 } 6360 6361 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 6362 6363 // Returns the related absolute value function that is larger, of 0 if one 6364 // does not exist. 6365 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 6366 switch (AbsFunction) { 6367 default: 6368 return 0; 6369 6370 case Builtin::BI__builtin_abs: 6371 return Builtin::BI__builtin_labs; 6372 case Builtin::BI__builtin_labs: 6373 return Builtin::BI__builtin_llabs; 6374 case Builtin::BI__builtin_llabs: 6375 return 0; 6376 6377 case Builtin::BI__builtin_fabsf: 6378 return Builtin::BI__builtin_fabs; 6379 case Builtin::BI__builtin_fabs: 6380 return Builtin::BI__builtin_fabsl; 6381 case Builtin::BI__builtin_fabsl: 6382 return 0; 6383 6384 case Builtin::BI__builtin_cabsf: 6385 return Builtin::BI__builtin_cabs; 6386 case Builtin::BI__builtin_cabs: 6387 return Builtin::BI__builtin_cabsl; 6388 case Builtin::BI__builtin_cabsl: 6389 return 0; 6390 6391 case Builtin::BIabs: 6392 return Builtin::BIlabs; 6393 case Builtin::BIlabs: 6394 return Builtin::BIllabs; 6395 case Builtin::BIllabs: 6396 return 0; 6397 6398 case Builtin::BIfabsf: 6399 return Builtin::BIfabs; 6400 case Builtin::BIfabs: 6401 return Builtin::BIfabsl; 6402 case Builtin::BIfabsl: 6403 return 0; 6404 6405 case Builtin::BIcabsf: 6406 return Builtin::BIcabs; 6407 case Builtin::BIcabs: 6408 return Builtin::BIcabsl; 6409 case Builtin::BIcabsl: 6410 return 0; 6411 } 6412 } 6413 6414 // Returns the argument type of the absolute value function. 6415 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 6416 unsigned AbsType) { 6417 if (AbsType == 0) 6418 return QualType(); 6419 6420 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 6421 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 6422 if (Error != ASTContext::GE_None) 6423 return QualType(); 6424 6425 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 6426 if (!FT) 6427 return QualType(); 6428 6429 if (FT->getNumParams() != 1) 6430 return QualType(); 6431 6432 return FT->getParamType(0); 6433 } 6434 6435 // Returns the best absolute value function, or zero, based on type and 6436 // current absolute value function. 6437 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 6438 unsigned AbsFunctionKind) { 6439 unsigned BestKind = 0; 6440 uint64_t ArgSize = Context.getTypeSize(ArgType); 6441 for (unsigned Kind = AbsFunctionKind; Kind != 0; 6442 Kind = getLargerAbsoluteValueFunction(Kind)) { 6443 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 6444 if (Context.getTypeSize(ParamType) >= ArgSize) { 6445 if (BestKind == 0) 6446 BestKind = Kind; 6447 else if (Context.hasSameType(ParamType, ArgType)) { 6448 BestKind = Kind; 6449 break; 6450 } 6451 } 6452 } 6453 return BestKind; 6454 } 6455 6456 enum AbsoluteValueKind { 6457 AVK_Integer, 6458 AVK_Floating, 6459 AVK_Complex 6460 }; 6461 6462 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 6463 if (T->isIntegralOrEnumerationType()) 6464 return AVK_Integer; 6465 if (T->isRealFloatingType()) 6466 return AVK_Floating; 6467 if (T->isAnyComplexType()) 6468 return AVK_Complex; 6469 6470 llvm_unreachable("Type not integer, floating, or complex"); 6471 } 6472 6473 // Changes the absolute value function to a different type. Preserves whether 6474 // the function is a builtin. 6475 static unsigned changeAbsFunction(unsigned AbsKind, 6476 AbsoluteValueKind ValueKind) { 6477 switch (ValueKind) { 6478 case AVK_Integer: 6479 switch (AbsKind) { 6480 default: 6481 return 0; 6482 case Builtin::BI__builtin_fabsf: 6483 case Builtin::BI__builtin_fabs: 6484 case Builtin::BI__builtin_fabsl: 6485 case Builtin::BI__builtin_cabsf: 6486 case Builtin::BI__builtin_cabs: 6487 case Builtin::BI__builtin_cabsl: 6488 return Builtin::BI__builtin_abs; 6489 case Builtin::BIfabsf: 6490 case Builtin::BIfabs: 6491 case Builtin::BIfabsl: 6492 case Builtin::BIcabsf: 6493 case Builtin::BIcabs: 6494 case Builtin::BIcabsl: 6495 return Builtin::BIabs; 6496 } 6497 case AVK_Floating: 6498 switch (AbsKind) { 6499 default: 6500 return 0; 6501 case Builtin::BI__builtin_abs: 6502 case Builtin::BI__builtin_labs: 6503 case Builtin::BI__builtin_llabs: 6504 case Builtin::BI__builtin_cabsf: 6505 case Builtin::BI__builtin_cabs: 6506 case Builtin::BI__builtin_cabsl: 6507 return Builtin::BI__builtin_fabsf; 6508 case Builtin::BIabs: 6509 case Builtin::BIlabs: 6510 case Builtin::BIllabs: 6511 case Builtin::BIcabsf: 6512 case Builtin::BIcabs: 6513 case Builtin::BIcabsl: 6514 return Builtin::BIfabsf; 6515 } 6516 case AVK_Complex: 6517 switch (AbsKind) { 6518 default: 6519 return 0; 6520 case Builtin::BI__builtin_abs: 6521 case Builtin::BI__builtin_labs: 6522 case Builtin::BI__builtin_llabs: 6523 case Builtin::BI__builtin_fabsf: 6524 case Builtin::BI__builtin_fabs: 6525 case Builtin::BI__builtin_fabsl: 6526 return Builtin::BI__builtin_cabsf; 6527 case Builtin::BIabs: 6528 case Builtin::BIlabs: 6529 case Builtin::BIllabs: 6530 case Builtin::BIfabsf: 6531 case Builtin::BIfabs: 6532 case Builtin::BIfabsl: 6533 return Builtin::BIcabsf; 6534 } 6535 } 6536 llvm_unreachable("Unable to convert function"); 6537 } 6538 6539 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 6540 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 6541 if (!FnInfo) 6542 return 0; 6543 6544 switch (FDecl->getBuiltinID()) { 6545 default: 6546 return 0; 6547 case Builtin::BI__builtin_abs: 6548 case Builtin::BI__builtin_fabs: 6549 case Builtin::BI__builtin_fabsf: 6550 case Builtin::BI__builtin_fabsl: 6551 case Builtin::BI__builtin_labs: 6552 case Builtin::BI__builtin_llabs: 6553 case Builtin::BI__builtin_cabs: 6554 case Builtin::BI__builtin_cabsf: 6555 case Builtin::BI__builtin_cabsl: 6556 case Builtin::BIabs: 6557 case Builtin::BIlabs: 6558 case Builtin::BIllabs: 6559 case Builtin::BIfabs: 6560 case Builtin::BIfabsf: 6561 case Builtin::BIfabsl: 6562 case Builtin::BIcabs: 6563 case Builtin::BIcabsf: 6564 case Builtin::BIcabsl: 6565 return FDecl->getBuiltinID(); 6566 } 6567 llvm_unreachable("Unknown Builtin type"); 6568 } 6569 6570 // If the replacement is valid, emit a note with replacement function. 6571 // Additionally, suggest including the proper header if not already included. 6572 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 6573 unsigned AbsKind, QualType ArgType) { 6574 bool EmitHeaderHint = true; 6575 const char *HeaderName = nullptr; 6576 const char *FunctionName = nullptr; 6577 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 6578 FunctionName = "std::abs"; 6579 if (ArgType->isIntegralOrEnumerationType()) { 6580 HeaderName = "cstdlib"; 6581 } else if (ArgType->isRealFloatingType()) { 6582 HeaderName = "cmath"; 6583 } else { 6584 llvm_unreachable("Invalid Type"); 6585 } 6586 6587 // Lookup all std::abs 6588 if (NamespaceDecl *Std = S.getStdNamespace()) { 6589 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 6590 R.suppressDiagnostics(); 6591 S.LookupQualifiedName(R, Std); 6592 6593 for (const auto *I : R) { 6594 const FunctionDecl *FDecl = nullptr; 6595 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 6596 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 6597 } else { 6598 FDecl = dyn_cast<FunctionDecl>(I); 6599 } 6600 if (!FDecl) 6601 continue; 6602 6603 // Found std::abs(), check that they are the right ones. 6604 if (FDecl->getNumParams() != 1) 6605 continue; 6606 6607 // Check that the parameter type can handle the argument. 6608 QualType ParamType = FDecl->getParamDecl(0)->getType(); 6609 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 6610 S.Context.getTypeSize(ArgType) <= 6611 S.Context.getTypeSize(ParamType)) { 6612 // Found a function, don't need the header hint. 6613 EmitHeaderHint = false; 6614 break; 6615 } 6616 } 6617 } 6618 } else { 6619 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 6620 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 6621 6622 if (HeaderName) { 6623 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 6624 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 6625 R.suppressDiagnostics(); 6626 S.LookupName(R, S.getCurScope()); 6627 6628 if (R.isSingleResult()) { 6629 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 6630 if (FD && FD->getBuiltinID() == AbsKind) { 6631 EmitHeaderHint = false; 6632 } else { 6633 return; 6634 } 6635 } else if (!R.empty()) { 6636 return; 6637 } 6638 } 6639 } 6640 6641 S.Diag(Loc, diag::note_replace_abs_function) 6642 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 6643 6644 if (!HeaderName) 6645 return; 6646 6647 if (!EmitHeaderHint) 6648 return; 6649 6650 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 6651 << FunctionName; 6652 } 6653 6654 static bool IsFunctionStdAbs(const FunctionDecl *FDecl) { 6655 if (!FDecl) 6656 return false; 6657 6658 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs")) 6659 return false; 6660 6661 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext()); 6662 6663 while (ND && ND->isInlineNamespace()) { 6664 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext()); 6665 } 6666 6667 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std")) 6668 return false; 6669 6670 if (!isa<TranslationUnitDecl>(ND->getDeclContext())) 6671 return false; 6672 6673 return true; 6674 } 6675 6676 // Warn when using the wrong abs() function. 6677 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 6678 const FunctionDecl *FDecl, 6679 IdentifierInfo *FnInfo) { 6680 if (Call->getNumArgs() != 1) 6681 return; 6682 6683 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 6684 bool IsStdAbs = IsFunctionStdAbs(FDecl); 6685 if (AbsKind == 0 && !IsStdAbs) 6686 return; 6687 6688 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 6689 QualType ParamType = Call->getArg(0)->getType(); 6690 6691 // Unsigned types cannot be negative. Suggest removing the absolute value 6692 // function call. 6693 if (ArgType->isUnsignedIntegerType()) { 6694 const char *FunctionName = 6695 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 6696 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 6697 Diag(Call->getExprLoc(), diag::note_remove_abs) 6698 << FunctionName 6699 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 6700 return; 6701 } 6702 6703 // Taking the absolute value of a pointer is very suspicious, they probably 6704 // wanted to index into an array, dereference a pointer, call a function, etc. 6705 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 6706 unsigned DiagType = 0; 6707 if (ArgType->isFunctionType()) 6708 DiagType = 1; 6709 else if (ArgType->isArrayType()) 6710 DiagType = 2; 6711 6712 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 6713 return; 6714 } 6715 6716 // std::abs has overloads which prevent most of the absolute value problems 6717 // from occurring. 6718 if (IsStdAbs) 6719 return; 6720 6721 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 6722 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 6723 6724 // The argument and parameter are the same kind. Check if they are the right 6725 // size. 6726 if (ArgValueKind == ParamValueKind) { 6727 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 6728 return; 6729 6730 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 6731 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 6732 << FDecl << ArgType << ParamType; 6733 6734 if (NewAbsKind == 0) 6735 return; 6736 6737 emitReplacement(*this, Call->getExprLoc(), 6738 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 6739 return; 6740 } 6741 6742 // ArgValueKind != ParamValueKind 6743 // The wrong type of absolute value function was used. Attempt to find the 6744 // proper one. 6745 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 6746 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 6747 if (NewAbsKind == 0) 6748 return; 6749 6750 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 6751 << FDecl << ParamValueKind << ArgValueKind; 6752 6753 emitReplacement(*this, Call->getExprLoc(), 6754 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 6755 } 6756 6757 //===--- CHECK: Standard memory functions ---------------------------------===// 6758 6759 /// \brief Takes the expression passed to the size_t parameter of functions 6760 /// such as memcmp, strncat, etc and warns if it's a comparison. 6761 /// 6762 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 6763 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 6764 IdentifierInfo *FnName, 6765 SourceLocation FnLoc, 6766 SourceLocation RParenLoc) { 6767 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 6768 if (!Size) 6769 return false; 6770 6771 // if E is binop and op is >, <, >=, <=, ==, &&, ||: 6772 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp()) 6773 return false; 6774 6775 SourceRange SizeRange = Size->getSourceRange(); 6776 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 6777 << SizeRange << FnName; 6778 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 6779 << FnName << FixItHint::CreateInsertion( 6780 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")") 6781 << FixItHint::CreateRemoval(RParenLoc); 6782 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 6783 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 6784 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 6785 ")"); 6786 6787 return true; 6788 } 6789 6790 /// \brief Determine whether the given type is or contains a dynamic class type 6791 /// (e.g., whether it has a vtable). 6792 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 6793 bool &IsContained) { 6794 // Look through array types while ignoring qualifiers. 6795 const Type *Ty = T->getBaseElementTypeUnsafe(); 6796 IsContained = false; 6797 6798 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 6799 RD = RD ? RD->getDefinition() : nullptr; 6800 if (!RD || RD->isInvalidDecl()) 6801 return nullptr; 6802 6803 if (RD->isDynamicClass()) 6804 return RD; 6805 6806 // Check all the fields. If any bases were dynamic, the class is dynamic. 6807 // It's impossible for a class to transitively contain itself by value, so 6808 // infinite recursion is impossible. 6809 for (auto *FD : RD->fields()) { 6810 bool SubContained; 6811 if (const CXXRecordDecl *ContainedRD = 6812 getContainedDynamicClass(FD->getType(), SubContained)) { 6813 IsContained = true; 6814 return ContainedRD; 6815 } 6816 } 6817 6818 return nullptr; 6819 } 6820 6821 /// \brief If E is a sizeof expression, returns its argument expression, 6822 /// otherwise returns NULL. 6823 static const Expr *getSizeOfExprArg(const Expr *E) { 6824 if (const UnaryExprOrTypeTraitExpr *SizeOf = 6825 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 6826 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType()) 6827 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 6828 6829 return nullptr; 6830 } 6831 6832 /// \brief If E is a sizeof expression, returns its argument type. 6833 static QualType getSizeOfArgType(const Expr *E) { 6834 if (const UnaryExprOrTypeTraitExpr *SizeOf = 6835 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 6836 if (SizeOf->getKind() == clang::UETT_SizeOf) 6837 return SizeOf->getTypeOfArgument(); 6838 6839 return QualType(); 6840 } 6841 6842 /// \brief Check for dangerous or invalid arguments to memset(). 6843 /// 6844 /// This issues warnings on known problematic, dangerous or unspecified 6845 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 6846 /// function calls. 6847 /// 6848 /// \param Call The call expression to diagnose. 6849 void Sema::CheckMemaccessArguments(const CallExpr *Call, 6850 unsigned BId, 6851 IdentifierInfo *FnName) { 6852 assert(BId != 0); 6853 6854 // It is possible to have a non-standard definition of memset. Validate 6855 // we have enough arguments, and if not, abort further checking. 6856 unsigned ExpectedNumArgs = 6857 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 6858 if (Call->getNumArgs() < ExpectedNumArgs) 6859 return; 6860 6861 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 6862 BId == Builtin::BIstrndup ? 1 : 2); 6863 unsigned LenArg = 6864 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 6865 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 6866 6867 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 6868 Call->getLocStart(), Call->getRParenLoc())) 6869 return; 6870 6871 // We have special checking when the length is a sizeof expression. 6872 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 6873 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 6874 llvm::FoldingSetNodeID SizeOfArgID; 6875 6876 // Although widely used, 'bzero' is not a standard function. Be more strict 6877 // with the argument types before allowing diagnostics and only allow the 6878 // form bzero(ptr, sizeof(...)). 6879 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 6880 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 6881 return; 6882 6883 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 6884 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 6885 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 6886 6887 QualType DestTy = Dest->getType(); 6888 QualType PointeeTy; 6889 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 6890 PointeeTy = DestPtrTy->getPointeeType(); 6891 6892 // Never warn about void type pointers. This can be used to suppress 6893 // false positives. 6894 if (PointeeTy->isVoidType()) 6895 continue; 6896 6897 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 6898 // actually comparing the expressions for equality. Because computing the 6899 // expression IDs can be expensive, we only do this if the diagnostic is 6900 // enabled. 6901 if (SizeOfArg && 6902 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 6903 SizeOfArg->getExprLoc())) { 6904 // We only compute IDs for expressions if the warning is enabled, and 6905 // cache the sizeof arg's ID. 6906 if (SizeOfArgID == llvm::FoldingSetNodeID()) 6907 SizeOfArg->Profile(SizeOfArgID, Context, true); 6908 llvm::FoldingSetNodeID DestID; 6909 Dest->Profile(DestID, Context, true); 6910 if (DestID == SizeOfArgID) { 6911 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 6912 // over sizeof(src) as well. 6913 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 6914 StringRef ReadableName = FnName->getName(); 6915 6916 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 6917 if (UnaryOp->getOpcode() == UO_AddrOf) 6918 ActionIdx = 1; // If its an address-of operator, just remove it. 6919 if (!PointeeTy->isIncompleteType() && 6920 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 6921 ActionIdx = 2; // If the pointee's size is sizeof(char), 6922 // suggest an explicit length. 6923 6924 // If the function is defined as a builtin macro, do not show macro 6925 // expansion. 6926 SourceLocation SL = SizeOfArg->getExprLoc(); 6927 SourceRange DSR = Dest->getSourceRange(); 6928 SourceRange SSR = SizeOfArg->getSourceRange(); 6929 SourceManager &SM = getSourceManager(); 6930 6931 if (SM.isMacroArgExpansion(SL)) { 6932 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 6933 SL = SM.getSpellingLoc(SL); 6934 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 6935 SM.getSpellingLoc(DSR.getEnd())); 6936 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 6937 SM.getSpellingLoc(SSR.getEnd())); 6938 } 6939 6940 DiagRuntimeBehavior(SL, SizeOfArg, 6941 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 6942 << ReadableName 6943 << PointeeTy 6944 << DestTy 6945 << DSR 6946 << SSR); 6947 DiagRuntimeBehavior(SL, SizeOfArg, 6948 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 6949 << ActionIdx 6950 << SSR); 6951 6952 break; 6953 } 6954 } 6955 6956 // Also check for cases where the sizeof argument is the exact same 6957 // type as the memory argument, and where it points to a user-defined 6958 // record type. 6959 if (SizeOfArgTy != QualType()) { 6960 if (PointeeTy->isRecordType() && 6961 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 6962 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 6963 PDiag(diag::warn_sizeof_pointer_type_memaccess) 6964 << FnName << SizeOfArgTy << ArgIdx 6965 << PointeeTy << Dest->getSourceRange() 6966 << LenExpr->getSourceRange()); 6967 break; 6968 } 6969 } 6970 } else if (DestTy->isArrayType()) { 6971 PointeeTy = DestTy; 6972 } 6973 6974 if (PointeeTy == QualType()) 6975 continue; 6976 6977 // Always complain about dynamic classes. 6978 bool IsContained; 6979 if (const CXXRecordDecl *ContainedRD = 6980 getContainedDynamicClass(PointeeTy, IsContained)) { 6981 6982 unsigned OperationType = 0; 6983 // "overwritten" if we're warning about the destination for any call 6984 // but memcmp; otherwise a verb appropriate to the call. 6985 if (ArgIdx != 0 || BId == Builtin::BImemcmp) { 6986 if (BId == Builtin::BImemcpy) 6987 OperationType = 1; 6988 else if(BId == Builtin::BImemmove) 6989 OperationType = 2; 6990 else if (BId == Builtin::BImemcmp) 6991 OperationType = 3; 6992 } 6993 6994 DiagRuntimeBehavior( 6995 Dest->getExprLoc(), Dest, 6996 PDiag(diag::warn_dyn_class_memaccess) 6997 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx) 6998 << FnName << IsContained << ContainedRD << OperationType 6999 << Call->getCallee()->getSourceRange()); 7000 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 7001 BId != Builtin::BImemset) 7002 DiagRuntimeBehavior( 7003 Dest->getExprLoc(), Dest, 7004 PDiag(diag::warn_arc_object_memaccess) 7005 << ArgIdx << FnName << PointeeTy 7006 << Call->getCallee()->getSourceRange()); 7007 else 7008 continue; 7009 7010 DiagRuntimeBehavior( 7011 Dest->getExprLoc(), Dest, 7012 PDiag(diag::note_bad_memaccess_silence) 7013 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 7014 break; 7015 } 7016 } 7017 7018 // A little helper routine: ignore addition and subtraction of integer literals. 7019 // This intentionally does not ignore all integer constant expressions because 7020 // we don't want to remove sizeof(). 7021 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 7022 Ex = Ex->IgnoreParenCasts(); 7023 7024 for (;;) { 7025 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 7026 if (!BO || !BO->isAdditiveOp()) 7027 break; 7028 7029 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 7030 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 7031 7032 if (isa<IntegerLiteral>(RHS)) 7033 Ex = LHS; 7034 else if (isa<IntegerLiteral>(LHS)) 7035 Ex = RHS; 7036 else 7037 break; 7038 } 7039 7040 return Ex; 7041 } 7042 7043 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 7044 ASTContext &Context) { 7045 // Only handle constant-sized or VLAs, but not flexible members. 7046 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 7047 // Only issue the FIXIT for arrays of size > 1. 7048 if (CAT->getSize().getSExtValue() <= 1) 7049 return false; 7050 } else if (!Ty->isVariableArrayType()) { 7051 return false; 7052 } 7053 return true; 7054 } 7055 7056 // Warn if the user has made the 'size' argument to strlcpy or strlcat 7057 // be the size of the source, instead of the destination. 7058 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 7059 IdentifierInfo *FnName) { 7060 7061 // Don't crash if the user has the wrong number of arguments 7062 unsigned NumArgs = Call->getNumArgs(); 7063 if ((NumArgs != 3) && (NumArgs != 4)) 7064 return; 7065 7066 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 7067 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 7068 const Expr *CompareWithSrc = nullptr; 7069 7070 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 7071 Call->getLocStart(), Call->getRParenLoc())) 7072 return; 7073 7074 // Look for 'strlcpy(dst, x, sizeof(x))' 7075 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 7076 CompareWithSrc = Ex; 7077 else { 7078 // Look for 'strlcpy(dst, x, strlen(x))' 7079 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 7080 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 7081 SizeCall->getNumArgs() == 1) 7082 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 7083 } 7084 } 7085 7086 if (!CompareWithSrc) 7087 return; 7088 7089 // Determine if the argument to sizeof/strlen is equal to the source 7090 // argument. In principle there's all kinds of things you could do 7091 // here, for instance creating an == expression and evaluating it with 7092 // EvaluateAsBooleanCondition, but this uses a more direct technique: 7093 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 7094 if (!SrcArgDRE) 7095 return; 7096 7097 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 7098 if (!CompareWithSrcDRE || 7099 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 7100 return; 7101 7102 const Expr *OriginalSizeArg = Call->getArg(2); 7103 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size) 7104 << OriginalSizeArg->getSourceRange() << FnName; 7105 7106 // Output a FIXIT hint if the destination is an array (rather than a 7107 // pointer to an array). This could be enhanced to handle some 7108 // pointers if we know the actual size, like if DstArg is 'array+2' 7109 // we could say 'sizeof(array)-2'. 7110 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 7111 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 7112 return; 7113 7114 SmallString<128> sizeString; 7115 llvm::raw_svector_ostream OS(sizeString); 7116 OS << "sizeof("; 7117 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 7118 OS << ")"; 7119 7120 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size) 7121 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 7122 OS.str()); 7123 } 7124 7125 /// Check if two expressions refer to the same declaration. 7126 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 7127 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 7128 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 7129 return D1->getDecl() == D2->getDecl(); 7130 return false; 7131 } 7132 7133 static const Expr *getStrlenExprArg(const Expr *E) { 7134 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 7135 const FunctionDecl *FD = CE->getDirectCallee(); 7136 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 7137 return nullptr; 7138 return CE->getArg(0)->IgnoreParenCasts(); 7139 } 7140 return nullptr; 7141 } 7142 7143 // Warn on anti-patterns as the 'size' argument to strncat. 7144 // The correct size argument should look like following: 7145 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 7146 void Sema::CheckStrncatArguments(const CallExpr *CE, 7147 IdentifierInfo *FnName) { 7148 // Don't crash if the user has the wrong number of arguments. 7149 if (CE->getNumArgs() < 3) 7150 return; 7151 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 7152 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 7153 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 7154 7155 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(), 7156 CE->getRParenLoc())) 7157 return; 7158 7159 // Identify common expressions, which are wrongly used as the size argument 7160 // to strncat and may lead to buffer overflows. 7161 unsigned PatternType = 0; 7162 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 7163 // - sizeof(dst) 7164 if (referToTheSameDecl(SizeOfArg, DstArg)) 7165 PatternType = 1; 7166 // - sizeof(src) 7167 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 7168 PatternType = 2; 7169 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 7170 if (BE->getOpcode() == BO_Sub) { 7171 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 7172 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 7173 // - sizeof(dst) - strlen(dst) 7174 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 7175 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 7176 PatternType = 1; 7177 // - sizeof(src) - (anything) 7178 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 7179 PatternType = 2; 7180 } 7181 } 7182 7183 if (PatternType == 0) 7184 return; 7185 7186 // Generate the diagnostic. 7187 SourceLocation SL = LenArg->getLocStart(); 7188 SourceRange SR = LenArg->getSourceRange(); 7189 SourceManager &SM = getSourceManager(); 7190 7191 // If the function is defined as a builtin macro, do not show macro expansion. 7192 if (SM.isMacroArgExpansion(SL)) { 7193 SL = SM.getSpellingLoc(SL); 7194 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 7195 SM.getSpellingLoc(SR.getEnd())); 7196 } 7197 7198 // Check if the destination is an array (rather than a pointer to an array). 7199 QualType DstTy = DstArg->getType(); 7200 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 7201 Context); 7202 if (!isKnownSizeArray) { 7203 if (PatternType == 1) 7204 Diag(SL, diag::warn_strncat_wrong_size) << SR; 7205 else 7206 Diag(SL, diag::warn_strncat_src_size) << SR; 7207 return; 7208 } 7209 7210 if (PatternType == 1) 7211 Diag(SL, diag::warn_strncat_large_size) << SR; 7212 else 7213 Diag(SL, diag::warn_strncat_src_size) << SR; 7214 7215 SmallString<128> sizeString; 7216 llvm::raw_svector_ostream OS(sizeString); 7217 OS << "sizeof("; 7218 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 7219 OS << ") - "; 7220 OS << "strlen("; 7221 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 7222 OS << ") - 1"; 7223 7224 Diag(SL, diag::note_strncat_wrong_size) 7225 << FixItHint::CreateReplacement(SR, OS.str()); 7226 } 7227 7228 //===--- CHECK: Return Address of Stack Variable --------------------------===// 7229 7230 static const Expr *EvalVal(const Expr *E, 7231 SmallVectorImpl<const DeclRefExpr *> &refVars, 7232 const Decl *ParentDecl); 7233 static const Expr *EvalAddr(const Expr *E, 7234 SmallVectorImpl<const DeclRefExpr *> &refVars, 7235 const Decl *ParentDecl); 7236 7237 /// CheckReturnStackAddr - Check if a return statement returns the address 7238 /// of a stack variable. 7239 static void 7240 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType, 7241 SourceLocation ReturnLoc) { 7242 7243 const Expr *stackE = nullptr; 7244 SmallVector<const DeclRefExpr *, 8> refVars; 7245 7246 // Perform checking for returned stack addresses, local blocks, 7247 // label addresses or references to temporaries. 7248 if (lhsType->isPointerType() || 7249 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) { 7250 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr); 7251 } else if (lhsType->isReferenceType()) { 7252 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr); 7253 } 7254 7255 if (!stackE) 7256 return; // Nothing suspicious was found. 7257 7258 // Parameters are initalized in the calling scope, so taking the address 7259 // of a parameter reference doesn't need a warning. 7260 for (auto *DRE : refVars) 7261 if (isa<ParmVarDecl>(DRE->getDecl())) 7262 return; 7263 7264 SourceLocation diagLoc; 7265 SourceRange diagRange; 7266 if (refVars.empty()) { 7267 diagLoc = stackE->getLocStart(); 7268 diagRange = stackE->getSourceRange(); 7269 } else { 7270 // We followed through a reference variable. 'stackE' contains the 7271 // problematic expression but we will warn at the return statement pointing 7272 // at the reference variable. We will later display the "trail" of 7273 // reference variables using notes. 7274 diagLoc = refVars[0]->getLocStart(); 7275 diagRange = refVars[0]->getSourceRange(); 7276 } 7277 7278 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { 7279 // address of local var 7280 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType() 7281 << DR->getDecl()->getDeclName() << diagRange; 7282 } else if (isa<BlockExpr>(stackE)) { // local block. 7283 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange; 7284 } else if (isa<AddrLabelExpr>(stackE)) { // address of label. 7285 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange; 7286 } else { // local temporary. 7287 // If there is an LValue->RValue conversion, then the value of the 7288 // reference type is used, not the reference. 7289 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) { 7290 if (ICE->getCastKind() == CK_LValueToRValue) { 7291 return; 7292 } 7293 } 7294 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref) 7295 << lhsType->isReferenceType() << diagRange; 7296 } 7297 7298 // Display the "trail" of reference variables that we followed until we 7299 // found the problematic expression using notes. 7300 for (unsigned i = 0, e = refVars.size(); i != e; ++i) { 7301 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl()); 7302 // If this var binds to another reference var, show the range of the next 7303 // var, otherwise the var binds to the problematic expression, in which case 7304 // show the range of the expression. 7305 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange() 7306 : stackE->getSourceRange(); 7307 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind) 7308 << VD->getDeclName() << range; 7309 } 7310 } 7311 7312 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that 7313 /// check if the expression in a return statement evaluates to an address 7314 /// to a location on the stack, a local block, an address of a label, or a 7315 /// reference to local temporary. The recursion is used to traverse the 7316 /// AST of the return expression, with recursion backtracking when we 7317 /// encounter a subexpression that (1) clearly does not lead to one of the 7318 /// above problematic expressions (2) is something we cannot determine leads to 7319 /// a problematic expression based on such local checking. 7320 /// 7321 /// Both EvalAddr and EvalVal follow through reference variables to evaluate 7322 /// the expression that they point to. Such variables are added to the 7323 /// 'refVars' vector so that we know what the reference variable "trail" was. 7324 /// 7325 /// EvalAddr processes expressions that are pointers that are used as 7326 /// references (and not L-values). EvalVal handles all other values. 7327 /// At the base case of the recursion is a check for the above problematic 7328 /// expressions. 7329 /// 7330 /// This implementation handles: 7331 /// 7332 /// * pointer-to-pointer casts 7333 /// * implicit conversions from array references to pointers 7334 /// * taking the address of fields 7335 /// * arbitrary interplay between "&" and "*" operators 7336 /// * pointer arithmetic from an address of a stack variable 7337 /// * taking the address of an array element where the array is on the stack 7338 static const Expr *EvalAddr(const Expr *E, 7339 SmallVectorImpl<const DeclRefExpr *> &refVars, 7340 const Decl *ParentDecl) { 7341 if (E->isTypeDependent()) 7342 return nullptr; 7343 7344 // We should only be called for evaluating pointer expressions. 7345 assert((E->getType()->isAnyPointerType() || 7346 E->getType()->isBlockPointerType() || 7347 E->getType()->isObjCQualifiedIdType()) && 7348 "EvalAddr only works on pointers"); 7349 7350 E = E->IgnoreParens(); 7351 7352 // Our "symbolic interpreter" is just a dispatch off the currently 7353 // viewed AST node. We then recursively traverse the AST by calling 7354 // EvalAddr and EvalVal appropriately. 7355 switch (E->getStmtClass()) { 7356 case Stmt::DeclRefExprClass: { 7357 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 7358 7359 // If we leave the immediate function, the lifetime isn't about to end. 7360 if (DR->refersToEnclosingVariableOrCapture()) 7361 return nullptr; 7362 7363 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) 7364 // If this is a reference variable, follow through to the expression that 7365 // it points to. 7366 if (V->hasLocalStorage() && 7367 V->getType()->isReferenceType() && V->hasInit()) { 7368 // Add the reference variable to the "trail". 7369 refVars.push_back(DR); 7370 return EvalAddr(V->getInit(), refVars, ParentDecl); 7371 } 7372 7373 return nullptr; 7374 } 7375 7376 case Stmt::UnaryOperatorClass: { 7377 // The only unary operator that make sense to handle here 7378 // is AddrOf. All others don't make sense as pointers. 7379 const UnaryOperator *U = cast<UnaryOperator>(E); 7380 7381 if (U->getOpcode() == UO_AddrOf) 7382 return EvalVal(U->getSubExpr(), refVars, ParentDecl); 7383 return nullptr; 7384 } 7385 7386 case Stmt::BinaryOperatorClass: { 7387 // Handle pointer arithmetic. All other binary operators are not valid 7388 // in this context. 7389 const BinaryOperator *B = cast<BinaryOperator>(E); 7390 BinaryOperatorKind op = B->getOpcode(); 7391 7392 if (op != BO_Add && op != BO_Sub) 7393 return nullptr; 7394 7395 const Expr *Base = B->getLHS(); 7396 7397 // Determine which argument is the real pointer base. It could be 7398 // the RHS argument instead of the LHS. 7399 if (!Base->getType()->isPointerType()) 7400 Base = B->getRHS(); 7401 7402 assert(Base->getType()->isPointerType()); 7403 return EvalAddr(Base, refVars, ParentDecl); 7404 } 7405 7406 // For conditional operators we need to see if either the LHS or RHS are 7407 // valid DeclRefExpr*s. If one of them is valid, we return it. 7408 case Stmt::ConditionalOperatorClass: { 7409 const ConditionalOperator *C = cast<ConditionalOperator>(E); 7410 7411 // Handle the GNU extension for missing LHS. 7412 // FIXME: That isn't a ConditionalOperator, so doesn't get here. 7413 if (const Expr *LHSExpr = C->getLHS()) { 7414 // In C++, we can have a throw-expression, which has 'void' type. 7415 if (!LHSExpr->getType()->isVoidType()) 7416 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl)) 7417 return LHS; 7418 } 7419 7420 // In C++, we can have a throw-expression, which has 'void' type. 7421 if (C->getRHS()->getType()->isVoidType()) 7422 return nullptr; 7423 7424 return EvalAddr(C->getRHS(), refVars, ParentDecl); 7425 } 7426 7427 case Stmt::BlockExprClass: 7428 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures()) 7429 return E; // local block. 7430 return nullptr; 7431 7432 case Stmt::AddrLabelExprClass: 7433 return E; // address of label. 7434 7435 case Stmt::ExprWithCleanupsClass: 7436 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars, 7437 ParentDecl); 7438 7439 // For casts, we need to handle conversions from arrays to 7440 // pointer values, and pointer-to-pointer conversions. 7441 case Stmt::ImplicitCastExprClass: 7442 case Stmt::CStyleCastExprClass: 7443 case Stmt::CXXFunctionalCastExprClass: 7444 case Stmt::ObjCBridgedCastExprClass: 7445 case Stmt::CXXStaticCastExprClass: 7446 case Stmt::CXXDynamicCastExprClass: 7447 case Stmt::CXXConstCastExprClass: 7448 case Stmt::CXXReinterpretCastExprClass: { 7449 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr(); 7450 switch (cast<CastExpr>(E)->getCastKind()) { 7451 case CK_LValueToRValue: 7452 case CK_NoOp: 7453 case CK_BaseToDerived: 7454 case CK_DerivedToBase: 7455 case CK_UncheckedDerivedToBase: 7456 case CK_Dynamic: 7457 case CK_CPointerToObjCPointerCast: 7458 case CK_BlockPointerToObjCPointerCast: 7459 case CK_AnyPointerToBlockPointerCast: 7460 return EvalAddr(SubExpr, refVars, ParentDecl); 7461 7462 case CK_ArrayToPointerDecay: 7463 return EvalVal(SubExpr, refVars, ParentDecl); 7464 7465 case CK_BitCast: 7466 if (SubExpr->getType()->isAnyPointerType() || 7467 SubExpr->getType()->isBlockPointerType() || 7468 SubExpr->getType()->isObjCQualifiedIdType()) 7469 return EvalAddr(SubExpr, refVars, ParentDecl); 7470 else 7471 return nullptr; 7472 7473 default: 7474 return nullptr; 7475 } 7476 } 7477 7478 case Stmt::MaterializeTemporaryExprClass: 7479 if (const Expr *Result = 7480 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 7481 refVars, ParentDecl)) 7482 return Result; 7483 return E; 7484 7485 // Everything else: we simply don't reason about them. 7486 default: 7487 return nullptr; 7488 } 7489 } 7490 7491 /// EvalVal - This function is complements EvalAddr in the mutual recursion. 7492 /// See the comments for EvalAddr for more details. 7493 static const Expr *EvalVal(const Expr *E, 7494 SmallVectorImpl<const DeclRefExpr *> &refVars, 7495 const Decl *ParentDecl) { 7496 do { 7497 // We should only be called for evaluating non-pointer expressions, or 7498 // expressions with a pointer type that are not used as references but 7499 // instead 7500 // are l-values (e.g., DeclRefExpr with a pointer type). 7501 7502 // Our "symbolic interpreter" is just a dispatch off the currently 7503 // viewed AST node. We then recursively traverse the AST by calling 7504 // EvalAddr and EvalVal appropriately. 7505 7506 E = E->IgnoreParens(); 7507 switch (E->getStmtClass()) { 7508 case Stmt::ImplicitCastExprClass: { 7509 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E); 7510 if (IE->getValueKind() == VK_LValue) { 7511 E = IE->getSubExpr(); 7512 continue; 7513 } 7514 return nullptr; 7515 } 7516 7517 case Stmt::ExprWithCleanupsClass: 7518 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars, 7519 ParentDecl); 7520 7521 case Stmt::DeclRefExprClass: { 7522 // When we hit a DeclRefExpr we are looking at code that refers to a 7523 // variable's name. If it's not a reference variable we check if it has 7524 // local storage within the function, and if so, return the expression. 7525 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 7526 7527 // If we leave the immediate function, the lifetime isn't about to end. 7528 if (DR->refersToEnclosingVariableOrCapture()) 7529 return nullptr; 7530 7531 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) { 7532 // Check if it refers to itself, e.g. "int& i = i;". 7533 if (V == ParentDecl) 7534 return DR; 7535 7536 if (V->hasLocalStorage()) { 7537 if (!V->getType()->isReferenceType()) 7538 return DR; 7539 7540 // Reference variable, follow through to the expression that 7541 // it points to. 7542 if (V->hasInit()) { 7543 // Add the reference variable to the "trail". 7544 refVars.push_back(DR); 7545 return EvalVal(V->getInit(), refVars, V); 7546 } 7547 } 7548 } 7549 7550 return nullptr; 7551 } 7552 7553 case Stmt::UnaryOperatorClass: { 7554 // The only unary operator that make sense to handle here 7555 // is Deref. All others don't resolve to a "name." This includes 7556 // handling all sorts of rvalues passed to a unary operator. 7557 const UnaryOperator *U = cast<UnaryOperator>(E); 7558 7559 if (U->getOpcode() == UO_Deref) 7560 return EvalAddr(U->getSubExpr(), refVars, ParentDecl); 7561 7562 return nullptr; 7563 } 7564 7565 case Stmt::ArraySubscriptExprClass: { 7566 // Array subscripts are potential references to data on the stack. We 7567 // retrieve the DeclRefExpr* for the array variable if it indeed 7568 // has local storage. 7569 const auto *ASE = cast<ArraySubscriptExpr>(E); 7570 if (ASE->isTypeDependent()) 7571 return nullptr; 7572 return EvalAddr(ASE->getBase(), refVars, ParentDecl); 7573 } 7574 7575 case Stmt::OMPArraySectionExprClass: { 7576 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars, 7577 ParentDecl); 7578 } 7579 7580 case Stmt::ConditionalOperatorClass: { 7581 // For conditional operators we need to see if either the LHS or RHS are 7582 // non-NULL Expr's. If one is non-NULL, we return it. 7583 const ConditionalOperator *C = cast<ConditionalOperator>(E); 7584 7585 // Handle the GNU extension for missing LHS. 7586 if (const Expr *LHSExpr = C->getLHS()) { 7587 // In C++, we can have a throw-expression, which has 'void' type. 7588 if (!LHSExpr->getType()->isVoidType()) 7589 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl)) 7590 return LHS; 7591 } 7592 7593 // In C++, we can have a throw-expression, which has 'void' type. 7594 if (C->getRHS()->getType()->isVoidType()) 7595 return nullptr; 7596 7597 return EvalVal(C->getRHS(), refVars, ParentDecl); 7598 } 7599 7600 // Accesses to members are potential references to data on the stack. 7601 case Stmt::MemberExprClass: { 7602 const MemberExpr *M = cast<MemberExpr>(E); 7603 7604 // Check for indirect access. We only want direct field accesses. 7605 if (M->isArrow()) 7606 return nullptr; 7607 7608 // Check whether the member type is itself a reference, in which case 7609 // we're not going to refer to the member, but to what the member refers 7610 // to. 7611 if (M->getMemberDecl()->getType()->isReferenceType()) 7612 return nullptr; 7613 7614 return EvalVal(M->getBase(), refVars, ParentDecl); 7615 } 7616 7617 case Stmt::MaterializeTemporaryExprClass: 7618 if (const Expr *Result = 7619 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 7620 refVars, ParentDecl)) 7621 return Result; 7622 return E; 7623 7624 default: 7625 // Check that we don't return or take the address of a reference to a 7626 // temporary. This is only useful in C++. 7627 if (!E->isTypeDependent() && E->isRValue()) 7628 return E; 7629 7630 // Everything else: we simply don't reason about them. 7631 return nullptr; 7632 } 7633 } while (true); 7634 } 7635 7636 void 7637 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 7638 SourceLocation ReturnLoc, 7639 bool isObjCMethod, 7640 const AttrVec *Attrs, 7641 const FunctionDecl *FD) { 7642 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc); 7643 7644 // Check if the return value is null but should not be. 7645 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 7646 (!isObjCMethod && isNonNullType(Context, lhsType))) && 7647 CheckNonNullExpr(*this, RetValExp)) 7648 Diag(ReturnLoc, diag::warn_null_ret) 7649 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 7650 7651 // C++11 [basic.stc.dynamic.allocation]p4: 7652 // If an allocation function declared with a non-throwing 7653 // exception-specification fails to allocate storage, it shall return 7654 // a null pointer. Any other allocation function that fails to allocate 7655 // storage shall indicate failure only by throwing an exception [...] 7656 if (FD) { 7657 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 7658 if (Op == OO_New || Op == OO_Array_New) { 7659 const FunctionProtoType *Proto 7660 = FD->getType()->castAs<FunctionProtoType>(); 7661 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) && 7662 CheckNonNullExpr(*this, RetValExp)) 7663 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 7664 << FD << getLangOpts().CPlusPlus11; 7665 } 7666 } 7667 } 7668 7669 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 7670 7671 /// Check for comparisons of floating point operands using != and ==. 7672 /// Issue a warning if these are no self-comparisons, as they are not likely 7673 /// to do what the programmer intended. 7674 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 7675 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 7676 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 7677 7678 // Special case: check for x == x (which is OK). 7679 // Do not emit warnings for such cases. 7680 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 7681 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 7682 if (DRL->getDecl() == DRR->getDecl()) 7683 return; 7684 7685 // Special case: check for comparisons against literals that can be exactly 7686 // represented by APFloat. In such cases, do not emit a warning. This 7687 // is a heuristic: often comparison against such literals are used to 7688 // detect if a value in a variable has not changed. This clearly can 7689 // lead to false negatives. 7690 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 7691 if (FLL->isExact()) 7692 return; 7693 } else 7694 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 7695 if (FLR->isExact()) 7696 return; 7697 7698 // Check for comparisons with builtin types. 7699 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 7700 if (CL->getBuiltinCallee()) 7701 return; 7702 7703 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 7704 if (CR->getBuiltinCallee()) 7705 return; 7706 7707 // Emit the diagnostic. 7708 Diag(Loc, diag::warn_floatingpoint_eq) 7709 << LHS->getSourceRange() << RHS->getSourceRange(); 7710 } 7711 7712 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 7713 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 7714 7715 namespace { 7716 7717 /// Structure recording the 'active' range of an integer-valued 7718 /// expression. 7719 struct IntRange { 7720 /// The number of bits active in the int. 7721 unsigned Width; 7722 7723 /// True if the int is known not to have negative values. 7724 bool NonNegative; 7725 7726 IntRange(unsigned Width, bool NonNegative) 7727 : Width(Width), NonNegative(NonNegative) 7728 {} 7729 7730 /// Returns the range of the bool type. 7731 static IntRange forBoolType() { 7732 return IntRange(1, true); 7733 } 7734 7735 /// Returns the range of an opaque value of the given integral type. 7736 static IntRange forValueOfType(ASTContext &C, QualType T) { 7737 return forValueOfCanonicalType(C, 7738 T->getCanonicalTypeInternal().getTypePtr()); 7739 } 7740 7741 /// Returns the range of an opaque value of a canonical integral type. 7742 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 7743 assert(T->isCanonicalUnqualified()); 7744 7745 if (const VectorType *VT = dyn_cast<VectorType>(T)) 7746 T = VT->getElementType().getTypePtr(); 7747 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 7748 T = CT->getElementType().getTypePtr(); 7749 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 7750 T = AT->getValueType().getTypePtr(); 7751 7752 // For enum types, use the known bit width of the enumerators. 7753 if (const EnumType *ET = dyn_cast<EnumType>(T)) { 7754 EnumDecl *Enum = ET->getDecl(); 7755 if (!Enum->isCompleteDefinition()) 7756 return IntRange(C.getIntWidth(QualType(T, 0)), false); 7757 7758 unsigned NumPositive = Enum->getNumPositiveBits(); 7759 unsigned NumNegative = Enum->getNumNegativeBits(); 7760 7761 if (NumNegative == 0) 7762 return IntRange(NumPositive, true/*NonNegative*/); 7763 else 7764 return IntRange(std::max(NumPositive + 1, NumNegative), 7765 false/*NonNegative*/); 7766 } 7767 7768 const BuiltinType *BT = cast<BuiltinType>(T); 7769 assert(BT->isInteger()); 7770 7771 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 7772 } 7773 7774 /// Returns the "target" range of a canonical integral type, i.e. 7775 /// the range of values expressible in the type. 7776 /// 7777 /// This matches forValueOfCanonicalType except that enums have the 7778 /// full range of their type, not the range of their enumerators. 7779 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 7780 assert(T->isCanonicalUnqualified()); 7781 7782 if (const VectorType *VT = dyn_cast<VectorType>(T)) 7783 T = VT->getElementType().getTypePtr(); 7784 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 7785 T = CT->getElementType().getTypePtr(); 7786 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 7787 T = AT->getValueType().getTypePtr(); 7788 if (const EnumType *ET = dyn_cast<EnumType>(T)) 7789 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 7790 7791 const BuiltinType *BT = cast<BuiltinType>(T); 7792 assert(BT->isInteger()); 7793 7794 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 7795 } 7796 7797 /// Returns the supremum of two ranges: i.e. their conservative merge. 7798 static IntRange join(IntRange L, IntRange R) { 7799 return IntRange(std::max(L.Width, R.Width), 7800 L.NonNegative && R.NonNegative); 7801 } 7802 7803 /// Returns the infinum of two ranges: i.e. their aggressive merge. 7804 static IntRange meet(IntRange L, IntRange R) { 7805 return IntRange(std::min(L.Width, R.Width), 7806 L.NonNegative || R.NonNegative); 7807 } 7808 }; 7809 7810 IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) { 7811 if (value.isSigned() && value.isNegative()) 7812 return IntRange(value.getMinSignedBits(), false); 7813 7814 if (value.getBitWidth() > MaxWidth) 7815 value = value.trunc(MaxWidth); 7816 7817 // isNonNegative() just checks the sign bit without considering 7818 // signedness. 7819 return IntRange(value.getActiveBits(), true); 7820 } 7821 7822 IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 7823 unsigned MaxWidth) { 7824 if (result.isInt()) 7825 return GetValueRange(C, result.getInt(), MaxWidth); 7826 7827 if (result.isVector()) { 7828 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 7829 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 7830 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 7831 R = IntRange::join(R, El); 7832 } 7833 return R; 7834 } 7835 7836 if (result.isComplexInt()) { 7837 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 7838 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 7839 return IntRange::join(R, I); 7840 } 7841 7842 // This can happen with lossless casts to intptr_t of "based" lvalues. 7843 // Assume it might use arbitrary bits. 7844 // FIXME: The only reason we need to pass the type in here is to get 7845 // the sign right on this one case. It would be nice if APValue 7846 // preserved this. 7847 assert(result.isLValue() || result.isAddrLabelDiff()); 7848 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 7849 } 7850 7851 QualType GetExprType(const Expr *E) { 7852 QualType Ty = E->getType(); 7853 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 7854 Ty = AtomicRHS->getValueType(); 7855 return Ty; 7856 } 7857 7858 /// Pseudo-evaluate the given integer expression, estimating the 7859 /// range of values it might take. 7860 /// 7861 /// \param MaxWidth - the width to which the value will be truncated 7862 IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) { 7863 E = E->IgnoreParens(); 7864 7865 // Try a full evaluation first. 7866 Expr::EvalResult result; 7867 if (E->EvaluateAsRValue(result, C)) 7868 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 7869 7870 // I think we only want to look through implicit casts here; if the 7871 // user has an explicit widening cast, we should treat the value as 7872 // being of the new, wider type. 7873 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 7874 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 7875 return GetExprRange(C, CE->getSubExpr(), MaxWidth); 7876 7877 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 7878 7879 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 7880 CE->getCastKind() == CK_BooleanToSignedIntegral; 7881 7882 // Assume that non-integer casts can span the full range of the type. 7883 if (!isIntegerCast) 7884 return OutputTypeRange; 7885 7886 IntRange SubRange 7887 = GetExprRange(C, CE->getSubExpr(), 7888 std::min(MaxWidth, OutputTypeRange.Width)); 7889 7890 // Bail out if the subexpr's range is as wide as the cast type. 7891 if (SubRange.Width >= OutputTypeRange.Width) 7892 return OutputTypeRange; 7893 7894 // Otherwise, we take the smaller width, and we're non-negative if 7895 // either the output type or the subexpr is. 7896 return IntRange(SubRange.Width, 7897 SubRange.NonNegative || OutputTypeRange.NonNegative); 7898 } 7899 7900 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 7901 // If we can fold the condition, just take that operand. 7902 bool CondResult; 7903 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 7904 return GetExprRange(C, CondResult ? CO->getTrueExpr() 7905 : CO->getFalseExpr(), 7906 MaxWidth); 7907 7908 // Otherwise, conservatively merge. 7909 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth); 7910 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth); 7911 return IntRange::join(L, R); 7912 } 7913 7914 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 7915 switch (BO->getOpcode()) { 7916 7917 // Boolean-valued operations are single-bit and positive. 7918 case BO_LAnd: 7919 case BO_LOr: 7920 case BO_LT: 7921 case BO_GT: 7922 case BO_LE: 7923 case BO_GE: 7924 case BO_EQ: 7925 case BO_NE: 7926 return IntRange::forBoolType(); 7927 7928 // The type of the assignments is the type of the LHS, so the RHS 7929 // is not necessarily the same type. 7930 case BO_MulAssign: 7931 case BO_DivAssign: 7932 case BO_RemAssign: 7933 case BO_AddAssign: 7934 case BO_SubAssign: 7935 case BO_XorAssign: 7936 case BO_OrAssign: 7937 // TODO: bitfields? 7938 return IntRange::forValueOfType(C, GetExprType(E)); 7939 7940 // Simple assignments just pass through the RHS, which will have 7941 // been coerced to the LHS type. 7942 case BO_Assign: 7943 // TODO: bitfields? 7944 return GetExprRange(C, BO->getRHS(), MaxWidth); 7945 7946 // Operations with opaque sources are black-listed. 7947 case BO_PtrMemD: 7948 case BO_PtrMemI: 7949 return IntRange::forValueOfType(C, GetExprType(E)); 7950 7951 // Bitwise-and uses the *infinum* of the two source ranges. 7952 case BO_And: 7953 case BO_AndAssign: 7954 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth), 7955 GetExprRange(C, BO->getRHS(), MaxWidth)); 7956 7957 // Left shift gets black-listed based on a judgement call. 7958 case BO_Shl: 7959 // ...except that we want to treat '1 << (blah)' as logically 7960 // positive. It's an important idiom. 7961 if (IntegerLiteral *I 7962 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 7963 if (I->getValue() == 1) { 7964 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 7965 return IntRange(R.Width, /*NonNegative*/ true); 7966 } 7967 } 7968 // fallthrough 7969 7970 case BO_ShlAssign: 7971 return IntRange::forValueOfType(C, GetExprType(E)); 7972 7973 // Right shift by a constant can narrow its left argument. 7974 case BO_Shr: 7975 case BO_ShrAssign: { 7976 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 7977 7978 // If the shift amount is a positive constant, drop the width by 7979 // that much. 7980 llvm::APSInt shift; 7981 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 7982 shift.isNonNegative()) { 7983 unsigned zext = shift.getZExtValue(); 7984 if (zext >= L.Width) 7985 L.Width = (L.NonNegative ? 0 : 1); 7986 else 7987 L.Width -= zext; 7988 } 7989 7990 return L; 7991 } 7992 7993 // Comma acts as its right operand. 7994 case BO_Comma: 7995 return GetExprRange(C, BO->getRHS(), MaxWidth); 7996 7997 // Black-list pointer subtractions. 7998 case BO_Sub: 7999 if (BO->getLHS()->getType()->isPointerType()) 8000 return IntRange::forValueOfType(C, GetExprType(E)); 8001 break; 8002 8003 // The width of a division result is mostly determined by the size 8004 // of the LHS. 8005 case BO_Div: { 8006 // Don't 'pre-truncate' the operands. 8007 unsigned opWidth = C.getIntWidth(GetExprType(E)); 8008 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 8009 8010 // If the divisor is constant, use that. 8011 llvm::APSInt divisor; 8012 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 8013 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 8014 if (log2 >= L.Width) 8015 L.Width = (L.NonNegative ? 0 : 1); 8016 else 8017 L.Width = std::min(L.Width - log2, MaxWidth); 8018 return L; 8019 } 8020 8021 // Otherwise, just use the LHS's width. 8022 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 8023 return IntRange(L.Width, L.NonNegative && R.NonNegative); 8024 } 8025 8026 // The result of a remainder can't be larger than the result of 8027 // either side. 8028 case BO_Rem: { 8029 // Don't 'pre-truncate' the operands. 8030 unsigned opWidth = C.getIntWidth(GetExprType(E)); 8031 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 8032 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 8033 8034 IntRange meet = IntRange::meet(L, R); 8035 meet.Width = std::min(meet.Width, MaxWidth); 8036 return meet; 8037 } 8038 8039 // The default behavior is okay for these. 8040 case BO_Mul: 8041 case BO_Add: 8042 case BO_Xor: 8043 case BO_Or: 8044 break; 8045 } 8046 8047 // The default case is to treat the operation as if it were closed 8048 // on the narrowest type that encompasses both operands. 8049 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 8050 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth); 8051 return IntRange::join(L, R); 8052 } 8053 8054 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 8055 switch (UO->getOpcode()) { 8056 // Boolean-valued operations are white-listed. 8057 case UO_LNot: 8058 return IntRange::forBoolType(); 8059 8060 // Operations with opaque sources are black-listed. 8061 case UO_Deref: 8062 case UO_AddrOf: // should be impossible 8063 return IntRange::forValueOfType(C, GetExprType(E)); 8064 8065 default: 8066 return GetExprRange(C, UO->getSubExpr(), MaxWidth); 8067 } 8068 } 8069 8070 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 8071 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth); 8072 8073 if (const auto *BitField = E->getSourceBitField()) 8074 return IntRange(BitField->getBitWidthValue(C), 8075 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 8076 8077 return IntRange::forValueOfType(C, GetExprType(E)); 8078 } 8079 8080 IntRange GetExprRange(ASTContext &C, const Expr *E) { 8081 return GetExprRange(C, E, C.getIntWidth(GetExprType(E))); 8082 } 8083 8084 /// Checks whether the given value, which currently has the given 8085 /// source semantics, has the same value when coerced through the 8086 /// target semantics. 8087 bool IsSameFloatAfterCast(const llvm::APFloat &value, 8088 const llvm::fltSemantics &Src, 8089 const llvm::fltSemantics &Tgt) { 8090 llvm::APFloat truncated = value; 8091 8092 bool ignored; 8093 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 8094 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 8095 8096 return truncated.bitwiseIsEqual(value); 8097 } 8098 8099 /// Checks whether the given value, which currently has the given 8100 /// source semantics, has the same value when coerced through the 8101 /// target semantics. 8102 /// 8103 /// The value might be a vector of floats (or a complex number). 8104 bool IsSameFloatAfterCast(const APValue &value, 8105 const llvm::fltSemantics &Src, 8106 const llvm::fltSemantics &Tgt) { 8107 if (value.isFloat()) 8108 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 8109 8110 if (value.isVector()) { 8111 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 8112 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 8113 return false; 8114 return true; 8115 } 8116 8117 assert(value.isComplexFloat()); 8118 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 8119 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 8120 } 8121 8122 void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC); 8123 8124 bool IsZero(Sema &S, Expr *E) { 8125 // Suppress cases where we are comparing against an enum constant. 8126 if (const DeclRefExpr *DR = 8127 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 8128 if (isa<EnumConstantDecl>(DR->getDecl())) 8129 return false; 8130 8131 // Suppress cases where the '0' value is expanded from a macro. 8132 if (E->getLocStart().isMacroID()) 8133 return false; 8134 8135 llvm::APSInt Value; 8136 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0; 8137 } 8138 8139 bool HasEnumType(Expr *E) { 8140 // Strip off implicit integral promotions. 8141 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 8142 if (ICE->getCastKind() != CK_IntegralCast && 8143 ICE->getCastKind() != CK_NoOp) 8144 break; 8145 E = ICE->getSubExpr(); 8146 } 8147 8148 return E->getType()->isEnumeralType(); 8149 } 8150 8151 void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) { 8152 // Disable warning in template instantiations. 8153 if (!S.ActiveTemplateInstantiations.empty()) 8154 return; 8155 8156 BinaryOperatorKind op = E->getOpcode(); 8157 if (E->isValueDependent()) 8158 return; 8159 8160 if (op == BO_LT && IsZero(S, E->getRHS())) { 8161 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 8162 << "< 0" << "false" << HasEnumType(E->getLHS()) 8163 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 8164 } else if (op == BO_GE && IsZero(S, E->getRHS())) { 8165 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 8166 << ">= 0" << "true" << HasEnumType(E->getLHS()) 8167 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 8168 } else if (op == BO_GT && IsZero(S, E->getLHS())) { 8169 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 8170 << "0 >" << "false" << HasEnumType(E->getRHS()) 8171 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 8172 } else if (op == BO_LE && IsZero(S, E->getLHS())) { 8173 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 8174 << "0 <=" << "true" << HasEnumType(E->getRHS()) 8175 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 8176 } 8177 } 8178 8179 void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant, 8180 Expr *Other, const llvm::APSInt &Value, 8181 bool RhsConstant) { 8182 // Disable warning in template instantiations. 8183 if (!S.ActiveTemplateInstantiations.empty()) 8184 return; 8185 8186 // TODO: Investigate using GetExprRange() to get tighter bounds 8187 // on the bit ranges. 8188 QualType OtherT = Other->getType(); 8189 if (const auto *AT = OtherT->getAs<AtomicType>()) 8190 OtherT = AT->getValueType(); 8191 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); 8192 unsigned OtherWidth = OtherRange.Width; 8193 8194 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue(); 8195 8196 // 0 values are handled later by CheckTrivialUnsignedComparison(). 8197 if ((Value == 0) && (!OtherIsBooleanType)) 8198 return; 8199 8200 BinaryOperatorKind op = E->getOpcode(); 8201 bool IsTrue = true; 8202 8203 // Used for diagnostic printout. 8204 enum { 8205 LiteralConstant = 0, 8206 CXXBoolLiteralTrue, 8207 CXXBoolLiteralFalse 8208 } LiteralOrBoolConstant = LiteralConstant; 8209 8210 if (!OtherIsBooleanType) { 8211 QualType ConstantT = Constant->getType(); 8212 QualType CommonT = E->getLHS()->getType(); 8213 8214 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT)) 8215 return; 8216 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) && 8217 "comparison with non-integer type"); 8218 8219 bool ConstantSigned = ConstantT->isSignedIntegerType(); 8220 bool CommonSigned = CommonT->isSignedIntegerType(); 8221 8222 bool EqualityOnly = false; 8223 8224 if (CommonSigned) { 8225 // The common type is signed, therefore no signed to unsigned conversion. 8226 if (!OtherRange.NonNegative) { 8227 // Check that the constant is representable in type OtherT. 8228 if (ConstantSigned) { 8229 if (OtherWidth >= Value.getMinSignedBits()) 8230 return; 8231 } else { // !ConstantSigned 8232 if (OtherWidth >= Value.getActiveBits() + 1) 8233 return; 8234 } 8235 } else { // !OtherSigned 8236 // Check that the constant is representable in type OtherT. 8237 // Negative values are out of range. 8238 if (ConstantSigned) { 8239 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits()) 8240 return; 8241 } else { // !ConstantSigned 8242 if (OtherWidth >= Value.getActiveBits()) 8243 return; 8244 } 8245 } 8246 } else { // !CommonSigned 8247 if (OtherRange.NonNegative) { 8248 if (OtherWidth >= Value.getActiveBits()) 8249 return; 8250 } else { // OtherSigned 8251 assert(!ConstantSigned && 8252 "Two signed types converted to unsigned types."); 8253 // Check to see if the constant is representable in OtherT. 8254 if (OtherWidth > Value.getActiveBits()) 8255 return; 8256 // Check to see if the constant is equivalent to a negative value 8257 // cast to CommonT. 8258 if (S.Context.getIntWidth(ConstantT) == 8259 S.Context.getIntWidth(CommonT) && 8260 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth) 8261 return; 8262 // The constant value rests between values that OtherT can represent 8263 // after conversion. Relational comparison still works, but equality 8264 // comparisons will be tautological. 8265 EqualityOnly = true; 8266 } 8267 } 8268 8269 bool PositiveConstant = !ConstantSigned || Value.isNonNegative(); 8270 8271 if (op == BO_EQ || op == BO_NE) { 8272 IsTrue = op == BO_NE; 8273 } else if (EqualityOnly) { 8274 return; 8275 } else if (RhsConstant) { 8276 if (op == BO_GT || op == BO_GE) 8277 IsTrue = !PositiveConstant; 8278 else // op == BO_LT || op == BO_LE 8279 IsTrue = PositiveConstant; 8280 } else { 8281 if (op == BO_LT || op == BO_LE) 8282 IsTrue = !PositiveConstant; 8283 else // op == BO_GT || op == BO_GE 8284 IsTrue = PositiveConstant; 8285 } 8286 } else { 8287 // Other isKnownToHaveBooleanValue 8288 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn }; 8289 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal }; 8290 enum ConstantSide { Lhs, Rhs, SizeOfConstSides }; 8291 8292 static const struct LinkedConditions { 8293 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal]; 8294 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal]; 8295 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal]; 8296 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal]; 8297 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal]; 8298 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal]; 8299 8300 } TruthTable = { 8301 // Constant on LHS. | Constant on RHS. | 8302 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One| 8303 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } }, 8304 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } }, 8305 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } }, 8306 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } }, 8307 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } }, 8308 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } } 8309 }; 8310 8311 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant); 8312 8313 enum ConstantValue ConstVal = Zero; 8314 if (Value.isUnsigned() || Value.isNonNegative()) { 8315 if (Value == 0) { 8316 LiteralOrBoolConstant = 8317 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant; 8318 ConstVal = Zero; 8319 } else if (Value == 1) { 8320 LiteralOrBoolConstant = 8321 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant; 8322 ConstVal = One; 8323 } else { 8324 LiteralOrBoolConstant = LiteralConstant; 8325 ConstVal = GT_One; 8326 } 8327 } else { 8328 ConstVal = LT_Zero; 8329 } 8330 8331 CompareBoolWithConstantResult CmpRes; 8332 8333 switch (op) { 8334 case BO_LT: 8335 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal]; 8336 break; 8337 case BO_GT: 8338 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal]; 8339 break; 8340 case BO_LE: 8341 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal]; 8342 break; 8343 case BO_GE: 8344 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal]; 8345 break; 8346 case BO_EQ: 8347 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal]; 8348 break; 8349 case BO_NE: 8350 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal]; 8351 break; 8352 default: 8353 CmpRes = Unkwn; 8354 break; 8355 } 8356 8357 if (CmpRes == AFals) { 8358 IsTrue = false; 8359 } else if (CmpRes == ATrue) { 8360 IsTrue = true; 8361 } else { 8362 return; 8363 } 8364 } 8365 8366 // If this is a comparison to an enum constant, include that 8367 // constant in the diagnostic. 8368 const EnumConstantDecl *ED = nullptr; 8369 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 8370 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 8371 8372 SmallString<64> PrettySourceValue; 8373 llvm::raw_svector_ostream OS(PrettySourceValue); 8374 if (ED) 8375 OS << '\'' << *ED << "' (" << Value << ")"; 8376 else 8377 OS << Value; 8378 8379 S.DiagRuntimeBehavior( 8380 E->getOperatorLoc(), E, 8381 S.PDiag(diag::warn_out_of_range_compare) 8382 << OS.str() << LiteralOrBoolConstant 8383 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue 8384 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 8385 } 8386 8387 /// Analyze the operands of the given comparison. Implements the 8388 /// fallback case from AnalyzeComparison. 8389 void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 8390 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 8391 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 8392 } 8393 8394 /// \brief Implements -Wsign-compare. 8395 /// 8396 /// \param E the binary operator to check for warnings 8397 void AnalyzeComparison(Sema &S, BinaryOperator *E) { 8398 // The type the comparison is being performed in. 8399 QualType T = E->getLHS()->getType(); 8400 8401 // Only analyze comparison operators where both sides have been converted to 8402 // the same type. 8403 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 8404 return AnalyzeImpConvsInComparison(S, E); 8405 8406 // Don't analyze value-dependent comparisons directly. 8407 if (E->isValueDependent()) 8408 return AnalyzeImpConvsInComparison(S, E); 8409 8410 Expr *LHS = E->getLHS()->IgnoreParenImpCasts(); 8411 Expr *RHS = E->getRHS()->IgnoreParenImpCasts(); 8412 8413 bool IsComparisonConstant = false; 8414 8415 // Check whether an integer constant comparison results in a value 8416 // of 'true' or 'false'. 8417 if (T->isIntegralType(S.Context)) { 8418 llvm::APSInt RHSValue; 8419 bool IsRHSIntegralLiteral = 8420 RHS->isIntegerConstantExpr(RHSValue, S.Context); 8421 llvm::APSInt LHSValue; 8422 bool IsLHSIntegralLiteral = 8423 LHS->isIntegerConstantExpr(LHSValue, S.Context); 8424 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral) 8425 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true); 8426 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral) 8427 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false); 8428 else 8429 IsComparisonConstant = 8430 (IsRHSIntegralLiteral && IsLHSIntegralLiteral); 8431 } else if (!T->hasUnsignedIntegerRepresentation()) 8432 IsComparisonConstant = E->isIntegerConstantExpr(S.Context); 8433 8434 // We don't do anything special if this isn't an unsigned integral 8435 // comparison: we're only interested in integral comparisons, and 8436 // signed comparisons only happen in cases we don't care to warn about. 8437 // 8438 // We also don't care about value-dependent expressions or expressions 8439 // whose result is a constant. 8440 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant) 8441 return AnalyzeImpConvsInComparison(S, E); 8442 8443 // Check to see if one of the (unmodified) operands is of different 8444 // signedness. 8445 Expr *signedOperand, *unsignedOperand; 8446 if (LHS->getType()->hasSignedIntegerRepresentation()) { 8447 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 8448 "unsigned comparison between two signed integer expressions?"); 8449 signedOperand = LHS; 8450 unsignedOperand = RHS; 8451 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 8452 signedOperand = RHS; 8453 unsignedOperand = LHS; 8454 } else { 8455 CheckTrivialUnsignedComparison(S, E); 8456 return AnalyzeImpConvsInComparison(S, E); 8457 } 8458 8459 // Otherwise, calculate the effective range of the signed operand. 8460 IntRange signedRange = GetExprRange(S.Context, signedOperand); 8461 8462 // Go ahead and analyze implicit conversions in the operands. Note 8463 // that we skip the implicit conversions on both sides. 8464 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 8465 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 8466 8467 // If the signed range is non-negative, -Wsign-compare won't fire, 8468 // but we should still check for comparisons which are always true 8469 // or false. 8470 if (signedRange.NonNegative) 8471 return CheckTrivialUnsignedComparison(S, E); 8472 8473 // For (in)equality comparisons, if the unsigned operand is a 8474 // constant which cannot collide with a overflowed signed operand, 8475 // then reinterpreting the signed operand as unsigned will not 8476 // change the result of the comparison. 8477 if (E->isEqualityOp()) { 8478 unsigned comparisonWidth = S.Context.getIntWidth(T); 8479 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand); 8480 8481 // We should never be unable to prove that the unsigned operand is 8482 // non-negative. 8483 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 8484 8485 if (unsignedRange.Width < comparisonWidth) 8486 return; 8487 } 8488 8489 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 8490 S.PDiag(diag::warn_mixed_sign_comparison) 8491 << LHS->getType() << RHS->getType() 8492 << LHS->getSourceRange() << RHS->getSourceRange()); 8493 } 8494 8495 /// Analyzes an attempt to assign the given value to a bitfield. 8496 /// 8497 /// Returns true if there was something fishy about the attempt. 8498 bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 8499 SourceLocation InitLoc) { 8500 assert(Bitfield->isBitField()); 8501 if (Bitfield->isInvalidDecl()) 8502 return false; 8503 8504 // White-list bool bitfields. 8505 if (Bitfield->getType()->isBooleanType()) 8506 return false; 8507 8508 // Ignore value- or type-dependent expressions. 8509 if (Bitfield->getBitWidth()->isValueDependent() || 8510 Bitfield->getBitWidth()->isTypeDependent() || 8511 Init->isValueDependent() || 8512 Init->isTypeDependent()) 8513 return false; 8514 8515 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 8516 8517 llvm::APSInt Value; 8518 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) 8519 return false; 8520 8521 unsigned OriginalWidth = Value.getBitWidth(); 8522 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 8523 8524 if (!Value.isSigned() || Value.isNegative()) 8525 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 8526 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 8527 OriginalWidth = Value.getMinSignedBits(); 8528 8529 if (OriginalWidth <= FieldWidth) 8530 return false; 8531 8532 // Compute the value which the bitfield will contain. 8533 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 8534 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType()); 8535 8536 // Check whether the stored value is equal to the original value. 8537 TruncatedValue = TruncatedValue.extend(OriginalWidth); 8538 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 8539 return false; 8540 8541 // Special-case bitfields of width 1: booleans are naturally 0/1, and 8542 // therefore don't strictly fit into a signed bitfield of width 1. 8543 if (FieldWidth == 1 && Value == 1) 8544 return false; 8545 8546 std::string PrettyValue = Value.toString(10); 8547 std::string PrettyTrunc = TruncatedValue.toString(10); 8548 8549 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 8550 << PrettyValue << PrettyTrunc << OriginalInit->getType() 8551 << Init->getSourceRange(); 8552 8553 return true; 8554 } 8555 8556 /// Analyze the given simple or compound assignment for warning-worthy 8557 /// operations. 8558 void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 8559 // Just recurse on the LHS. 8560 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 8561 8562 // We want to recurse on the RHS as normal unless we're assigning to 8563 // a bitfield. 8564 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 8565 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 8566 E->getOperatorLoc())) { 8567 // Recurse, ignoring any implicit conversions on the RHS. 8568 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 8569 E->getOperatorLoc()); 8570 } 8571 } 8572 8573 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 8574 } 8575 8576 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 8577 void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 8578 SourceLocation CContext, unsigned diag, 8579 bool pruneControlFlow = false) { 8580 if (pruneControlFlow) { 8581 S.DiagRuntimeBehavior(E->getExprLoc(), E, 8582 S.PDiag(diag) 8583 << SourceType << T << E->getSourceRange() 8584 << SourceRange(CContext)); 8585 return; 8586 } 8587 S.Diag(E->getExprLoc(), diag) 8588 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 8589 } 8590 8591 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 8592 void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext, 8593 unsigned diag, bool pruneControlFlow = false) { 8594 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 8595 } 8596 8597 8598 /// Diagnose an implicit cast from a floating point value to an integer value. 8599 void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 8600 8601 SourceLocation CContext) { 8602 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 8603 const bool PruneWarnings = !S.ActiveTemplateInstantiations.empty(); 8604 8605 Expr *InnerE = E->IgnoreParenImpCasts(); 8606 // We also want to warn on, e.g., "int i = -1.234" 8607 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 8608 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 8609 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 8610 8611 const bool IsLiteral = 8612 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 8613 8614 llvm::APFloat Value(0.0); 8615 bool IsConstant = 8616 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 8617 if (!IsConstant) { 8618 return DiagnoseImpCast(S, E, T, CContext, 8619 diag::warn_impcast_float_integer, PruneWarnings); 8620 } 8621 8622 bool isExact = false; 8623 8624 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 8625 T->hasUnsignedIntegerRepresentation()); 8626 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero, 8627 &isExact) == llvm::APFloat::opOK && 8628 isExact) { 8629 if (IsLiteral) return; 8630 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 8631 PruneWarnings); 8632 } 8633 8634 unsigned DiagID = 0; 8635 if (IsLiteral) { 8636 // Warn on floating point literal to integer. 8637 DiagID = diag::warn_impcast_literal_float_to_integer; 8638 } else if (IntegerValue == 0) { 8639 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 8640 return DiagnoseImpCast(S, E, T, CContext, 8641 diag::warn_impcast_float_integer, PruneWarnings); 8642 } 8643 // Warn on non-zero to zero conversion. 8644 DiagID = diag::warn_impcast_float_to_integer_zero; 8645 } else { 8646 if (IntegerValue.isUnsigned()) { 8647 if (!IntegerValue.isMaxValue()) { 8648 return DiagnoseImpCast(S, E, T, CContext, 8649 diag::warn_impcast_float_integer, PruneWarnings); 8650 } 8651 } else { // IntegerValue.isSigned() 8652 if (!IntegerValue.isMaxSignedValue() && 8653 !IntegerValue.isMinSignedValue()) { 8654 return DiagnoseImpCast(S, E, T, CContext, 8655 diag::warn_impcast_float_integer, PruneWarnings); 8656 } 8657 } 8658 // Warn on evaluatable floating point expression to integer conversion. 8659 DiagID = diag::warn_impcast_float_to_integer; 8660 } 8661 8662 // FIXME: Force the precision of the source value down so we don't print 8663 // digits which are usually useless (we don't really care here if we 8664 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 8665 // would automatically print the shortest representation, but it's a bit 8666 // tricky to implement. 8667 SmallString<16> PrettySourceValue; 8668 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 8669 precision = (precision * 59 + 195) / 196; 8670 Value.toString(PrettySourceValue, precision); 8671 8672 SmallString<16> PrettyTargetValue; 8673 if (IsBool) 8674 PrettyTargetValue = Value.isZero() ? "false" : "true"; 8675 else 8676 IntegerValue.toString(PrettyTargetValue); 8677 8678 if (PruneWarnings) { 8679 S.DiagRuntimeBehavior(E->getExprLoc(), E, 8680 S.PDiag(DiagID) 8681 << E->getType() << T.getUnqualifiedType() 8682 << PrettySourceValue << PrettyTargetValue 8683 << E->getSourceRange() << SourceRange(CContext)); 8684 } else { 8685 S.Diag(E->getExprLoc(), DiagID) 8686 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 8687 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 8688 } 8689 } 8690 8691 std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) { 8692 if (!Range.Width) return "0"; 8693 8694 llvm::APSInt ValueInRange = Value; 8695 ValueInRange.setIsSigned(!Range.NonNegative); 8696 ValueInRange = ValueInRange.trunc(Range.Width); 8697 return ValueInRange.toString(10); 8698 } 8699 8700 bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 8701 if (!isa<ImplicitCastExpr>(Ex)) 8702 return false; 8703 8704 Expr *InnerE = Ex->IgnoreParenImpCasts(); 8705 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 8706 const Type *Source = 8707 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 8708 if (Target->isDependentType()) 8709 return false; 8710 8711 const BuiltinType *FloatCandidateBT = 8712 dyn_cast<BuiltinType>(ToBool ? Source : Target); 8713 const Type *BoolCandidateType = ToBool ? Target : Source; 8714 8715 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 8716 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 8717 } 8718 8719 void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 8720 SourceLocation CC) { 8721 unsigned NumArgs = TheCall->getNumArgs(); 8722 for (unsigned i = 0; i < NumArgs; ++i) { 8723 Expr *CurrA = TheCall->getArg(i); 8724 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 8725 continue; 8726 8727 bool IsSwapped = ((i > 0) && 8728 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 8729 IsSwapped |= ((i < (NumArgs - 1)) && 8730 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 8731 if (IsSwapped) { 8732 // Warn on this floating-point to bool conversion. 8733 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 8734 CurrA->getType(), CC, 8735 diag::warn_impcast_floating_point_to_bool); 8736 } 8737 } 8738 } 8739 8740 void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) { 8741 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 8742 E->getExprLoc())) 8743 return; 8744 8745 // Don't warn on functions which have return type nullptr_t. 8746 if (isa<CallExpr>(E)) 8747 return; 8748 8749 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 8750 const Expr::NullPointerConstantKind NullKind = 8751 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 8752 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 8753 return; 8754 8755 // Return if target type is a safe conversion. 8756 if (T->isAnyPointerType() || T->isBlockPointerType() || 8757 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 8758 return; 8759 8760 SourceLocation Loc = E->getSourceRange().getBegin(); 8761 8762 // Venture through the macro stacks to get to the source of macro arguments. 8763 // The new location is a better location than the complete location that was 8764 // passed in. 8765 while (S.SourceMgr.isMacroArgExpansion(Loc)) 8766 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc); 8767 8768 while (S.SourceMgr.isMacroArgExpansion(CC)) 8769 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC); 8770 8771 // __null is usually wrapped in a macro. Go up a macro if that is the case. 8772 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 8773 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 8774 Loc, S.SourceMgr, S.getLangOpts()); 8775 if (MacroName == "NULL") 8776 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first; 8777 } 8778 8779 // Only warn if the null and context location are in the same macro expansion. 8780 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 8781 return; 8782 8783 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 8784 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC) 8785 << FixItHint::CreateReplacement(Loc, 8786 S.getFixItZeroLiteralForType(T, Loc)); 8787 } 8788 8789 void checkObjCArrayLiteral(Sema &S, QualType TargetType, 8790 ObjCArrayLiteral *ArrayLiteral); 8791 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 8792 ObjCDictionaryLiteral *DictionaryLiteral); 8793 8794 /// Check a single element within a collection literal against the 8795 /// target element type. 8796 void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType, 8797 Expr *Element, unsigned ElementKind) { 8798 // Skip a bitcast to 'id' or qualified 'id'. 8799 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 8800 if (ICE->getCastKind() == CK_BitCast && 8801 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 8802 Element = ICE->getSubExpr(); 8803 } 8804 8805 QualType ElementType = Element->getType(); 8806 ExprResult ElementResult(Element); 8807 if (ElementType->getAs<ObjCObjectPointerType>() && 8808 S.CheckSingleAssignmentConstraints(TargetElementType, 8809 ElementResult, 8810 false, false) 8811 != Sema::Compatible) { 8812 S.Diag(Element->getLocStart(), 8813 diag::warn_objc_collection_literal_element) 8814 << ElementType << ElementKind << TargetElementType 8815 << Element->getSourceRange(); 8816 } 8817 8818 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 8819 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 8820 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 8821 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 8822 } 8823 8824 /// Check an Objective-C array literal being converted to the given 8825 /// target type. 8826 void checkObjCArrayLiteral(Sema &S, QualType TargetType, 8827 ObjCArrayLiteral *ArrayLiteral) { 8828 if (!S.NSArrayDecl) 8829 return; 8830 8831 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 8832 if (!TargetObjCPtr) 8833 return; 8834 8835 if (TargetObjCPtr->isUnspecialized() || 8836 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 8837 != S.NSArrayDecl->getCanonicalDecl()) 8838 return; 8839 8840 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 8841 if (TypeArgs.size() != 1) 8842 return; 8843 8844 QualType TargetElementType = TypeArgs[0]; 8845 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 8846 checkObjCCollectionLiteralElement(S, TargetElementType, 8847 ArrayLiteral->getElement(I), 8848 0); 8849 } 8850 } 8851 8852 /// Check an Objective-C dictionary literal being converted to the given 8853 /// target type. 8854 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 8855 ObjCDictionaryLiteral *DictionaryLiteral) { 8856 if (!S.NSDictionaryDecl) 8857 return; 8858 8859 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 8860 if (!TargetObjCPtr) 8861 return; 8862 8863 if (TargetObjCPtr->isUnspecialized() || 8864 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 8865 != S.NSDictionaryDecl->getCanonicalDecl()) 8866 return; 8867 8868 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 8869 if (TypeArgs.size() != 2) 8870 return; 8871 8872 QualType TargetKeyType = TypeArgs[0]; 8873 QualType TargetObjectType = TypeArgs[1]; 8874 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 8875 auto Element = DictionaryLiteral->getKeyValueElement(I); 8876 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 8877 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 8878 } 8879 } 8880 8881 // Helper function to filter out cases for constant width constant conversion. 8882 // Don't warn on char array initialization or for non-decimal values. 8883 bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 8884 SourceLocation CC) { 8885 // If initializing from a constant, and the constant starts with '0', 8886 // then it is a binary, octal, or hexadecimal. Allow these constants 8887 // to fill all the bits, even if there is a sign change. 8888 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 8889 const char FirstLiteralCharacter = 8890 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0]; 8891 if (FirstLiteralCharacter == '0') 8892 return false; 8893 } 8894 8895 // If the CC location points to a '{', and the type is char, then assume 8896 // assume it is an array initialization. 8897 if (CC.isValid() && T->isCharType()) { 8898 const char FirstContextCharacter = 8899 S.getSourceManager().getCharacterData(CC)[0]; 8900 if (FirstContextCharacter == '{') 8901 return false; 8902 } 8903 8904 return true; 8905 } 8906 8907 void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 8908 SourceLocation CC, bool *ICContext = nullptr) { 8909 if (E->isTypeDependent() || E->isValueDependent()) return; 8910 8911 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 8912 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 8913 if (Source == Target) return; 8914 if (Target->isDependentType()) return; 8915 8916 // If the conversion context location is invalid don't complain. We also 8917 // don't want to emit a warning if the issue occurs from the expansion of 8918 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 8919 // delay this check as long as possible. Once we detect we are in that 8920 // scenario, we just return. 8921 if (CC.isInvalid()) 8922 return; 8923 8924 // Diagnose implicit casts to bool. 8925 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 8926 if (isa<StringLiteral>(E)) 8927 // Warn on string literal to bool. Checks for string literals in logical 8928 // and expressions, for instance, assert(0 && "error here"), are 8929 // prevented by a check in AnalyzeImplicitConversions(). 8930 return DiagnoseImpCast(S, E, T, CC, 8931 diag::warn_impcast_string_literal_to_bool); 8932 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 8933 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 8934 // This covers the literal expressions that evaluate to Objective-C 8935 // objects. 8936 return DiagnoseImpCast(S, E, T, CC, 8937 diag::warn_impcast_objective_c_literal_to_bool); 8938 } 8939 if (Source->isPointerType() || Source->canDecayToPointerType()) { 8940 // Warn on pointer to bool conversion that is always true. 8941 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 8942 SourceRange(CC)); 8943 } 8944 } 8945 8946 // Check implicit casts from Objective-C collection literals to specialized 8947 // collection types, e.g., NSArray<NSString *> *. 8948 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 8949 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 8950 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 8951 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 8952 8953 // Strip vector types. 8954 if (isa<VectorType>(Source)) { 8955 if (!isa<VectorType>(Target)) { 8956 if (S.SourceMgr.isInSystemMacro(CC)) 8957 return; 8958 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 8959 } 8960 8961 // If the vector cast is cast between two vectors of the same size, it is 8962 // a bitcast, not a conversion. 8963 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 8964 return; 8965 8966 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 8967 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 8968 } 8969 if (auto VecTy = dyn_cast<VectorType>(Target)) 8970 Target = VecTy->getElementType().getTypePtr(); 8971 8972 // Strip complex types. 8973 if (isa<ComplexType>(Source)) { 8974 if (!isa<ComplexType>(Target)) { 8975 if (S.SourceMgr.isInSystemMacro(CC)) 8976 return; 8977 8978 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar); 8979 } 8980 8981 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 8982 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 8983 } 8984 8985 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 8986 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 8987 8988 // If the source is floating point... 8989 if (SourceBT && SourceBT->isFloatingPoint()) { 8990 // ...and the target is floating point... 8991 if (TargetBT && TargetBT->isFloatingPoint()) { 8992 // ...then warn if we're dropping FP rank. 8993 8994 // Builtin FP kinds are ordered by increasing FP rank. 8995 if (SourceBT->getKind() > TargetBT->getKind()) { 8996 // Don't warn about float constants that are precisely 8997 // representable in the target type. 8998 Expr::EvalResult result; 8999 if (E->EvaluateAsRValue(result, S.Context)) { 9000 // Value might be a float, a float vector, or a float complex. 9001 if (IsSameFloatAfterCast(result.Val, 9002 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 9003 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 9004 return; 9005 } 9006 9007 if (S.SourceMgr.isInSystemMacro(CC)) 9008 return; 9009 9010 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 9011 } 9012 // ... or possibly if we're increasing rank, too 9013 else if (TargetBT->getKind() > SourceBT->getKind()) { 9014 if (S.SourceMgr.isInSystemMacro(CC)) 9015 return; 9016 9017 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 9018 } 9019 return; 9020 } 9021 9022 // If the target is integral, always warn. 9023 if (TargetBT && TargetBT->isInteger()) { 9024 if (S.SourceMgr.isInSystemMacro(CC)) 9025 return; 9026 9027 DiagnoseFloatingImpCast(S, E, T, CC); 9028 } 9029 9030 // Detect the case where a call result is converted from floating-point to 9031 // to bool, and the final argument to the call is converted from bool, to 9032 // discover this typo: 9033 // 9034 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 9035 // 9036 // FIXME: This is an incredibly special case; is there some more general 9037 // way to detect this class of misplaced-parentheses bug? 9038 if (Target->isBooleanType() && isa<CallExpr>(E)) { 9039 // Check last argument of function call to see if it is an 9040 // implicit cast from a type matching the type the result 9041 // is being cast to. 9042 CallExpr *CEx = cast<CallExpr>(E); 9043 if (unsigned NumArgs = CEx->getNumArgs()) { 9044 Expr *LastA = CEx->getArg(NumArgs - 1); 9045 Expr *InnerE = LastA->IgnoreParenImpCasts(); 9046 if (isa<ImplicitCastExpr>(LastA) && 9047 InnerE->getType()->isBooleanType()) { 9048 // Warn on this floating-point to bool conversion 9049 DiagnoseImpCast(S, E, T, CC, 9050 diag::warn_impcast_floating_point_to_bool); 9051 } 9052 } 9053 } 9054 return; 9055 } 9056 9057 DiagnoseNullConversion(S, E, T, CC); 9058 9059 S.DiscardMisalignedMemberAddress(Target, E); 9060 9061 if (!Source->isIntegerType() || !Target->isIntegerType()) 9062 return; 9063 9064 // TODO: remove this early return once the false positives for constant->bool 9065 // in templates, macros, etc, are reduced or removed. 9066 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 9067 return; 9068 9069 IntRange SourceRange = GetExprRange(S.Context, E); 9070 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 9071 9072 if (SourceRange.Width > TargetRange.Width) { 9073 // If the source is a constant, use a default-on diagnostic. 9074 // TODO: this should happen for bitfield stores, too. 9075 llvm::APSInt Value(32); 9076 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) { 9077 if (S.SourceMgr.isInSystemMacro(CC)) 9078 return; 9079 9080 std::string PrettySourceValue = Value.toString(10); 9081 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 9082 9083 S.DiagRuntimeBehavior(E->getExprLoc(), E, 9084 S.PDiag(diag::warn_impcast_integer_precision_constant) 9085 << PrettySourceValue << PrettyTargetValue 9086 << E->getType() << T << E->getSourceRange() 9087 << clang::SourceRange(CC)); 9088 return; 9089 } 9090 9091 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 9092 if (S.SourceMgr.isInSystemMacro(CC)) 9093 return; 9094 9095 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 9096 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 9097 /* pruneControlFlow */ true); 9098 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 9099 } 9100 9101 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative && 9102 SourceRange.NonNegative && Source->isSignedIntegerType()) { 9103 // Warn when doing a signed to signed conversion, warn if the positive 9104 // source value is exactly the width of the target type, which will 9105 // cause a negative value to be stored. 9106 9107 llvm::APSInt Value; 9108 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) && 9109 !S.SourceMgr.isInSystemMacro(CC)) { 9110 if (isSameWidthConstantConversion(S, E, T, CC)) { 9111 std::string PrettySourceValue = Value.toString(10); 9112 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 9113 9114 S.DiagRuntimeBehavior( 9115 E->getExprLoc(), E, 9116 S.PDiag(diag::warn_impcast_integer_precision_constant) 9117 << PrettySourceValue << PrettyTargetValue << E->getType() << T 9118 << E->getSourceRange() << clang::SourceRange(CC)); 9119 return; 9120 } 9121 } 9122 9123 // Fall through for non-constants to give a sign conversion warning. 9124 } 9125 9126 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 9127 (!TargetRange.NonNegative && SourceRange.NonNegative && 9128 SourceRange.Width == TargetRange.Width)) { 9129 if (S.SourceMgr.isInSystemMacro(CC)) 9130 return; 9131 9132 unsigned DiagID = diag::warn_impcast_integer_sign; 9133 9134 // Traditionally, gcc has warned about this under -Wsign-compare. 9135 // We also want to warn about it in -Wconversion. 9136 // So if -Wconversion is off, use a completely identical diagnostic 9137 // in the sign-compare group. 9138 // The conditional-checking code will 9139 if (ICContext) { 9140 DiagID = diag::warn_impcast_integer_sign_conditional; 9141 *ICContext = true; 9142 } 9143 9144 return DiagnoseImpCast(S, E, T, CC, DiagID); 9145 } 9146 9147 // Diagnose conversions between different enumeration types. 9148 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 9149 // type, to give us better diagnostics. 9150 QualType SourceType = E->getType(); 9151 if (!S.getLangOpts().CPlusPlus) { 9152 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 9153 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 9154 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 9155 SourceType = S.Context.getTypeDeclType(Enum); 9156 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 9157 } 9158 } 9159 9160 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 9161 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 9162 if (SourceEnum->getDecl()->hasNameForLinkage() && 9163 TargetEnum->getDecl()->hasNameForLinkage() && 9164 SourceEnum != TargetEnum) { 9165 if (S.SourceMgr.isInSystemMacro(CC)) 9166 return; 9167 9168 return DiagnoseImpCast(S, E, SourceType, T, CC, 9169 diag::warn_impcast_different_enum_types); 9170 } 9171 } 9172 9173 void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 9174 SourceLocation CC, QualType T); 9175 9176 void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 9177 SourceLocation CC, bool &ICContext) { 9178 E = E->IgnoreParenImpCasts(); 9179 9180 if (isa<ConditionalOperator>(E)) 9181 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T); 9182 9183 AnalyzeImplicitConversions(S, E, CC); 9184 if (E->getType() != T) 9185 return CheckImplicitConversion(S, E, T, CC, &ICContext); 9186 } 9187 9188 void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 9189 SourceLocation CC, QualType T) { 9190 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 9191 9192 bool Suspicious = false; 9193 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 9194 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 9195 9196 // If -Wconversion would have warned about either of the candidates 9197 // for a signedness conversion to the context type... 9198 if (!Suspicious) return; 9199 9200 // ...but it's currently ignored... 9201 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 9202 return; 9203 9204 // ...then check whether it would have warned about either of the 9205 // candidates for a signedness conversion to the condition type. 9206 if (E->getType() == T) return; 9207 9208 Suspicious = false; 9209 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 9210 E->getType(), CC, &Suspicious); 9211 if (!Suspicious) 9212 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 9213 E->getType(), CC, &Suspicious); 9214 } 9215 9216 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 9217 /// Input argument E is a logical expression. 9218 void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 9219 if (S.getLangOpts().Bool) 9220 return; 9221 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 9222 } 9223 9224 /// AnalyzeImplicitConversions - Find and report any interesting 9225 /// implicit conversions in the given expression. There are a couple 9226 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 9227 void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) { 9228 QualType T = OrigE->getType(); 9229 Expr *E = OrigE->IgnoreParenImpCasts(); 9230 9231 if (E->isTypeDependent() || E->isValueDependent()) 9232 return; 9233 9234 // For conditional operators, we analyze the arguments as if they 9235 // were being fed directly into the output. 9236 if (isa<ConditionalOperator>(E)) { 9237 ConditionalOperator *CO = cast<ConditionalOperator>(E); 9238 CheckConditionalOperator(S, CO, CC, T); 9239 return; 9240 } 9241 9242 // Check implicit argument conversions for function calls. 9243 if (CallExpr *Call = dyn_cast<CallExpr>(E)) 9244 CheckImplicitArgumentConversions(S, Call, CC); 9245 9246 // Go ahead and check any implicit conversions we might have skipped. 9247 // The non-canonical typecheck is just an optimization; 9248 // CheckImplicitConversion will filter out dead implicit conversions. 9249 if (E->getType() != T) 9250 CheckImplicitConversion(S, E, T, CC); 9251 9252 // Now continue drilling into this expression. 9253 9254 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 9255 // The bound subexpressions in a PseudoObjectExpr are not reachable 9256 // as transitive children. 9257 // FIXME: Use a more uniform representation for this. 9258 for (auto *SE : POE->semantics()) 9259 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 9260 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC); 9261 } 9262 9263 // Skip past explicit casts. 9264 if (isa<ExplicitCastExpr>(E)) { 9265 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts(); 9266 return AnalyzeImplicitConversions(S, E, CC); 9267 } 9268 9269 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 9270 // Do a somewhat different check with comparison operators. 9271 if (BO->isComparisonOp()) 9272 return AnalyzeComparison(S, BO); 9273 9274 // And with simple assignments. 9275 if (BO->getOpcode() == BO_Assign) 9276 return AnalyzeAssignment(S, BO); 9277 } 9278 9279 // These break the otherwise-useful invariant below. Fortunately, 9280 // we don't really need to recurse into them, because any internal 9281 // expressions should have been analyzed already when they were 9282 // built into statements. 9283 if (isa<StmtExpr>(E)) return; 9284 9285 // Don't descend into unevaluated contexts. 9286 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 9287 9288 // Now just recurse over the expression's children. 9289 CC = E->getExprLoc(); 9290 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 9291 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 9292 for (Stmt *SubStmt : E->children()) { 9293 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 9294 if (!ChildExpr) 9295 continue; 9296 9297 if (IsLogicalAndOperator && 9298 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 9299 // Ignore checking string literals that are in logical and operators. 9300 // This is a common pattern for asserts. 9301 continue; 9302 AnalyzeImplicitConversions(S, ChildExpr, CC); 9303 } 9304 9305 if (BO && BO->isLogicalOp()) { 9306 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 9307 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 9308 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 9309 9310 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 9311 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 9312 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 9313 } 9314 9315 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) 9316 if (U->getOpcode() == UO_LNot) 9317 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 9318 } 9319 9320 } // end anonymous namespace 9321 9322 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 9323 unsigned Start, unsigned End) { 9324 bool IllegalParams = false; 9325 for (unsigned I = Start; I <= End; ++I) { 9326 QualType Ty = TheCall->getArg(I)->getType(); 9327 // Taking into account implicit conversions, 9328 // allow any integer within 32 bits range 9329 if (!Ty->isIntegerType() || 9330 S.Context.getTypeSizeInChars(Ty).getQuantity() > 4) { 9331 S.Diag(TheCall->getArg(I)->getLocStart(), 9332 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 9333 IllegalParams = true; 9334 } 9335 // Potentially emit standard warnings for implicit conversions if enabled 9336 // using -Wconversion. 9337 CheckImplicitConversion(S, TheCall->getArg(I), S.Context.UnsignedIntTy, 9338 TheCall->getArg(I)->getLocStart()); 9339 } 9340 return IllegalParams; 9341 } 9342 9343 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 9344 // Returns true when emitting a warning about taking the address of a reference. 9345 static bool CheckForReference(Sema &SemaRef, const Expr *E, 9346 const PartialDiagnostic &PD) { 9347 E = E->IgnoreParenImpCasts(); 9348 9349 const FunctionDecl *FD = nullptr; 9350 9351 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 9352 if (!DRE->getDecl()->getType()->isReferenceType()) 9353 return false; 9354 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 9355 if (!M->getMemberDecl()->getType()->isReferenceType()) 9356 return false; 9357 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 9358 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 9359 return false; 9360 FD = Call->getDirectCallee(); 9361 } else { 9362 return false; 9363 } 9364 9365 SemaRef.Diag(E->getExprLoc(), PD); 9366 9367 // If possible, point to location of function. 9368 if (FD) { 9369 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 9370 } 9371 9372 return true; 9373 } 9374 9375 // Returns true if the SourceLocation is expanded from any macro body. 9376 // Returns false if the SourceLocation is invalid, is from not in a macro 9377 // expansion, or is from expanded from a top-level macro argument. 9378 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 9379 if (Loc.isInvalid()) 9380 return false; 9381 9382 while (Loc.isMacroID()) { 9383 if (SM.isMacroBodyExpansion(Loc)) 9384 return true; 9385 Loc = SM.getImmediateMacroCallerLoc(Loc); 9386 } 9387 9388 return false; 9389 } 9390 9391 /// \brief Diagnose pointers that are always non-null. 9392 /// \param E the expression containing the pointer 9393 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 9394 /// compared to a null pointer 9395 /// \param IsEqual True when the comparison is equal to a null pointer 9396 /// \param Range Extra SourceRange to highlight in the diagnostic 9397 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 9398 Expr::NullPointerConstantKind NullKind, 9399 bool IsEqual, SourceRange Range) { 9400 if (!E) 9401 return; 9402 9403 // Don't warn inside macros. 9404 if (E->getExprLoc().isMacroID()) { 9405 const SourceManager &SM = getSourceManager(); 9406 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 9407 IsInAnyMacroBody(SM, Range.getBegin())) 9408 return; 9409 } 9410 E = E->IgnoreImpCasts(); 9411 9412 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 9413 9414 if (isa<CXXThisExpr>(E)) { 9415 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 9416 : diag::warn_this_bool_conversion; 9417 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 9418 return; 9419 } 9420 9421 bool IsAddressOf = false; 9422 9423 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 9424 if (UO->getOpcode() != UO_AddrOf) 9425 return; 9426 IsAddressOf = true; 9427 E = UO->getSubExpr(); 9428 } 9429 9430 if (IsAddressOf) { 9431 unsigned DiagID = IsCompare 9432 ? diag::warn_address_of_reference_null_compare 9433 : diag::warn_address_of_reference_bool_conversion; 9434 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 9435 << IsEqual; 9436 if (CheckForReference(*this, E, PD)) { 9437 return; 9438 } 9439 } 9440 9441 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 9442 bool IsParam = isa<NonNullAttr>(NonnullAttr); 9443 std::string Str; 9444 llvm::raw_string_ostream S(Str); 9445 E->printPretty(S, nullptr, getPrintingPolicy()); 9446 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 9447 : diag::warn_cast_nonnull_to_bool; 9448 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 9449 << E->getSourceRange() << Range << IsEqual; 9450 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 9451 }; 9452 9453 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 9454 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 9455 if (auto *Callee = Call->getDirectCallee()) { 9456 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 9457 ComplainAboutNonnullParamOrCall(A); 9458 return; 9459 } 9460 } 9461 } 9462 9463 // Expect to find a single Decl. Skip anything more complicated. 9464 ValueDecl *D = nullptr; 9465 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 9466 D = R->getDecl(); 9467 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 9468 D = M->getMemberDecl(); 9469 } 9470 9471 // Weak Decls can be null. 9472 if (!D || D->isWeak()) 9473 return; 9474 9475 // Check for parameter decl with nonnull attribute 9476 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 9477 if (getCurFunction() && 9478 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 9479 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 9480 ComplainAboutNonnullParamOrCall(A); 9481 return; 9482 } 9483 9484 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 9485 auto ParamIter = llvm::find(FD->parameters(), PV); 9486 assert(ParamIter != FD->param_end()); 9487 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 9488 9489 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 9490 if (!NonNull->args_size()) { 9491 ComplainAboutNonnullParamOrCall(NonNull); 9492 return; 9493 } 9494 9495 for (unsigned ArgNo : NonNull->args()) { 9496 if (ArgNo == ParamNo) { 9497 ComplainAboutNonnullParamOrCall(NonNull); 9498 return; 9499 } 9500 } 9501 } 9502 } 9503 } 9504 } 9505 9506 QualType T = D->getType(); 9507 const bool IsArray = T->isArrayType(); 9508 const bool IsFunction = T->isFunctionType(); 9509 9510 // Address of function is used to silence the function warning. 9511 if (IsAddressOf && IsFunction) { 9512 return; 9513 } 9514 9515 // Found nothing. 9516 if (!IsAddressOf && !IsFunction && !IsArray) 9517 return; 9518 9519 // Pretty print the expression for the diagnostic. 9520 std::string Str; 9521 llvm::raw_string_ostream S(Str); 9522 E->printPretty(S, nullptr, getPrintingPolicy()); 9523 9524 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 9525 : diag::warn_impcast_pointer_to_bool; 9526 enum { 9527 AddressOf, 9528 FunctionPointer, 9529 ArrayPointer 9530 } DiagType; 9531 if (IsAddressOf) 9532 DiagType = AddressOf; 9533 else if (IsFunction) 9534 DiagType = FunctionPointer; 9535 else if (IsArray) 9536 DiagType = ArrayPointer; 9537 else 9538 llvm_unreachable("Could not determine diagnostic."); 9539 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 9540 << Range << IsEqual; 9541 9542 if (!IsFunction) 9543 return; 9544 9545 // Suggest '&' to silence the function warning. 9546 Diag(E->getExprLoc(), diag::note_function_warning_silence) 9547 << FixItHint::CreateInsertion(E->getLocStart(), "&"); 9548 9549 // Check to see if '()' fixit should be emitted. 9550 QualType ReturnType; 9551 UnresolvedSet<4> NonTemplateOverloads; 9552 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 9553 if (ReturnType.isNull()) 9554 return; 9555 9556 if (IsCompare) { 9557 // There are two cases here. If there is null constant, the only suggest 9558 // for a pointer return type. If the null is 0, then suggest if the return 9559 // type is a pointer or an integer type. 9560 if (!ReturnType->isPointerType()) { 9561 if (NullKind == Expr::NPCK_ZeroExpression || 9562 NullKind == Expr::NPCK_ZeroLiteral) { 9563 if (!ReturnType->isIntegerType()) 9564 return; 9565 } else { 9566 return; 9567 } 9568 } 9569 } else { // !IsCompare 9570 // For function to bool, only suggest if the function pointer has bool 9571 // return type. 9572 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 9573 return; 9574 } 9575 Diag(E->getExprLoc(), diag::note_function_to_function_call) 9576 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()"); 9577 } 9578 9579 /// Diagnoses "dangerous" implicit conversions within the given 9580 /// expression (which is a full expression). Implements -Wconversion 9581 /// and -Wsign-compare. 9582 /// 9583 /// \param CC the "context" location of the implicit conversion, i.e. 9584 /// the most location of the syntactic entity requiring the implicit 9585 /// conversion 9586 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 9587 // Don't diagnose in unevaluated contexts. 9588 if (isUnevaluatedContext()) 9589 return; 9590 9591 // Don't diagnose for value- or type-dependent expressions. 9592 if (E->isTypeDependent() || E->isValueDependent()) 9593 return; 9594 9595 // Check for array bounds violations in cases where the check isn't triggered 9596 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 9597 // ArraySubscriptExpr is on the RHS of a variable initialization. 9598 CheckArrayAccess(E); 9599 9600 // This is not the right CC for (e.g.) a variable initialization. 9601 AnalyzeImplicitConversions(*this, E, CC); 9602 } 9603 9604 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 9605 /// Input argument E is a logical expression. 9606 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 9607 ::CheckBoolLikeConversion(*this, E, CC); 9608 } 9609 9610 /// Diagnose when expression is an integer constant expression and its evaluation 9611 /// results in integer overflow 9612 void Sema::CheckForIntOverflow (Expr *E) { 9613 // Use a work list to deal with nested struct initializers. 9614 SmallVector<Expr *, 2> Exprs(1, E); 9615 9616 do { 9617 Expr *E = Exprs.pop_back_val(); 9618 9619 if (isa<BinaryOperator>(E->IgnoreParenCasts())) { 9620 E->IgnoreParenCasts()->EvaluateForOverflow(Context); 9621 continue; 9622 } 9623 9624 if (auto InitList = dyn_cast<InitListExpr>(E)) 9625 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 9626 } while (!Exprs.empty()); 9627 } 9628 9629 namespace { 9630 /// \brief Visitor for expressions which looks for unsequenced operations on the 9631 /// same object. 9632 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> { 9633 typedef EvaluatedExprVisitor<SequenceChecker> Base; 9634 9635 /// \brief A tree of sequenced regions within an expression. Two regions are 9636 /// unsequenced if one is an ancestor or a descendent of the other. When we 9637 /// finish processing an expression with sequencing, such as a comma 9638 /// expression, we fold its tree nodes into its parent, since they are 9639 /// unsequenced with respect to nodes we will visit later. 9640 class SequenceTree { 9641 struct Value { 9642 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 9643 unsigned Parent : 31; 9644 unsigned Merged : 1; 9645 }; 9646 SmallVector<Value, 8> Values; 9647 9648 public: 9649 /// \brief A region within an expression which may be sequenced with respect 9650 /// to some other region. 9651 class Seq { 9652 explicit Seq(unsigned N) : Index(N) {} 9653 unsigned Index; 9654 friend class SequenceTree; 9655 public: 9656 Seq() : Index(0) {} 9657 }; 9658 9659 SequenceTree() { Values.push_back(Value(0)); } 9660 Seq root() const { return Seq(0); } 9661 9662 /// \brief Create a new sequence of operations, which is an unsequenced 9663 /// subset of \p Parent. This sequence of operations is sequenced with 9664 /// respect to other children of \p Parent. 9665 Seq allocate(Seq Parent) { 9666 Values.push_back(Value(Parent.Index)); 9667 return Seq(Values.size() - 1); 9668 } 9669 9670 /// \brief Merge a sequence of operations into its parent. 9671 void merge(Seq S) { 9672 Values[S.Index].Merged = true; 9673 } 9674 9675 /// \brief Determine whether two operations are unsequenced. This operation 9676 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 9677 /// should have been merged into its parent as appropriate. 9678 bool isUnsequenced(Seq Cur, Seq Old) { 9679 unsigned C = representative(Cur.Index); 9680 unsigned Target = representative(Old.Index); 9681 while (C >= Target) { 9682 if (C == Target) 9683 return true; 9684 C = Values[C].Parent; 9685 } 9686 return false; 9687 } 9688 9689 private: 9690 /// \brief Pick a representative for a sequence. 9691 unsigned representative(unsigned K) { 9692 if (Values[K].Merged) 9693 // Perform path compression as we go. 9694 return Values[K].Parent = representative(Values[K].Parent); 9695 return K; 9696 } 9697 }; 9698 9699 /// An object for which we can track unsequenced uses. 9700 typedef NamedDecl *Object; 9701 9702 /// Different flavors of object usage which we track. We only track the 9703 /// least-sequenced usage of each kind. 9704 enum UsageKind { 9705 /// A read of an object. Multiple unsequenced reads are OK. 9706 UK_Use, 9707 /// A modification of an object which is sequenced before the value 9708 /// computation of the expression, such as ++n in C++. 9709 UK_ModAsValue, 9710 /// A modification of an object which is not sequenced before the value 9711 /// computation of the expression, such as n++. 9712 UK_ModAsSideEffect, 9713 9714 UK_Count = UK_ModAsSideEffect + 1 9715 }; 9716 9717 struct Usage { 9718 Usage() : Use(nullptr), Seq() {} 9719 Expr *Use; 9720 SequenceTree::Seq Seq; 9721 }; 9722 9723 struct UsageInfo { 9724 UsageInfo() : Diagnosed(false) {} 9725 Usage Uses[UK_Count]; 9726 /// Have we issued a diagnostic for this variable already? 9727 bool Diagnosed; 9728 }; 9729 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap; 9730 9731 Sema &SemaRef; 9732 /// Sequenced regions within the expression. 9733 SequenceTree Tree; 9734 /// Declaration modifications and references which we have seen. 9735 UsageInfoMap UsageMap; 9736 /// The region we are currently within. 9737 SequenceTree::Seq Region; 9738 /// Filled in with declarations which were modified as a side-effect 9739 /// (that is, post-increment operations). 9740 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect; 9741 /// Expressions to check later. We defer checking these to reduce 9742 /// stack usage. 9743 SmallVectorImpl<Expr *> &WorkList; 9744 9745 /// RAII object wrapping the visitation of a sequenced subexpression of an 9746 /// expression. At the end of this process, the side-effects of the evaluation 9747 /// become sequenced with respect to the value computation of the result, so 9748 /// we downgrade any UK_ModAsSideEffect within the evaluation to 9749 /// UK_ModAsValue. 9750 struct SequencedSubexpression { 9751 SequencedSubexpression(SequenceChecker &Self) 9752 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 9753 Self.ModAsSideEffect = &ModAsSideEffect; 9754 } 9755 ~SequencedSubexpression() { 9756 for (auto &M : llvm::reverse(ModAsSideEffect)) { 9757 UsageInfo &U = Self.UsageMap[M.first]; 9758 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect]; 9759 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue); 9760 SideEffectUsage = M.second; 9761 } 9762 Self.ModAsSideEffect = OldModAsSideEffect; 9763 } 9764 9765 SequenceChecker &Self; 9766 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 9767 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect; 9768 }; 9769 9770 /// RAII object wrapping the visitation of a subexpression which we might 9771 /// choose to evaluate as a constant. If any subexpression is evaluated and 9772 /// found to be non-constant, this allows us to suppress the evaluation of 9773 /// the outer expression. 9774 class EvaluationTracker { 9775 public: 9776 EvaluationTracker(SequenceChecker &Self) 9777 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) { 9778 Self.EvalTracker = this; 9779 } 9780 ~EvaluationTracker() { 9781 Self.EvalTracker = Prev; 9782 if (Prev) 9783 Prev->EvalOK &= EvalOK; 9784 } 9785 9786 bool evaluate(const Expr *E, bool &Result) { 9787 if (!EvalOK || E->isValueDependent()) 9788 return false; 9789 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context); 9790 return EvalOK; 9791 } 9792 9793 private: 9794 SequenceChecker &Self; 9795 EvaluationTracker *Prev; 9796 bool EvalOK; 9797 } *EvalTracker; 9798 9799 /// \brief Find the object which is produced by the specified expression, 9800 /// if any. 9801 Object getObject(Expr *E, bool Mod) const { 9802 E = E->IgnoreParenCasts(); 9803 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 9804 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 9805 return getObject(UO->getSubExpr(), Mod); 9806 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 9807 if (BO->getOpcode() == BO_Comma) 9808 return getObject(BO->getRHS(), Mod); 9809 if (Mod && BO->isAssignmentOp()) 9810 return getObject(BO->getLHS(), Mod); 9811 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 9812 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 9813 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 9814 return ME->getMemberDecl(); 9815 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 9816 // FIXME: If this is a reference, map through to its value. 9817 return DRE->getDecl(); 9818 return nullptr; 9819 } 9820 9821 /// \brief Note that an object was modified or used by an expression. 9822 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) { 9823 Usage &U = UI.Uses[UK]; 9824 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) { 9825 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 9826 ModAsSideEffect->push_back(std::make_pair(O, U)); 9827 U.Use = Ref; 9828 U.Seq = Region; 9829 } 9830 } 9831 /// \brief Check whether a modification or use conflicts with a prior usage. 9832 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind, 9833 bool IsModMod) { 9834 if (UI.Diagnosed) 9835 return; 9836 9837 const Usage &U = UI.Uses[OtherKind]; 9838 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) 9839 return; 9840 9841 Expr *Mod = U.Use; 9842 Expr *ModOrUse = Ref; 9843 if (OtherKind == UK_Use) 9844 std::swap(Mod, ModOrUse); 9845 9846 SemaRef.Diag(Mod->getExprLoc(), 9847 IsModMod ? diag::warn_unsequenced_mod_mod 9848 : diag::warn_unsequenced_mod_use) 9849 << O << SourceRange(ModOrUse->getExprLoc()); 9850 UI.Diagnosed = true; 9851 } 9852 9853 void notePreUse(Object O, Expr *Use) { 9854 UsageInfo &U = UsageMap[O]; 9855 // Uses conflict with other modifications. 9856 checkUsage(O, U, Use, UK_ModAsValue, false); 9857 } 9858 void notePostUse(Object O, Expr *Use) { 9859 UsageInfo &U = UsageMap[O]; 9860 checkUsage(O, U, Use, UK_ModAsSideEffect, false); 9861 addUsage(U, O, Use, UK_Use); 9862 } 9863 9864 void notePreMod(Object O, Expr *Mod) { 9865 UsageInfo &U = UsageMap[O]; 9866 // Modifications conflict with other modifications and with uses. 9867 checkUsage(O, U, Mod, UK_ModAsValue, true); 9868 checkUsage(O, U, Mod, UK_Use, false); 9869 } 9870 void notePostMod(Object O, Expr *Use, UsageKind UK) { 9871 UsageInfo &U = UsageMap[O]; 9872 checkUsage(O, U, Use, UK_ModAsSideEffect, true); 9873 addUsage(U, O, Use, UK); 9874 } 9875 9876 public: 9877 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList) 9878 : Base(S.Context), SemaRef(S), Region(Tree.root()), 9879 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) { 9880 Visit(E); 9881 } 9882 9883 void VisitStmt(Stmt *S) { 9884 // Skip all statements which aren't expressions for now. 9885 } 9886 9887 void VisitExpr(Expr *E) { 9888 // By default, just recurse to evaluated subexpressions. 9889 Base::VisitStmt(E); 9890 } 9891 9892 void VisitCastExpr(CastExpr *E) { 9893 Object O = Object(); 9894 if (E->getCastKind() == CK_LValueToRValue) 9895 O = getObject(E->getSubExpr(), false); 9896 9897 if (O) 9898 notePreUse(O, E); 9899 VisitExpr(E); 9900 if (O) 9901 notePostUse(O, E); 9902 } 9903 9904 void VisitBinComma(BinaryOperator *BO) { 9905 // C++11 [expr.comma]p1: 9906 // Every value computation and side effect associated with the left 9907 // expression is sequenced before every value computation and side 9908 // effect associated with the right expression. 9909 SequenceTree::Seq LHS = Tree.allocate(Region); 9910 SequenceTree::Seq RHS = Tree.allocate(Region); 9911 SequenceTree::Seq OldRegion = Region; 9912 9913 { 9914 SequencedSubexpression SeqLHS(*this); 9915 Region = LHS; 9916 Visit(BO->getLHS()); 9917 } 9918 9919 Region = RHS; 9920 Visit(BO->getRHS()); 9921 9922 Region = OldRegion; 9923 9924 // Forget that LHS and RHS are sequenced. They are both unsequenced 9925 // with respect to other stuff. 9926 Tree.merge(LHS); 9927 Tree.merge(RHS); 9928 } 9929 9930 void VisitBinAssign(BinaryOperator *BO) { 9931 // The modification is sequenced after the value computation of the LHS 9932 // and RHS, so check it before inspecting the operands and update the 9933 // map afterwards. 9934 Object O = getObject(BO->getLHS(), true); 9935 if (!O) 9936 return VisitExpr(BO); 9937 9938 notePreMod(O, BO); 9939 9940 // C++11 [expr.ass]p7: 9941 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated 9942 // only once. 9943 // 9944 // Therefore, for a compound assignment operator, O is considered used 9945 // everywhere except within the evaluation of E1 itself. 9946 if (isa<CompoundAssignOperator>(BO)) 9947 notePreUse(O, BO); 9948 9949 Visit(BO->getLHS()); 9950 9951 if (isa<CompoundAssignOperator>(BO)) 9952 notePostUse(O, BO); 9953 9954 Visit(BO->getRHS()); 9955 9956 // C++11 [expr.ass]p1: 9957 // the assignment is sequenced [...] before the value computation of the 9958 // assignment expression. 9959 // C11 6.5.16/3 has no such rule. 9960 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 9961 : UK_ModAsSideEffect); 9962 } 9963 9964 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) { 9965 VisitBinAssign(CAO); 9966 } 9967 9968 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 9969 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 9970 void VisitUnaryPreIncDec(UnaryOperator *UO) { 9971 Object O = getObject(UO->getSubExpr(), true); 9972 if (!O) 9973 return VisitExpr(UO); 9974 9975 notePreMod(O, UO); 9976 Visit(UO->getSubExpr()); 9977 // C++11 [expr.pre.incr]p1: 9978 // the expression ++x is equivalent to x+=1 9979 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 9980 : UK_ModAsSideEffect); 9981 } 9982 9983 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 9984 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 9985 void VisitUnaryPostIncDec(UnaryOperator *UO) { 9986 Object O = getObject(UO->getSubExpr(), true); 9987 if (!O) 9988 return VisitExpr(UO); 9989 9990 notePreMod(O, UO); 9991 Visit(UO->getSubExpr()); 9992 notePostMod(O, UO, UK_ModAsSideEffect); 9993 } 9994 9995 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated. 9996 void VisitBinLOr(BinaryOperator *BO) { 9997 // The side-effects of the LHS of an '&&' are sequenced before the 9998 // value computation of the RHS, and hence before the value computation 9999 // of the '&&' itself, unless the LHS evaluates to zero. We treat them 10000 // as if they were unconditionally sequenced. 10001 EvaluationTracker Eval(*this); 10002 { 10003 SequencedSubexpression Sequenced(*this); 10004 Visit(BO->getLHS()); 10005 } 10006 10007 bool Result; 10008 if (Eval.evaluate(BO->getLHS(), Result)) { 10009 if (!Result) 10010 Visit(BO->getRHS()); 10011 } else { 10012 // Check for unsequenced operations in the RHS, treating it as an 10013 // entirely separate evaluation. 10014 // 10015 // FIXME: If there are operations in the RHS which are unsequenced 10016 // with respect to operations outside the RHS, and those operations 10017 // are unconditionally evaluated, diagnose them. 10018 WorkList.push_back(BO->getRHS()); 10019 } 10020 } 10021 void VisitBinLAnd(BinaryOperator *BO) { 10022 EvaluationTracker Eval(*this); 10023 { 10024 SequencedSubexpression Sequenced(*this); 10025 Visit(BO->getLHS()); 10026 } 10027 10028 bool Result; 10029 if (Eval.evaluate(BO->getLHS(), Result)) { 10030 if (Result) 10031 Visit(BO->getRHS()); 10032 } else { 10033 WorkList.push_back(BO->getRHS()); 10034 } 10035 } 10036 10037 // Only visit the condition, unless we can be sure which subexpression will 10038 // be chosen. 10039 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) { 10040 EvaluationTracker Eval(*this); 10041 { 10042 SequencedSubexpression Sequenced(*this); 10043 Visit(CO->getCond()); 10044 } 10045 10046 bool Result; 10047 if (Eval.evaluate(CO->getCond(), Result)) 10048 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr()); 10049 else { 10050 WorkList.push_back(CO->getTrueExpr()); 10051 WorkList.push_back(CO->getFalseExpr()); 10052 } 10053 } 10054 10055 void VisitCallExpr(CallExpr *CE) { 10056 // C++11 [intro.execution]p15: 10057 // When calling a function [...], every value computation and side effect 10058 // associated with any argument expression, or with the postfix expression 10059 // designating the called function, is sequenced before execution of every 10060 // expression or statement in the body of the function [and thus before 10061 // the value computation of its result]. 10062 SequencedSubexpression Sequenced(*this); 10063 Base::VisitCallExpr(CE); 10064 10065 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 10066 } 10067 10068 void VisitCXXConstructExpr(CXXConstructExpr *CCE) { 10069 // This is a call, so all subexpressions are sequenced before the result. 10070 SequencedSubexpression Sequenced(*this); 10071 10072 if (!CCE->isListInitialization()) 10073 return VisitExpr(CCE); 10074 10075 // In C++11, list initializations are sequenced. 10076 SmallVector<SequenceTree::Seq, 32> Elts; 10077 SequenceTree::Seq Parent = Region; 10078 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(), 10079 E = CCE->arg_end(); 10080 I != E; ++I) { 10081 Region = Tree.allocate(Parent); 10082 Elts.push_back(Region); 10083 Visit(*I); 10084 } 10085 10086 // Forget that the initializers are sequenced. 10087 Region = Parent; 10088 for (unsigned I = 0; I < Elts.size(); ++I) 10089 Tree.merge(Elts[I]); 10090 } 10091 10092 void VisitInitListExpr(InitListExpr *ILE) { 10093 if (!SemaRef.getLangOpts().CPlusPlus11) 10094 return VisitExpr(ILE); 10095 10096 // In C++11, list initializations are sequenced. 10097 SmallVector<SequenceTree::Seq, 32> Elts; 10098 SequenceTree::Seq Parent = Region; 10099 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 10100 Expr *E = ILE->getInit(I); 10101 if (!E) continue; 10102 Region = Tree.allocate(Parent); 10103 Elts.push_back(Region); 10104 Visit(E); 10105 } 10106 10107 // Forget that the initializers are sequenced. 10108 Region = Parent; 10109 for (unsigned I = 0; I < Elts.size(); ++I) 10110 Tree.merge(Elts[I]); 10111 } 10112 }; 10113 } // end anonymous namespace 10114 10115 void Sema::CheckUnsequencedOperations(Expr *E) { 10116 SmallVector<Expr *, 8> WorkList; 10117 WorkList.push_back(E); 10118 while (!WorkList.empty()) { 10119 Expr *Item = WorkList.pop_back_val(); 10120 SequenceChecker(*this, Item, WorkList); 10121 } 10122 } 10123 10124 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 10125 bool IsConstexpr) { 10126 CheckImplicitConversions(E, CheckLoc); 10127 if (!E->isInstantiationDependent()) 10128 CheckUnsequencedOperations(E); 10129 if (!IsConstexpr && !E->isValueDependent()) 10130 CheckForIntOverflow(E); 10131 DiagnoseMisalignedMembers(); 10132 } 10133 10134 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 10135 FieldDecl *BitField, 10136 Expr *Init) { 10137 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 10138 } 10139 10140 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 10141 SourceLocation Loc) { 10142 if (!PType->isVariablyModifiedType()) 10143 return; 10144 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 10145 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 10146 return; 10147 } 10148 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 10149 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 10150 return; 10151 } 10152 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 10153 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 10154 return; 10155 } 10156 10157 const ArrayType *AT = S.Context.getAsArrayType(PType); 10158 if (!AT) 10159 return; 10160 10161 if (AT->getSizeModifier() != ArrayType::Star) { 10162 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 10163 return; 10164 } 10165 10166 S.Diag(Loc, diag::err_array_star_in_function_definition); 10167 } 10168 10169 /// CheckParmsForFunctionDef - Check that the parameters of the given 10170 /// function are appropriate for the definition of a function. This 10171 /// takes care of any checks that cannot be performed on the 10172 /// declaration itself, e.g., that the types of each of the function 10173 /// parameters are complete. 10174 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 10175 bool CheckParameterNames) { 10176 bool HasInvalidParm = false; 10177 for (ParmVarDecl *Param : Parameters) { 10178 // C99 6.7.5.3p4: the parameters in a parameter type list in a 10179 // function declarator that is part of a function definition of 10180 // that function shall not have incomplete type. 10181 // 10182 // This is also C++ [dcl.fct]p6. 10183 if (!Param->isInvalidDecl() && 10184 RequireCompleteType(Param->getLocation(), Param->getType(), 10185 diag::err_typecheck_decl_incomplete_type)) { 10186 Param->setInvalidDecl(); 10187 HasInvalidParm = true; 10188 } 10189 10190 // C99 6.9.1p5: If the declarator includes a parameter type list, the 10191 // declaration of each parameter shall include an identifier. 10192 if (CheckParameterNames && 10193 Param->getIdentifier() == nullptr && 10194 !Param->isImplicit() && 10195 !getLangOpts().CPlusPlus) 10196 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 10197 10198 // C99 6.7.5.3p12: 10199 // If the function declarator is not part of a definition of that 10200 // function, parameters may have incomplete type and may use the [*] 10201 // notation in their sequences of declarator specifiers to specify 10202 // variable length array types. 10203 QualType PType = Param->getOriginalType(); 10204 // FIXME: This diagnostic should point the '[*]' if source-location 10205 // information is added for it. 10206 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 10207 10208 // MSVC destroys objects passed by value in the callee. Therefore a 10209 // function definition which takes such a parameter must be able to call the 10210 // object's destructor. However, we don't perform any direct access check 10211 // on the dtor. 10212 if (getLangOpts().CPlusPlus && Context.getTargetInfo() 10213 .getCXXABI() 10214 .areArgsDestroyedLeftToRightInCallee()) { 10215 if (!Param->isInvalidDecl()) { 10216 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) { 10217 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 10218 if (!ClassDecl->isInvalidDecl() && 10219 !ClassDecl->hasIrrelevantDestructor() && 10220 !ClassDecl->isDependentContext()) { 10221 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 10222 MarkFunctionReferenced(Param->getLocation(), Destructor); 10223 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 10224 } 10225 } 10226 } 10227 } 10228 10229 // Parameters with the pass_object_size attribute only need to be marked 10230 // constant at function definitions. Because we lack information about 10231 // whether we're on a declaration or definition when we're instantiating the 10232 // attribute, we need to check for constness here. 10233 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 10234 if (!Param->getType().isConstQualified()) 10235 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 10236 << Attr->getSpelling() << 1; 10237 } 10238 10239 return HasInvalidParm; 10240 } 10241 10242 /// CheckCastAlign - Implements -Wcast-align, which warns when a 10243 /// pointer cast increases the alignment requirements. 10244 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 10245 // This is actually a lot of work to potentially be doing on every 10246 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 10247 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 10248 return; 10249 10250 // Ignore dependent types. 10251 if (T->isDependentType() || Op->getType()->isDependentType()) 10252 return; 10253 10254 // Require that the destination be a pointer type. 10255 const PointerType *DestPtr = T->getAs<PointerType>(); 10256 if (!DestPtr) return; 10257 10258 // If the destination has alignment 1, we're done. 10259 QualType DestPointee = DestPtr->getPointeeType(); 10260 if (DestPointee->isIncompleteType()) return; 10261 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 10262 if (DestAlign.isOne()) return; 10263 10264 // Require that the source be a pointer type. 10265 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 10266 if (!SrcPtr) return; 10267 QualType SrcPointee = SrcPtr->getPointeeType(); 10268 10269 // Whitelist casts from cv void*. We already implicitly 10270 // whitelisted casts to cv void*, since they have alignment 1. 10271 // Also whitelist casts involving incomplete types, which implicitly 10272 // includes 'void'. 10273 if (SrcPointee->isIncompleteType()) return; 10274 10275 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee); 10276 if (SrcAlign >= DestAlign) return; 10277 10278 Diag(TRange.getBegin(), diag::warn_cast_align) 10279 << Op->getType() << T 10280 << static_cast<unsigned>(SrcAlign.getQuantity()) 10281 << static_cast<unsigned>(DestAlign.getQuantity()) 10282 << TRange << Op->getSourceRange(); 10283 } 10284 10285 /// \brief Check whether this array fits the idiom of a size-one tail padded 10286 /// array member of a struct. 10287 /// 10288 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 10289 /// commonly used to emulate flexible arrays in C89 code. 10290 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 10291 const NamedDecl *ND) { 10292 if (Size != 1 || !ND) return false; 10293 10294 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 10295 if (!FD) return false; 10296 10297 // Don't consider sizes resulting from macro expansions or template argument 10298 // substitution to form C89 tail-padded arrays. 10299 10300 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 10301 while (TInfo) { 10302 TypeLoc TL = TInfo->getTypeLoc(); 10303 // Look through typedefs. 10304 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 10305 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 10306 TInfo = TDL->getTypeSourceInfo(); 10307 continue; 10308 } 10309 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 10310 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 10311 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 10312 return false; 10313 } 10314 break; 10315 } 10316 10317 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 10318 if (!RD) return false; 10319 if (RD->isUnion()) return false; 10320 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 10321 if (!CRD->isStandardLayout()) return false; 10322 } 10323 10324 // See if this is the last field decl in the record. 10325 const Decl *D = FD; 10326 while ((D = D->getNextDeclInContext())) 10327 if (isa<FieldDecl>(D)) 10328 return false; 10329 return true; 10330 } 10331 10332 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 10333 const ArraySubscriptExpr *ASE, 10334 bool AllowOnePastEnd, bool IndexNegated) { 10335 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 10336 if (IndexExpr->isValueDependent()) 10337 return; 10338 10339 const Type *EffectiveType = 10340 BaseExpr->getType()->getPointeeOrArrayElementType(); 10341 BaseExpr = BaseExpr->IgnoreParenCasts(); 10342 const ConstantArrayType *ArrayTy = 10343 Context.getAsConstantArrayType(BaseExpr->getType()); 10344 if (!ArrayTy) 10345 return; 10346 10347 llvm::APSInt index; 10348 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects)) 10349 return; 10350 if (IndexNegated) 10351 index = -index; 10352 10353 const NamedDecl *ND = nullptr; 10354 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 10355 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 10356 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 10357 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 10358 10359 if (index.isUnsigned() || !index.isNegative()) { 10360 llvm::APInt size = ArrayTy->getSize(); 10361 if (!size.isStrictlyPositive()) 10362 return; 10363 10364 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType(); 10365 if (BaseType != EffectiveType) { 10366 // Make sure we're comparing apples to apples when comparing index to size 10367 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 10368 uint64_t array_typesize = Context.getTypeSize(BaseType); 10369 // Handle ptrarith_typesize being zero, such as when casting to void* 10370 if (!ptrarith_typesize) ptrarith_typesize = 1; 10371 if (ptrarith_typesize != array_typesize) { 10372 // There's a cast to a different size type involved 10373 uint64_t ratio = array_typesize / ptrarith_typesize; 10374 // TODO: Be smarter about handling cases where array_typesize is not a 10375 // multiple of ptrarith_typesize 10376 if (ptrarith_typesize * ratio == array_typesize) 10377 size *= llvm::APInt(size.getBitWidth(), ratio); 10378 } 10379 } 10380 10381 if (size.getBitWidth() > index.getBitWidth()) 10382 index = index.zext(size.getBitWidth()); 10383 else if (size.getBitWidth() < index.getBitWidth()) 10384 size = size.zext(index.getBitWidth()); 10385 10386 // For array subscripting the index must be less than size, but for pointer 10387 // arithmetic also allow the index (offset) to be equal to size since 10388 // computing the next address after the end of the array is legal and 10389 // commonly done e.g. in C++ iterators and range-based for loops. 10390 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 10391 return; 10392 10393 // Also don't warn for arrays of size 1 which are members of some 10394 // structure. These are often used to approximate flexible arrays in C89 10395 // code. 10396 if (IsTailPaddedMemberArray(*this, size, ND)) 10397 return; 10398 10399 // Suppress the warning if the subscript expression (as identified by the 10400 // ']' location) and the index expression are both from macro expansions 10401 // within a system header. 10402 if (ASE) { 10403 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 10404 ASE->getRBracketLoc()); 10405 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 10406 SourceLocation IndexLoc = SourceMgr.getSpellingLoc( 10407 IndexExpr->getLocStart()); 10408 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 10409 return; 10410 } 10411 } 10412 10413 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 10414 if (ASE) 10415 DiagID = diag::warn_array_index_exceeds_bounds; 10416 10417 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 10418 PDiag(DiagID) << index.toString(10, true) 10419 << size.toString(10, true) 10420 << (unsigned)size.getLimitedValue(~0U) 10421 << IndexExpr->getSourceRange()); 10422 } else { 10423 unsigned DiagID = diag::warn_array_index_precedes_bounds; 10424 if (!ASE) { 10425 DiagID = diag::warn_ptr_arith_precedes_bounds; 10426 if (index.isNegative()) index = -index; 10427 } 10428 10429 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 10430 PDiag(DiagID) << index.toString(10, true) 10431 << IndexExpr->getSourceRange()); 10432 } 10433 10434 if (!ND) { 10435 // Try harder to find a NamedDecl to point at in the note. 10436 while (const ArraySubscriptExpr *ASE = 10437 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 10438 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 10439 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 10440 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 10441 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 10442 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 10443 } 10444 10445 if (ND) 10446 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr, 10447 PDiag(diag::note_array_index_out_of_bounds) 10448 << ND->getDeclName()); 10449 } 10450 10451 void Sema::CheckArrayAccess(const Expr *expr) { 10452 int AllowOnePastEnd = 0; 10453 while (expr) { 10454 expr = expr->IgnoreParenImpCasts(); 10455 switch (expr->getStmtClass()) { 10456 case Stmt::ArraySubscriptExprClass: { 10457 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 10458 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 10459 AllowOnePastEnd > 0); 10460 return; 10461 } 10462 case Stmt::OMPArraySectionExprClass: { 10463 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 10464 if (ASE->getLowerBound()) 10465 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 10466 /*ASE=*/nullptr, AllowOnePastEnd > 0); 10467 return; 10468 } 10469 case Stmt::UnaryOperatorClass: { 10470 // Only unwrap the * and & unary operators 10471 const UnaryOperator *UO = cast<UnaryOperator>(expr); 10472 expr = UO->getSubExpr(); 10473 switch (UO->getOpcode()) { 10474 case UO_AddrOf: 10475 AllowOnePastEnd++; 10476 break; 10477 case UO_Deref: 10478 AllowOnePastEnd--; 10479 break; 10480 default: 10481 return; 10482 } 10483 break; 10484 } 10485 case Stmt::ConditionalOperatorClass: { 10486 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 10487 if (const Expr *lhs = cond->getLHS()) 10488 CheckArrayAccess(lhs); 10489 if (const Expr *rhs = cond->getRHS()) 10490 CheckArrayAccess(rhs); 10491 return; 10492 } 10493 default: 10494 return; 10495 } 10496 } 10497 } 10498 10499 //===--- CHECK: Objective-C retain cycles ----------------------------------// 10500 10501 namespace { 10502 struct RetainCycleOwner { 10503 RetainCycleOwner() : Variable(nullptr), Indirect(false) {} 10504 VarDecl *Variable; 10505 SourceRange Range; 10506 SourceLocation Loc; 10507 bool Indirect; 10508 10509 void setLocsFrom(Expr *e) { 10510 Loc = e->getExprLoc(); 10511 Range = e->getSourceRange(); 10512 } 10513 }; 10514 } // end anonymous namespace 10515 10516 /// Consider whether capturing the given variable can possibly lead to 10517 /// a retain cycle. 10518 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 10519 // In ARC, it's captured strongly iff the variable has __strong 10520 // lifetime. In MRR, it's captured strongly if the variable is 10521 // __block and has an appropriate type. 10522 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 10523 return false; 10524 10525 owner.Variable = var; 10526 if (ref) 10527 owner.setLocsFrom(ref); 10528 return true; 10529 } 10530 10531 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 10532 while (true) { 10533 e = e->IgnoreParens(); 10534 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 10535 switch (cast->getCastKind()) { 10536 case CK_BitCast: 10537 case CK_LValueBitCast: 10538 case CK_LValueToRValue: 10539 case CK_ARCReclaimReturnedObject: 10540 e = cast->getSubExpr(); 10541 continue; 10542 10543 default: 10544 return false; 10545 } 10546 } 10547 10548 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 10549 ObjCIvarDecl *ivar = ref->getDecl(); 10550 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 10551 return false; 10552 10553 // Try to find a retain cycle in the base. 10554 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 10555 return false; 10556 10557 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 10558 owner.Indirect = true; 10559 return true; 10560 } 10561 10562 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 10563 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 10564 if (!var) return false; 10565 return considerVariable(var, ref, owner); 10566 } 10567 10568 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 10569 if (member->isArrow()) return false; 10570 10571 // Don't count this as an indirect ownership. 10572 e = member->getBase(); 10573 continue; 10574 } 10575 10576 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 10577 // Only pay attention to pseudo-objects on property references. 10578 ObjCPropertyRefExpr *pre 10579 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 10580 ->IgnoreParens()); 10581 if (!pre) return false; 10582 if (pre->isImplicitProperty()) return false; 10583 ObjCPropertyDecl *property = pre->getExplicitProperty(); 10584 if (!property->isRetaining() && 10585 !(property->getPropertyIvarDecl() && 10586 property->getPropertyIvarDecl()->getType() 10587 .getObjCLifetime() == Qualifiers::OCL_Strong)) 10588 return false; 10589 10590 owner.Indirect = true; 10591 if (pre->isSuperReceiver()) { 10592 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 10593 if (!owner.Variable) 10594 return false; 10595 owner.Loc = pre->getLocation(); 10596 owner.Range = pre->getSourceRange(); 10597 return true; 10598 } 10599 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 10600 ->getSourceExpr()); 10601 continue; 10602 } 10603 10604 // Array ivars? 10605 10606 return false; 10607 } 10608 } 10609 10610 namespace { 10611 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 10612 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 10613 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 10614 Context(Context), Variable(variable), Capturer(nullptr), 10615 VarWillBeReased(false) {} 10616 ASTContext &Context; 10617 VarDecl *Variable; 10618 Expr *Capturer; 10619 bool VarWillBeReased; 10620 10621 void VisitDeclRefExpr(DeclRefExpr *ref) { 10622 if (ref->getDecl() == Variable && !Capturer) 10623 Capturer = ref; 10624 } 10625 10626 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 10627 if (Capturer) return; 10628 Visit(ref->getBase()); 10629 if (Capturer && ref->isFreeIvar()) 10630 Capturer = ref; 10631 } 10632 10633 void VisitBlockExpr(BlockExpr *block) { 10634 // Look inside nested blocks 10635 if (block->getBlockDecl()->capturesVariable(Variable)) 10636 Visit(block->getBlockDecl()->getBody()); 10637 } 10638 10639 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 10640 if (Capturer) return; 10641 if (OVE->getSourceExpr()) 10642 Visit(OVE->getSourceExpr()); 10643 } 10644 void VisitBinaryOperator(BinaryOperator *BinOp) { 10645 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 10646 return; 10647 Expr *LHS = BinOp->getLHS(); 10648 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 10649 if (DRE->getDecl() != Variable) 10650 return; 10651 if (Expr *RHS = BinOp->getRHS()) { 10652 RHS = RHS->IgnoreParenCasts(); 10653 llvm::APSInt Value; 10654 VarWillBeReased = 10655 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0); 10656 } 10657 } 10658 } 10659 }; 10660 } // end anonymous namespace 10661 10662 /// Check whether the given argument is a block which captures a 10663 /// variable. 10664 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 10665 assert(owner.Variable && owner.Loc.isValid()); 10666 10667 e = e->IgnoreParenCasts(); 10668 10669 // Look through [^{...} copy] and Block_copy(^{...}). 10670 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 10671 Selector Cmd = ME->getSelector(); 10672 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 10673 e = ME->getInstanceReceiver(); 10674 if (!e) 10675 return nullptr; 10676 e = e->IgnoreParenCasts(); 10677 } 10678 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 10679 if (CE->getNumArgs() == 1) { 10680 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 10681 if (Fn) { 10682 const IdentifierInfo *FnI = Fn->getIdentifier(); 10683 if (FnI && FnI->isStr("_Block_copy")) { 10684 e = CE->getArg(0)->IgnoreParenCasts(); 10685 } 10686 } 10687 } 10688 } 10689 10690 BlockExpr *block = dyn_cast<BlockExpr>(e); 10691 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 10692 return nullptr; 10693 10694 FindCaptureVisitor visitor(S.Context, owner.Variable); 10695 visitor.Visit(block->getBlockDecl()->getBody()); 10696 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 10697 } 10698 10699 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 10700 RetainCycleOwner &owner) { 10701 assert(capturer); 10702 assert(owner.Variable && owner.Loc.isValid()); 10703 10704 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 10705 << owner.Variable << capturer->getSourceRange(); 10706 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 10707 << owner.Indirect << owner.Range; 10708 } 10709 10710 /// Check for a keyword selector that starts with the word 'add' or 10711 /// 'set'. 10712 static bool isSetterLikeSelector(Selector sel) { 10713 if (sel.isUnarySelector()) return false; 10714 10715 StringRef str = sel.getNameForSlot(0); 10716 while (!str.empty() && str.front() == '_') str = str.substr(1); 10717 if (str.startswith("set")) 10718 str = str.substr(3); 10719 else if (str.startswith("add")) { 10720 // Specially whitelist 'addOperationWithBlock:'. 10721 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 10722 return false; 10723 str = str.substr(3); 10724 } 10725 else 10726 return false; 10727 10728 if (str.empty()) return true; 10729 return !isLowercase(str.front()); 10730 } 10731 10732 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 10733 ObjCMessageExpr *Message) { 10734 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 10735 Message->getReceiverInterface(), 10736 NSAPI::ClassId_NSMutableArray); 10737 if (!IsMutableArray) { 10738 return None; 10739 } 10740 10741 Selector Sel = Message->getSelector(); 10742 10743 Optional<NSAPI::NSArrayMethodKind> MKOpt = 10744 S.NSAPIObj->getNSArrayMethodKind(Sel); 10745 if (!MKOpt) { 10746 return None; 10747 } 10748 10749 NSAPI::NSArrayMethodKind MK = *MKOpt; 10750 10751 switch (MK) { 10752 case NSAPI::NSMutableArr_addObject: 10753 case NSAPI::NSMutableArr_insertObjectAtIndex: 10754 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 10755 return 0; 10756 case NSAPI::NSMutableArr_replaceObjectAtIndex: 10757 return 1; 10758 10759 default: 10760 return None; 10761 } 10762 10763 return None; 10764 } 10765 10766 static 10767 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 10768 ObjCMessageExpr *Message) { 10769 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 10770 Message->getReceiverInterface(), 10771 NSAPI::ClassId_NSMutableDictionary); 10772 if (!IsMutableDictionary) { 10773 return None; 10774 } 10775 10776 Selector Sel = Message->getSelector(); 10777 10778 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 10779 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 10780 if (!MKOpt) { 10781 return None; 10782 } 10783 10784 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 10785 10786 switch (MK) { 10787 case NSAPI::NSMutableDict_setObjectForKey: 10788 case NSAPI::NSMutableDict_setValueForKey: 10789 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 10790 return 0; 10791 10792 default: 10793 return None; 10794 } 10795 10796 return None; 10797 } 10798 10799 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 10800 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 10801 Message->getReceiverInterface(), 10802 NSAPI::ClassId_NSMutableSet); 10803 10804 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 10805 Message->getReceiverInterface(), 10806 NSAPI::ClassId_NSMutableOrderedSet); 10807 if (!IsMutableSet && !IsMutableOrderedSet) { 10808 return None; 10809 } 10810 10811 Selector Sel = Message->getSelector(); 10812 10813 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 10814 if (!MKOpt) { 10815 return None; 10816 } 10817 10818 NSAPI::NSSetMethodKind MK = *MKOpt; 10819 10820 switch (MK) { 10821 case NSAPI::NSMutableSet_addObject: 10822 case NSAPI::NSOrderedSet_setObjectAtIndex: 10823 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 10824 case NSAPI::NSOrderedSet_insertObjectAtIndex: 10825 return 0; 10826 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 10827 return 1; 10828 } 10829 10830 return None; 10831 } 10832 10833 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 10834 if (!Message->isInstanceMessage()) { 10835 return; 10836 } 10837 10838 Optional<int> ArgOpt; 10839 10840 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 10841 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 10842 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 10843 return; 10844 } 10845 10846 int ArgIndex = *ArgOpt; 10847 10848 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 10849 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 10850 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 10851 } 10852 10853 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 10854 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 10855 if (ArgRE->isObjCSelfExpr()) { 10856 Diag(Message->getSourceRange().getBegin(), 10857 diag::warn_objc_circular_container) 10858 << ArgRE->getDecl()->getName() << StringRef("super"); 10859 } 10860 } 10861 } else { 10862 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 10863 10864 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 10865 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 10866 } 10867 10868 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 10869 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 10870 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 10871 ValueDecl *Decl = ReceiverRE->getDecl(); 10872 Diag(Message->getSourceRange().getBegin(), 10873 diag::warn_objc_circular_container) 10874 << Decl->getName() << Decl->getName(); 10875 if (!ArgRE->isObjCSelfExpr()) { 10876 Diag(Decl->getLocation(), 10877 diag::note_objc_circular_container_declared_here) 10878 << Decl->getName(); 10879 } 10880 } 10881 } 10882 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 10883 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 10884 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 10885 ObjCIvarDecl *Decl = IvarRE->getDecl(); 10886 Diag(Message->getSourceRange().getBegin(), 10887 diag::warn_objc_circular_container) 10888 << Decl->getName() << Decl->getName(); 10889 Diag(Decl->getLocation(), 10890 diag::note_objc_circular_container_declared_here) 10891 << Decl->getName(); 10892 } 10893 } 10894 } 10895 } 10896 } 10897 10898 /// Check a message send to see if it's likely to cause a retain cycle. 10899 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 10900 // Only check instance methods whose selector looks like a setter. 10901 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 10902 return; 10903 10904 // Try to find a variable that the receiver is strongly owned by. 10905 RetainCycleOwner owner; 10906 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 10907 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 10908 return; 10909 } else { 10910 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 10911 owner.Variable = getCurMethodDecl()->getSelfDecl(); 10912 owner.Loc = msg->getSuperLoc(); 10913 owner.Range = msg->getSuperLoc(); 10914 } 10915 10916 // Check whether the receiver is captured by any of the arguments. 10917 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) 10918 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) 10919 return diagnoseRetainCycle(*this, capturer, owner); 10920 } 10921 10922 /// Check a property assign to see if it's likely to cause a retain cycle. 10923 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 10924 RetainCycleOwner owner; 10925 if (!findRetainCycleOwner(*this, receiver, owner)) 10926 return; 10927 10928 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 10929 diagnoseRetainCycle(*this, capturer, owner); 10930 } 10931 10932 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 10933 RetainCycleOwner Owner; 10934 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 10935 return; 10936 10937 // Because we don't have an expression for the variable, we have to set the 10938 // location explicitly here. 10939 Owner.Loc = Var->getLocation(); 10940 Owner.Range = Var->getSourceRange(); 10941 10942 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 10943 diagnoseRetainCycle(*this, Capturer, Owner); 10944 } 10945 10946 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 10947 Expr *RHS, bool isProperty) { 10948 // Check if RHS is an Objective-C object literal, which also can get 10949 // immediately zapped in a weak reference. Note that we explicitly 10950 // allow ObjCStringLiterals, since those are designed to never really die. 10951 RHS = RHS->IgnoreParenImpCasts(); 10952 10953 // This enum needs to match with the 'select' in 10954 // warn_objc_arc_literal_assign (off-by-1). 10955 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 10956 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 10957 return false; 10958 10959 S.Diag(Loc, diag::warn_arc_literal_assign) 10960 << (unsigned) Kind 10961 << (isProperty ? 0 : 1) 10962 << RHS->getSourceRange(); 10963 10964 return true; 10965 } 10966 10967 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 10968 Qualifiers::ObjCLifetime LT, 10969 Expr *RHS, bool isProperty) { 10970 // Strip off any implicit cast added to get to the one ARC-specific. 10971 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 10972 if (cast->getCastKind() == CK_ARCConsumeObject) { 10973 S.Diag(Loc, diag::warn_arc_retained_assign) 10974 << (LT == Qualifiers::OCL_ExplicitNone) 10975 << (isProperty ? 0 : 1) 10976 << RHS->getSourceRange(); 10977 return true; 10978 } 10979 RHS = cast->getSubExpr(); 10980 } 10981 10982 if (LT == Qualifiers::OCL_Weak && 10983 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 10984 return true; 10985 10986 return false; 10987 } 10988 10989 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 10990 QualType LHS, Expr *RHS) { 10991 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 10992 10993 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 10994 return false; 10995 10996 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 10997 return true; 10998 10999 return false; 11000 } 11001 11002 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 11003 Expr *LHS, Expr *RHS) { 11004 QualType LHSType; 11005 // PropertyRef on LHS type need be directly obtained from 11006 // its declaration as it has a PseudoType. 11007 ObjCPropertyRefExpr *PRE 11008 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 11009 if (PRE && !PRE->isImplicitProperty()) { 11010 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 11011 if (PD) 11012 LHSType = PD->getType(); 11013 } 11014 11015 if (LHSType.isNull()) 11016 LHSType = LHS->getType(); 11017 11018 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 11019 11020 if (LT == Qualifiers::OCL_Weak) { 11021 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 11022 getCurFunction()->markSafeWeakUse(LHS); 11023 } 11024 11025 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 11026 return; 11027 11028 // FIXME. Check for other life times. 11029 if (LT != Qualifiers::OCL_None) 11030 return; 11031 11032 if (PRE) { 11033 if (PRE->isImplicitProperty()) 11034 return; 11035 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 11036 if (!PD) 11037 return; 11038 11039 unsigned Attributes = PD->getPropertyAttributes(); 11040 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) { 11041 // when 'assign' attribute was not explicitly specified 11042 // by user, ignore it and rely on property type itself 11043 // for lifetime info. 11044 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 11045 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) && 11046 LHSType->isObjCRetainableType()) 11047 return; 11048 11049 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 11050 if (cast->getCastKind() == CK_ARCConsumeObject) { 11051 Diag(Loc, diag::warn_arc_retained_property_assign) 11052 << RHS->getSourceRange(); 11053 return; 11054 } 11055 RHS = cast->getSubExpr(); 11056 } 11057 } 11058 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) { 11059 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 11060 return; 11061 } 11062 } 11063 } 11064 11065 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 11066 11067 namespace { 11068 bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 11069 SourceLocation StmtLoc, 11070 const NullStmt *Body) { 11071 // Do not warn if the body is a macro that expands to nothing, e.g: 11072 // 11073 // #define CALL(x) 11074 // if (condition) 11075 // CALL(0); 11076 // 11077 if (Body->hasLeadingEmptyMacro()) 11078 return false; 11079 11080 // Get line numbers of statement and body. 11081 bool StmtLineInvalid; 11082 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 11083 &StmtLineInvalid); 11084 if (StmtLineInvalid) 11085 return false; 11086 11087 bool BodyLineInvalid; 11088 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 11089 &BodyLineInvalid); 11090 if (BodyLineInvalid) 11091 return false; 11092 11093 // Warn if null statement and body are on the same line. 11094 if (StmtLine != BodyLine) 11095 return false; 11096 11097 return true; 11098 } 11099 } // end anonymous namespace 11100 11101 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 11102 const Stmt *Body, 11103 unsigned DiagID) { 11104 // Since this is a syntactic check, don't emit diagnostic for template 11105 // instantiations, this just adds noise. 11106 if (CurrentInstantiationScope) 11107 return; 11108 11109 // The body should be a null statement. 11110 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 11111 if (!NBody) 11112 return; 11113 11114 // Do the usual checks. 11115 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 11116 return; 11117 11118 Diag(NBody->getSemiLoc(), DiagID); 11119 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 11120 } 11121 11122 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 11123 const Stmt *PossibleBody) { 11124 assert(!CurrentInstantiationScope); // Ensured by caller 11125 11126 SourceLocation StmtLoc; 11127 const Stmt *Body; 11128 unsigned DiagID; 11129 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 11130 StmtLoc = FS->getRParenLoc(); 11131 Body = FS->getBody(); 11132 DiagID = diag::warn_empty_for_body; 11133 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 11134 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 11135 Body = WS->getBody(); 11136 DiagID = diag::warn_empty_while_body; 11137 } else 11138 return; // Neither `for' nor `while'. 11139 11140 // The body should be a null statement. 11141 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 11142 if (!NBody) 11143 return; 11144 11145 // Skip expensive checks if diagnostic is disabled. 11146 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 11147 return; 11148 11149 // Do the usual checks. 11150 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 11151 return; 11152 11153 // `for(...);' and `while(...);' are popular idioms, so in order to keep 11154 // noise level low, emit diagnostics only if for/while is followed by a 11155 // CompoundStmt, e.g.: 11156 // for (int i = 0; i < n; i++); 11157 // { 11158 // a(i); 11159 // } 11160 // or if for/while is followed by a statement with more indentation 11161 // than for/while itself: 11162 // for (int i = 0; i < n; i++); 11163 // a(i); 11164 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 11165 if (!ProbableTypo) { 11166 bool BodyColInvalid; 11167 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 11168 PossibleBody->getLocStart(), 11169 &BodyColInvalid); 11170 if (BodyColInvalid) 11171 return; 11172 11173 bool StmtColInvalid; 11174 unsigned StmtCol = SourceMgr.getPresumedColumnNumber( 11175 S->getLocStart(), 11176 &StmtColInvalid); 11177 if (StmtColInvalid) 11178 return; 11179 11180 if (BodyCol > StmtCol) 11181 ProbableTypo = true; 11182 } 11183 11184 if (ProbableTypo) { 11185 Diag(NBody->getSemiLoc(), DiagID); 11186 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 11187 } 11188 } 11189 11190 //===--- CHECK: Warn on self move with std::move. -------------------------===// 11191 11192 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 11193 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 11194 SourceLocation OpLoc) { 11195 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 11196 return; 11197 11198 if (!ActiveTemplateInstantiations.empty()) 11199 return; 11200 11201 // Strip parens and casts away. 11202 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 11203 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 11204 11205 // Check for a call expression 11206 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 11207 if (!CE || CE->getNumArgs() != 1) 11208 return; 11209 11210 // Check for a call to std::move 11211 const FunctionDecl *FD = CE->getDirectCallee(); 11212 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() || 11213 !FD->getIdentifier()->isStr("move")) 11214 return; 11215 11216 // Get argument from std::move 11217 RHSExpr = CE->getArg(0); 11218 11219 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 11220 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 11221 11222 // Two DeclRefExpr's, check that the decls are the same. 11223 if (LHSDeclRef && RHSDeclRef) { 11224 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 11225 return; 11226 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 11227 RHSDeclRef->getDecl()->getCanonicalDecl()) 11228 return; 11229 11230 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 11231 << LHSExpr->getSourceRange() 11232 << RHSExpr->getSourceRange(); 11233 return; 11234 } 11235 11236 // Member variables require a different approach to check for self moves. 11237 // MemberExpr's are the same if every nested MemberExpr refers to the same 11238 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 11239 // the base Expr's are CXXThisExpr's. 11240 const Expr *LHSBase = LHSExpr; 11241 const Expr *RHSBase = RHSExpr; 11242 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 11243 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 11244 if (!LHSME || !RHSME) 11245 return; 11246 11247 while (LHSME && RHSME) { 11248 if (LHSME->getMemberDecl()->getCanonicalDecl() != 11249 RHSME->getMemberDecl()->getCanonicalDecl()) 11250 return; 11251 11252 LHSBase = LHSME->getBase(); 11253 RHSBase = RHSME->getBase(); 11254 LHSME = dyn_cast<MemberExpr>(LHSBase); 11255 RHSME = dyn_cast<MemberExpr>(RHSBase); 11256 } 11257 11258 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 11259 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 11260 if (LHSDeclRef && RHSDeclRef) { 11261 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 11262 return; 11263 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 11264 RHSDeclRef->getDecl()->getCanonicalDecl()) 11265 return; 11266 11267 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 11268 << LHSExpr->getSourceRange() 11269 << RHSExpr->getSourceRange(); 11270 return; 11271 } 11272 11273 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 11274 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 11275 << LHSExpr->getSourceRange() 11276 << RHSExpr->getSourceRange(); 11277 } 11278 11279 //===--- Layout compatibility ----------------------------------------------// 11280 11281 namespace { 11282 11283 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 11284 11285 /// \brief Check if two enumeration types are layout-compatible. 11286 bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 11287 // C++11 [dcl.enum] p8: 11288 // Two enumeration types are layout-compatible if they have the same 11289 // underlying type. 11290 return ED1->isComplete() && ED2->isComplete() && 11291 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 11292 } 11293 11294 /// \brief Check if two fields are layout-compatible. 11295 bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) { 11296 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 11297 return false; 11298 11299 if (Field1->isBitField() != Field2->isBitField()) 11300 return false; 11301 11302 if (Field1->isBitField()) { 11303 // Make sure that the bit-fields are the same length. 11304 unsigned Bits1 = Field1->getBitWidthValue(C); 11305 unsigned Bits2 = Field2->getBitWidthValue(C); 11306 11307 if (Bits1 != Bits2) 11308 return false; 11309 } 11310 11311 return true; 11312 } 11313 11314 /// \brief Check if two standard-layout structs are layout-compatible. 11315 /// (C++11 [class.mem] p17) 11316 bool isLayoutCompatibleStruct(ASTContext &C, 11317 RecordDecl *RD1, 11318 RecordDecl *RD2) { 11319 // If both records are C++ classes, check that base classes match. 11320 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 11321 // If one of records is a CXXRecordDecl we are in C++ mode, 11322 // thus the other one is a CXXRecordDecl, too. 11323 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 11324 // Check number of base classes. 11325 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 11326 return false; 11327 11328 // Check the base classes. 11329 for (CXXRecordDecl::base_class_const_iterator 11330 Base1 = D1CXX->bases_begin(), 11331 BaseEnd1 = D1CXX->bases_end(), 11332 Base2 = D2CXX->bases_begin(); 11333 Base1 != BaseEnd1; 11334 ++Base1, ++Base2) { 11335 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 11336 return false; 11337 } 11338 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 11339 // If only RD2 is a C++ class, it should have zero base classes. 11340 if (D2CXX->getNumBases() > 0) 11341 return false; 11342 } 11343 11344 // Check the fields. 11345 RecordDecl::field_iterator Field2 = RD2->field_begin(), 11346 Field2End = RD2->field_end(), 11347 Field1 = RD1->field_begin(), 11348 Field1End = RD1->field_end(); 11349 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 11350 if (!isLayoutCompatible(C, *Field1, *Field2)) 11351 return false; 11352 } 11353 if (Field1 != Field1End || Field2 != Field2End) 11354 return false; 11355 11356 return true; 11357 } 11358 11359 /// \brief Check if two standard-layout unions are layout-compatible. 11360 /// (C++11 [class.mem] p18) 11361 bool isLayoutCompatibleUnion(ASTContext &C, 11362 RecordDecl *RD1, 11363 RecordDecl *RD2) { 11364 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 11365 for (auto *Field2 : RD2->fields()) 11366 UnmatchedFields.insert(Field2); 11367 11368 for (auto *Field1 : RD1->fields()) { 11369 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 11370 I = UnmatchedFields.begin(), 11371 E = UnmatchedFields.end(); 11372 11373 for ( ; I != E; ++I) { 11374 if (isLayoutCompatible(C, Field1, *I)) { 11375 bool Result = UnmatchedFields.erase(*I); 11376 (void) Result; 11377 assert(Result); 11378 break; 11379 } 11380 } 11381 if (I == E) 11382 return false; 11383 } 11384 11385 return UnmatchedFields.empty(); 11386 } 11387 11388 bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) { 11389 if (RD1->isUnion() != RD2->isUnion()) 11390 return false; 11391 11392 if (RD1->isUnion()) 11393 return isLayoutCompatibleUnion(C, RD1, RD2); 11394 else 11395 return isLayoutCompatibleStruct(C, RD1, RD2); 11396 } 11397 11398 /// \brief Check if two types are layout-compatible in C++11 sense. 11399 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 11400 if (T1.isNull() || T2.isNull()) 11401 return false; 11402 11403 // C++11 [basic.types] p11: 11404 // If two types T1 and T2 are the same type, then T1 and T2 are 11405 // layout-compatible types. 11406 if (C.hasSameType(T1, T2)) 11407 return true; 11408 11409 T1 = T1.getCanonicalType().getUnqualifiedType(); 11410 T2 = T2.getCanonicalType().getUnqualifiedType(); 11411 11412 const Type::TypeClass TC1 = T1->getTypeClass(); 11413 const Type::TypeClass TC2 = T2->getTypeClass(); 11414 11415 if (TC1 != TC2) 11416 return false; 11417 11418 if (TC1 == Type::Enum) { 11419 return isLayoutCompatible(C, 11420 cast<EnumType>(T1)->getDecl(), 11421 cast<EnumType>(T2)->getDecl()); 11422 } else if (TC1 == Type::Record) { 11423 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 11424 return false; 11425 11426 return isLayoutCompatible(C, 11427 cast<RecordType>(T1)->getDecl(), 11428 cast<RecordType>(T2)->getDecl()); 11429 } 11430 11431 return false; 11432 } 11433 } // end anonymous namespace 11434 11435 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 11436 11437 namespace { 11438 /// \brief Given a type tag expression find the type tag itself. 11439 /// 11440 /// \param TypeExpr Type tag expression, as it appears in user's code. 11441 /// 11442 /// \param VD Declaration of an identifier that appears in a type tag. 11443 /// 11444 /// \param MagicValue Type tag magic value. 11445 bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 11446 const ValueDecl **VD, uint64_t *MagicValue) { 11447 while(true) { 11448 if (!TypeExpr) 11449 return false; 11450 11451 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 11452 11453 switch (TypeExpr->getStmtClass()) { 11454 case Stmt::UnaryOperatorClass: { 11455 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 11456 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 11457 TypeExpr = UO->getSubExpr(); 11458 continue; 11459 } 11460 return false; 11461 } 11462 11463 case Stmt::DeclRefExprClass: { 11464 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 11465 *VD = DRE->getDecl(); 11466 return true; 11467 } 11468 11469 case Stmt::IntegerLiteralClass: { 11470 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 11471 llvm::APInt MagicValueAPInt = IL->getValue(); 11472 if (MagicValueAPInt.getActiveBits() <= 64) { 11473 *MagicValue = MagicValueAPInt.getZExtValue(); 11474 return true; 11475 } else 11476 return false; 11477 } 11478 11479 case Stmt::BinaryConditionalOperatorClass: 11480 case Stmt::ConditionalOperatorClass: { 11481 const AbstractConditionalOperator *ACO = 11482 cast<AbstractConditionalOperator>(TypeExpr); 11483 bool Result; 11484 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) { 11485 if (Result) 11486 TypeExpr = ACO->getTrueExpr(); 11487 else 11488 TypeExpr = ACO->getFalseExpr(); 11489 continue; 11490 } 11491 return false; 11492 } 11493 11494 case Stmt::BinaryOperatorClass: { 11495 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 11496 if (BO->getOpcode() == BO_Comma) { 11497 TypeExpr = BO->getRHS(); 11498 continue; 11499 } 11500 return false; 11501 } 11502 11503 default: 11504 return false; 11505 } 11506 } 11507 } 11508 11509 /// \brief Retrieve the C type corresponding to type tag TypeExpr. 11510 /// 11511 /// \param TypeExpr Expression that specifies a type tag. 11512 /// 11513 /// \param MagicValues Registered magic values. 11514 /// 11515 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 11516 /// kind. 11517 /// 11518 /// \param TypeInfo Information about the corresponding C type. 11519 /// 11520 /// \returns true if the corresponding C type was found. 11521 bool GetMatchingCType( 11522 const IdentifierInfo *ArgumentKind, 11523 const Expr *TypeExpr, const ASTContext &Ctx, 11524 const llvm::DenseMap<Sema::TypeTagMagicValue, 11525 Sema::TypeTagData> *MagicValues, 11526 bool &FoundWrongKind, 11527 Sema::TypeTagData &TypeInfo) { 11528 FoundWrongKind = false; 11529 11530 // Variable declaration that has type_tag_for_datatype attribute. 11531 const ValueDecl *VD = nullptr; 11532 11533 uint64_t MagicValue; 11534 11535 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue)) 11536 return false; 11537 11538 if (VD) { 11539 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 11540 if (I->getArgumentKind() != ArgumentKind) { 11541 FoundWrongKind = true; 11542 return false; 11543 } 11544 TypeInfo.Type = I->getMatchingCType(); 11545 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 11546 TypeInfo.MustBeNull = I->getMustBeNull(); 11547 return true; 11548 } 11549 return false; 11550 } 11551 11552 if (!MagicValues) 11553 return false; 11554 11555 llvm::DenseMap<Sema::TypeTagMagicValue, 11556 Sema::TypeTagData>::const_iterator I = 11557 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 11558 if (I == MagicValues->end()) 11559 return false; 11560 11561 TypeInfo = I->second; 11562 return true; 11563 } 11564 } // end anonymous namespace 11565 11566 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 11567 uint64_t MagicValue, QualType Type, 11568 bool LayoutCompatible, 11569 bool MustBeNull) { 11570 if (!TypeTagForDatatypeMagicValues) 11571 TypeTagForDatatypeMagicValues.reset( 11572 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 11573 11574 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 11575 (*TypeTagForDatatypeMagicValues)[Magic] = 11576 TypeTagData(Type, LayoutCompatible, MustBeNull); 11577 } 11578 11579 namespace { 11580 bool IsSameCharType(QualType T1, QualType T2) { 11581 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 11582 if (!BT1) 11583 return false; 11584 11585 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 11586 if (!BT2) 11587 return false; 11588 11589 BuiltinType::Kind T1Kind = BT1->getKind(); 11590 BuiltinType::Kind T2Kind = BT2->getKind(); 11591 11592 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 11593 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 11594 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 11595 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 11596 } 11597 } // end anonymous namespace 11598 11599 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 11600 const Expr * const *ExprArgs) { 11601 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 11602 bool IsPointerAttr = Attr->getIsPointer(); 11603 11604 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()]; 11605 bool FoundWrongKind; 11606 TypeTagData TypeInfo; 11607 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 11608 TypeTagForDatatypeMagicValues.get(), 11609 FoundWrongKind, TypeInfo)) { 11610 if (FoundWrongKind) 11611 Diag(TypeTagExpr->getExprLoc(), 11612 diag::warn_type_tag_for_datatype_wrong_kind) 11613 << TypeTagExpr->getSourceRange(); 11614 return; 11615 } 11616 11617 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()]; 11618 if (IsPointerAttr) { 11619 // Skip implicit cast of pointer to `void *' (as a function argument). 11620 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 11621 if (ICE->getType()->isVoidPointerType() && 11622 ICE->getCastKind() == CK_BitCast) 11623 ArgumentExpr = ICE->getSubExpr(); 11624 } 11625 QualType ArgumentType = ArgumentExpr->getType(); 11626 11627 // Passing a `void*' pointer shouldn't trigger a warning. 11628 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 11629 return; 11630 11631 if (TypeInfo.MustBeNull) { 11632 // Type tag with matching void type requires a null pointer. 11633 if (!ArgumentExpr->isNullPointerConstant(Context, 11634 Expr::NPC_ValueDependentIsNotNull)) { 11635 Diag(ArgumentExpr->getExprLoc(), 11636 diag::warn_type_safety_null_pointer_required) 11637 << ArgumentKind->getName() 11638 << ArgumentExpr->getSourceRange() 11639 << TypeTagExpr->getSourceRange(); 11640 } 11641 return; 11642 } 11643 11644 QualType RequiredType = TypeInfo.Type; 11645 if (IsPointerAttr) 11646 RequiredType = Context.getPointerType(RequiredType); 11647 11648 bool mismatch = false; 11649 if (!TypeInfo.LayoutCompatible) { 11650 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 11651 11652 // C++11 [basic.fundamental] p1: 11653 // Plain char, signed char, and unsigned char are three distinct types. 11654 // 11655 // But we treat plain `char' as equivalent to `signed char' or `unsigned 11656 // char' depending on the current char signedness mode. 11657 if (mismatch) 11658 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 11659 RequiredType->getPointeeType())) || 11660 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 11661 mismatch = false; 11662 } else 11663 if (IsPointerAttr) 11664 mismatch = !isLayoutCompatible(Context, 11665 ArgumentType->getPointeeType(), 11666 RequiredType->getPointeeType()); 11667 else 11668 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 11669 11670 if (mismatch) 11671 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 11672 << ArgumentType << ArgumentKind 11673 << TypeInfo.LayoutCompatible << RequiredType 11674 << ArgumentExpr->getSourceRange() 11675 << TypeTagExpr->getSourceRange(); 11676 } 11677 11678 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 11679 CharUnits Alignment) { 11680 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 11681 } 11682 11683 void Sema::DiagnoseMisalignedMembers() { 11684 for (MisalignedMember &m : MisalignedMembers) { 11685 const NamedDecl *ND = m.RD; 11686 if (ND->getName().empty()) { 11687 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 11688 ND = TD; 11689 } 11690 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member) 11691 << m.MD << ND << m.E->getSourceRange(); 11692 } 11693 MisalignedMembers.clear(); 11694 } 11695 11696 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 11697 if (!T->isPointerType()) 11698 return; 11699 if (isa<UnaryOperator>(E) && 11700 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 11701 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 11702 if (isa<MemberExpr>(Op)) { 11703 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(), 11704 MisalignedMember(Op)); 11705 if (MA != MisalignedMembers.end() && 11706 Context.getTypeAlignInChars(T->getPointeeType()) <= MA->Alignment) 11707 MisalignedMembers.erase(MA); 11708 } 11709 } 11710 } 11711 11712 void Sema::RefersToMemberWithReducedAlignment( 11713 Expr *E, 11714 std::function<void(Expr *, RecordDecl *, ValueDecl *, CharUnits)> Action) { 11715 const auto *ME = dyn_cast<MemberExpr>(E); 11716 while (ME && isa<FieldDecl>(ME->getMemberDecl())) { 11717 QualType BaseType = ME->getBase()->getType(); 11718 if (ME->isArrow()) 11719 BaseType = BaseType->getPointeeType(); 11720 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl(); 11721 11722 ValueDecl *MD = ME->getMemberDecl(); 11723 bool ByteAligned = Context.getTypeAlignInChars(MD->getType()).isOne(); 11724 if (ByteAligned) // Attribute packed does not have any effect. 11725 break; 11726 11727 if (!ByteAligned && 11728 (RD->hasAttr<PackedAttr>() || (MD->hasAttr<PackedAttr>()))) { 11729 CharUnits Alignment = std::min(Context.getTypeAlignInChars(MD->getType()), 11730 Context.getTypeAlignInChars(BaseType)); 11731 // Notify that this expression designates a member with reduced alignment 11732 Action(E, RD, MD, Alignment); 11733 break; 11734 } 11735 ME = dyn_cast<MemberExpr>(ME->getBase()); 11736 } 11737 } 11738 11739 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 11740 using namespace std::placeholders; 11741 RefersToMemberWithReducedAlignment( 11742 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 11743 _2, _3, _4)); 11744 } 11745 11746