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 break; 1024 case Builtin::BIreserve_read_pipe: 1025 case Builtin::BIreserve_write_pipe: 1026 case Builtin::BIwork_group_reserve_read_pipe: 1027 case Builtin::BIwork_group_reserve_write_pipe: 1028 case Builtin::BIsub_group_reserve_read_pipe: 1029 case Builtin::BIsub_group_reserve_write_pipe: 1030 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1031 return ExprError(); 1032 // Since return type of reserve_read/write_pipe built-in function is 1033 // reserve_id_t, which is not defined in the builtin def file , we used int 1034 // as return type and need to override the return type of these functions. 1035 TheCall->setType(Context.OCLReserveIDTy); 1036 break; 1037 case Builtin::BIcommit_read_pipe: 1038 case Builtin::BIcommit_write_pipe: 1039 case Builtin::BIwork_group_commit_read_pipe: 1040 case Builtin::BIwork_group_commit_write_pipe: 1041 case Builtin::BIsub_group_commit_read_pipe: 1042 case Builtin::BIsub_group_commit_write_pipe: 1043 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1044 return ExprError(); 1045 break; 1046 case Builtin::BIget_pipe_num_packets: 1047 case Builtin::BIget_pipe_max_packets: 1048 if (SemaBuiltinPipePackets(*this, TheCall)) 1049 return ExprError(); 1050 break; 1051 case Builtin::BIto_global: 1052 case Builtin::BIto_local: 1053 case Builtin::BIto_private: 1054 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1055 return ExprError(); 1056 break; 1057 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1058 case Builtin::BIenqueue_kernel: 1059 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1060 return ExprError(); 1061 break; 1062 case Builtin::BIget_kernel_work_group_size: 1063 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1064 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1065 return ExprError(); 1066 } 1067 1068 // Since the target specific builtins for each arch overlap, only check those 1069 // of the arch we are compiling for. 1070 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 1071 switch (Context.getTargetInfo().getTriple().getArch()) { 1072 case llvm::Triple::arm: 1073 case llvm::Triple::armeb: 1074 case llvm::Triple::thumb: 1075 case llvm::Triple::thumbeb: 1076 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall)) 1077 return ExprError(); 1078 break; 1079 case llvm::Triple::aarch64: 1080 case llvm::Triple::aarch64_be: 1081 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall)) 1082 return ExprError(); 1083 break; 1084 case llvm::Triple::mips: 1085 case llvm::Triple::mipsel: 1086 case llvm::Triple::mips64: 1087 case llvm::Triple::mips64el: 1088 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall)) 1089 return ExprError(); 1090 break; 1091 case llvm::Triple::systemz: 1092 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall)) 1093 return ExprError(); 1094 break; 1095 case llvm::Triple::x86: 1096 case llvm::Triple::x86_64: 1097 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall)) 1098 return ExprError(); 1099 break; 1100 case llvm::Triple::ppc: 1101 case llvm::Triple::ppc64: 1102 case llvm::Triple::ppc64le: 1103 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall)) 1104 return ExprError(); 1105 break; 1106 default: 1107 break; 1108 } 1109 } 1110 1111 return TheCallResult; 1112 } 1113 1114 // Get the valid immediate range for the specified NEON type code. 1115 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 1116 NeonTypeFlags Type(t); 1117 int IsQuad = ForceQuad ? true : Type.isQuad(); 1118 switch (Type.getEltType()) { 1119 case NeonTypeFlags::Int8: 1120 case NeonTypeFlags::Poly8: 1121 return shift ? 7 : (8 << IsQuad) - 1; 1122 case NeonTypeFlags::Int16: 1123 case NeonTypeFlags::Poly16: 1124 return shift ? 15 : (4 << IsQuad) - 1; 1125 case NeonTypeFlags::Int32: 1126 return shift ? 31 : (2 << IsQuad) - 1; 1127 case NeonTypeFlags::Int64: 1128 case NeonTypeFlags::Poly64: 1129 return shift ? 63 : (1 << IsQuad) - 1; 1130 case NeonTypeFlags::Poly128: 1131 return shift ? 127 : (1 << IsQuad) - 1; 1132 case NeonTypeFlags::Float16: 1133 assert(!shift && "cannot shift float types!"); 1134 return (4 << IsQuad) - 1; 1135 case NeonTypeFlags::Float32: 1136 assert(!shift && "cannot shift float types!"); 1137 return (2 << IsQuad) - 1; 1138 case NeonTypeFlags::Float64: 1139 assert(!shift && "cannot shift float types!"); 1140 return (1 << IsQuad) - 1; 1141 } 1142 llvm_unreachable("Invalid NeonTypeFlag!"); 1143 } 1144 1145 /// getNeonEltType - Return the QualType corresponding to the elements of 1146 /// the vector type specified by the NeonTypeFlags. This is used to check 1147 /// the pointer arguments for Neon load/store intrinsics. 1148 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 1149 bool IsPolyUnsigned, bool IsInt64Long) { 1150 switch (Flags.getEltType()) { 1151 case NeonTypeFlags::Int8: 1152 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 1153 case NeonTypeFlags::Int16: 1154 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 1155 case NeonTypeFlags::Int32: 1156 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 1157 case NeonTypeFlags::Int64: 1158 if (IsInt64Long) 1159 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 1160 else 1161 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 1162 : Context.LongLongTy; 1163 case NeonTypeFlags::Poly8: 1164 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 1165 case NeonTypeFlags::Poly16: 1166 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 1167 case NeonTypeFlags::Poly64: 1168 if (IsInt64Long) 1169 return Context.UnsignedLongTy; 1170 else 1171 return Context.UnsignedLongLongTy; 1172 case NeonTypeFlags::Poly128: 1173 break; 1174 case NeonTypeFlags::Float16: 1175 return Context.HalfTy; 1176 case NeonTypeFlags::Float32: 1177 return Context.FloatTy; 1178 case NeonTypeFlags::Float64: 1179 return Context.DoubleTy; 1180 } 1181 llvm_unreachable("Invalid NeonTypeFlag!"); 1182 } 1183 1184 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1185 llvm::APSInt Result; 1186 uint64_t mask = 0; 1187 unsigned TV = 0; 1188 int PtrArgNum = -1; 1189 bool HasConstPtr = false; 1190 switch (BuiltinID) { 1191 #define GET_NEON_OVERLOAD_CHECK 1192 #include "clang/Basic/arm_neon.inc" 1193 #undef GET_NEON_OVERLOAD_CHECK 1194 } 1195 1196 // For NEON intrinsics which are overloaded on vector element type, validate 1197 // the immediate which specifies which variant to emit. 1198 unsigned ImmArg = TheCall->getNumArgs()-1; 1199 if (mask) { 1200 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 1201 return true; 1202 1203 TV = Result.getLimitedValue(64); 1204 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 1205 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code) 1206 << TheCall->getArg(ImmArg)->getSourceRange(); 1207 } 1208 1209 if (PtrArgNum >= 0) { 1210 // Check that pointer arguments have the specified type. 1211 Expr *Arg = TheCall->getArg(PtrArgNum); 1212 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 1213 Arg = ICE->getSubExpr(); 1214 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 1215 QualType RHSTy = RHS.get()->getType(); 1216 1217 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 1218 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64; 1219 bool IsInt64Long = 1220 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong; 1221 QualType EltTy = 1222 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 1223 if (HasConstPtr) 1224 EltTy = EltTy.withConst(); 1225 QualType LHSTy = Context.getPointerType(EltTy); 1226 AssignConvertType ConvTy; 1227 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 1228 if (RHS.isInvalid()) 1229 return true; 1230 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy, 1231 RHS.get(), AA_Assigning)) 1232 return true; 1233 } 1234 1235 // For NEON intrinsics which take an immediate value as part of the 1236 // instruction, range check them here. 1237 unsigned i = 0, l = 0, u = 0; 1238 switch (BuiltinID) { 1239 default: 1240 return false; 1241 #define GET_NEON_IMMEDIATE_CHECK 1242 #include "clang/Basic/arm_neon.inc" 1243 #undef GET_NEON_IMMEDIATE_CHECK 1244 } 1245 1246 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1247 } 1248 1249 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 1250 unsigned MaxWidth) { 1251 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 1252 BuiltinID == ARM::BI__builtin_arm_ldaex || 1253 BuiltinID == ARM::BI__builtin_arm_strex || 1254 BuiltinID == ARM::BI__builtin_arm_stlex || 1255 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1256 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1257 BuiltinID == AArch64::BI__builtin_arm_strex || 1258 BuiltinID == AArch64::BI__builtin_arm_stlex) && 1259 "unexpected ARM builtin"); 1260 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 1261 BuiltinID == ARM::BI__builtin_arm_ldaex || 1262 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1263 BuiltinID == AArch64::BI__builtin_arm_ldaex; 1264 1265 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 1266 1267 // Ensure that we have the proper number of arguments. 1268 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 1269 return true; 1270 1271 // Inspect the pointer argument of the atomic builtin. This should always be 1272 // a pointer type, whose element is an integral scalar or pointer type. 1273 // Because it is a pointer type, we don't have to worry about any implicit 1274 // casts here. 1275 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 1276 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 1277 if (PointerArgRes.isInvalid()) 1278 return true; 1279 PointerArg = PointerArgRes.get(); 1280 1281 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 1282 if (!pointerType) { 1283 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 1284 << PointerArg->getType() << PointerArg->getSourceRange(); 1285 return true; 1286 } 1287 1288 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 1289 // task is to insert the appropriate casts into the AST. First work out just 1290 // what the appropriate type is. 1291 QualType ValType = pointerType->getPointeeType(); 1292 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 1293 if (IsLdrex) 1294 AddrType.addConst(); 1295 1296 // Issue a warning if the cast is dodgy. 1297 CastKind CastNeeded = CK_NoOp; 1298 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 1299 CastNeeded = CK_BitCast; 1300 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers) 1301 << PointerArg->getType() 1302 << Context.getPointerType(AddrType) 1303 << AA_Passing << PointerArg->getSourceRange(); 1304 } 1305 1306 // Finally, do the cast and replace the argument with the corrected version. 1307 AddrType = Context.getPointerType(AddrType); 1308 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 1309 if (PointerArgRes.isInvalid()) 1310 return true; 1311 PointerArg = PointerArgRes.get(); 1312 1313 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 1314 1315 // In general, we allow ints, floats and pointers to be loaded and stored. 1316 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 1317 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 1318 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 1319 << PointerArg->getType() << PointerArg->getSourceRange(); 1320 return true; 1321 } 1322 1323 // But ARM doesn't have instructions to deal with 128-bit versions. 1324 if (Context.getTypeSize(ValType) > MaxWidth) { 1325 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 1326 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size) 1327 << PointerArg->getType() << PointerArg->getSourceRange(); 1328 return true; 1329 } 1330 1331 switch (ValType.getObjCLifetime()) { 1332 case Qualifiers::OCL_None: 1333 case Qualifiers::OCL_ExplicitNone: 1334 // okay 1335 break; 1336 1337 case Qualifiers::OCL_Weak: 1338 case Qualifiers::OCL_Strong: 1339 case Qualifiers::OCL_Autoreleasing: 1340 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 1341 << ValType << PointerArg->getSourceRange(); 1342 return true; 1343 } 1344 1345 if (IsLdrex) { 1346 TheCall->setType(ValType); 1347 return false; 1348 } 1349 1350 // Initialize the argument to be stored. 1351 ExprResult ValArg = TheCall->getArg(0); 1352 InitializedEntity Entity = InitializedEntity::InitializeParameter( 1353 Context, ValType, /*consume*/ false); 1354 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 1355 if (ValArg.isInvalid()) 1356 return true; 1357 TheCall->setArg(0, ValArg.get()); 1358 1359 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 1360 // but the custom checker bypasses all default analysis. 1361 TheCall->setType(Context.IntTy); 1362 return false; 1363 } 1364 1365 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1366 llvm::APSInt Result; 1367 1368 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 1369 BuiltinID == ARM::BI__builtin_arm_ldaex || 1370 BuiltinID == ARM::BI__builtin_arm_strex || 1371 BuiltinID == ARM::BI__builtin_arm_stlex) { 1372 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 1373 } 1374 1375 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 1376 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1377 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 1378 } 1379 1380 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 1381 BuiltinID == ARM::BI__builtin_arm_wsr64) 1382 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 1383 1384 if (BuiltinID == ARM::BI__builtin_arm_rsr || 1385 BuiltinID == ARM::BI__builtin_arm_rsrp || 1386 BuiltinID == ARM::BI__builtin_arm_wsr || 1387 BuiltinID == ARM::BI__builtin_arm_wsrp) 1388 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1389 1390 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1391 return true; 1392 1393 // For intrinsics which take an immediate value as part of the instruction, 1394 // range check them here. 1395 unsigned i = 0, l = 0, u = 0; 1396 switch (BuiltinID) { 1397 default: return false; 1398 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break; 1399 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break; 1400 case ARM::BI__builtin_arm_vcvtr_f: 1401 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break; 1402 case ARM::BI__builtin_arm_dmb: 1403 case ARM::BI__builtin_arm_dsb: 1404 case ARM::BI__builtin_arm_isb: 1405 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break; 1406 } 1407 1408 // FIXME: VFP Intrinsics should error if VFP not present. 1409 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1410 } 1411 1412 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, 1413 CallExpr *TheCall) { 1414 llvm::APSInt Result; 1415 1416 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 1417 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1418 BuiltinID == AArch64::BI__builtin_arm_strex || 1419 BuiltinID == AArch64::BI__builtin_arm_stlex) { 1420 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 1421 } 1422 1423 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 1424 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1425 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 1426 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 1427 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 1428 } 1429 1430 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 1431 BuiltinID == AArch64::BI__builtin_arm_wsr64) 1432 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1433 1434 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 1435 BuiltinID == AArch64::BI__builtin_arm_rsrp || 1436 BuiltinID == AArch64::BI__builtin_arm_wsr || 1437 BuiltinID == AArch64::BI__builtin_arm_wsrp) 1438 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1439 1440 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1441 return true; 1442 1443 // For intrinsics which take an immediate value as part of the instruction, 1444 // range check them here. 1445 unsigned i = 0, l = 0, u = 0; 1446 switch (BuiltinID) { 1447 default: return false; 1448 case AArch64::BI__builtin_arm_dmb: 1449 case AArch64::BI__builtin_arm_dsb: 1450 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 1451 } 1452 1453 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1454 } 1455 1456 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1457 unsigned i = 0, l = 0, u = 0; 1458 switch (BuiltinID) { 1459 default: return false; 1460 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 1461 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 1462 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 1463 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 1464 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 1465 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 1466 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 1467 } 1468 1469 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 1470 } 1471 1472 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1473 unsigned i = 0, l = 0, u = 0; 1474 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde || 1475 BuiltinID == PPC::BI__builtin_divdeu || 1476 BuiltinID == PPC::BI__builtin_bpermd; 1477 bool IsTarget64Bit = Context.getTargetInfo() 1478 .getTypeWidth(Context 1479 .getTargetInfo() 1480 .getIntPtrType()) == 64; 1481 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe || 1482 BuiltinID == PPC::BI__builtin_divweu || 1483 BuiltinID == PPC::BI__builtin_divde || 1484 BuiltinID == PPC::BI__builtin_divdeu; 1485 1486 if (Is64BitBltin && !IsTarget64Bit) 1487 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt) 1488 << TheCall->getSourceRange(); 1489 1490 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) || 1491 (BuiltinID == PPC::BI__builtin_bpermd && 1492 !Context.getTargetInfo().hasFeature("bpermd"))) 1493 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7) 1494 << TheCall->getSourceRange(); 1495 1496 switch (BuiltinID) { 1497 default: return false; 1498 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 1499 case PPC::BI__builtin_altivec_crypto_vshasigmad: 1500 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1501 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 1502 case PPC::BI__builtin_tbegin: 1503 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 1504 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 1505 case PPC::BI__builtin_tabortwc: 1506 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 1507 case PPC::BI__builtin_tabortwci: 1508 case PPC::BI__builtin_tabortdci: 1509 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 1510 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 1511 } 1512 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 1513 } 1514 1515 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 1516 CallExpr *TheCall) { 1517 if (BuiltinID == SystemZ::BI__builtin_tabort) { 1518 Expr *Arg = TheCall->getArg(0); 1519 llvm::APSInt AbortCode(32); 1520 if (Arg->isIntegerConstantExpr(AbortCode, Context) && 1521 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256) 1522 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code) 1523 << Arg->getSourceRange(); 1524 } 1525 1526 // For intrinsics which take an immediate value as part of the instruction, 1527 // range check them here. 1528 unsigned i = 0, l = 0, u = 0; 1529 switch (BuiltinID) { 1530 default: return false; 1531 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 1532 case SystemZ::BI__builtin_s390_verimb: 1533 case SystemZ::BI__builtin_s390_verimh: 1534 case SystemZ::BI__builtin_s390_verimf: 1535 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 1536 case SystemZ::BI__builtin_s390_vfaeb: 1537 case SystemZ::BI__builtin_s390_vfaeh: 1538 case SystemZ::BI__builtin_s390_vfaef: 1539 case SystemZ::BI__builtin_s390_vfaebs: 1540 case SystemZ::BI__builtin_s390_vfaehs: 1541 case SystemZ::BI__builtin_s390_vfaefs: 1542 case SystemZ::BI__builtin_s390_vfaezb: 1543 case SystemZ::BI__builtin_s390_vfaezh: 1544 case SystemZ::BI__builtin_s390_vfaezf: 1545 case SystemZ::BI__builtin_s390_vfaezbs: 1546 case SystemZ::BI__builtin_s390_vfaezhs: 1547 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 1548 case SystemZ::BI__builtin_s390_vfidb: 1549 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 1550 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 1551 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 1552 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 1553 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 1554 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 1555 case SystemZ::BI__builtin_s390_vstrcb: 1556 case SystemZ::BI__builtin_s390_vstrch: 1557 case SystemZ::BI__builtin_s390_vstrcf: 1558 case SystemZ::BI__builtin_s390_vstrczb: 1559 case SystemZ::BI__builtin_s390_vstrczh: 1560 case SystemZ::BI__builtin_s390_vstrczf: 1561 case SystemZ::BI__builtin_s390_vstrcbs: 1562 case SystemZ::BI__builtin_s390_vstrchs: 1563 case SystemZ::BI__builtin_s390_vstrcfs: 1564 case SystemZ::BI__builtin_s390_vstrczbs: 1565 case SystemZ::BI__builtin_s390_vstrczhs: 1566 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 1567 } 1568 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 1569 } 1570 1571 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 1572 /// This checks that the target supports __builtin_cpu_supports and 1573 /// that the string argument is constant and valid. 1574 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) { 1575 Expr *Arg = TheCall->getArg(0); 1576 1577 // Check if the argument is a string literal. 1578 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 1579 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal) 1580 << Arg->getSourceRange(); 1581 1582 // Check the contents of the string. 1583 StringRef Feature = 1584 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 1585 if (!S.Context.getTargetInfo().validateCpuSupports(Feature)) 1586 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports) 1587 << Arg->getSourceRange(); 1588 return false; 1589 } 1590 1591 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1592 int i = 0, l = 0, u = 0; 1593 switch (BuiltinID) { 1594 default: 1595 return false; 1596 case X86::BI__builtin_cpu_supports: 1597 return SemaBuiltinCpuSupports(*this, TheCall); 1598 case X86::BI__builtin_ms_va_start: 1599 return SemaBuiltinMSVAStart(TheCall); 1600 case X86::BI__builtin_ia32_addcarryx_u64: 1601 case X86::BI__builtin_ia32_addcarry_u64: 1602 case X86::BI__builtin_ia32_subborrow_u64: 1603 case X86::BI__builtin_ia32_readeflags_u64: 1604 case X86::BI__builtin_ia32_writeeflags_u64: 1605 case X86::BI__builtin_ia32_bextr_u64: 1606 case X86::BI__builtin_ia32_bextri_u64: 1607 case X86::BI__builtin_ia32_bzhi_di: 1608 case X86::BI__builtin_ia32_pdep_di: 1609 case X86::BI__builtin_ia32_pext_di: 1610 case X86::BI__builtin_ia32_crc32di: 1611 case X86::BI__builtin_ia32_fxsave64: 1612 case X86::BI__builtin_ia32_fxrstor64: 1613 case X86::BI__builtin_ia32_xsave64: 1614 case X86::BI__builtin_ia32_xrstor64: 1615 case X86::BI__builtin_ia32_xsaveopt64: 1616 case X86::BI__builtin_ia32_xrstors64: 1617 case X86::BI__builtin_ia32_xsavec64: 1618 case X86::BI__builtin_ia32_xsaves64: 1619 case X86::BI__builtin_ia32_rdfsbase64: 1620 case X86::BI__builtin_ia32_rdgsbase64: 1621 case X86::BI__builtin_ia32_wrfsbase64: 1622 case X86::BI__builtin_ia32_wrgsbase64: 1623 case X86::BI__builtin_ia32_pbroadcastq512_gpr_mask: 1624 case X86::BI__builtin_ia32_pbroadcastq256_gpr_mask: 1625 case X86::BI__builtin_ia32_pbroadcastq128_gpr_mask: 1626 case X86::BI__builtin_ia32_vcvtsd2si64: 1627 case X86::BI__builtin_ia32_vcvtsd2usi64: 1628 case X86::BI__builtin_ia32_vcvtss2si64: 1629 case X86::BI__builtin_ia32_vcvtss2usi64: 1630 case X86::BI__builtin_ia32_vcvttsd2si64: 1631 case X86::BI__builtin_ia32_vcvttsd2usi64: 1632 case X86::BI__builtin_ia32_vcvttss2si64: 1633 case X86::BI__builtin_ia32_vcvttss2usi64: 1634 case X86::BI__builtin_ia32_cvtss2si64: 1635 case X86::BI__builtin_ia32_cvttss2si64: 1636 case X86::BI__builtin_ia32_cvtsd2si64: 1637 case X86::BI__builtin_ia32_cvttsd2si64: 1638 case X86::BI__builtin_ia32_cvtsi2sd64: 1639 case X86::BI__builtin_ia32_cvtsi2ss64: 1640 case X86::BI__builtin_ia32_cvtusi2sd64: 1641 case X86::BI__builtin_ia32_cvtusi2ss64: 1642 case X86::BI__builtin_ia32_rdseed64_step: { 1643 // These builtins only work on x86-64 targets. 1644 const llvm::Triple &TT = Context.getTargetInfo().getTriple(); 1645 if (TT.getArch() != llvm::Triple::x86_64) 1646 return Diag(TheCall->getCallee()->getLocStart(), 1647 diag::err_x86_builtin_32_bit_tgt); 1648 return false; 1649 } 1650 case X86::BI__builtin_ia32_extractf64x4_mask: 1651 case X86::BI__builtin_ia32_extracti64x4_mask: 1652 case X86::BI__builtin_ia32_extractf32x8_mask: 1653 case X86::BI__builtin_ia32_extracti32x8_mask: 1654 case X86::BI__builtin_ia32_extractf64x2_256_mask: 1655 case X86::BI__builtin_ia32_extracti64x2_256_mask: 1656 case X86::BI__builtin_ia32_extractf32x4_256_mask: 1657 case X86::BI__builtin_ia32_extracti32x4_256_mask: 1658 i = 1; l = 0; u = 1; 1659 break; 1660 case X86::BI_mm_prefetch: 1661 case X86::BI__builtin_ia32_extractf32x4_mask: 1662 case X86::BI__builtin_ia32_extracti32x4_mask: 1663 case X86::BI__builtin_ia32_extractf64x2_512_mask: 1664 case X86::BI__builtin_ia32_extracti64x2_512_mask: 1665 i = 1; l = 0; u = 3; 1666 break; 1667 case X86::BI__builtin_ia32_insertf32x8_mask: 1668 case X86::BI__builtin_ia32_inserti32x8_mask: 1669 case X86::BI__builtin_ia32_insertf64x4_mask: 1670 case X86::BI__builtin_ia32_inserti64x4_mask: 1671 case X86::BI__builtin_ia32_insertf64x2_256_mask: 1672 case X86::BI__builtin_ia32_inserti64x2_256_mask: 1673 case X86::BI__builtin_ia32_insertf32x4_256_mask: 1674 case X86::BI__builtin_ia32_inserti32x4_256_mask: 1675 i = 2; l = 0; u = 1; 1676 break; 1677 case X86::BI__builtin_ia32_sha1rnds4: 1678 case X86::BI__builtin_ia32_shuf_f32x4_256_mask: 1679 case X86::BI__builtin_ia32_shuf_f64x2_256_mask: 1680 case X86::BI__builtin_ia32_shuf_i32x4_256_mask: 1681 case X86::BI__builtin_ia32_shuf_i64x2_256_mask: 1682 case X86::BI__builtin_ia32_insertf64x2_512_mask: 1683 case X86::BI__builtin_ia32_inserti64x2_512_mask: 1684 case X86::BI__builtin_ia32_insertf32x4_mask: 1685 case X86::BI__builtin_ia32_inserti32x4_mask: 1686 i = 2; l = 0; u = 3; 1687 break; 1688 case X86::BI__builtin_ia32_vpermil2pd: 1689 case X86::BI__builtin_ia32_vpermil2pd256: 1690 case X86::BI__builtin_ia32_vpermil2ps: 1691 case X86::BI__builtin_ia32_vpermil2ps256: 1692 i = 3; l = 0; u = 3; 1693 break; 1694 case X86::BI__builtin_ia32_cmpb128_mask: 1695 case X86::BI__builtin_ia32_cmpw128_mask: 1696 case X86::BI__builtin_ia32_cmpd128_mask: 1697 case X86::BI__builtin_ia32_cmpq128_mask: 1698 case X86::BI__builtin_ia32_cmpb256_mask: 1699 case X86::BI__builtin_ia32_cmpw256_mask: 1700 case X86::BI__builtin_ia32_cmpd256_mask: 1701 case X86::BI__builtin_ia32_cmpq256_mask: 1702 case X86::BI__builtin_ia32_cmpb512_mask: 1703 case X86::BI__builtin_ia32_cmpw512_mask: 1704 case X86::BI__builtin_ia32_cmpd512_mask: 1705 case X86::BI__builtin_ia32_cmpq512_mask: 1706 case X86::BI__builtin_ia32_ucmpb128_mask: 1707 case X86::BI__builtin_ia32_ucmpw128_mask: 1708 case X86::BI__builtin_ia32_ucmpd128_mask: 1709 case X86::BI__builtin_ia32_ucmpq128_mask: 1710 case X86::BI__builtin_ia32_ucmpb256_mask: 1711 case X86::BI__builtin_ia32_ucmpw256_mask: 1712 case X86::BI__builtin_ia32_ucmpd256_mask: 1713 case X86::BI__builtin_ia32_ucmpq256_mask: 1714 case X86::BI__builtin_ia32_ucmpb512_mask: 1715 case X86::BI__builtin_ia32_ucmpw512_mask: 1716 case X86::BI__builtin_ia32_ucmpd512_mask: 1717 case X86::BI__builtin_ia32_ucmpq512_mask: 1718 case X86::BI__builtin_ia32_vpcomub: 1719 case X86::BI__builtin_ia32_vpcomuw: 1720 case X86::BI__builtin_ia32_vpcomud: 1721 case X86::BI__builtin_ia32_vpcomuq: 1722 case X86::BI__builtin_ia32_vpcomb: 1723 case X86::BI__builtin_ia32_vpcomw: 1724 case X86::BI__builtin_ia32_vpcomd: 1725 case X86::BI__builtin_ia32_vpcomq: 1726 i = 2; l = 0; u = 7; 1727 break; 1728 case X86::BI__builtin_ia32_roundps: 1729 case X86::BI__builtin_ia32_roundpd: 1730 case X86::BI__builtin_ia32_roundps256: 1731 case X86::BI__builtin_ia32_roundpd256: 1732 i = 1; l = 0; u = 15; 1733 break; 1734 case X86::BI__builtin_ia32_roundss: 1735 case X86::BI__builtin_ia32_roundsd: 1736 case X86::BI__builtin_ia32_rangepd128_mask: 1737 case X86::BI__builtin_ia32_rangepd256_mask: 1738 case X86::BI__builtin_ia32_rangepd512_mask: 1739 case X86::BI__builtin_ia32_rangeps128_mask: 1740 case X86::BI__builtin_ia32_rangeps256_mask: 1741 case X86::BI__builtin_ia32_rangeps512_mask: 1742 case X86::BI__builtin_ia32_getmantsd_round_mask: 1743 case X86::BI__builtin_ia32_getmantss_round_mask: 1744 i = 2; l = 0; u = 15; 1745 break; 1746 case X86::BI__builtin_ia32_cmpps: 1747 case X86::BI__builtin_ia32_cmpss: 1748 case X86::BI__builtin_ia32_cmppd: 1749 case X86::BI__builtin_ia32_cmpsd: 1750 case X86::BI__builtin_ia32_cmpps256: 1751 case X86::BI__builtin_ia32_cmppd256: 1752 case X86::BI__builtin_ia32_cmpps128_mask: 1753 case X86::BI__builtin_ia32_cmppd128_mask: 1754 case X86::BI__builtin_ia32_cmpps256_mask: 1755 case X86::BI__builtin_ia32_cmppd256_mask: 1756 case X86::BI__builtin_ia32_cmpps512_mask: 1757 case X86::BI__builtin_ia32_cmppd512_mask: 1758 case X86::BI__builtin_ia32_cmpsd_mask: 1759 case X86::BI__builtin_ia32_cmpss_mask: 1760 i = 2; l = 0; u = 31; 1761 break; 1762 case X86::BI__builtin_ia32_xabort: 1763 i = 0; l = -128; u = 255; 1764 break; 1765 case X86::BI__builtin_ia32_pshufw: 1766 case X86::BI__builtin_ia32_aeskeygenassist128: 1767 i = 1; l = -128; u = 255; 1768 break; 1769 case X86::BI__builtin_ia32_vcvtps2ph: 1770 case X86::BI__builtin_ia32_vcvtps2ph256: 1771 case X86::BI__builtin_ia32_rndscaleps_128_mask: 1772 case X86::BI__builtin_ia32_rndscalepd_128_mask: 1773 case X86::BI__builtin_ia32_rndscaleps_256_mask: 1774 case X86::BI__builtin_ia32_rndscalepd_256_mask: 1775 case X86::BI__builtin_ia32_rndscaleps_mask: 1776 case X86::BI__builtin_ia32_rndscalepd_mask: 1777 case X86::BI__builtin_ia32_reducepd128_mask: 1778 case X86::BI__builtin_ia32_reducepd256_mask: 1779 case X86::BI__builtin_ia32_reducepd512_mask: 1780 case X86::BI__builtin_ia32_reduceps128_mask: 1781 case X86::BI__builtin_ia32_reduceps256_mask: 1782 case X86::BI__builtin_ia32_reduceps512_mask: 1783 case X86::BI__builtin_ia32_prold512_mask: 1784 case X86::BI__builtin_ia32_prolq512_mask: 1785 case X86::BI__builtin_ia32_prold128_mask: 1786 case X86::BI__builtin_ia32_prold256_mask: 1787 case X86::BI__builtin_ia32_prolq128_mask: 1788 case X86::BI__builtin_ia32_prolq256_mask: 1789 case X86::BI__builtin_ia32_prord128_mask: 1790 case X86::BI__builtin_ia32_prord256_mask: 1791 case X86::BI__builtin_ia32_prorq128_mask: 1792 case X86::BI__builtin_ia32_prorq256_mask: 1793 case X86::BI__builtin_ia32_psllwi512_mask: 1794 case X86::BI__builtin_ia32_psllwi128_mask: 1795 case X86::BI__builtin_ia32_psllwi256_mask: 1796 case X86::BI__builtin_ia32_psrldi128_mask: 1797 case X86::BI__builtin_ia32_psrldi256_mask: 1798 case X86::BI__builtin_ia32_psrldi512_mask: 1799 case X86::BI__builtin_ia32_psrlqi128_mask: 1800 case X86::BI__builtin_ia32_psrlqi256_mask: 1801 case X86::BI__builtin_ia32_psrlqi512_mask: 1802 case X86::BI__builtin_ia32_psrawi512_mask: 1803 case X86::BI__builtin_ia32_psrawi128_mask: 1804 case X86::BI__builtin_ia32_psrawi256_mask: 1805 case X86::BI__builtin_ia32_psrlwi512_mask: 1806 case X86::BI__builtin_ia32_psrlwi128_mask: 1807 case X86::BI__builtin_ia32_psrlwi256_mask: 1808 case X86::BI__builtin_ia32_psradi128_mask: 1809 case X86::BI__builtin_ia32_psradi256_mask: 1810 case X86::BI__builtin_ia32_psradi512_mask: 1811 case X86::BI__builtin_ia32_psraqi128_mask: 1812 case X86::BI__builtin_ia32_psraqi256_mask: 1813 case X86::BI__builtin_ia32_psraqi512_mask: 1814 case X86::BI__builtin_ia32_pslldi128_mask: 1815 case X86::BI__builtin_ia32_pslldi256_mask: 1816 case X86::BI__builtin_ia32_pslldi512_mask: 1817 case X86::BI__builtin_ia32_psllqi128_mask: 1818 case X86::BI__builtin_ia32_psllqi256_mask: 1819 case X86::BI__builtin_ia32_psllqi512_mask: 1820 case X86::BI__builtin_ia32_fpclasspd128_mask: 1821 case X86::BI__builtin_ia32_fpclasspd256_mask: 1822 case X86::BI__builtin_ia32_fpclassps128_mask: 1823 case X86::BI__builtin_ia32_fpclassps256_mask: 1824 case X86::BI__builtin_ia32_fpclassps512_mask: 1825 case X86::BI__builtin_ia32_fpclasspd512_mask: 1826 case X86::BI__builtin_ia32_fpclasssd_mask: 1827 case X86::BI__builtin_ia32_fpclassss_mask: 1828 i = 1; l = 0; u = 255; 1829 break; 1830 case X86::BI__builtin_ia32_palignr: 1831 case X86::BI__builtin_ia32_insertps128: 1832 case X86::BI__builtin_ia32_dpps: 1833 case X86::BI__builtin_ia32_dppd: 1834 case X86::BI__builtin_ia32_dpps256: 1835 case X86::BI__builtin_ia32_mpsadbw128: 1836 case X86::BI__builtin_ia32_mpsadbw256: 1837 case X86::BI__builtin_ia32_pcmpistrm128: 1838 case X86::BI__builtin_ia32_pcmpistri128: 1839 case X86::BI__builtin_ia32_pcmpistria128: 1840 case X86::BI__builtin_ia32_pcmpistric128: 1841 case X86::BI__builtin_ia32_pcmpistrio128: 1842 case X86::BI__builtin_ia32_pcmpistris128: 1843 case X86::BI__builtin_ia32_pcmpistriz128: 1844 case X86::BI__builtin_ia32_pclmulqdq128: 1845 case X86::BI__builtin_ia32_vperm2f128_pd256: 1846 case X86::BI__builtin_ia32_vperm2f128_ps256: 1847 case X86::BI__builtin_ia32_vperm2f128_si256: 1848 case X86::BI__builtin_ia32_permti256: 1849 i = 2; l = -128; u = 255; 1850 break; 1851 case X86::BI__builtin_ia32_palignr128: 1852 case X86::BI__builtin_ia32_palignr256: 1853 case X86::BI__builtin_ia32_palignr128_mask: 1854 case X86::BI__builtin_ia32_palignr256_mask: 1855 case X86::BI__builtin_ia32_palignr512_mask: 1856 case X86::BI__builtin_ia32_alignq512_mask: 1857 case X86::BI__builtin_ia32_alignd512_mask: 1858 case X86::BI__builtin_ia32_alignd128_mask: 1859 case X86::BI__builtin_ia32_alignd256_mask: 1860 case X86::BI__builtin_ia32_alignq128_mask: 1861 case X86::BI__builtin_ia32_alignq256_mask: 1862 case X86::BI__builtin_ia32_vcomisd: 1863 case X86::BI__builtin_ia32_vcomiss: 1864 case X86::BI__builtin_ia32_shuf_f32x4_mask: 1865 case X86::BI__builtin_ia32_shuf_f64x2_mask: 1866 case X86::BI__builtin_ia32_shuf_i32x4_mask: 1867 case X86::BI__builtin_ia32_shuf_i64x2_mask: 1868 case X86::BI__builtin_ia32_dbpsadbw128_mask: 1869 case X86::BI__builtin_ia32_dbpsadbw256_mask: 1870 case X86::BI__builtin_ia32_dbpsadbw512_mask: 1871 i = 2; l = 0; u = 255; 1872 break; 1873 case X86::BI__builtin_ia32_fixupimmpd512_mask: 1874 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 1875 case X86::BI__builtin_ia32_fixupimmps512_mask: 1876 case X86::BI__builtin_ia32_fixupimmps512_maskz: 1877 case X86::BI__builtin_ia32_fixupimmsd_mask: 1878 case X86::BI__builtin_ia32_fixupimmsd_maskz: 1879 case X86::BI__builtin_ia32_fixupimmss_mask: 1880 case X86::BI__builtin_ia32_fixupimmss_maskz: 1881 case X86::BI__builtin_ia32_fixupimmpd128_mask: 1882 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 1883 case X86::BI__builtin_ia32_fixupimmpd256_mask: 1884 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 1885 case X86::BI__builtin_ia32_fixupimmps128_mask: 1886 case X86::BI__builtin_ia32_fixupimmps128_maskz: 1887 case X86::BI__builtin_ia32_fixupimmps256_mask: 1888 case X86::BI__builtin_ia32_fixupimmps256_maskz: 1889 case X86::BI__builtin_ia32_pternlogd512_mask: 1890 case X86::BI__builtin_ia32_pternlogd512_maskz: 1891 case X86::BI__builtin_ia32_pternlogq512_mask: 1892 case X86::BI__builtin_ia32_pternlogq512_maskz: 1893 case X86::BI__builtin_ia32_pternlogd128_mask: 1894 case X86::BI__builtin_ia32_pternlogd128_maskz: 1895 case X86::BI__builtin_ia32_pternlogd256_mask: 1896 case X86::BI__builtin_ia32_pternlogd256_maskz: 1897 case X86::BI__builtin_ia32_pternlogq128_mask: 1898 case X86::BI__builtin_ia32_pternlogq128_maskz: 1899 case X86::BI__builtin_ia32_pternlogq256_mask: 1900 case X86::BI__builtin_ia32_pternlogq256_maskz: 1901 i = 3; l = 0; u = 255; 1902 break; 1903 case X86::BI__builtin_ia32_pcmpestrm128: 1904 case X86::BI__builtin_ia32_pcmpestri128: 1905 case X86::BI__builtin_ia32_pcmpestria128: 1906 case X86::BI__builtin_ia32_pcmpestric128: 1907 case X86::BI__builtin_ia32_pcmpestrio128: 1908 case X86::BI__builtin_ia32_pcmpestris128: 1909 case X86::BI__builtin_ia32_pcmpestriz128: 1910 i = 4; l = -128; u = 255; 1911 break; 1912 case X86::BI__builtin_ia32_rndscalesd_round_mask: 1913 case X86::BI__builtin_ia32_rndscaless_round_mask: 1914 i = 4; l = 0; u = 255; 1915 break; 1916 } 1917 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 1918 } 1919 1920 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 1921 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 1922 /// Returns true when the format fits the function and the FormatStringInfo has 1923 /// been populated. 1924 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 1925 FormatStringInfo *FSI) { 1926 FSI->HasVAListArg = Format->getFirstArg() == 0; 1927 FSI->FormatIdx = Format->getFormatIdx() - 1; 1928 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 1929 1930 // The way the format attribute works in GCC, the implicit this argument 1931 // of member functions is counted. However, it doesn't appear in our own 1932 // lists, so decrement format_idx in that case. 1933 if (IsCXXMember) { 1934 if(FSI->FormatIdx == 0) 1935 return false; 1936 --FSI->FormatIdx; 1937 if (FSI->FirstDataArg != 0) 1938 --FSI->FirstDataArg; 1939 } 1940 return true; 1941 } 1942 1943 /// Checks if a the given expression evaluates to null. 1944 /// 1945 /// \brief Returns true if the value evaluates to null. 1946 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 1947 // If the expression has non-null type, it doesn't evaluate to null. 1948 if (auto nullability 1949 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 1950 if (*nullability == NullabilityKind::NonNull) 1951 return false; 1952 } 1953 1954 // As a special case, transparent unions initialized with zero are 1955 // considered null for the purposes of the nonnull attribute. 1956 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 1957 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1958 if (const CompoundLiteralExpr *CLE = 1959 dyn_cast<CompoundLiteralExpr>(Expr)) 1960 if (const InitListExpr *ILE = 1961 dyn_cast<InitListExpr>(CLE->getInitializer())) 1962 Expr = ILE->getInit(0); 1963 } 1964 1965 bool Result; 1966 return (!Expr->isValueDependent() && 1967 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 1968 !Result); 1969 } 1970 1971 static void CheckNonNullArgument(Sema &S, 1972 const Expr *ArgExpr, 1973 SourceLocation CallSiteLoc) { 1974 if (CheckNonNullExpr(S, ArgExpr)) 1975 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 1976 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange()); 1977 } 1978 1979 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 1980 FormatStringInfo FSI; 1981 if ((GetFormatStringType(Format) == FST_NSString) && 1982 getFormatStringInfo(Format, false, &FSI)) { 1983 Idx = FSI.FormatIdx; 1984 return true; 1985 } 1986 return false; 1987 } 1988 /// \brief Diagnose use of %s directive in an NSString which is being passed 1989 /// as formatting string to formatting method. 1990 static void 1991 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 1992 const NamedDecl *FDecl, 1993 Expr **Args, 1994 unsigned NumArgs) { 1995 unsigned Idx = 0; 1996 bool Format = false; 1997 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 1998 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 1999 Idx = 2; 2000 Format = true; 2001 } 2002 else 2003 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 2004 if (S.GetFormatNSStringIdx(I, Idx)) { 2005 Format = true; 2006 break; 2007 } 2008 } 2009 if (!Format || NumArgs <= Idx) 2010 return; 2011 const Expr *FormatExpr = Args[Idx]; 2012 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 2013 FormatExpr = CSCE->getSubExpr(); 2014 const StringLiteral *FormatString; 2015 if (const ObjCStringLiteral *OSL = 2016 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 2017 FormatString = OSL->getString(); 2018 else 2019 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 2020 if (!FormatString) 2021 return; 2022 if (S.FormatStringHasSArg(FormatString)) { 2023 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 2024 << "%s" << 1 << 1; 2025 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 2026 << FDecl->getDeclName(); 2027 } 2028 } 2029 2030 /// Determine whether the given type has a non-null nullability annotation. 2031 static bool isNonNullType(ASTContext &ctx, QualType type) { 2032 if (auto nullability = type->getNullability(ctx)) 2033 return *nullability == NullabilityKind::NonNull; 2034 2035 return false; 2036 } 2037 2038 static void CheckNonNullArguments(Sema &S, 2039 const NamedDecl *FDecl, 2040 const FunctionProtoType *Proto, 2041 ArrayRef<const Expr *> Args, 2042 SourceLocation CallSiteLoc) { 2043 assert((FDecl || Proto) && "Need a function declaration or prototype"); 2044 2045 // Check the attributes attached to the method/function itself. 2046 llvm::SmallBitVector NonNullArgs; 2047 if (FDecl) { 2048 // Handle the nonnull attribute on the function/method declaration itself. 2049 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 2050 if (!NonNull->args_size()) { 2051 // Easy case: all pointer arguments are nonnull. 2052 for (const auto *Arg : Args) 2053 if (S.isValidPointerAttrType(Arg->getType())) 2054 CheckNonNullArgument(S, Arg, CallSiteLoc); 2055 return; 2056 } 2057 2058 for (unsigned Val : NonNull->args()) { 2059 if (Val >= Args.size()) 2060 continue; 2061 if (NonNullArgs.empty()) 2062 NonNullArgs.resize(Args.size()); 2063 NonNullArgs.set(Val); 2064 } 2065 } 2066 } 2067 2068 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 2069 // Handle the nonnull attribute on the parameters of the 2070 // function/method. 2071 ArrayRef<ParmVarDecl*> parms; 2072 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 2073 parms = FD->parameters(); 2074 else 2075 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 2076 2077 unsigned ParamIndex = 0; 2078 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 2079 I != E; ++I, ++ParamIndex) { 2080 const ParmVarDecl *PVD = *I; 2081 if (PVD->hasAttr<NonNullAttr>() || 2082 isNonNullType(S.Context, PVD->getType())) { 2083 if (NonNullArgs.empty()) 2084 NonNullArgs.resize(Args.size()); 2085 2086 NonNullArgs.set(ParamIndex); 2087 } 2088 } 2089 } else { 2090 // If we have a non-function, non-method declaration but no 2091 // function prototype, try to dig out the function prototype. 2092 if (!Proto) { 2093 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 2094 QualType type = VD->getType().getNonReferenceType(); 2095 if (auto pointerType = type->getAs<PointerType>()) 2096 type = pointerType->getPointeeType(); 2097 else if (auto blockType = type->getAs<BlockPointerType>()) 2098 type = blockType->getPointeeType(); 2099 // FIXME: data member pointers? 2100 2101 // Dig out the function prototype, if there is one. 2102 Proto = type->getAs<FunctionProtoType>(); 2103 } 2104 } 2105 2106 // Fill in non-null argument information from the nullability 2107 // information on the parameter types (if we have them). 2108 if (Proto) { 2109 unsigned Index = 0; 2110 for (auto paramType : Proto->getParamTypes()) { 2111 if (isNonNullType(S.Context, paramType)) { 2112 if (NonNullArgs.empty()) 2113 NonNullArgs.resize(Args.size()); 2114 2115 NonNullArgs.set(Index); 2116 } 2117 2118 ++Index; 2119 } 2120 } 2121 } 2122 2123 // Check for non-null arguments. 2124 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 2125 ArgIndex != ArgIndexEnd; ++ArgIndex) { 2126 if (NonNullArgs[ArgIndex]) 2127 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 2128 } 2129 } 2130 2131 /// Handles the checks for format strings, non-POD arguments to vararg 2132 /// functions, and NULL arguments passed to non-NULL parameters. 2133 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 2134 ArrayRef<const Expr *> Args, bool IsMemberFunction, 2135 SourceLocation Loc, SourceRange Range, 2136 VariadicCallType CallType) { 2137 // FIXME: We should check as much as we can in the template definition. 2138 if (CurContext->isDependentContext()) 2139 return; 2140 2141 // Printf and scanf checking. 2142 llvm::SmallBitVector CheckedVarArgs; 2143 if (FDecl) { 2144 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 2145 // Only create vector if there are format attributes. 2146 CheckedVarArgs.resize(Args.size()); 2147 2148 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 2149 CheckedVarArgs); 2150 } 2151 } 2152 2153 // Refuse POD arguments that weren't caught by the format string 2154 // checks above. 2155 if (CallType != VariadicDoesNotApply) { 2156 unsigned NumParams = Proto ? Proto->getNumParams() 2157 : FDecl && isa<FunctionDecl>(FDecl) 2158 ? cast<FunctionDecl>(FDecl)->getNumParams() 2159 : FDecl && isa<ObjCMethodDecl>(FDecl) 2160 ? cast<ObjCMethodDecl>(FDecl)->param_size() 2161 : 0; 2162 2163 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 2164 // Args[ArgIdx] can be null in malformed code. 2165 if (const Expr *Arg = Args[ArgIdx]) { 2166 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 2167 checkVariadicArgument(Arg, CallType); 2168 } 2169 } 2170 } 2171 2172 if (FDecl || Proto) { 2173 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 2174 2175 // Type safety checking. 2176 if (FDecl) { 2177 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 2178 CheckArgumentWithTypeTag(I, Args.data()); 2179 } 2180 } 2181 } 2182 2183 /// CheckConstructorCall - Check a constructor call for correctness and safety 2184 /// properties not enforced by the C type system. 2185 void Sema::CheckConstructorCall(FunctionDecl *FDecl, 2186 ArrayRef<const Expr *> Args, 2187 const FunctionProtoType *Proto, 2188 SourceLocation Loc) { 2189 VariadicCallType CallType = 2190 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 2191 checkCall(FDecl, Proto, Args, /*IsMemberFunction=*/true, Loc, SourceRange(), 2192 CallType); 2193 } 2194 2195 /// CheckFunctionCall - Check a direct function call for various correctness 2196 /// and safety properties not strictly enforced by the C type system. 2197 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 2198 const FunctionProtoType *Proto) { 2199 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 2200 isa<CXXMethodDecl>(FDecl); 2201 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 2202 IsMemberOperatorCall; 2203 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 2204 TheCall->getCallee()); 2205 Expr** Args = TheCall->getArgs(); 2206 unsigned NumArgs = TheCall->getNumArgs(); 2207 if (IsMemberOperatorCall) { 2208 // If this is a call to a member operator, hide the first argument 2209 // from checkCall. 2210 // FIXME: Our choice of AST representation here is less than ideal. 2211 ++Args; 2212 --NumArgs; 2213 } 2214 checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs), 2215 IsMemberFunction, TheCall->getRParenLoc(), 2216 TheCall->getCallee()->getSourceRange(), CallType); 2217 2218 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 2219 // None of the checks below are needed for functions that don't have 2220 // simple names (e.g., C++ conversion functions). 2221 if (!FnInfo) 2222 return false; 2223 2224 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo); 2225 if (getLangOpts().ObjC1) 2226 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 2227 2228 unsigned CMId = FDecl->getMemoryFunctionKind(); 2229 if (CMId == 0) 2230 return false; 2231 2232 // Handle memory setting and copying functions. 2233 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 2234 CheckStrlcpycatArguments(TheCall, FnInfo); 2235 else if (CMId == Builtin::BIstrncat) 2236 CheckStrncatArguments(TheCall, FnInfo); 2237 else 2238 CheckMemaccessArguments(TheCall, CMId, FnInfo); 2239 2240 return false; 2241 } 2242 2243 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 2244 ArrayRef<const Expr *> Args) { 2245 VariadicCallType CallType = 2246 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 2247 2248 checkCall(Method, nullptr, Args, 2249 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 2250 CallType); 2251 2252 return false; 2253 } 2254 2255 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 2256 const FunctionProtoType *Proto) { 2257 QualType Ty; 2258 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 2259 Ty = V->getType().getNonReferenceType(); 2260 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 2261 Ty = F->getType().getNonReferenceType(); 2262 else 2263 return false; 2264 2265 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 2266 !Ty->isFunctionProtoType()) 2267 return false; 2268 2269 VariadicCallType CallType; 2270 if (!Proto || !Proto->isVariadic()) { 2271 CallType = VariadicDoesNotApply; 2272 } else if (Ty->isBlockPointerType()) { 2273 CallType = VariadicBlock; 2274 } else { // Ty->isFunctionPointerType() 2275 CallType = VariadicFunction; 2276 } 2277 2278 checkCall(NDecl, Proto, 2279 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 2280 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 2281 TheCall->getCallee()->getSourceRange(), CallType); 2282 2283 return false; 2284 } 2285 2286 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 2287 /// such as function pointers returned from functions. 2288 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 2289 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 2290 TheCall->getCallee()); 2291 checkCall(/*FDecl=*/nullptr, Proto, 2292 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 2293 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 2294 TheCall->getCallee()->getSourceRange(), CallType); 2295 2296 return false; 2297 } 2298 2299 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 2300 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 2301 return false; 2302 2303 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 2304 switch (Op) { 2305 case AtomicExpr::AO__c11_atomic_init: 2306 llvm_unreachable("There is no ordering argument for an init"); 2307 2308 case AtomicExpr::AO__c11_atomic_load: 2309 case AtomicExpr::AO__atomic_load_n: 2310 case AtomicExpr::AO__atomic_load: 2311 return OrderingCABI != llvm::AtomicOrderingCABI::release && 2312 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 2313 2314 case AtomicExpr::AO__c11_atomic_store: 2315 case AtomicExpr::AO__atomic_store: 2316 case AtomicExpr::AO__atomic_store_n: 2317 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 2318 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 2319 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 2320 2321 default: 2322 return true; 2323 } 2324 } 2325 2326 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 2327 AtomicExpr::AtomicOp Op) { 2328 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 2329 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 2330 2331 // All these operations take one of the following forms: 2332 enum { 2333 // C __c11_atomic_init(A *, C) 2334 Init, 2335 // C __c11_atomic_load(A *, int) 2336 Load, 2337 // void __atomic_load(A *, CP, int) 2338 LoadCopy, 2339 // void __atomic_store(A *, CP, int) 2340 Copy, 2341 // C __c11_atomic_add(A *, M, int) 2342 Arithmetic, 2343 // C __atomic_exchange_n(A *, CP, int) 2344 Xchg, 2345 // void __atomic_exchange(A *, C *, CP, int) 2346 GNUXchg, 2347 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 2348 C11CmpXchg, 2349 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 2350 GNUCmpXchg 2351 } Form = Init; 2352 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 2353 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 2354 // where: 2355 // C is an appropriate type, 2356 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 2357 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 2358 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 2359 // the int parameters are for orderings. 2360 2361 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 2362 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == 2363 AtomicExpr::AO__atomic_load, 2364 "need to update code for modified C11 atomics"); 2365 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init && 2366 Op <= AtomicExpr::AO__c11_atomic_fetch_xor; 2367 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 2368 Op == AtomicExpr::AO__atomic_store_n || 2369 Op == AtomicExpr::AO__atomic_exchange_n || 2370 Op == AtomicExpr::AO__atomic_compare_exchange_n; 2371 bool IsAddSub = false; 2372 2373 switch (Op) { 2374 case AtomicExpr::AO__c11_atomic_init: 2375 Form = Init; 2376 break; 2377 2378 case AtomicExpr::AO__c11_atomic_load: 2379 case AtomicExpr::AO__atomic_load_n: 2380 Form = Load; 2381 break; 2382 2383 case AtomicExpr::AO__atomic_load: 2384 Form = LoadCopy; 2385 break; 2386 2387 case AtomicExpr::AO__c11_atomic_store: 2388 case AtomicExpr::AO__atomic_store: 2389 case AtomicExpr::AO__atomic_store_n: 2390 Form = Copy; 2391 break; 2392 2393 case AtomicExpr::AO__c11_atomic_fetch_add: 2394 case AtomicExpr::AO__c11_atomic_fetch_sub: 2395 case AtomicExpr::AO__atomic_fetch_add: 2396 case AtomicExpr::AO__atomic_fetch_sub: 2397 case AtomicExpr::AO__atomic_add_fetch: 2398 case AtomicExpr::AO__atomic_sub_fetch: 2399 IsAddSub = true; 2400 // Fall through. 2401 case AtomicExpr::AO__c11_atomic_fetch_and: 2402 case AtomicExpr::AO__c11_atomic_fetch_or: 2403 case AtomicExpr::AO__c11_atomic_fetch_xor: 2404 case AtomicExpr::AO__atomic_fetch_and: 2405 case AtomicExpr::AO__atomic_fetch_or: 2406 case AtomicExpr::AO__atomic_fetch_xor: 2407 case AtomicExpr::AO__atomic_fetch_nand: 2408 case AtomicExpr::AO__atomic_and_fetch: 2409 case AtomicExpr::AO__atomic_or_fetch: 2410 case AtomicExpr::AO__atomic_xor_fetch: 2411 case AtomicExpr::AO__atomic_nand_fetch: 2412 Form = Arithmetic; 2413 break; 2414 2415 case AtomicExpr::AO__c11_atomic_exchange: 2416 case AtomicExpr::AO__atomic_exchange_n: 2417 Form = Xchg; 2418 break; 2419 2420 case AtomicExpr::AO__atomic_exchange: 2421 Form = GNUXchg; 2422 break; 2423 2424 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 2425 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 2426 Form = C11CmpXchg; 2427 break; 2428 2429 case AtomicExpr::AO__atomic_compare_exchange: 2430 case AtomicExpr::AO__atomic_compare_exchange_n: 2431 Form = GNUCmpXchg; 2432 break; 2433 } 2434 2435 // Check we have the right number of arguments. 2436 if (TheCall->getNumArgs() < NumArgs[Form]) { 2437 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 2438 << 0 << NumArgs[Form] << TheCall->getNumArgs() 2439 << TheCall->getCallee()->getSourceRange(); 2440 return ExprError(); 2441 } else if (TheCall->getNumArgs() > NumArgs[Form]) { 2442 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(), 2443 diag::err_typecheck_call_too_many_args) 2444 << 0 << NumArgs[Form] << TheCall->getNumArgs() 2445 << TheCall->getCallee()->getSourceRange(); 2446 return ExprError(); 2447 } 2448 2449 // Inspect the first argument of the atomic operation. 2450 Expr *Ptr = TheCall->getArg(0); 2451 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 2452 if (ConvertedPtr.isInvalid()) 2453 return ExprError(); 2454 2455 Ptr = ConvertedPtr.get(); 2456 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 2457 if (!pointerType) { 2458 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 2459 << Ptr->getType() << Ptr->getSourceRange(); 2460 return ExprError(); 2461 } 2462 2463 // For a __c11 builtin, this should be a pointer to an _Atomic type. 2464 QualType AtomTy = pointerType->getPointeeType(); // 'A' 2465 QualType ValType = AtomTy; // 'C' 2466 if (IsC11) { 2467 if (!AtomTy->isAtomicType()) { 2468 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic) 2469 << Ptr->getType() << Ptr->getSourceRange(); 2470 return ExprError(); 2471 } 2472 if (AtomTy.isConstQualified()) { 2473 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic) 2474 << Ptr->getType() << Ptr->getSourceRange(); 2475 return ExprError(); 2476 } 2477 ValType = AtomTy->getAs<AtomicType>()->getValueType(); 2478 } else if (Form != Load && Form != LoadCopy) { 2479 if (ValType.isConstQualified()) { 2480 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer) 2481 << Ptr->getType() << Ptr->getSourceRange(); 2482 return ExprError(); 2483 } 2484 } 2485 2486 // For an arithmetic operation, the implied arithmetic must be well-formed. 2487 if (Form == Arithmetic) { 2488 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 2489 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) { 2490 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 2491 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 2492 return ExprError(); 2493 } 2494 if (!IsAddSub && !ValType->isIntegerType()) { 2495 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int) 2496 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 2497 return ExprError(); 2498 } 2499 if (IsC11 && ValType->isPointerType() && 2500 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(), 2501 diag::err_incomplete_type)) { 2502 return ExprError(); 2503 } 2504 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 2505 // For __atomic_*_n operations, the value type must be a scalar integral or 2506 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 2507 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 2508 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 2509 return ExprError(); 2510 } 2511 2512 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 2513 !AtomTy->isScalarType()) { 2514 // For GNU atomics, require a trivially-copyable type. This is not part of 2515 // the GNU atomics specification, but we enforce it for sanity. 2516 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy) 2517 << Ptr->getType() << Ptr->getSourceRange(); 2518 return ExprError(); 2519 } 2520 2521 switch (ValType.getObjCLifetime()) { 2522 case Qualifiers::OCL_None: 2523 case Qualifiers::OCL_ExplicitNone: 2524 // okay 2525 break; 2526 2527 case Qualifiers::OCL_Weak: 2528 case Qualifiers::OCL_Strong: 2529 case Qualifiers::OCL_Autoreleasing: 2530 // FIXME: Can this happen? By this point, ValType should be known 2531 // to be trivially copyable. 2532 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 2533 << ValType << Ptr->getSourceRange(); 2534 return ExprError(); 2535 } 2536 2537 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the 2538 // volatile-ness of the pointee-type inject itself into the result or the 2539 // other operands. Similarly atomic_load can take a pointer to a const 'A'. 2540 ValType.removeLocalVolatile(); 2541 ValType.removeLocalConst(); 2542 QualType ResultType = ValType; 2543 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init) 2544 ResultType = Context.VoidTy; 2545 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 2546 ResultType = Context.BoolTy; 2547 2548 // The type of a parameter passed 'by value'. In the GNU atomics, such 2549 // arguments are actually passed as pointers. 2550 QualType ByValType = ValType; // 'CP' 2551 if (!IsC11 && !IsN) 2552 ByValType = Ptr->getType(); 2553 2554 // The first argument --- the pointer --- has a fixed type; we 2555 // deduce the types of the rest of the arguments accordingly. Walk 2556 // the remaining arguments, converting them to the deduced value type. 2557 for (unsigned i = 1; i != NumArgs[Form]; ++i) { 2558 QualType Ty; 2559 if (i < NumVals[Form] + 1) { 2560 switch (i) { 2561 case 1: 2562 // The second argument is the non-atomic operand. For arithmetic, this 2563 // is always passed by value, and for a compare_exchange it is always 2564 // passed by address. For the rest, GNU uses by-address and C11 uses 2565 // by-value. 2566 assert(Form != Load); 2567 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 2568 Ty = ValType; 2569 else if (Form == Copy || Form == Xchg) 2570 Ty = ByValType; 2571 else if (Form == Arithmetic) 2572 Ty = Context.getPointerDiffType(); 2573 else { 2574 Expr *ValArg = TheCall->getArg(i); 2575 unsigned AS = 0; 2576 // Keep address space of non-atomic pointer type. 2577 if (const PointerType *PtrTy = 2578 ValArg->getType()->getAs<PointerType>()) { 2579 AS = PtrTy->getPointeeType().getAddressSpace(); 2580 } 2581 Ty = Context.getPointerType( 2582 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 2583 } 2584 break; 2585 case 2: 2586 // The third argument to compare_exchange / GNU exchange is a 2587 // (pointer to a) desired value. 2588 Ty = ByValType; 2589 break; 2590 case 3: 2591 // The fourth argument to GNU compare_exchange is a 'weak' flag. 2592 Ty = Context.BoolTy; 2593 break; 2594 } 2595 } else { 2596 // The order(s) are always converted to int. 2597 Ty = Context.IntTy; 2598 } 2599 2600 InitializedEntity Entity = 2601 InitializedEntity::InitializeParameter(Context, Ty, false); 2602 ExprResult Arg = TheCall->getArg(i); 2603 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 2604 if (Arg.isInvalid()) 2605 return true; 2606 TheCall->setArg(i, Arg.get()); 2607 } 2608 2609 // Permute the arguments into a 'consistent' order. 2610 SmallVector<Expr*, 5> SubExprs; 2611 SubExprs.push_back(Ptr); 2612 switch (Form) { 2613 case Init: 2614 // Note, AtomicExpr::getVal1() has a special case for this atomic. 2615 SubExprs.push_back(TheCall->getArg(1)); // Val1 2616 break; 2617 case Load: 2618 SubExprs.push_back(TheCall->getArg(1)); // Order 2619 break; 2620 case LoadCopy: 2621 case Copy: 2622 case Arithmetic: 2623 case Xchg: 2624 SubExprs.push_back(TheCall->getArg(2)); // Order 2625 SubExprs.push_back(TheCall->getArg(1)); // Val1 2626 break; 2627 case GNUXchg: 2628 // Note, AtomicExpr::getVal2() has a special case for this atomic. 2629 SubExprs.push_back(TheCall->getArg(3)); // Order 2630 SubExprs.push_back(TheCall->getArg(1)); // Val1 2631 SubExprs.push_back(TheCall->getArg(2)); // Val2 2632 break; 2633 case C11CmpXchg: 2634 SubExprs.push_back(TheCall->getArg(3)); // Order 2635 SubExprs.push_back(TheCall->getArg(1)); // Val1 2636 SubExprs.push_back(TheCall->getArg(4)); // OrderFail 2637 SubExprs.push_back(TheCall->getArg(2)); // Val2 2638 break; 2639 case GNUCmpXchg: 2640 SubExprs.push_back(TheCall->getArg(4)); // Order 2641 SubExprs.push_back(TheCall->getArg(1)); // Val1 2642 SubExprs.push_back(TheCall->getArg(5)); // OrderFail 2643 SubExprs.push_back(TheCall->getArg(2)); // Val2 2644 SubExprs.push_back(TheCall->getArg(3)); // Weak 2645 break; 2646 } 2647 2648 if (SubExprs.size() >= 2 && Form != Init) { 2649 llvm::APSInt Result(32); 2650 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) && 2651 !isValidOrderingForOp(Result.getSExtValue(), Op)) 2652 Diag(SubExprs[1]->getLocStart(), 2653 diag::warn_atomic_op_has_invalid_memory_order) 2654 << SubExprs[1]->getSourceRange(); 2655 } 2656 2657 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(), 2658 SubExprs, ResultType, Op, 2659 TheCall->getRParenLoc()); 2660 2661 if ((Op == AtomicExpr::AO__c11_atomic_load || 2662 (Op == AtomicExpr::AO__c11_atomic_store)) && 2663 Context.AtomicUsesUnsupportedLibcall(AE)) 2664 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) << 2665 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1); 2666 2667 return AE; 2668 } 2669 2670 /// checkBuiltinArgument - Given a call to a builtin function, perform 2671 /// normal type-checking on the given argument, updating the call in 2672 /// place. This is useful when a builtin function requires custom 2673 /// type-checking for some of its arguments but not necessarily all of 2674 /// them. 2675 /// 2676 /// Returns true on error. 2677 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 2678 FunctionDecl *Fn = E->getDirectCallee(); 2679 assert(Fn && "builtin call without direct callee!"); 2680 2681 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 2682 InitializedEntity Entity = 2683 InitializedEntity::InitializeParameter(S.Context, Param); 2684 2685 ExprResult Arg = E->getArg(0); 2686 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 2687 if (Arg.isInvalid()) 2688 return true; 2689 2690 E->setArg(ArgIndex, Arg.get()); 2691 return false; 2692 } 2693 2694 /// SemaBuiltinAtomicOverloaded - We have a call to a function like 2695 /// __sync_fetch_and_add, which is an overloaded function based on the pointer 2696 /// type of its first argument. The main ActOnCallExpr routines have already 2697 /// promoted the types of arguments because all of these calls are prototyped as 2698 /// void(...). 2699 /// 2700 /// This function goes through and does final semantic checking for these 2701 /// builtins, 2702 ExprResult 2703 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 2704 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 2705 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 2706 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 2707 2708 // Ensure that we have at least one argument to do type inference from. 2709 if (TheCall->getNumArgs() < 1) { 2710 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 2711 << 0 << 1 << TheCall->getNumArgs() 2712 << TheCall->getCallee()->getSourceRange(); 2713 return ExprError(); 2714 } 2715 2716 // Inspect the first argument of the atomic builtin. This should always be 2717 // a pointer type, whose element is an integral scalar or pointer type. 2718 // Because it is a pointer type, we don't have to worry about any implicit 2719 // casts here. 2720 // FIXME: We don't allow floating point scalars as input. 2721 Expr *FirstArg = TheCall->getArg(0); 2722 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 2723 if (FirstArgResult.isInvalid()) 2724 return ExprError(); 2725 FirstArg = FirstArgResult.get(); 2726 TheCall->setArg(0, FirstArg); 2727 2728 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 2729 if (!pointerType) { 2730 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 2731 << FirstArg->getType() << FirstArg->getSourceRange(); 2732 return ExprError(); 2733 } 2734 2735 QualType ValType = pointerType->getPointeeType(); 2736 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 2737 !ValType->isBlockPointerType()) { 2738 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr) 2739 << FirstArg->getType() << FirstArg->getSourceRange(); 2740 return ExprError(); 2741 } 2742 2743 switch (ValType.getObjCLifetime()) { 2744 case Qualifiers::OCL_None: 2745 case Qualifiers::OCL_ExplicitNone: 2746 // okay 2747 break; 2748 2749 case Qualifiers::OCL_Weak: 2750 case Qualifiers::OCL_Strong: 2751 case Qualifiers::OCL_Autoreleasing: 2752 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 2753 << ValType << FirstArg->getSourceRange(); 2754 return ExprError(); 2755 } 2756 2757 // Strip any qualifiers off ValType. 2758 ValType = ValType.getUnqualifiedType(); 2759 2760 // The majority of builtins return a value, but a few have special return 2761 // types, so allow them to override appropriately below. 2762 QualType ResultType = ValType; 2763 2764 // We need to figure out which concrete builtin this maps onto. For example, 2765 // __sync_fetch_and_add with a 2 byte object turns into 2766 // __sync_fetch_and_add_2. 2767 #define BUILTIN_ROW(x) \ 2768 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 2769 Builtin::BI##x##_8, Builtin::BI##x##_16 } 2770 2771 static const unsigned BuiltinIndices[][5] = { 2772 BUILTIN_ROW(__sync_fetch_and_add), 2773 BUILTIN_ROW(__sync_fetch_and_sub), 2774 BUILTIN_ROW(__sync_fetch_and_or), 2775 BUILTIN_ROW(__sync_fetch_and_and), 2776 BUILTIN_ROW(__sync_fetch_and_xor), 2777 BUILTIN_ROW(__sync_fetch_and_nand), 2778 2779 BUILTIN_ROW(__sync_add_and_fetch), 2780 BUILTIN_ROW(__sync_sub_and_fetch), 2781 BUILTIN_ROW(__sync_and_and_fetch), 2782 BUILTIN_ROW(__sync_or_and_fetch), 2783 BUILTIN_ROW(__sync_xor_and_fetch), 2784 BUILTIN_ROW(__sync_nand_and_fetch), 2785 2786 BUILTIN_ROW(__sync_val_compare_and_swap), 2787 BUILTIN_ROW(__sync_bool_compare_and_swap), 2788 BUILTIN_ROW(__sync_lock_test_and_set), 2789 BUILTIN_ROW(__sync_lock_release), 2790 BUILTIN_ROW(__sync_swap) 2791 }; 2792 #undef BUILTIN_ROW 2793 2794 // Determine the index of the size. 2795 unsigned SizeIndex; 2796 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 2797 case 1: SizeIndex = 0; break; 2798 case 2: SizeIndex = 1; break; 2799 case 4: SizeIndex = 2; break; 2800 case 8: SizeIndex = 3; break; 2801 case 16: SizeIndex = 4; break; 2802 default: 2803 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size) 2804 << FirstArg->getType() << FirstArg->getSourceRange(); 2805 return ExprError(); 2806 } 2807 2808 // Each of these builtins has one pointer argument, followed by some number of 2809 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 2810 // that we ignore. Find out which row of BuiltinIndices to read from as well 2811 // as the number of fixed args. 2812 unsigned BuiltinID = FDecl->getBuiltinID(); 2813 unsigned BuiltinIndex, NumFixed = 1; 2814 bool WarnAboutSemanticsChange = false; 2815 switch (BuiltinID) { 2816 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 2817 case Builtin::BI__sync_fetch_and_add: 2818 case Builtin::BI__sync_fetch_and_add_1: 2819 case Builtin::BI__sync_fetch_and_add_2: 2820 case Builtin::BI__sync_fetch_and_add_4: 2821 case Builtin::BI__sync_fetch_and_add_8: 2822 case Builtin::BI__sync_fetch_and_add_16: 2823 BuiltinIndex = 0; 2824 break; 2825 2826 case Builtin::BI__sync_fetch_and_sub: 2827 case Builtin::BI__sync_fetch_and_sub_1: 2828 case Builtin::BI__sync_fetch_and_sub_2: 2829 case Builtin::BI__sync_fetch_and_sub_4: 2830 case Builtin::BI__sync_fetch_and_sub_8: 2831 case Builtin::BI__sync_fetch_and_sub_16: 2832 BuiltinIndex = 1; 2833 break; 2834 2835 case Builtin::BI__sync_fetch_and_or: 2836 case Builtin::BI__sync_fetch_and_or_1: 2837 case Builtin::BI__sync_fetch_and_or_2: 2838 case Builtin::BI__sync_fetch_and_or_4: 2839 case Builtin::BI__sync_fetch_and_or_8: 2840 case Builtin::BI__sync_fetch_and_or_16: 2841 BuiltinIndex = 2; 2842 break; 2843 2844 case Builtin::BI__sync_fetch_and_and: 2845 case Builtin::BI__sync_fetch_and_and_1: 2846 case Builtin::BI__sync_fetch_and_and_2: 2847 case Builtin::BI__sync_fetch_and_and_4: 2848 case Builtin::BI__sync_fetch_and_and_8: 2849 case Builtin::BI__sync_fetch_and_and_16: 2850 BuiltinIndex = 3; 2851 break; 2852 2853 case Builtin::BI__sync_fetch_and_xor: 2854 case Builtin::BI__sync_fetch_and_xor_1: 2855 case Builtin::BI__sync_fetch_and_xor_2: 2856 case Builtin::BI__sync_fetch_and_xor_4: 2857 case Builtin::BI__sync_fetch_and_xor_8: 2858 case Builtin::BI__sync_fetch_and_xor_16: 2859 BuiltinIndex = 4; 2860 break; 2861 2862 case Builtin::BI__sync_fetch_and_nand: 2863 case Builtin::BI__sync_fetch_and_nand_1: 2864 case Builtin::BI__sync_fetch_and_nand_2: 2865 case Builtin::BI__sync_fetch_and_nand_4: 2866 case Builtin::BI__sync_fetch_and_nand_8: 2867 case Builtin::BI__sync_fetch_and_nand_16: 2868 BuiltinIndex = 5; 2869 WarnAboutSemanticsChange = true; 2870 break; 2871 2872 case Builtin::BI__sync_add_and_fetch: 2873 case Builtin::BI__sync_add_and_fetch_1: 2874 case Builtin::BI__sync_add_and_fetch_2: 2875 case Builtin::BI__sync_add_and_fetch_4: 2876 case Builtin::BI__sync_add_and_fetch_8: 2877 case Builtin::BI__sync_add_and_fetch_16: 2878 BuiltinIndex = 6; 2879 break; 2880 2881 case Builtin::BI__sync_sub_and_fetch: 2882 case Builtin::BI__sync_sub_and_fetch_1: 2883 case Builtin::BI__sync_sub_and_fetch_2: 2884 case Builtin::BI__sync_sub_and_fetch_4: 2885 case Builtin::BI__sync_sub_and_fetch_8: 2886 case Builtin::BI__sync_sub_and_fetch_16: 2887 BuiltinIndex = 7; 2888 break; 2889 2890 case Builtin::BI__sync_and_and_fetch: 2891 case Builtin::BI__sync_and_and_fetch_1: 2892 case Builtin::BI__sync_and_and_fetch_2: 2893 case Builtin::BI__sync_and_and_fetch_4: 2894 case Builtin::BI__sync_and_and_fetch_8: 2895 case Builtin::BI__sync_and_and_fetch_16: 2896 BuiltinIndex = 8; 2897 break; 2898 2899 case Builtin::BI__sync_or_and_fetch: 2900 case Builtin::BI__sync_or_and_fetch_1: 2901 case Builtin::BI__sync_or_and_fetch_2: 2902 case Builtin::BI__sync_or_and_fetch_4: 2903 case Builtin::BI__sync_or_and_fetch_8: 2904 case Builtin::BI__sync_or_and_fetch_16: 2905 BuiltinIndex = 9; 2906 break; 2907 2908 case Builtin::BI__sync_xor_and_fetch: 2909 case Builtin::BI__sync_xor_and_fetch_1: 2910 case Builtin::BI__sync_xor_and_fetch_2: 2911 case Builtin::BI__sync_xor_and_fetch_4: 2912 case Builtin::BI__sync_xor_and_fetch_8: 2913 case Builtin::BI__sync_xor_and_fetch_16: 2914 BuiltinIndex = 10; 2915 break; 2916 2917 case Builtin::BI__sync_nand_and_fetch: 2918 case Builtin::BI__sync_nand_and_fetch_1: 2919 case Builtin::BI__sync_nand_and_fetch_2: 2920 case Builtin::BI__sync_nand_and_fetch_4: 2921 case Builtin::BI__sync_nand_and_fetch_8: 2922 case Builtin::BI__sync_nand_and_fetch_16: 2923 BuiltinIndex = 11; 2924 WarnAboutSemanticsChange = true; 2925 break; 2926 2927 case Builtin::BI__sync_val_compare_and_swap: 2928 case Builtin::BI__sync_val_compare_and_swap_1: 2929 case Builtin::BI__sync_val_compare_and_swap_2: 2930 case Builtin::BI__sync_val_compare_and_swap_4: 2931 case Builtin::BI__sync_val_compare_and_swap_8: 2932 case Builtin::BI__sync_val_compare_and_swap_16: 2933 BuiltinIndex = 12; 2934 NumFixed = 2; 2935 break; 2936 2937 case Builtin::BI__sync_bool_compare_and_swap: 2938 case Builtin::BI__sync_bool_compare_and_swap_1: 2939 case Builtin::BI__sync_bool_compare_and_swap_2: 2940 case Builtin::BI__sync_bool_compare_and_swap_4: 2941 case Builtin::BI__sync_bool_compare_and_swap_8: 2942 case Builtin::BI__sync_bool_compare_and_swap_16: 2943 BuiltinIndex = 13; 2944 NumFixed = 2; 2945 ResultType = Context.BoolTy; 2946 break; 2947 2948 case Builtin::BI__sync_lock_test_and_set: 2949 case Builtin::BI__sync_lock_test_and_set_1: 2950 case Builtin::BI__sync_lock_test_and_set_2: 2951 case Builtin::BI__sync_lock_test_and_set_4: 2952 case Builtin::BI__sync_lock_test_and_set_8: 2953 case Builtin::BI__sync_lock_test_and_set_16: 2954 BuiltinIndex = 14; 2955 break; 2956 2957 case Builtin::BI__sync_lock_release: 2958 case Builtin::BI__sync_lock_release_1: 2959 case Builtin::BI__sync_lock_release_2: 2960 case Builtin::BI__sync_lock_release_4: 2961 case Builtin::BI__sync_lock_release_8: 2962 case Builtin::BI__sync_lock_release_16: 2963 BuiltinIndex = 15; 2964 NumFixed = 0; 2965 ResultType = Context.VoidTy; 2966 break; 2967 2968 case Builtin::BI__sync_swap: 2969 case Builtin::BI__sync_swap_1: 2970 case Builtin::BI__sync_swap_2: 2971 case Builtin::BI__sync_swap_4: 2972 case Builtin::BI__sync_swap_8: 2973 case Builtin::BI__sync_swap_16: 2974 BuiltinIndex = 16; 2975 break; 2976 } 2977 2978 // Now that we know how many fixed arguments we expect, first check that we 2979 // have at least that many. 2980 if (TheCall->getNumArgs() < 1+NumFixed) { 2981 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 2982 << 0 << 1+NumFixed << TheCall->getNumArgs() 2983 << TheCall->getCallee()->getSourceRange(); 2984 return ExprError(); 2985 } 2986 2987 if (WarnAboutSemanticsChange) { 2988 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change) 2989 << TheCall->getCallee()->getSourceRange(); 2990 } 2991 2992 // Get the decl for the concrete builtin from this, we can tell what the 2993 // concrete integer type we should convert to is. 2994 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 2995 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 2996 FunctionDecl *NewBuiltinDecl; 2997 if (NewBuiltinID == BuiltinID) 2998 NewBuiltinDecl = FDecl; 2999 else { 3000 // Perform builtin lookup to avoid redeclaring it. 3001 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 3002 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName); 3003 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 3004 assert(Res.getFoundDecl()); 3005 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 3006 if (!NewBuiltinDecl) 3007 return ExprError(); 3008 } 3009 3010 // The first argument --- the pointer --- has a fixed type; we 3011 // deduce the types of the rest of the arguments accordingly. Walk 3012 // the remaining arguments, converting them to the deduced value type. 3013 for (unsigned i = 0; i != NumFixed; ++i) { 3014 ExprResult Arg = TheCall->getArg(i+1); 3015 3016 // GCC does an implicit conversion to the pointer or integer ValType. This 3017 // can fail in some cases (1i -> int**), check for this error case now. 3018 // Initialize the argument. 3019 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 3020 ValType, /*consume*/ false); 3021 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 3022 if (Arg.isInvalid()) 3023 return ExprError(); 3024 3025 // Okay, we have something that *can* be converted to the right type. Check 3026 // to see if there is a potentially weird extension going on here. This can 3027 // happen when you do an atomic operation on something like an char* and 3028 // pass in 42. The 42 gets converted to char. This is even more strange 3029 // for things like 45.123 -> char, etc. 3030 // FIXME: Do this check. 3031 TheCall->setArg(i+1, Arg.get()); 3032 } 3033 3034 ASTContext& Context = this->getASTContext(); 3035 3036 // Create a new DeclRefExpr to refer to the new decl. 3037 DeclRefExpr* NewDRE = DeclRefExpr::Create( 3038 Context, 3039 DRE->getQualifierLoc(), 3040 SourceLocation(), 3041 NewBuiltinDecl, 3042 /*enclosing*/ false, 3043 DRE->getLocation(), 3044 Context.BuiltinFnTy, 3045 DRE->getValueKind()); 3046 3047 // Set the callee in the CallExpr. 3048 // FIXME: This loses syntactic information. 3049 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 3050 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 3051 CK_BuiltinFnToFnPtr); 3052 TheCall->setCallee(PromotedCall.get()); 3053 3054 // Change the result type of the call to match the original value type. This 3055 // is arbitrary, but the codegen for these builtins ins design to handle it 3056 // gracefully. 3057 TheCall->setType(ResultType); 3058 3059 return TheCallResult; 3060 } 3061 3062 /// SemaBuiltinNontemporalOverloaded - We have a call to 3063 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 3064 /// overloaded function based on the pointer type of its last argument. 3065 /// 3066 /// This function goes through and does final semantic checking for these 3067 /// builtins. 3068 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 3069 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 3070 DeclRefExpr *DRE = 3071 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 3072 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 3073 unsigned BuiltinID = FDecl->getBuiltinID(); 3074 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 3075 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 3076 "Unexpected nontemporal load/store builtin!"); 3077 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 3078 unsigned numArgs = isStore ? 2 : 1; 3079 3080 // Ensure that we have the proper number of arguments. 3081 if (checkArgCount(*this, TheCall, numArgs)) 3082 return ExprError(); 3083 3084 // Inspect the last argument of the nontemporal builtin. This should always 3085 // be a pointer type, from which we imply the type of the memory access. 3086 // Because it is a pointer type, we don't have to worry about any implicit 3087 // casts here. 3088 Expr *PointerArg = TheCall->getArg(numArgs - 1); 3089 ExprResult PointerArgResult = 3090 DefaultFunctionArrayLvalueConversion(PointerArg); 3091 3092 if (PointerArgResult.isInvalid()) 3093 return ExprError(); 3094 PointerArg = PointerArgResult.get(); 3095 TheCall->setArg(numArgs - 1, PointerArg); 3096 3097 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 3098 if (!pointerType) { 3099 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer) 3100 << PointerArg->getType() << PointerArg->getSourceRange(); 3101 return ExprError(); 3102 } 3103 3104 QualType ValType = pointerType->getPointeeType(); 3105 3106 // Strip any qualifiers off ValType. 3107 ValType = ValType.getUnqualifiedType(); 3108 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 3109 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 3110 !ValType->isVectorType()) { 3111 Diag(DRE->getLocStart(), 3112 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 3113 << PointerArg->getType() << PointerArg->getSourceRange(); 3114 return ExprError(); 3115 } 3116 3117 if (!isStore) { 3118 TheCall->setType(ValType); 3119 return TheCallResult; 3120 } 3121 3122 ExprResult ValArg = TheCall->getArg(0); 3123 InitializedEntity Entity = InitializedEntity::InitializeParameter( 3124 Context, ValType, /*consume*/ false); 3125 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 3126 if (ValArg.isInvalid()) 3127 return ExprError(); 3128 3129 TheCall->setArg(0, ValArg.get()); 3130 TheCall->setType(Context.VoidTy); 3131 return TheCallResult; 3132 } 3133 3134 /// CheckObjCString - Checks that the argument to the builtin 3135 /// CFString constructor is correct 3136 /// Note: It might also make sense to do the UTF-16 conversion here (would 3137 /// simplify the backend). 3138 bool Sema::CheckObjCString(Expr *Arg) { 3139 Arg = Arg->IgnoreParenCasts(); 3140 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 3141 3142 if (!Literal || !Literal->isAscii()) { 3143 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant) 3144 << Arg->getSourceRange(); 3145 return true; 3146 } 3147 3148 if (Literal->containsNonAsciiOrNull()) { 3149 StringRef String = Literal->getString(); 3150 unsigned NumBytes = String.size(); 3151 SmallVector<UTF16, 128> ToBuf(NumBytes); 3152 const UTF8 *FromPtr = (const UTF8 *)String.data(); 3153 UTF16 *ToPtr = &ToBuf[0]; 3154 3155 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, 3156 &ToPtr, ToPtr + NumBytes, 3157 strictConversion); 3158 // Check for conversion failure. 3159 if (Result != conversionOK) 3160 Diag(Arg->getLocStart(), 3161 diag::warn_cfstring_truncated) << Arg->getSourceRange(); 3162 } 3163 return false; 3164 } 3165 3166 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 3167 /// for validity. Emit an error and return true on failure; return false 3168 /// on success. 3169 bool Sema::SemaBuiltinVAStartImpl(CallExpr *TheCall) { 3170 Expr *Fn = TheCall->getCallee(); 3171 if (TheCall->getNumArgs() > 2) { 3172 Diag(TheCall->getArg(2)->getLocStart(), 3173 diag::err_typecheck_call_too_many_args) 3174 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 3175 << Fn->getSourceRange() 3176 << SourceRange(TheCall->getArg(2)->getLocStart(), 3177 (*(TheCall->arg_end()-1))->getLocEnd()); 3178 return true; 3179 } 3180 3181 if (TheCall->getNumArgs() < 2) { 3182 return Diag(TheCall->getLocEnd(), 3183 diag::err_typecheck_call_too_few_args_at_least) 3184 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 3185 } 3186 3187 // Type-check the first argument normally. 3188 if (checkBuiltinArgument(*this, TheCall, 0)) 3189 return true; 3190 3191 // Determine whether the current function is variadic or not. 3192 BlockScopeInfo *CurBlock = getCurBlock(); 3193 bool isVariadic; 3194 if (CurBlock) 3195 isVariadic = CurBlock->TheDecl->isVariadic(); 3196 else if (FunctionDecl *FD = getCurFunctionDecl()) 3197 isVariadic = FD->isVariadic(); 3198 else 3199 isVariadic = getCurMethodDecl()->isVariadic(); 3200 3201 if (!isVariadic) { 3202 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function); 3203 return true; 3204 } 3205 3206 // Verify that the second argument to the builtin is the last argument of the 3207 // current function or method. 3208 bool SecondArgIsLastNamedArgument = false; 3209 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 3210 3211 // These are valid if SecondArgIsLastNamedArgument is false after the next 3212 // block. 3213 QualType Type; 3214 SourceLocation ParamLoc; 3215 bool IsCRegister = false; 3216 3217 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 3218 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 3219 // FIXME: This isn't correct for methods (results in bogus warning). 3220 // Get the last formal in the current function. 3221 const ParmVarDecl *LastArg; 3222 if (CurBlock) 3223 LastArg = CurBlock->TheDecl->parameters().back(); 3224 else if (FunctionDecl *FD = getCurFunctionDecl()) 3225 LastArg = FD->parameters().back(); 3226 else 3227 LastArg = getCurMethodDecl()->parameters().back(); 3228 SecondArgIsLastNamedArgument = PV == LastArg; 3229 3230 Type = PV->getType(); 3231 ParamLoc = PV->getLocation(); 3232 IsCRegister = 3233 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 3234 } 3235 } 3236 3237 if (!SecondArgIsLastNamedArgument) 3238 Diag(TheCall->getArg(1)->getLocStart(), 3239 diag::warn_second_arg_of_va_start_not_last_named_param); 3240 else if (IsCRegister || Type->isReferenceType() || 3241 Type->isPromotableIntegerType() || 3242 Type->isSpecificBuiltinType(BuiltinType::Float)) { 3243 unsigned Reason = 0; 3244 if (Type->isReferenceType()) Reason = 1; 3245 else if (IsCRegister) Reason = 2; 3246 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason; 3247 Diag(ParamLoc, diag::note_parameter_type) << Type; 3248 } 3249 3250 TheCall->setType(Context.VoidTy); 3251 return false; 3252 } 3253 3254 /// Check the arguments to '__builtin_va_start' for validity, and that 3255 /// it was called from a function of the native ABI. 3256 /// Emit an error and return true on failure; return false on success. 3257 bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) { 3258 // On x86-64 Unix, don't allow this in Win64 ABI functions. 3259 // On x64 Windows, don't allow this in System V ABI functions. 3260 // (Yes, that means there's no corresponding way to support variadic 3261 // System V ABI functions on Windows.) 3262 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) { 3263 unsigned OS = Context.getTargetInfo().getTriple().getOS(); 3264 clang::CallingConv CC = CC_C; 3265 if (const FunctionDecl *FD = getCurFunctionDecl()) 3266 CC = FD->getType()->getAs<FunctionType>()->getCallConv(); 3267 if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) || 3268 (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64)) 3269 return Diag(TheCall->getCallee()->getLocStart(), 3270 diag::err_va_start_used_in_wrong_abi_function) 3271 << (OS != llvm::Triple::Win32); 3272 } 3273 return SemaBuiltinVAStartImpl(TheCall); 3274 } 3275 3276 /// Check the arguments to '__builtin_ms_va_start' for validity, and that 3277 /// it was called from a Win64 ABI function. 3278 /// Emit an error and return true on failure; return false on success. 3279 bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) { 3280 // This only makes sense for x86-64. 3281 const llvm::Triple &TT = Context.getTargetInfo().getTriple(); 3282 Expr *Callee = TheCall->getCallee(); 3283 if (TT.getArch() != llvm::Triple::x86_64) 3284 return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt); 3285 // Don't allow this in System V ABI functions. 3286 clang::CallingConv CC = CC_C; 3287 if (const FunctionDecl *FD = getCurFunctionDecl()) 3288 CC = FD->getType()->getAs<FunctionType>()->getCallConv(); 3289 if (CC == CC_X86_64SysV || 3290 (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64)) 3291 return Diag(Callee->getLocStart(), 3292 diag::err_ms_va_start_used_in_sysv_function); 3293 return SemaBuiltinVAStartImpl(TheCall); 3294 } 3295 3296 bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) { 3297 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 3298 // const char *named_addr); 3299 3300 Expr *Func = Call->getCallee(); 3301 3302 if (Call->getNumArgs() < 3) 3303 return Diag(Call->getLocEnd(), 3304 diag::err_typecheck_call_too_few_args_at_least) 3305 << 0 /*function call*/ << 3 << Call->getNumArgs(); 3306 3307 // Determine whether the current function is variadic or not. 3308 bool IsVariadic; 3309 if (BlockScopeInfo *CurBlock = getCurBlock()) 3310 IsVariadic = CurBlock->TheDecl->isVariadic(); 3311 else if (FunctionDecl *FD = getCurFunctionDecl()) 3312 IsVariadic = FD->isVariadic(); 3313 else if (ObjCMethodDecl *MD = getCurMethodDecl()) 3314 IsVariadic = MD->isVariadic(); 3315 else 3316 llvm_unreachable("unexpected statement type"); 3317 3318 if (!IsVariadic) { 3319 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function); 3320 return true; 3321 } 3322 3323 // Type-check the first argument normally. 3324 if (checkBuiltinArgument(*this, Call, 0)) 3325 return true; 3326 3327 const struct { 3328 unsigned ArgNo; 3329 QualType Type; 3330 } ArgumentTypes[] = { 3331 { 1, Context.getPointerType(Context.CharTy.withConst()) }, 3332 { 2, Context.getSizeType() }, 3333 }; 3334 3335 for (const auto &AT : ArgumentTypes) { 3336 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens(); 3337 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType()) 3338 continue; 3339 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible) 3340 << Arg->getType() << AT.Type << 1 /* different class */ 3341 << 0 /* qualifier difference */ << 3 /* parameter mismatch */ 3342 << AT.ArgNo + 1 << Arg->getType() << AT.Type; 3343 } 3344 3345 return false; 3346 } 3347 3348 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 3349 /// friends. This is declared to take (...), so we have to check everything. 3350 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 3351 if (TheCall->getNumArgs() < 2) 3352 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 3353 << 0 << 2 << TheCall->getNumArgs()/*function call*/; 3354 if (TheCall->getNumArgs() > 2) 3355 return Diag(TheCall->getArg(2)->getLocStart(), 3356 diag::err_typecheck_call_too_many_args) 3357 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 3358 << SourceRange(TheCall->getArg(2)->getLocStart(), 3359 (*(TheCall->arg_end()-1))->getLocEnd()); 3360 3361 ExprResult OrigArg0 = TheCall->getArg(0); 3362 ExprResult OrigArg1 = TheCall->getArg(1); 3363 3364 // Do standard promotions between the two arguments, returning their common 3365 // type. 3366 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false); 3367 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 3368 return true; 3369 3370 // Make sure any conversions are pushed back into the call; this is 3371 // type safe since unordered compare builtins are declared as "_Bool 3372 // foo(...)". 3373 TheCall->setArg(0, OrigArg0.get()); 3374 TheCall->setArg(1, OrigArg1.get()); 3375 3376 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 3377 return false; 3378 3379 // If the common type isn't a real floating type, then the arguments were 3380 // invalid for this operation. 3381 if (Res.isNull() || !Res->isRealFloatingType()) 3382 return Diag(OrigArg0.get()->getLocStart(), 3383 diag::err_typecheck_call_invalid_ordered_compare) 3384 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 3385 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd()); 3386 3387 return false; 3388 } 3389 3390 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 3391 /// __builtin_isnan and friends. This is declared to take (...), so we have 3392 /// to check everything. We expect the last argument to be a floating point 3393 /// value. 3394 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 3395 if (TheCall->getNumArgs() < NumArgs) 3396 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 3397 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/; 3398 if (TheCall->getNumArgs() > NumArgs) 3399 return Diag(TheCall->getArg(NumArgs)->getLocStart(), 3400 diag::err_typecheck_call_too_many_args) 3401 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 3402 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(), 3403 (*(TheCall->arg_end()-1))->getLocEnd()); 3404 3405 Expr *OrigArg = TheCall->getArg(NumArgs-1); 3406 3407 if (OrigArg->isTypeDependent()) 3408 return false; 3409 3410 // This operation requires a non-_Complex floating-point number. 3411 if (!OrigArg->getType()->isRealFloatingType()) 3412 return Diag(OrigArg->getLocStart(), 3413 diag::err_typecheck_call_invalid_unary_fp) 3414 << OrigArg->getType() << OrigArg->getSourceRange(); 3415 3416 // If this is an implicit conversion from float -> double, remove it. 3417 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) { 3418 Expr *CastArg = Cast->getSubExpr(); 3419 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) { 3420 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) && 3421 "promotion from float to double is the only expected cast here"); 3422 Cast->setSubExpr(nullptr); 3423 TheCall->setArg(NumArgs-1, CastArg); 3424 } 3425 } 3426 3427 return false; 3428 } 3429 3430 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 3431 // This is declared to take (...), so we have to check everything. 3432 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 3433 if (TheCall->getNumArgs() < 2) 3434 return ExprError(Diag(TheCall->getLocEnd(), 3435 diag::err_typecheck_call_too_few_args_at_least) 3436 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 3437 << TheCall->getSourceRange()); 3438 3439 // Determine which of the following types of shufflevector we're checking: 3440 // 1) unary, vector mask: (lhs, mask) 3441 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 3442 QualType resType = TheCall->getArg(0)->getType(); 3443 unsigned numElements = 0; 3444 3445 if (!TheCall->getArg(0)->isTypeDependent() && 3446 !TheCall->getArg(1)->isTypeDependent()) { 3447 QualType LHSType = TheCall->getArg(0)->getType(); 3448 QualType RHSType = TheCall->getArg(1)->getType(); 3449 3450 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 3451 return ExprError(Diag(TheCall->getLocStart(), 3452 diag::err_shufflevector_non_vector) 3453 << SourceRange(TheCall->getArg(0)->getLocStart(), 3454 TheCall->getArg(1)->getLocEnd())); 3455 3456 numElements = LHSType->getAs<VectorType>()->getNumElements(); 3457 unsigned numResElements = TheCall->getNumArgs() - 2; 3458 3459 // Check to see if we have a call with 2 vector arguments, the unary shuffle 3460 // with mask. If so, verify that RHS is an integer vector type with the 3461 // same number of elts as lhs. 3462 if (TheCall->getNumArgs() == 2) { 3463 if (!RHSType->hasIntegerRepresentation() || 3464 RHSType->getAs<VectorType>()->getNumElements() != numElements) 3465 return ExprError(Diag(TheCall->getLocStart(), 3466 diag::err_shufflevector_incompatible_vector) 3467 << SourceRange(TheCall->getArg(1)->getLocStart(), 3468 TheCall->getArg(1)->getLocEnd())); 3469 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 3470 return ExprError(Diag(TheCall->getLocStart(), 3471 diag::err_shufflevector_incompatible_vector) 3472 << SourceRange(TheCall->getArg(0)->getLocStart(), 3473 TheCall->getArg(1)->getLocEnd())); 3474 } else if (numElements != numResElements) { 3475 QualType eltType = LHSType->getAs<VectorType>()->getElementType(); 3476 resType = Context.getVectorType(eltType, numResElements, 3477 VectorType::GenericVector); 3478 } 3479 } 3480 3481 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 3482 if (TheCall->getArg(i)->isTypeDependent() || 3483 TheCall->getArg(i)->isValueDependent()) 3484 continue; 3485 3486 llvm::APSInt Result(32); 3487 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 3488 return ExprError(Diag(TheCall->getLocStart(), 3489 diag::err_shufflevector_nonconstant_argument) 3490 << TheCall->getArg(i)->getSourceRange()); 3491 3492 // Allow -1 which will be translated to undef in the IR. 3493 if (Result.isSigned() && Result.isAllOnesValue()) 3494 continue; 3495 3496 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 3497 return ExprError(Diag(TheCall->getLocStart(), 3498 diag::err_shufflevector_argument_too_large) 3499 << TheCall->getArg(i)->getSourceRange()); 3500 } 3501 3502 SmallVector<Expr*, 32> exprs; 3503 3504 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 3505 exprs.push_back(TheCall->getArg(i)); 3506 TheCall->setArg(i, nullptr); 3507 } 3508 3509 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 3510 TheCall->getCallee()->getLocStart(), 3511 TheCall->getRParenLoc()); 3512 } 3513 3514 /// SemaConvertVectorExpr - Handle __builtin_convertvector 3515 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 3516 SourceLocation BuiltinLoc, 3517 SourceLocation RParenLoc) { 3518 ExprValueKind VK = VK_RValue; 3519 ExprObjectKind OK = OK_Ordinary; 3520 QualType DstTy = TInfo->getType(); 3521 QualType SrcTy = E->getType(); 3522 3523 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 3524 return ExprError(Diag(BuiltinLoc, 3525 diag::err_convertvector_non_vector) 3526 << E->getSourceRange()); 3527 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 3528 return ExprError(Diag(BuiltinLoc, 3529 diag::err_convertvector_non_vector_type)); 3530 3531 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 3532 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements(); 3533 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements(); 3534 if (SrcElts != DstElts) 3535 return ExprError(Diag(BuiltinLoc, 3536 diag::err_convertvector_incompatible_vector) 3537 << E->getSourceRange()); 3538 } 3539 3540 return new (Context) 3541 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 3542 } 3543 3544 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 3545 // This is declared to take (const void*, ...) and can take two 3546 // optional constant int args. 3547 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 3548 unsigned NumArgs = TheCall->getNumArgs(); 3549 3550 if (NumArgs > 3) 3551 return Diag(TheCall->getLocEnd(), 3552 diag::err_typecheck_call_too_many_args_at_most) 3553 << 0 /*function call*/ << 3 << NumArgs 3554 << TheCall->getSourceRange(); 3555 3556 // Argument 0 is checked for us and the remaining arguments must be 3557 // constant integers. 3558 for (unsigned i = 1; i != NumArgs; ++i) 3559 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 3560 return true; 3561 3562 return false; 3563 } 3564 3565 /// SemaBuiltinAssume - Handle __assume (MS Extension). 3566 // __assume does not evaluate its arguments, and should warn if its argument 3567 // has side effects. 3568 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 3569 Expr *Arg = TheCall->getArg(0); 3570 if (Arg->isInstantiationDependent()) return false; 3571 3572 if (Arg->HasSideEffects(Context)) 3573 Diag(Arg->getLocStart(), diag::warn_assume_side_effects) 3574 << Arg->getSourceRange() 3575 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 3576 3577 return false; 3578 } 3579 3580 /// Handle __builtin_assume_aligned. This is declared 3581 /// as (const void*, size_t, ...) and can take one optional constant int arg. 3582 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 3583 unsigned NumArgs = TheCall->getNumArgs(); 3584 3585 if (NumArgs > 3) 3586 return Diag(TheCall->getLocEnd(), 3587 diag::err_typecheck_call_too_many_args_at_most) 3588 << 0 /*function call*/ << 3 << NumArgs 3589 << TheCall->getSourceRange(); 3590 3591 // The alignment must be a constant integer. 3592 Expr *Arg = TheCall->getArg(1); 3593 3594 // We can't check the value of a dependent argument. 3595 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 3596 llvm::APSInt Result; 3597 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 3598 return true; 3599 3600 if (!Result.isPowerOf2()) 3601 return Diag(TheCall->getLocStart(), 3602 diag::err_alignment_not_power_of_two) 3603 << Arg->getSourceRange(); 3604 } 3605 3606 if (NumArgs > 2) { 3607 ExprResult Arg(TheCall->getArg(2)); 3608 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 3609 Context.getSizeType(), false); 3610 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 3611 if (Arg.isInvalid()) return true; 3612 TheCall->setArg(2, Arg.get()); 3613 } 3614 3615 return false; 3616 } 3617 3618 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 3619 /// TheCall is a constant expression. 3620 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 3621 llvm::APSInt &Result) { 3622 Expr *Arg = TheCall->getArg(ArgNum); 3623 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 3624 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 3625 3626 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 3627 3628 if (!Arg->isIntegerConstantExpr(Result, Context)) 3629 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type) 3630 << FDecl->getDeclName() << Arg->getSourceRange(); 3631 3632 return false; 3633 } 3634 3635 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 3636 /// TheCall is a constant expression in the range [Low, High]. 3637 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 3638 int Low, int High) { 3639 llvm::APSInt Result; 3640 3641 // We can't check the value of a dependent argument. 3642 Expr *Arg = TheCall->getArg(ArgNum); 3643 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3644 return false; 3645 3646 // Check constant-ness first. 3647 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3648 return true; 3649 3650 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) 3651 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 3652 << Low << High << Arg->getSourceRange(); 3653 3654 return false; 3655 } 3656 3657 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 3658 /// TheCall is an ARM/AArch64 special register string literal. 3659 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 3660 int ArgNum, unsigned ExpectedFieldNum, 3661 bool AllowName) { 3662 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 3663 BuiltinID == ARM::BI__builtin_arm_wsr64 || 3664 BuiltinID == ARM::BI__builtin_arm_rsr || 3665 BuiltinID == ARM::BI__builtin_arm_rsrp || 3666 BuiltinID == ARM::BI__builtin_arm_wsr || 3667 BuiltinID == ARM::BI__builtin_arm_wsrp; 3668 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 3669 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 3670 BuiltinID == AArch64::BI__builtin_arm_rsr || 3671 BuiltinID == AArch64::BI__builtin_arm_rsrp || 3672 BuiltinID == AArch64::BI__builtin_arm_wsr || 3673 BuiltinID == AArch64::BI__builtin_arm_wsrp; 3674 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 3675 3676 // We can't check the value of a dependent argument. 3677 Expr *Arg = TheCall->getArg(ArgNum); 3678 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3679 return false; 3680 3681 // Check if the argument is a string literal. 3682 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3683 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal) 3684 << Arg->getSourceRange(); 3685 3686 // Check the type of special register given. 3687 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3688 SmallVector<StringRef, 6> Fields; 3689 Reg.split(Fields, ":"); 3690 3691 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 3692 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg) 3693 << Arg->getSourceRange(); 3694 3695 // If the string is the name of a register then we cannot check that it is 3696 // valid here but if the string is of one the forms described in ACLE then we 3697 // can check that the supplied fields are integers and within the valid 3698 // ranges. 3699 if (Fields.size() > 1) { 3700 bool FiveFields = Fields.size() == 5; 3701 3702 bool ValidString = true; 3703 if (IsARMBuiltin) { 3704 ValidString &= Fields[0].startswith_lower("cp") || 3705 Fields[0].startswith_lower("p"); 3706 if (ValidString) 3707 Fields[0] = 3708 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 3709 3710 ValidString &= Fields[2].startswith_lower("c"); 3711 if (ValidString) 3712 Fields[2] = Fields[2].drop_front(1); 3713 3714 if (FiveFields) { 3715 ValidString &= Fields[3].startswith_lower("c"); 3716 if (ValidString) 3717 Fields[3] = Fields[3].drop_front(1); 3718 } 3719 } 3720 3721 SmallVector<int, 5> Ranges; 3722 if (FiveFields) 3723 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 7, 15, 15}); 3724 else 3725 Ranges.append({15, 7, 15}); 3726 3727 for (unsigned i=0; i<Fields.size(); ++i) { 3728 int IntField; 3729 ValidString &= !Fields[i].getAsInteger(10, IntField); 3730 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 3731 } 3732 3733 if (!ValidString) 3734 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg) 3735 << Arg->getSourceRange(); 3736 3737 } else if (IsAArch64Builtin && Fields.size() == 1) { 3738 // If the register name is one of those that appear in the condition below 3739 // and the special register builtin being used is one of the write builtins, 3740 // then we require that the argument provided for writing to the register 3741 // is an integer constant expression. This is because it will be lowered to 3742 // an MSR (immediate) instruction, so we need to know the immediate at 3743 // compile time. 3744 if (TheCall->getNumArgs() != 2) 3745 return false; 3746 3747 std::string RegLower = Reg.lower(); 3748 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 3749 RegLower != "pan" && RegLower != "uao") 3750 return false; 3751 3752 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 3753 } 3754 3755 return false; 3756 } 3757 3758 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 3759 /// This checks that the target supports __builtin_longjmp and 3760 /// that val is a constant 1. 3761 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 3762 if (!Context.getTargetInfo().hasSjLjLowering()) 3763 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported) 3764 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd()); 3765 3766 Expr *Arg = TheCall->getArg(1); 3767 llvm::APSInt Result; 3768 3769 // TODO: This is less than ideal. Overload this to take a value. 3770 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 3771 return true; 3772 3773 if (Result != 1) 3774 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val) 3775 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 3776 3777 return false; 3778 } 3779 3780 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 3781 /// This checks that the target supports __builtin_setjmp. 3782 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 3783 if (!Context.getTargetInfo().hasSjLjLowering()) 3784 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported) 3785 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd()); 3786 return false; 3787 } 3788 3789 namespace { 3790 class UncoveredArgHandler { 3791 enum { Unknown = -1, AllCovered = -2 }; 3792 signed FirstUncoveredArg; 3793 SmallVector<const Expr *, 4> DiagnosticExprs; 3794 3795 public: 3796 UncoveredArgHandler() : FirstUncoveredArg(Unknown) { } 3797 3798 bool hasUncoveredArg() const { 3799 return (FirstUncoveredArg >= 0); 3800 } 3801 3802 unsigned getUncoveredArg() const { 3803 assert(hasUncoveredArg() && "no uncovered argument"); 3804 return FirstUncoveredArg; 3805 } 3806 3807 void setAllCovered() { 3808 // A string has been found with all arguments covered, so clear out 3809 // the diagnostics. 3810 DiagnosticExprs.clear(); 3811 FirstUncoveredArg = AllCovered; 3812 } 3813 3814 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 3815 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 3816 3817 // Don't update if a previous string covers all arguments. 3818 if (FirstUncoveredArg == AllCovered) 3819 return; 3820 3821 // UncoveredArgHandler tracks the highest uncovered argument index 3822 // and with it all the strings that match this index. 3823 if (NewFirstUncoveredArg == FirstUncoveredArg) 3824 DiagnosticExprs.push_back(StrExpr); 3825 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 3826 DiagnosticExprs.clear(); 3827 DiagnosticExprs.push_back(StrExpr); 3828 FirstUncoveredArg = NewFirstUncoveredArg; 3829 } 3830 } 3831 3832 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 3833 }; 3834 3835 enum StringLiteralCheckType { 3836 SLCT_NotALiteral, 3837 SLCT_UncheckedLiteral, 3838 SLCT_CheckedLiteral 3839 }; 3840 } // end anonymous namespace 3841 3842 static void CheckFormatString(Sema &S, const StringLiteral *FExpr, 3843 const Expr *OrigFormatExpr, 3844 ArrayRef<const Expr *> Args, 3845 bool HasVAListArg, unsigned format_idx, 3846 unsigned firstDataArg, 3847 Sema::FormatStringType Type, 3848 bool inFunctionCall, 3849 Sema::VariadicCallType CallType, 3850 llvm::SmallBitVector &CheckedVarArgs, 3851 UncoveredArgHandler &UncoveredArg); 3852 3853 // Determine if an expression is a string literal or constant string. 3854 // If this function returns false on the arguments to a function expecting a 3855 // format string, we will usually need to emit a warning. 3856 // True string literals are then checked by CheckFormatString. 3857 static StringLiteralCheckType 3858 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 3859 bool HasVAListArg, unsigned format_idx, 3860 unsigned firstDataArg, Sema::FormatStringType Type, 3861 Sema::VariadicCallType CallType, bool InFunctionCall, 3862 llvm::SmallBitVector &CheckedVarArgs, 3863 UncoveredArgHandler &UncoveredArg) { 3864 tryAgain: 3865 if (E->isTypeDependent() || E->isValueDependent()) 3866 return SLCT_NotALiteral; 3867 3868 E = E->IgnoreParenCasts(); 3869 3870 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 3871 // Technically -Wformat-nonliteral does not warn about this case. 3872 // The behavior of printf and friends in this case is implementation 3873 // dependent. Ideally if the format string cannot be null then 3874 // it should have a 'nonnull' attribute in the function prototype. 3875 return SLCT_UncheckedLiteral; 3876 3877 switch (E->getStmtClass()) { 3878 case Stmt::BinaryConditionalOperatorClass: 3879 case Stmt::ConditionalOperatorClass: { 3880 // The expression is a literal if both sub-expressions were, and it was 3881 // completely checked only if both sub-expressions were checked. 3882 const AbstractConditionalOperator *C = 3883 cast<AbstractConditionalOperator>(E); 3884 3885 // Determine whether it is necessary to check both sub-expressions, for 3886 // example, because the condition expression is a constant that can be 3887 // evaluated at compile time. 3888 bool CheckLeft = true, CheckRight = true; 3889 3890 bool Cond; 3891 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) { 3892 if (Cond) 3893 CheckRight = false; 3894 else 3895 CheckLeft = false; 3896 } 3897 3898 StringLiteralCheckType Left; 3899 if (!CheckLeft) 3900 Left = SLCT_UncheckedLiteral; 3901 else { 3902 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 3903 HasVAListArg, format_idx, firstDataArg, 3904 Type, CallType, InFunctionCall, 3905 CheckedVarArgs, UncoveredArg); 3906 if (Left == SLCT_NotALiteral || !CheckRight) 3907 return Left; 3908 } 3909 3910 StringLiteralCheckType Right = 3911 checkFormatStringExpr(S, C->getFalseExpr(), Args, 3912 HasVAListArg, format_idx, firstDataArg, 3913 Type, CallType, InFunctionCall, CheckedVarArgs, 3914 UncoveredArg); 3915 3916 return (CheckLeft && Left < Right) ? Left : Right; 3917 } 3918 3919 case Stmt::ImplicitCastExprClass: { 3920 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 3921 goto tryAgain; 3922 } 3923 3924 case Stmt::OpaqueValueExprClass: 3925 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 3926 E = src; 3927 goto tryAgain; 3928 } 3929 return SLCT_NotALiteral; 3930 3931 case Stmt::PredefinedExprClass: 3932 // While __func__, etc., are technically not string literals, they 3933 // cannot contain format specifiers and thus are not a security 3934 // liability. 3935 return SLCT_UncheckedLiteral; 3936 3937 case Stmt::DeclRefExprClass: { 3938 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 3939 3940 // As an exception, do not flag errors for variables binding to 3941 // const string literals. 3942 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 3943 bool isConstant = false; 3944 QualType T = DR->getType(); 3945 3946 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 3947 isConstant = AT->getElementType().isConstant(S.Context); 3948 } else if (const PointerType *PT = T->getAs<PointerType>()) { 3949 isConstant = T.isConstant(S.Context) && 3950 PT->getPointeeType().isConstant(S.Context); 3951 } else if (T->isObjCObjectPointerType()) { 3952 // In ObjC, there is usually no "const ObjectPointer" type, 3953 // so don't check if the pointee type is constant. 3954 isConstant = T.isConstant(S.Context); 3955 } 3956 3957 if (isConstant) { 3958 if (const Expr *Init = VD->getAnyInitializer()) { 3959 // Look through initializers like const char c[] = { "foo" } 3960 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 3961 if (InitList->isStringLiteralInit()) 3962 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 3963 } 3964 return checkFormatStringExpr(S, Init, Args, 3965 HasVAListArg, format_idx, 3966 firstDataArg, Type, CallType, 3967 /*InFunctionCall*/false, CheckedVarArgs, 3968 UncoveredArg); 3969 } 3970 } 3971 3972 // For vprintf* functions (i.e., HasVAListArg==true), we add a 3973 // special check to see if the format string is a function parameter 3974 // of the function calling the printf function. If the function 3975 // has an attribute indicating it is a printf-like function, then we 3976 // should suppress warnings concerning non-literals being used in a call 3977 // to a vprintf function. For example: 3978 // 3979 // void 3980 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 3981 // va_list ap; 3982 // va_start(ap, fmt); 3983 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 3984 // ... 3985 // } 3986 if (HasVAListArg) { 3987 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 3988 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 3989 int PVIndex = PV->getFunctionScopeIndex() + 1; 3990 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 3991 // adjust for implicit parameter 3992 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 3993 if (MD->isInstance()) 3994 ++PVIndex; 3995 // We also check if the formats are compatible. 3996 // We can't pass a 'scanf' string to a 'printf' function. 3997 if (PVIndex == PVFormat->getFormatIdx() && 3998 Type == S.GetFormatStringType(PVFormat)) 3999 return SLCT_UncheckedLiteral; 4000 } 4001 } 4002 } 4003 } 4004 } 4005 4006 return SLCT_NotALiteral; 4007 } 4008 4009 case Stmt::CallExprClass: 4010 case Stmt::CXXMemberCallExprClass: { 4011 const CallExpr *CE = cast<CallExpr>(E); 4012 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 4013 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) { 4014 unsigned ArgIndex = FA->getFormatIdx(); 4015 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 4016 if (MD->isInstance()) 4017 --ArgIndex; 4018 const Expr *Arg = CE->getArg(ArgIndex - 1); 4019 4020 return checkFormatStringExpr(S, Arg, Args, 4021 HasVAListArg, format_idx, firstDataArg, 4022 Type, CallType, InFunctionCall, 4023 CheckedVarArgs, UncoveredArg); 4024 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) { 4025 unsigned BuiltinID = FD->getBuiltinID(); 4026 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 4027 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 4028 const Expr *Arg = CE->getArg(0); 4029 return checkFormatStringExpr(S, Arg, Args, 4030 HasVAListArg, format_idx, 4031 firstDataArg, Type, CallType, 4032 InFunctionCall, CheckedVarArgs, 4033 UncoveredArg); 4034 } 4035 } 4036 } 4037 4038 return SLCT_NotALiteral; 4039 } 4040 case Stmt::ObjCStringLiteralClass: 4041 case Stmt::StringLiteralClass: { 4042 const StringLiteral *StrE = nullptr; 4043 4044 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 4045 StrE = ObjCFExpr->getString(); 4046 else 4047 StrE = cast<StringLiteral>(E); 4048 4049 if (StrE) { 4050 CheckFormatString(S, StrE, E, Args, HasVAListArg, format_idx, 4051 firstDataArg, Type, InFunctionCall, CallType, 4052 CheckedVarArgs, UncoveredArg); 4053 return SLCT_CheckedLiteral; 4054 } 4055 4056 return SLCT_NotALiteral; 4057 } 4058 4059 default: 4060 return SLCT_NotALiteral; 4061 } 4062 } 4063 4064 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 4065 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 4066 .Case("scanf", FST_Scanf) 4067 .Cases("printf", "printf0", FST_Printf) 4068 .Cases("NSString", "CFString", FST_NSString) 4069 .Case("strftime", FST_Strftime) 4070 .Case("strfmon", FST_Strfmon) 4071 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 4072 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 4073 .Case("os_trace", FST_OSTrace) 4074 .Default(FST_Unknown); 4075 } 4076 4077 /// CheckFormatArguments - Check calls to printf and scanf (and similar 4078 /// functions) for correct use of format strings. 4079 /// Returns true if a format string has been fully checked. 4080 bool Sema::CheckFormatArguments(const FormatAttr *Format, 4081 ArrayRef<const Expr *> Args, 4082 bool IsCXXMember, 4083 VariadicCallType CallType, 4084 SourceLocation Loc, SourceRange Range, 4085 llvm::SmallBitVector &CheckedVarArgs) { 4086 FormatStringInfo FSI; 4087 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 4088 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 4089 FSI.FirstDataArg, GetFormatStringType(Format), 4090 CallType, Loc, Range, CheckedVarArgs); 4091 return false; 4092 } 4093 4094 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 4095 bool HasVAListArg, unsigned format_idx, 4096 unsigned firstDataArg, FormatStringType Type, 4097 VariadicCallType CallType, 4098 SourceLocation Loc, SourceRange Range, 4099 llvm::SmallBitVector &CheckedVarArgs) { 4100 // CHECK: printf/scanf-like function is called with no format string. 4101 if (format_idx >= Args.size()) { 4102 Diag(Loc, diag::warn_missing_format_string) << Range; 4103 return false; 4104 } 4105 4106 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 4107 4108 // CHECK: format string is not a string literal. 4109 // 4110 // Dynamically generated format strings are difficult to 4111 // automatically vet at compile time. Requiring that format strings 4112 // are string literals: (1) permits the checking of format strings by 4113 // the compiler and thereby (2) can practically remove the source of 4114 // many format string exploits. 4115 4116 // Format string can be either ObjC string (e.g. @"%d") or 4117 // C string (e.g. "%d") 4118 // ObjC string uses the same format specifiers as C string, so we can use 4119 // the same format string checking logic for both ObjC and C strings. 4120 UncoveredArgHandler UncoveredArg; 4121 StringLiteralCheckType CT = 4122 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 4123 format_idx, firstDataArg, Type, CallType, 4124 /*IsFunctionCall*/true, CheckedVarArgs, 4125 UncoveredArg); 4126 4127 // Generate a diagnostic where an uncovered argument is detected. 4128 if (UncoveredArg.hasUncoveredArg()) { 4129 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 4130 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 4131 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 4132 } 4133 4134 if (CT != SLCT_NotALiteral) 4135 // Literal format string found, check done! 4136 return CT == SLCT_CheckedLiteral; 4137 4138 // Strftime is particular as it always uses a single 'time' argument, 4139 // so it is safe to pass a non-literal string. 4140 if (Type == FST_Strftime) 4141 return false; 4142 4143 // Do not emit diag when the string param is a macro expansion and the 4144 // format is either NSString or CFString. This is a hack to prevent 4145 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 4146 // which are usually used in place of NS and CF string literals. 4147 SourceLocation FormatLoc = Args[format_idx]->getLocStart(); 4148 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 4149 return false; 4150 4151 // If there are no arguments specified, warn with -Wformat-security, otherwise 4152 // warn only with -Wformat-nonliteral. 4153 if (Args.size() == firstDataArg) { 4154 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 4155 << OrigFormatExpr->getSourceRange(); 4156 switch (Type) { 4157 default: 4158 break; 4159 case FST_Kprintf: 4160 case FST_FreeBSDKPrintf: 4161 case FST_Printf: 4162 Diag(FormatLoc, diag::note_format_security_fixit) 4163 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 4164 break; 4165 case FST_NSString: 4166 Diag(FormatLoc, diag::note_format_security_fixit) 4167 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 4168 break; 4169 } 4170 } else { 4171 Diag(FormatLoc, diag::warn_format_nonliteral) 4172 << OrigFormatExpr->getSourceRange(); 4173 } 4174 return false; 4175 } 4176 4177 namespace { 4178 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 4179 protected: 4180 Sema &S; 4181 const StringLiteral *FExpr; 4182 const Expr *OrigFormatExpr; 4183 const unsigned FirstDataArg; 4184 const unsigned NumDataArgs; 4185 const char *Beg; // Start of format string. 4186 const bool HasVAListArg; 4187 ArrayRef<const Expr *> Args; 4188 unsigned FormatIdx; 4189 llvm::SmallBitVector CoveredArgs; 4190 bool usesPositionalArgs; 4191 bool atFirstArg; 4192 bool inFunctionCall; 4193 Sema::VariadicCallType CallType; 4194 llvm::SmallBitVector &CheckedVarArgs; 4195 UncoveredArgHandler &UncoveredArg; 4196 4197 public: 4198 CheckFormatHandler(Sema &s, const StringLiteral *fexpr, 4199 const Expr *origFormatExpr, unsigned firstDataArg, 4200 unsigned numDataArgs, const char *beg, bool hasVAListArg, 4201 ArrayRef<const Expr *> Args, 4202 unsigned formatIdx, bool inFunctionCall, 4203 Sema::VariadicCallType callType, 4204 llvm::SmallBitVector &CheckedVarArgs, 4205 UncoveredArgHandler &UncoveredArg) 4206 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), 4207 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), 4208 Beg(beg), HasVAListArg(hasVAListArg), 4209 Args(Args), FormatIdx(formatIdx), 4210 usesPositionalArgs(false), atFirstArg(true), 4211 inFunctionCall(inFunctionCall), CallType(callType), 4212 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 4213 CoveredArgs.resize(numDataArgs); 4214 CoveredArgs.reset(); 4215 } 4216 4217 void DoneProcessing(); 4218 4219 void HandleIncompleteSpecifier(const char *startSpecifier, 4220 unsigned specifierLen) override; 4221 4222 void HandleInvalidLengthModifier( 4223 const analyze_format_string::FormatSpecifier &FS, 4224 const analyze_format_string::ConversionSpecifier &CS, 4225 const char *startSpecifier, unsigned specifierLen, 4226 unsigned DiagID); 4227 4228 void HandleNonStandardLengthModifier( 4229 const analyze_format_string::FormatSpecifier &FS, 4230 const char *startSpecifier, unsigned specifierLen); 4231 4232 void HandleNonStandardConversionSpecifier( 4233 const analyze_format_string::ConversionSpecifier &CS, 4234 const char *startSpecifier, unsigned specifierLen); 4235 4236 void HandlePosition(const char *startPos, unsigned posLen) override; 4237 4238 void HandleInvalidPosition(const char *startSpecifier, 4239 unsigned specifierLen, 4240 analyze_format_string::PositionContext p) override; 4241 4242 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 4243 4244 void HandleNullChar(const char *nullCharacter) override; 4245 4246 template <typename Range> 4247 static void 4248 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 4249 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 4250 bool IsStringLocation, Range StringRange, 4251 ArrayRef<FixItHint> Fixit = None); 4252 4253 protected: 4254 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 4255 const char *startSpec, 4256 unsigned specifierLen, 4257 const char *csStart, unsigned csLen); 4258 4259 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 4260 const char *startSpec, 4261 unsigned specifierLen); 4262 4263 SourceRange getFormatStringRange(); 4264 CharSourceRange getSpecifierRange(const char *startSpecifier, 4265 unsigned specifierLen); 4266 SourceLocation getLocationOfByte(const char *x); 4267 4268 const Expr *getDataArg(unsigned i) const; 4269 4270 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 4271 const analyze_format_string::ConversionSpecifier &CS, 4272 const char *startSpecifier, unsigned specifierLen, 4273 unsigned argIndex); 4274 4275 template <typename Range> 4276 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 4277 bool IsStringLocation, Range StringRange, 4278 ArrayRef<FixItHint> Fixit = None); 4279 }; 4280 } // end anonymous namespace 4281 4282 SourceRange CheckFormatHandler::getFormatStringRange() { 4283 return OrigFormatExpr->getSourceRange(); 4284 } 4285 4286 CharSourceRange CheckFormatHandler:: 4287 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 4288 SourceLocation Start = getLocationOfByte(startSpecifier); 4289 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 4290 4291 // Advance the end SourceLocation by one due to half-open ranges. 4292 End = End.getLocWithOffset(1); 4293 4294 return CharSourceRange::getCharRange(Start, End); 4295 } 4296 4297 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 4298 return S.getLocationOfStringLiteralByte(FExpr, x - Beg); 4299 } 4300 4301 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 4302 unsigned specifierLen){ 4303 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 4304 getLocationOfByte(startSpecifier), 4305 /*IsStringLocation*/true, 4306 getSpecifierRange(startSpecifier, specifierLen)); 4307 } 4308 4309 void CheckFormatHandler::HandleInvalidLengthModifier( 4310 const analyze_format_string::FormatSpecifier &FS, 4311 const analyze_format_string::ConversionSpecifier &CS, 4312 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 4313 using namespace analyze_format_string; 4314 4315 const LengthModifier &LM = FS.getLengthModifier(); 4316 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 4317 4318 // See if we know how to fix this length modifier. 4319 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 4320 if (FixedLM) { 4321 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 4322 getLocationOfByte(LM.getStart()), 4323 /*IsStringLocation*/true, 4324 getSpecifierRange(startSpecifier, specifierLen)); 4325 4326 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 4327 << FixedLM->toString() 4328 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 4329 4330 } else { 4331 FixItHint Hint; 4332 if (DiagID == diag::warn_format_nonsensical_length) 4333 Hint = FixItHint::CreateRemoval(LMRange); 4334 4335 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 4336 getLocationOfByte(LM.getStart()), 4337 /*IsStringLocation*/true, 4338 getSpecifierRange(startSpecifier, specifierLen), 4339 Hint); 4340 } 4341 } 4342 4343 void CheckFormatHandler::HandleNonStandardLengthModifier( 4344 const analyze_format_string::FormatSpecifier &FS, 4345 const char *startSpecifier, unsigned specifierLen) { 4346 using namespace analyze_format_string; 4347 4348 const LengthModifier &LM = FS.getLengthModifier(); 4349 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 4350 4351 // See if we know how to fix this length modifier. 4352 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 4353 if (FixedLM) { 4354 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 4355 << LM.toString() << 0, 4356 getLocationOfByte(LM.getStart()), 4357 /*IsStringLocation*/true, 4358 getSpecifierRange(startSpecifier, specifierLen)); 4359 4360 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 4361 << FixedLM->toString() 4362 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 4363 4364 } else { 4365 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 4366 << LM.toString() << 0, 4367 getLocationOfByte(LM.getStart()), 4368 /*IsStringLocation*/true, 4369 getSpecifierRange(startSpecifier, specifierLen)); 4370 } 4371 } 4372 4373 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 4374 const analyze_format_string::ConversionSpecifier &CS, 4375 const char *startSpecifier, unsigned specifierLen) { 4376 using namespace analyze_format_string; 4377 4378 // See if we know how to fix this conversion specifier. 4379 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 4380 if (FixedCS) { 4381 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 4382 << CS.toString() << /*conversion specifier*/1, 4383 getLocationOfByte(CS.getStart()), 4384 /*IsStringLocation*/true, 4385 getSpecifierRange(startSpecifier, specifierLen)); 4386 4387 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 4388 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 4389 << FixedCS->toString() 4390 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 4391 } else { 4392 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 4393 << CS.toString() << /*conversion specifier*/1, 4394 getLocationOfByte(CS.getStart()), 4395 /*IsStringLocation*/true, 4396 getSpecifierRange(startSpecifier, specifierLen)); 4397 } 4398 } 4399 4400 void CheckFormatHandler::HandlePosition(const char *startPos, 4401 unsigned posLen) { 4402 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 4403 getLocationOfByte(startPos), 4404 /*IsStringLocation*/true, 4405 getSpecifierRange(startPos, posLen)); 4406 } 4407 4408 void 4409 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 4410 analyze_format_string::PositionContext p) { 4411 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 4412 << (unsigned) p, 4413 getLocationOfByte(startPos), /*IsStringLocation*/true, 4414 getSpecifierRange(startPos, posLen)); 4415 } 4416 4417 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 4418 unsigned posLen) { 4419 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 4420 getLocationOfByte(startPos), 4421 /*IsStringLocation*/true, 4422 getSpecifierRange(startPos, posLen)); 4423 } 4424 4425 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 4426 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 4427 // The presence of a null character is likely an error. 4428 EmitFormatDiagnostic( 4429 S.PDiag(diag::warn_printf_format_string_contains_null_char), 4430 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 4431 getFormatStringRange()); 4432 } 4433 } 4434 4435 // Note that this may return NULL if there was an error parsing or building 4436 // one of the argument expressions. 4437 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 4438 return Args[FirstDataArg + i]; 4439 } 4440 4441 void CheckFormatHandler::DoneProcessing() { 4442 // Does the number of data arguments exceed the number of 4443 // format conversions in the format string? 4444 if (!HasVAListArg) { 4445 // Find any arguments that weren't covered. 4446 CoveredArgs.flip(); 4447 signed notCoveredArg = CoveredArgs.find_first(); 4448 if (notCoveredArg >= 0) { 4449 assert((unsigned)notCoveredArg < NumDataArgs); 4450 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 4451 } else { 4452 UncoveredArg.setAllCovered(); 4453 } 4454 } 4455 } 4456 4457 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 4458 const Expr *ArgExpr) { 4459 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 4460 "Invalid state"); 4461 4462 if (!ArgExpr) 4463 return; 4464 4465 SourceLocation Loc = ArgExpr->getLocStart(); 4466 4467 if (S.getSourceManager().isInSystemMacro(Loc)) 4468 return; 4469 4470 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 4471 for (auto E : DiagnosticExprs) 4472 PDiag << E->getSourceRange(); 4473 4474 CheckFormatHandler::EmitFormatDiagnostic( 4475 S, IsFunctionCall, DiagnosticExprs[0], 4476 PDiag, Loc, /*IsStringLocation*/false, 4477 DiagnosticExprs[0]->getSourceRange()); 4478 } 4479 4480 bool 4481 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 4482 SourceLocation Loc, 4483 const char *startSpec, 4484 unsigned specifierLen, 4485 const char *csStart, 4486 unsigned csLen) { 4487 bool keepGoing = true; 4488 if (argIndex < NumDataArgs) { 4489 // Consider the argument coverered, even though the specifier doesn't 4490 // make sense. 4491 CoveredArgs.set(argIndex); 4492 } 4493 else { 4494 // If argIndex exceeds the number of data arguments we 4495 // don't issue a warning because that is just a cascade of warnings (and 4496 // they may have intended '%%' anyway). We don't want to continue processing 4497 // the format string after this point, however, as we will like just get 4498 // gibberish when trying to match arguments. 4499 keepGoing = false; 4500 } 4501 4502 StringRef Specifier(csStart, csLen); 4503 4504 // If the specifier in non-printable, it could be the first byte of a UTF-8 4505 // sequence. In that case, print the UTF-8 code point. If not, print the byte 4506 // hex value. 4507 std::string CodePointStr; 4508 if (!llvm::sys::locale::isPrint(*csStart)) { 4509 UTF32 CodePoint; 4510 const UTF8 **B = reinterpret_cast<const UTF8 **>(&csStart); 4511 const UTF8 *E = 4512 reinterpret_cast<const UTF8 *>(csStart + csLen); 4513 ConversionResult Result = 4514 llvm::convertUTF8Sequence(B, E, &CodePoint, strictConversion); 4515 4516 if (Result != conversionOK) { 4517 unsigned char FirstChar = *csStart; 4518 CodePoint = (UTF32)FirstChar; 4519 } 4520 4521 llvm::raw_string_ostream OS(CodePointStr); 4522 if (CodePoint < 256) 4523 OS << "\\x" << llvm::format("%02x", CodePoint); 4524 else if (CodePoint <= 0xFFFF) 4525 OS << "\\u" << llvm::format("%04x", CodePoint); 4526 else 4527 OS << "\\U" << llvm::format("%08x", CodePoint); 4528 OS.flush(); 4529 Specifier = CodePointStr; 4530 } 4531 4532 EmitFormatDiagnostic( 4533 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 4534 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 4535 4536 return keepGoing; 4537 } 4538 4539 void 4540 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 4541 const char *startSpec, 4542 unsigned specifierLen) { 4543 EmitFormatDiagnostic( 4544 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 4545 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 4546 } 4547 4548 bool 4549 CheckFormatHandler::CheckNumArgs( 4550 const analyze_format_string::FormatSpecifier &FS, 4551 const analyze_format_string::ConversionSpecifier &CS, 4552 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 4553 4554 if (argIndex >= NumDataArgs) { 4555 PartialDiagnostic PDiag = FS.usesPositionalArg() 4556 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 4557 << (argIndex+1) << NumDataArgs) 4558 : S.PDiag(diag::warn_printf_insufficient_data_args); 4559 EmitFormatDiagnostic( 4560 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 4561 getSpecifierRange(startSpecifier, specifierLen)); 4562 4563 // Since more arguments than conversion tokens are given, by extension 4564 // all arguments are covered, so mark this as so. 4565 UncoveredArg.setAllCovered(); 4566 return false; 4567 } 4568 return true; 4569 } 4570 4571 template<typename Range> 4572 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 4573 SourceLocation Loc, 4574 bool IsStringLocation, 4575 Range StringRange, 4576 ArrayRef<FixItHint> FixIt) { 4577 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 4578 Loc, IsStringLocation, StringRange, FixIt); 4579 } 4580 4581 /// \brief If the format string is not within the funcion call, emit a note 4582 /// so that the function call and string are in diagnostic messages. 4583 /// 4584 /// \param InFunctionCall if true, the format string is within the function 4585 /// call and only one diagnostic message will be produced. Otherwise, an 4586 /// extra note will be emitted pointing to location of the format string. 4587 /// 4588 /// \param ArgumentExpr the expression that is passed as the format string 4589 /// argument in the function call. Used for getting locations when two 4590 /// diagnostics are emitted. 4591 /// 4592 /// \param PDiag the callee should already have provided any strings for the 4593 /// diagnostic message. This function only adds locations and fixits 4594 /// to diagnostics. 4595 /// 4596 /// \param Loc primary location for diagnostic. If two diagnostics are 4597 /// required, one will be at Loc and a new SourceLocation will be created for 4598 /// the other one. 4599 /// 4600 /// \param IsStringLocation if true, Loc points to the format string should be 4601 /// used for the note. Otherwise, Loc points to the argument list and will 4602 /// be used with PDiag. 4603 /// 4604 /// \param StringRange some or all of the string to highlight. This is 4605 /// templated so it can accept either a CharSourceRange or a SourceRange. 4606 /// 4607 /// \param FixIt optional fix it hint for the format string. 4608 template <typename Range> 4609 void CheckFormatHandler::EmitFormatDiagnostic( 4610 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 4611 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 4612 Range StringRange, ArrayRef<FixItHint> FixIt) { 4613 if (InFunctionCall) { 4614 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 4615 D << StringRange; 4616 D << FixIt; 4617 } else { 4618 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 4619 << ArgumentExpr->getSourceRange(); 4620 4621 const Sema::SemaDiagnosticBuilder &Note = 4622 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 4623 diag::note_format_string_defined); 4624 4625 Note << StringRange; 4626 Note << FixIt; 4627 } 4628 } 4629 4630 //===--- CHECK: Printf format string checking ------------------------------===// 4631 4632 namespace { 4633 class CheckPrintfHandler : public CheckFormatHandler { 4634 bool ObjCContext; 4635 4636 public: 4637 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr, 4638 const Expr *origFormatExpr, unsigned firstDataArg, 4639 unsigned numDataArgs, bool isObjC, 4640 const char *beg, bool hasVAListArg, 4641 ArrayRef<const Expr *> Args, 4642 unsigned formatIdx, bool inFunctionCall, 4643 Sema::VariadicCallType CallType, 4644 llvm::SmallBitVector &CheckedVarArgs, 4645 UncoveredArgHandler &UncoveredArg) 4646 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg, 4647 numDataArgs, beg, hasVAListArg, Args, 4648 formatIdx, inFunctionCall, CallType, CheckedVarArgs, 4649 UncoveredArg), 4650 ObjCContext(isObjC) 4651 {} 4652 4653 bool HandleInvalidPrintfConversionSpecifier( 4654 const analyze_printf::PrintfSpecifier &FS, 4655 const char *startSpecifier, 4656 unsigned specifierLen) override; 4657 4658 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 4659 const char *startSpecifier, 4660 unsigned specifierLen) override; 4661 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 4662 const char *StartSpecifier, 4663 unsigned SpecifierLen, 4664 const Expr *E); 4665 4666 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 4667 const char *startSpecifier, unsigned specifierLen); 4668 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 4669 const analyze_printf::OptionalAmount &Amt, 4670 unsigned type, 4671 const char *startSpecifier, unsigned specifierLen); 4672 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 4673 const analyze_printf::OptionalFlag &flag, 4674 const char *startSpecifier, unsigned specifierLen); 4675 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 4676 const analyze_printf::OptionalFlag &ignoredFlag, 4677 const analyze_printf::OptionalFlag &flag, 4678 const char *startSpecifier, unsigned specifierLen); 4679 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 4680 const Expr *E); 4681 4682 void HandleEmptyObjCModifierFlag(const char *startFlag, 4683 unsigned flagLen) override; 4684 4685 void HandleInvalidObjCModifierFlag(const char *startFlag, 4686 unsigned flagLen) override; 4687 4688 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 4689 const char *flagsEnd, 4690 const char *conversionPosition) 4691 override; 4692 }; 4693 } // end anonymous namespace 4694 4695 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 4696 const analyze_printf::PrintfSpecifier &FS, 4697 const char *startSpecifier, 4698 unsigned specifierLen) { 4699 const analyze_printf::PrintfConversionSpecifier &CS = 4700 FS.getConversionSpecifier(); 4701 4702 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 4703 getLocationOfByte(CS.getStart()), 4704 startSpecifier, specifierLen, 4705 CS.getStart(), CS.getLength()); 4706 } 4707 4708 bool CheckPrintfHandler::HandleAmount( 4709 const analyze_format_string::OptionalAmount &Amt, 4710 unsigned k, const char *startSpecifier, 4711 unsigned specifierLen) { 4712 if (Amt.hasDataArgument()) { 4713 if (!HasVAListArg) { 4714 unsigned argIndex = Amt.getArgIndex(); 4715 if (argIndex >= NumDataArgs) { 4716 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 4717 << k, 4718 getLocationOfByte(Amt.getStart()), 4719 /*IsStringLocation*/true, 4720 getSpecifierRange(startSpecifier, specifierLen)); 4721 // Don't do any more checking. We will just emit 4722 // spurious errors. 4723 return false; 4724 } 4725 4726 // Type check the data argument. It should be an 'int'. 4727 // Although not in conformance with C99, we also allow the argument to be 4728 // an 'unsigned int' as that is a reasonably safe case. GCC also 4729 // doesn't emit a warning for that case. 4730 CoveredArgs.set(argIndex); 4731 const Expr *Arg = getDataArg(argIndex); 4732 if (!Arg) 4733 return false; 4734 4735 QualType T = Arg->getType(); 4736 4737 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 4738 assert(AT.isValid()); 4739 4740 if (!AT.matchesType(S.Context, T)) { 4741 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 4742 << k << AT.getRepresentativeTypeName(S.Context) 4743 << T << Arg->getSourceRange(), 4744 getLocationOfByte(Amt.getStart()), 4745 /*IsStringLocation*/true, 4746 getSpecifierRange(startSpecifier, specifierLen)); 4747 // Don't do any more checking. We will just emit 4748 // spurious errors. 4749 return false; 4750 } 4751 } 4752 } 4753 return true; 4754 } 4755 4756 void CheckPrintfHandler::HandleInvalidAmount( 4757 const analyze_printf::PrintfSpecifier &FS, 4758 const analyze_printf::OptionalAmount &Amt, 4759 unsigned type, 4760 const char *startSpecifier, 4761 unsigned specifierLen) { 4762 const analyze_printf::PrintfConversionSpecifier &CS = 4763 FS.getConversionSpecifier(); 4764 4765 FixItHint fixit = 4766 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 4767 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 4768 Amt.getConstantLength())) 4769 : FixItHint(); 4770 4771 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 4772 << type << CS.toString(), 4773 getLocationOfByte(Amt.getStart()), 4774 /*IsStringLocation*/true, 4775 getSpecifierRange(startSpecifier, specifierLen), 4776 fixit); 4777 } 4778 4779 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 4780 const analyze_printf::OptionalFlag &flag, 4781 const char *startSpecifier, 4782 unsigned specifierLen) { 4783 // Warn about pointless flag with a fixit removal. 4784 const analyze_printf::PrintfConversionSpecifier &CS = 4785 FS.getConversionSpecifier(); 4786 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 4787 << flag.toString() << CS.toString(), 4788 getLocationOfByte(flag.getPosition()), 4789 /*IsStringLocation*/true, 4790 getSpecifierRange(startSpecifier, specifierLen), 4791 FixItHint::CreateRemoval( 4792 getSpecifierRange(flag.getPosition(), 1))); 4793 } 4794 4795 void CheckPrintfHandler::HandleIgnoredFlag( 4796 const analyze_printf::PrintfSpecifier &FS, 4797 const analyze_printf::OptionalFlag &ignoredFlag, 4798 const analyze_printf::OptionalFlag &flag, 4799 const char *startSpecifier, 4800 unsigned specifierLen) { 4801 // Warn about ignored flag with a fixit removal. 4802 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 4803 << ignoredFlag.toString() << flag.toString(), 4804 getLocationOfByte(ignoredFlag.getPosition()), 4805 /*IsStringLocation*/true, 4806 getSpecifierRange(startSpecifier, specifierLen), 4807 FixItHint::CreateRemoval( 4808 getSpecifierRange(ignoredFlag.getPosition(), 1))); 4809 } 4810 4811 // void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 4812 // bool IsStringLocation, Range StringRange, 4813 // ArrayRef<FixItHint> Fixit = None); 4814 4815 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 4816 unsigned flagLen) { 4817 // Warn about an empty flag. 4818 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 4819 getLocationOfByte(startFlag), 4820 /*IsStringLocation*/true, 4821 getSpecifierRange(startFlag, flagLen)); 4822 } 4823 4824 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 4825 unsigned flagLen) { 4826 // Warn about an invalid flag. 4827 auto Range = getSpecifierRange(startFlag, flagLen); 4828 StringRef flag(startFlag, flagLen); 4829 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 4830 getLocationOfByte(startFlag), 4831 /*IsStringLocation*/true, 4832 Range, FixItHint::CreateRemoval(Range)); 4833 } 4834 4835 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 4836 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 4837 // Warn about using '[...]' without a '@' conversion. 4838 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 4839 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 4840 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 4841 getLocationOfByte(conversionPosition), 4842 /*IsStringLocation*/true, 4843 Range, FixItHint::CreateRemoval(Range)); 4844 } 4845 4846 // Determines if the specified is a C++ class or struct containing 4847 // a member with the specified name and kind (e.g. a CXXMethodDecl named 4848 // "c_str()"). 4849 template<typename MemberKind> 4850 static llvm::SmallPtrSet<MemberKind*, 1> 4851 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 4852 const RecordType *RT = Ty->getAs<RecordType>(); 4853 llvm::SmallPtrSet<MemberKind*, 1> Results; 4854 4855 if (!RT) 4856 return Results; 4857 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 4858 if (!RD || !RD->getDefinition()) 4859 return Results; 4860 4861 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 4862 Sema::LookupMemberName); 4863 R.suppressDiagnostics(); 4864 4865 // We just need to include all members of the right kind turned up by the 4866 // filter, at this point. 4867 if (S.LookupQualifiedName(R, RT->getDecl())) 4868 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 4869 NamedDecl *decl = (*I)->getUnderlyingDecl(); 4870 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 4871 Results.insert(FK); 4872 } 4873 return Results; 4874 } 4875 4876 /// Check if we could call '.c_str()' on an object. 4877 /// 4878 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 4879 /// allow the call, or if it would be ambiguous). 4880 bool Sema::hasCStrMethod(const Expr *E) { 4881 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet; 4882 MethodSet Results = 4883 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 4884 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 4885 MI != ME; ++MI) 4886 if ((*MI)->getMinRequiredArguments() == 0) 4887 return true; 4888 return false; 4889 } 4890 4891 // Check if a (w)string was passed when a (w)char* was needed, and offer a 4892 // better diagnostic if so. AT is assumed to be valid. 4893 // Returns true when a c_str() conversion method is found. 4894 bool CheckPrintfHandler::checkForCStrMembers( 4895 const analyze_printf::ArgType &AT, const Expr *E) { 4896 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet; 4897 4898 MethodSet Results = 4899 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 4900 4901 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 4902 MI != ME; ++MI) { 4903 const CXXMethodDecl *Method = *MI; 4904 if (Method->getMinRequiredArguments() == 0 && 4905 AT.matchesType(S.Context, Method->getReturnType())) { 4906 // FIXME: Suggest parens if the expression needs them. 4907 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd()); 4908 S.Diag(E->getLocStart(), diag::note_printf_c_str) 4909 << "c_str()" 4910 << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 4911 return true; 4912 } 4913 } 4914 4915 return false; 4916 } 4917 4918 bool 4919 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 4920 &FS, 4921 const char *startSpecifier, 4922 unsigned specifierLen) { 4923 using namespace analyze_format_string; 4924 using namespace analyze_printf; 4925 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 4926 4927 if (FS.consumesDataArgument()) { 4928 if (atFirstArg) { 4929 atFirstArg = false; 4930 usesPositionalArgs = FS.usesPositionalArg(); 4931 } 4932 else if (usesPositionalArgs != FS.usesPositionalArg()) { 4933 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 4934 startSpecifier, specifierLen); 4935 return false; 4936 } 4937 } 4938 4939 // First check if the field width, precision, and conversion specifier 4940 // have matching data arguments. 4941 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 4942 startSpecifier, specifierLen)) { 4943 return false; 4944 } 4945 4946 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 4947 startSpecifier, specifierLen)) { 4948 return false; 4949 } 4950 4951 if (!CS.consumesDataArgument()) { 4952 // FIXME: Technically specifying a precision or field width here 4953 // makes no sense. Worth issuing a warning at some point. 4954 return true; 4955 } 4956 4957 // Consume the argument. 4958 unsigned argIndex = FS.getArgIndex(); 4959 if (argIndex < NumDataArgs) { 4960 // The check to see if the argIndex is valid will come later. 4961 // We set the bit here because we may exit early from this 4962 // function if we encounter some other error. 4963 CoveredArgs.set(argIndex); 4964 } 4965 4966 // FreeBSD kernel extensions. 4967 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 4968 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 4969 // We need at least two arguments. 4970 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 4971 return false; 4972 4973 // Claim the second argument. 4974 CoveredArgs.set(argIndex + 1); 4975 4976 // Type check the first argument (int for %b, pointer for %D) 4977 const Expr *Ex = getDataArg(argIndex); 4978 const analyze_printf::ArgType &AT = 4979 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 4980 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 4981 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 4982 EmitFormatDiagnostic( 4983 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 4984 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 4985 << false << Ex->getSourceRange(), 4986 Ex->getLocStart(), /*IsStringLocation*/false, 4987 getSpecifierRange(startSpecifier, specifierLen)); 4988 4989 // Type check the second argument (char * for both %b and %D) 4990 Ex = getDataArg(argIndex + 1); 4991 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 4992 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 4993 EmitFormatDiagnostic( 4994 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 4995 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 4996 << false << Ex->getSourceRange(), 4997 Ex->getLocStart(), /*IsStringLocation*/false, 4998 getSpecifierRange(startSpecifier, specifierLen)); 4999 5000 return true; 5001 } 5002 5003 // Check for using an Objective-C specific conversion specifier 5004 // in a non-ObjC literal. 5005 if (!ObjCContext && CS.isObjCArg()) { 5006 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 5007 specifierLen); 5008 } 5009 5010 // Check for invalid use of field width 5011 if (!FS.hasValidFieldWidth()) { 5012 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 5013 startSpecifier, specifierLen); 5014 } 5015 5016 // Check for invalid use of precision 5017 if (!FS.hasValidPrecision()) { 5018 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 5019 startSpecifier, specifierLen); 5020 } 5021 5022 // Check each flag does not conflict with any other component. 5023 if (!FS.hasValidThousandsGroupingPrefix()) 5024 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 5025 if (!FS.hasValidLeadingZeros()) 5026 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 5027 if (!FS.hasValidPlusPrefix()) 5028 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 5029 if (!FS.hasValidSpacePrefix()) 5030 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 5031 if (!FS.hasValidAlternativeForm()) 5032 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 5033 if (!FS.hasValidLeftJustified()) 5034 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 5035 5036 // Check that flags are not ignored by another flag 5037 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 5038 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 5039 startSpecifier, specifierLen); 5040 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 5041 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 5042 startSpecifier, specifierLen); 5043 5044 // Check the length modifier is valid with the given conversion specifier. 5045 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 5046 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 5047 diag::warn_format_nonsensical_length); 5048 else if (!FS.hasStandardLengthModifier()) 5049 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 5050 else if (!FS.hasStandardLengthConversionCombination()) 5051 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 5052 diag::warn_format_non_standard_conversion_spec); 5053 5054 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 5055 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 5056 5057 // The remaining checks depend on the data arguments. 5058 if (HasVAListArg) 5059 return true; 5060 5061 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 5062 return false; 5063 5064 const Expr *Arg = getDataArg(argIndex); 5065 if (!Arg) 5066 return true; 5067 5068 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 5069 } 5070 5071 static bool requiresParensToAddCast(const Expr *E) { 5072 // FIXME: We should have a general way to reason about operator 5073 // precedence and whether parens are actually needed here. 5074 // Take care of a few common cases where they aren't. 5075 const Expr *Inside = E->IgnoreImpCasts(); 5076 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 5077 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 5078 5079 switch (Inside->getStmtClass()) { 5080 case Stmt::ArraySubscriptExprClass: 5081 case Stmt::CallExprClass: 5082 case Stmt::CharacterLiteralClass: 5083 case Stmt::CXXBoolLiteralExprClass: 5084 case Stmt::DeclRefExprClass: 5085 case Stmt::FloatingLiteralClass: 5086 case Stmt::IntegerLiteralClass: 5087 case Stmt::MemberExprClass: 5088 case Stmt::ObjCArrayLiteralClass: 5089 case Stmt::ObjCBoolLiteralExprClass: 5090 case Stmt::ObjCBoxedExprClass: 5091 case Stmt::ObjCDictionaryLiteralClass: 5092 case Stmt::ObjCEncodeExprClass: 5093 case Stmt::ObjCIvarRefExprClass: 5094 case Stmt::ObjCMessageExprClass: 5095 case Stmt::ObjCPropertyRefExprClass: 5096 case Stmt::ObjCStringLiteralClass: 5097 case Stmt::ObjCSubscriptRefExprClass: 5098 case Stmt::ParenExprClass: 5099 case Stmt::StringLiteralClass: 5100 case Stmt::UnaryOperatorClass: 5101 return false; 5102 default: 5103 return true; 5104 } 5105 } 5106 5107 static std::pair<QualType, StringRef> 5108 shouldNotPrintDirectly(const ASTContext &Context, 5109 QualType IntendedTy, 5110 const Expr *E) { 5111 // Use a 'while' to peel off layers of typedefs. 5112 QualType TyTy = IntendedTy; 5113 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 5114 StringRef Name = UserTy->getDecl()->getName(); 5115 QualType CastTy = llvm::StringSwitch<QualType>(Name) 5116 .Case("NSInteger", Context.LongTy) 5117 .Case("NSUInteger", Context.UnsignedLongTy) 5118 .Case("SInt32", Context.IntTy) 5119 .Case("UInt32", Context.UnsignedIntTy) 5120 .Default(QualType()); 5121 5122 if (!CastTy.isNull()) 5123 return std::make_pair(CastTy, Name); 5124 5125 TyTy = UserTy->desugar(); 5126 } 5127 5128 // Strip parens if necessary. 5129 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 5130 return shouldNotPrintDirectly(Context, 5131 PE->getSubExpr()->getType(), 5132 PE->getSubExpr()); 5133 5134 // If this is a conditional expression, then its result type is constructed 5135 // via usual arithmetic conversions and thus there might be no necessary 5136 // typedef sugar there. Recurse to operands to check for NSInteger & 5137 // Co. usage condition. 5138 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 5139 QualType TrueTy, FalseTy; 5140 StringRef TrueName, FalseName; 5141 5142 std::tie(TrueTy, TrueName) = 5143 shouldNotPrintDirectly(Context, 5144 CO->getTrueExpr()->getType(), 5145 CO->getTrueExpr()); 5146 std::tie(FalseTy, FalseName) = 5147 shouldNotPrintDirectly(Context, 5148 CO->getFalseExpr()->getType(), 5149 CO->getFalseExpr()); 5150 5151 if (TrueTy == FalseTy) 5152 return std::make_pair(TrueTy, TrueName); 5153 else if (TrueTy.isNull()) 5154 return std::make_pair(FalseTy, FalseName); 5155 else if (FalseTy.isNull()) 5156 return std::make_pair(TrueTy, TrueName); 5157 } 5158 5159 return std::make_pair(QualType(), StringRef()); 5160 } 5161 5162 bool 5163 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 5164 const char *StartSpecifier, 5165 unsigned SpecifierLen, 5166 const Expr *E) { 5167 using namespace analyze_format_string; 5168 using namespace analyze_printf; 5169 // Now type check the data expression that matches the 5170 // format specifier. 5171 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, 5172 ObjCContext); 5173 if (!AT.isValid()) 5174 return true; 5175 5176 QualType ExprTy = E->getType(); 5177 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 5178 ExprTy = TET->getUnderlyingExpr()->getType(); 5179 } 5180 5181 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy); 5182 5183 if (match == analyze_printf::ArgType::Match) { 5184 return true; 5185 } 5186 5187 // Look through argument promotions for our error message's reported type. 5188 // This includes the integral and floating promotions, but excludes array 5189 // and function pointer decay; seeing that an argument intended to be a 5190 // string has type 'char [6]' is probably more confusing than 'char *'. 5191 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 5192 if (ICE->getCastKind() == CK_IntegralCast || 5193 ICE->getCastKind() == CK_FloatingCast) { 5194 E = ICE->getSubExpr(); 5195 ExprTy = E->getType(); 5196 5197 // Check if we didn't match because of an implicit cast from a 'char' 5198 // or 'short' to an 'int'. This is done because printf is a varargs 5199 // function. 5200 if (ICE->getType() == S.Context.IntTy || 5201 ICE->getType() == S.Context.UnsignedIntTy) { 5202 // All further checking is done on the subexpression. 5203 if (AT.matchesType(S.Context, ExprTy)) 5204 return true; 5205 } 5206 } 5207 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 5208 // Special case for 'a', which has type 'int' in C. 5209 // Note, however, that we do /not/ want to treat multibyte constants like 5210 // 'MooV' as characters! This form is deprecated but still exists. 5211 if (ExprTy == S.Context.IntTy) 5212 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 5213 ExprTy = S.Context.CharTy; 5214 } 5215 5216 // Look through enums to their underlying type. 5217 bool IsEnum = false; 5218 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 5219 ExprTy = EnumTy->getDecl()->getIntegerType(); 5220 IsEnum = true; 5221 } 5222 5223 // %C in an Objective-C context prints a unichar, not a wchar_t. 5224 // If the argument is an integer of some kind, believe the %C and suggest 5225 // a cast instead of changing the conversion specifier. 5226 QualType IntendedTy = ExprTy; 5227 if (ObjCContext && 5228 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 5229 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 5230 !ExprTy->isCharType()) { 5231 // 'unichar' is defined as a typedef of unsigned short, but we should 5232 // prefer using the typedef if it is visible. 5233 IntendedTy = S.Context.UnsignedShortTy; 5234 5235 // While we are here, check if the value is an IntegerLiteral that happens 5236 // to be within the valid range. 5237 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 5238 const llvm::APInt &V = IL->getValue(); 5239 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 5240 return true; 5241 } 5242 5243 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(), 5244 Sema::LookupOrdinaryName); 5245 if (S.LookupName(Result, S.getCurScope())) { 5246 NamedDecl *ND = Result.getFoundDecl(); 5247 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 5248 if (TD->getUnderlyingType() == IntendedTy) 5249 IntendedTy = S.Context.getTypedefType(TD); 5250 } 5251 } 5252 } 5253 5254 // Special-case some of Darwin's platform-independence types by suggesting 5255 // casts to primitive types that are known to be large enough. 5256 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 5257 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 5258 QualType CastTy; 5259 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 5260 if (!CastTy.isNull()) { 5261 IntendedTy = CastTy; 5262 ShouldNotPrintDirectly = true; 5263 } 5264 } 5265 5266 // We may be able to offer a FixItHint if it is a supported type. 5267 PrintfSpecifier fixedFS = FS; 5268 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(), 5269 S.Context, ObjCContext); 5270 5271 if (success) { 5272 // Get the fix string from the fixed format specifier 5273 SmallString<16> buf; 5274 llvm::raw_svector_ostream os(buf); 5275 fixedFS.toString(os); 5276 5277 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 5278 5279 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 5280 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 5281 if (match == analyze_format_string::ArgType::NoMatchPedantic) { 5282 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 5283 } 5284 // In this case, the specifier is wrong and should be changed to match 5285 // the argument. 5286 EmitFormatDiagnostic(S.PDiag(diag) 5287 << AT.getRepresentativeTypeName(S.Context) 5288 << IntendedTy << IsEnum << E->getSourceRange(), 5289 E->getLocStart(), 5290 /*IsStringLocation*/ false, SpecRange, 5291 FixItHint::CreateReplacement(SpecRange, os.str())); 5292 } else { 5293 // The canonical type for formatting this value is different from the 5294 // actual type of the expression. (This occurs, for example, with Darwin's 5295 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 5296 // should be printed as 'long' for 64-bit compatibility.) 5297 // Rather than emitting a normal format/argument mismatch, we want to 5298 // add a cast to the recommended type (and correct the format string 5299 // if necessary). 5300 SmallString<16> CastBuf; 5301 llvm::raw_svector_ostream CastFix(CastBuf); 5302 CastFix << "("; 5303 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 5304 CastFix << ")"; 5305 5306 SmallVector<FixItHint,4> Hints; 5307 if (!AT.matchesType(S.Context, IntendedTy)) 5308 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 5309 5310 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 5311 // If there's already a cast present, just replace it. 5312 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 5313 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 5314 5315 } else if (!requiresParensToAddCast(E)) { 5316 // If the expression has high enough precedence, 5317 // just write the C-style cast. 5318 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(), 5319 CastFix.str())); 5320 } else { 5321 // Otherwise, add parens around the expression as well as the cast. 5322 CastFix << "("; 5323 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(), 5324 CastFix.str())); 5325 5326 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd()); 5327 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 5328 } 5329 5330 if (ShouldNotPrintDirectly) { 5331 // The expression has a type that should not be printed directly. 5332 // We extract the name from the typedef because we don't want to show 5333 // the underlying type in the diagnostic. 5334 StringRef Name; 5335 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 5336 Name = TypedefTy->getDecl()->getName(); 5337 else 5338 Name = CastTyName; 5339 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast) 5340 << Name << IntendedTy << IsEnum 5341 << E->getSourceRange(), 5342 E->getLocStart(), /*IsStringLocation=*/false, 5343 SpecRange, Hints); 5344 } else { 5345 // In this case, the expression could be printed using a different 5346 // specifier, but we've decided that the specifier is probably correct 5347 // and we should cast instead. Just use the normal warning message. 5348 EmitFormatDiagnostic( 5349 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 5350 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 5351 << E->getSourceRange(), 5352 E->getLocStart(), /*IsStringLocation*/false, 5353 SpecRange, Hints); 5354 } 5355 } 5356 } else { 5357 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 5358 SpecifierLen); 5359 // Since the warning for passing non-POD types to variadic functions 5360 // was deferred until now, we emit a warning for non-POD 5361 // arguments here. 5362 switch (S.isValidVarArgType(ExprTy)) { 5363 case Sema::VAK_Valid: 5364 case Sema::VAK_ValidInCXX11: { 5365 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 5366 if (match == analyze_printf::ArgType::NoMatchPedantic) { 5367 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 5368 } 5369 5370 EmitFormatDiagnostic( 5371 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 5372 << IsEnum << CSR << E->getSourceRange(), 5373 E->getLocStart(), /*IsStringLocation*/ false, CSR); 5374 break; 5375 } 5376 case Sema::VAK_Undefined: 5377 case Sema::VAK_MSVCUndefined: 5378 EmitFormatDiagnostic( 5379 S.PDiag(diag::warn_non_pod_vararg_with_format_string) 5380 << S.getLangOpts().CPlusPlus11 5381 << ExprTy 5382 << CallType 5383 << AT.getRepresentativeTypeName(S.Context) 5384 << CSR 5385 << E->getSourceRange(), 5386 E->getLocStart(), /*IsStringLocation*/false, CSR); 5387 checkForCStrMembers(AT, E); 5388 break; 5389 5390 case Sema::VAK_Invalid: 5391 if (ExprTy->isObjCObjectType()) 5392 EmitFormatDiagnostic( 5393 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 5394 << S.getLangOpts().CPlusPlus11 5395 << ExprTy 5396 << CallType 5397 << AT.getRepresentativeTypeName(S.Context) 5398 << CSR 5399 << E->getSourceRange(), 5400 E->getLocStart(), /*IsStringLocation*/false, CSR); 5401 else 5402 // FIXME: If this is an initializer list, suggest removing the braces 5403 // or inserting a cast to the target type. 5404 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format) 5405 << isa<InitListExpr>(E) << ExprTy << CallType 5406 << AT.getRepresentativeTypeName(S.Context) 5407 << E->getSourceRange(); 5408 break; 5409 } 5410 5411 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 5412 "format string specifier index out of range"); 5413 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 5414 } 5415 5416 return true; 5417 } 5418 5419 //===--- CHECK: Scanf format string checking ------------------------------===// 5420 5421 namespace { 5422 class CheckScanfHandler : public CheckFormatHandler { 5423 public: 5424 CheckScanfHandler(Sema &s, const StringLiteral *fexpr, 5425 const Expr *origFormatExpr, unsigned firstDataArg, 5426 unsigned numDataArgs, const char *beg, bool hasVAListArg, 5427 ArrayRef<const Expr *> Args, 5428 unsigned formatIdx, bool inFunctionCall, 5429 Sema::VariadicCallType CallType, 5430 llvm::SmallBitVector &CheckedVarArgs, 5431 UncoveredArgHandler &UncoveredArg) 5432 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg, 5433 numDataArgs, beg, hasVAListArg, 5434 Args, formatIdx, inFunctionCall, CallType, 5435 CheckedVarArgs, UncoveredArg) 5436 {} 5437 5438 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 5439 const char *startSpecifier, 5440 unsigned specifierLen) override; 5441 5442 bool HandleInvalidScanfConversionSpecifier( 5443 const analyze_scanf::ScanfSpecifier &FS, 5444 const char *startSpecifier, 5445 unsigned specifierLen) override; 5446 5447 void HandleIncompleteScanList(const char *start, const char *end) override; 5448 }; 5449 } // end anonymous namespace 5450 5451 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 5452 const char *end) { 5453 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 5454 getLocationOfByte(end), /*IsStringLocation*/true, 5455 getSpecifierRange(start, end - start)); 5456 } 5457 5458 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 5459 const analyze_scanf::ScanfSpecifier &FS, 5460 const char *startSpecifier, 5461 unsigned specifierLen) { 5462 5463 const analyze_scanf::ScanfConversionSpecifier &CS = 5464 FS.getConversionSpecifier(); 5465 5466 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 5467 getLocationOfByte(CS.getStart()), 5468 startSpecifier, specifierLen, 5469 CS.getStart(), CS.getLength()); 5470 } 5471 5472 bool CheckScanfHandler::HandleScanfSpecifier( 5473 const analyze_scanf::ScanfSpecifier &FS, 5474 const char *startSpecifier, 5475 unsigned specifierLen) { 5476 using namespace analyze_scanf; 5477 using namespace analyze_format_string; 5478 5479 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 5480 5481 // Handle case where '%' and '*' don't consume an argument. These shouldn't 5482 // be used to decide if we are using positional arguments consistently. 5483 if (FS.consumesDataArgument()) { 5484 if (atFirstArg) { 5485 atFirstArg = false; 5486 usesPositionalArgs = FS.usesPositionalArg(); 5487 } 5488 else if (usesPositionalArgs != FS.usesPositionalArg()) { 5489 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 5490 startSpecifier, specifierLen); 5491 return false; 5492 } 5493 } 5494 5495 // Check if the field with is non-zero. 5496 const OptionalAmount &Amt = FS.getFieldWidth(); 5497 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 5498 if (Amt.getConstantAmount() == 0) { 5499 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 5500 Amt.getConstantLength()); 5501 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 5502 getLocationOfByte(Amt.getStart()), 5503 /*IsStringLocation*/true, R, 5504 FixItHint::CreateRemoval(R)); 5505 } 5506 } 5507 5508 if (!FS.consumesDataArgument()) { 5509 // FIXME: Technically specifying a precision or field width here 5510 // makes no sense. Worth issuing a warning at some point. 5511 return true; 5512 } 5513 5514 // Consume the argument. 5515 unsigned argIndex = FS.getArgIndex(); 5516 if (argIndex < NumDataArgs) { 5517 // The check to see if the argIndex is valid will come later. 5518 // We set the bit here because we may exit early from this 5519 // function if we encounter some other error. 5520 CoveredArgs.set(argIndex); 5521 } 5522 5523 // Check the length modifier is valid with the given conversion specifier. 5524 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 5525 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 5526 diag::warn_format_nonsensical_length); 5527 else if (!FS.hasStandardLengthModifier()) 5528 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 5529 else if (!FS.hasStandardLengthConversionCombination()) 5530 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 5531 diag::warn_format_non_standard_conversion_spec); 5532 5533 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 5534 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 5535 5536 // The remaining checks depend on the data arguments. 5537 if (HasVAListArg) 5538 return true; 5539 5540 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 5541 return false; 5542 5543 // Check that the argument type matches the format specifier. 5544 const Expr *Ex = getDataArg(argIndex); 5545 if (!Ex) 5546 return true; 5547 5548 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 5549 5550 if (!AT.isValid()) { 5551 return true; 5552 } 5553 5554 analyze_format_string::ArgType::MatchKind match = 5555 AT.matchesType(S.Context, Ex->getType()); 5556 if (match == analyze_format_string::ArgType::Match) { 5557 return true; 5558 } 5559 5560 ScanfSpecifier fixedFS = FS; 5561 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 5562 S.getLangOpts(), S.Context); 5563 5564 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 5565 if (match == analyze_format_string::ArgType::NoMatchPedantic) { 5566 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 5567 } 5568 5569 if (success) { 5570 // Get the fix string from the fixed format specifier. 5571 SmallString<128> buf; 5572 llvm::raw_svector_ostream os(buf); 5573 fixedFS.toString(os); 5574 5575 EmitFormatDiagnostic( 5576 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) 5577 << Ex->getType() << false << Ex->getSourceRange(), 5578 Ex->getLocStart(), 5579 /*IsStringLocation*/ false, 5580 getSpecifierRange(startSpecifier, specifierLen), 5581 FixItHint::CreateReplacement( 5582 getSpecifierRange(startSpecifier, specifierLen), os.str())); 5583 } else { 5584 EmitFormatDiagnostic(S.PDiag(diag) 5585 << AT.getRepresentativeTypeName(S.Context) 5586 << Ex->getType() << false << Ex->getSourceRange(), 5587 Ex->getLocStart(), 5588 /*IsStringLocation*/ false, 5589 getSpecifierRange(startSpecifier, specifierLen)); 5590 } 5591 5592 return true; 5593 } 5594 5595 static void CheckFormatString(Sema &S, const StringLiteral *FExpr, 5596 const Expr *OrigFormatExpr, 5597 ArrayRef<const Expr *> Args, 5598 bool HasVAListArg, unsigned format_idx, 5599 unsigned firstDataArg, 5600 Sema::FormatStringType Type, 5601 bool inFunctionCall, 5602 Sema::VariadicCallType CallType, 5603 llvm::SmallBitVector &CheckedVarArgs, 5604 UncoveredArgHandler &UncoveredArg) { 5605 // CHECK: is the format string a wide literal? 5606 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 5607 CheckFormatHandler::EmitFormatDiagnostic( 5608 S, inFunctionCall, Args[format_idx], 5609 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(), 5610 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 5611 return; 5612 } 5613 5614 // Str - The format string. NOTE: this is NOT null-terminated! 5615 StringRef StrRef = FExpr->getString(); 5616 const char *Str = StrRef.data(); 5617 // Account for cases where the string literal is truncated in a declaration. 5618 const ConstantArrayType *T = 5619 S.Context.getAsConstantArrayType(FExpr->getType()); 5620 assert(T && "String literal not of constant array type!"); 5621 size_t TypeSize = T->getSize().getZExtValue(); 5622 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 5623 const unsigned numDataArgs = Args.size() - firstDataArg; 5624 5625 // Emit a warning if the string literal is truncated and does not contain an 5626 // embedded null character. 5627 if (TypeSize <= StrRef.size() && 5628 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 5629 CheckFormatHandler::EmitFormatDiagnostic( 5630 S, inFunctionCall, Args[format_idx], 5631 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 5632 FExpr->getLocStart(), 5633 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 5634 return; 5635 } 5636 5637 // CHECK: empty format string? 5638 if (StrLen == 0 && numDataArgs > 0) { 5639 CheckFormatHandler::EmitFormatDiagnostic( 5640 S, inFunctionCall, Args[format_idx], 5641 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(), 5642 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 5643 return; 5644 } 5645 5646 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 5647 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSTrace) { 5648 CheckPrintfHandler H(S, FExpr, OrigFormatExpr, firstDataArg, 5649 numDataArgs, (Type == Sema::FST_NSString || 5650 Type == Sema::FST_OSTrace), 5651 Str, HasVAListArg, Args, format_idx, 5652 inFunctionCall, CallType, CheckedVarArgs, 5653 UncoveredArg); 5654 5655 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 5656 S.getLangOpts(), 5657 S.Context.getTargetInfo(), 5658 Type == Sema::FST_FreeBSDKPrintf)) 5659 H.DoneProcessing(); 5660 } else if (Type == Sema::FST_Scanf) { 5661 CheckScanfHandler H(S, FExpr, OrigFormatExpr, firstDataArg, numDataArgs, 5662 Str, HasVAListArg, Args, format_idx, 5663 inFunctionCall, CallType, CheckedVarArgs, 5664 UncoveredArg); 5665 5666 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 5667 S.getLangOpts(), 5668 S.Context.getTargetInfo())) 5669 H.DoneProcessing(); 5670 } // TODO: handle other formats 5671 } 5672 5673 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 5674 // Str - The format string. NOTE: this is NOT null-terminated! 5675 StringRef StrRef = FExpr->getString(); 5676 const char *Str = StrRef.data(); 5677 // Account for cases where the string literal is truncated in a declaration. 5678 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 5679 assert(T && "String literal not of constant array type!"); 5680 size_t TypeSize = T->getSize().getZExtValue(); 5681 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 5682 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 5683 getLangOpts(), 5684 Context.getTargetInfo()); 5685 } 5686 5687 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 5688 5689 // Returns the related absolute value function that is larger, of 0 if one 5690 // does not exist. 5691 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 5692 switch (AbsFunction) { 5693 default: 5694 return 0; 5695 5696 case Builtin::BI__builtin_abs: 5697 return Builtin::BI__builtin_labs; 5698 case Builtin::BI__builtin_labs: 5699 return Builtin::BI__builtin_llabs; 5700 case Builtin::BI__builtin_llabs: 5701 return 0; 5702 5703 case Builtin::BI__builtin_fabsf: 5704 return Builtin::BI__builtin_fabs; 5705 case Builtin::BI__builtin_fabs: 5706 return Builtin::BI__builtin_fabsl; 5707 case Builtin::BI__builtin_fabsl: 5708 return 0; 5709 5710 case Builtin::BI__builtin_cabsf: 5711 return Builtin::BI__builtin_cabs; 5712 case Builtin::BI__builtin_cabs: 5713 return Builtin::BI__builtin_cabsl; 5714 case Builtin::BI__builtin_cabsl: 5715 return 0; 5716 5717 case Builtin::BIabs: 5718 return Builtin::BIlabs; 5719 case Builtin::BIlabs: 5720 return Builtin::BIllabs; 5721 case Builtin::BIllabs: 5722 return 0; 5723 5724 case Builtin::BIfabsf: 5725 return Builtin::BIfabs; 5726 case Builtin::BIfabs: 5727 return Builtin::BIfabsl; 5728 case Builtin::BIfabsl: 5729 return 0; 5730 5731 case Builtin::BIcabsf: 5732 return Builtin::BIcabs; 5733 case Builtin::BIcabs: 5734 return Builtin::BIcabsl; 5735 case Builtin::BIcabsl: 5736 return 0; 5737 } 5738 } 5739 5740 // Returns the argument type of the absolute value function. 5741 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 5742 unsigned AbsType) { 5743 if (AbsType == 0) 5744 return QualType(); 5745 5746 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 5747 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 5748 if (Error != ASTContext::GE_None) 5749 return QualType(); 5750 5751 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 5752 if (!FT) 5753 return QualType(); 5754 5755 if (FT->getNumParams() != 1) 5756 return QualType(); 5757 5758 return FT->getParamType(0); 5759 } 5760 5761 // Returns the best absolute value function, or zero, based on type and 5762 // current absolute value function. 5763 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 5764 unsigned AbsFunctionKind) { 5765 unsigned BestKind = 0; 5766 uint64_t ArgSize = Context.getTypeSize(ArgType); 5767 for (unsigned Kind = AbsFunctionKind; Kind != 0; 5768 Kind = getLargerAbsoluteValueFunction(Kind)) { 5769 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 5770 if (Context.getTypeSize(ParamType) >= ArgSize) { 5771 if (BestKind == 0) 5772 BestKind = Kind; 5773 else if (Context.hasSameType(ParamType, ArgType)) { 5774 BestKind = Kind; 5775 break; 5776 } 5777 } 5778 } 5779 return BestKind; 5780 } 5781 5782 enum AbsoluteValueKind { 5783 AVK_Integer, 5784 AVK_Floating, 5785 AVK_Complex 5786 }; 5787 5788 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 5789 if (T->isIntegralOrEnumerationType()) 5790 return AVK_Integer; 5791 if (T->isRealFloatingType()) 5792 return AVK_Floating; 5793 if (T->isAnyComplexType()) 5794 return AVK_Complex; 5795 5796 llvm_unreachable("Type not integer, floating, or complex"); 5797 } 5798 5799 // Changes the absolute value function to a different type. Preserves whether 5800 // the function is a builtin. 5801 static unsigned changeAbsFunction(unsigned AbsKind, 5802 AbsoluteValueKind ValueKind) { 5803 switch (ValueKind) { 5804 case AVK_Integer: 5805 switch (AbsKind) { 5806 default: 5807 return 0; 5808 case Builtin::BI__builtin_fabsf: 5809 case Builtin::BI__builtin_fabs: 5810 case Builtin::BI__builtin_fabsl: 5811 case Builtin::BI__builtin_cabsf: 5812 case Builtin::BI__builtin_cabs: 5813 case Builtin::BI__builtin_cabsl: 5814 return Builtin::BI__builtin_abs; 5815 case Builtin::BIfabsf: 5816 case Builtin::BIfabs: 5817 case Builtin::BIfabsl: 5818 case Builtin::BIcabsf: 5819 case Builtin::BIcabs: 5820 case Builtin::BIcabsl: 5821 return Builtin::BIabs; 5822 } 5823 case AVK_Floating: 5824 switch (AbsKind) { 5825 default: 5826 return 0; 5827 case Builtin::BI__builtin_abs: 5828 case Builtin::BI__builtin_labs: 5829 case Builtin::BI__builtin_llabs: 5830 case Builtin::BI__builtin_cabsf: 5831 case Builtin::BI__builtin_cabs: 5832 case Builtin::BI__builtin_cabsl: 5833 return Builtin::BI__builtin_fabsf; 5834 case Builtin::BIabs: 5835 case Builtin::BIlabs: 5836 case Builtin::BIllabs: 5837 case Builtin::BIcabsf: 5838 case Builtin::BIcabs: 5839 case Builtin::BIcabsl: 5840 return Builtin::BIfabsf; 5841 } 5842 case AVK_Complex: 5843 switch (AbsKind) { 5844 default: 5845 return 0; 5846 case Builtin::BI__builtin_abs: 5847 case Builtin::BI__builtin_labs: 5848 case Builtin::BI__builtin_llabs: 5849 case Builtin::BI__builtin_fabsf: 5850 case Builtin::BI__builtin_fabs: 5851 case Builtin::BI__builtin_fabsl: 5852 return Builtin::BI__builtin_cabsf; 5853 case Builtin::BIabs: 5854 case Builtin::BIlabs: 5855 case Builtin::BIllabs: 5856 case Builtin::BIfabsf: 5857 case Builtin::BIfabs: 5858 case Builtin::BIfabsl: 5859 return Builtin::BIcabsf; 5860 } 5861 } 5862 llvm_unreachable("Unable to convert function"); 5863 } 5864 5865 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 5866 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 5867 if (!FnInfo) 5868 return 0; 5869 5870 switch (FDecl->getBuiltinID()) { 5871 default: 5872 return 0; 5873 case Builtin::BI__builtin_abs: 5874 case Builtin::BI__builtin_fabs: 5875 case Builtin::BI__builtin_fabsf: 5876 case Builtin::BI__builtin_fabsl: 5877 case Builtin::BI__builtin_labs: 5878 case Builtin::BI__builtin_llabs: 5879 case Builtin::BI__builtin_cabs: 5880 case Builtin::BI__builtin_cabsf: 5881 case Builtin::BI__builtin_cabsl: 5882 case Builtin::BIabs: 5883 case Builtin::BIlabs: 5884 case Builtin::BIllabs: 5885 case Builtin::BIfabs: 5886 case Builtin::BIfabsf: 5887 case Builtin::BIfabsl: 5888 case Builtin::BIcabs: 5889 case Builtin::BIcabsf: 5890 case Builtin::BIcabsl: 5891 return FDecl->getBuiltinID(); 5892 } 5893 llvm_unreachable("Unknown Builtin type"); 5894 } 5895 5896 // If the replacement is valid, emit a note with replacement function. 5897 // Additionally, suggest including the proper header if not already included. 5898 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 5899 unsigned AbsKind, QualType ArgType) { 5900 bool EmitHeaderHint = true; 5901 const char *HeaderName = nullptr; 5902 const char *FunctionName = nullptr; 5903 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 5904 FunctionName = "std::abs"; 5905 if (ArgType->isIntegralOrEnumerationType()) { 5906 HeaderName = "cstdlib"; 5907 } else if (ArgType->isRealFloatingType()) { 5908 HeaderName = "cmath"; 5909 } else { 5910 llvm_unreachable("Invalid Type"); 5911 } 5912 5913 // Lookup all std::abs 5914 if (NamespaceDecl *Std = S.getStdNamespace()) { 5915 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 5916 R.suppressDiagnostics(); 5917 S.LookupQualifiedName(R, Std); 5918 5919 for (const auto *I : R) { 5920 const FunctionDecl *FDecl = nullptr; 5921 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 5922 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 5923 } else { 5924 FDecl = dyn_cast<FunctionDecl>(I); 5925 } 5926 if (!FDecl) 5927 continue; 5928 5929 // Found std::abs(), check that they are the right ones. 5930 if (FDecl->getNumParams() != 1) 5931 continue; 5932 5933 // Check that the parameter type can handle the argument. 5934 QualType ParamType = FDecl->getParamDecl(0)->getType(); 5935 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 5936 S.Context.getTypeSize(ArgType) <= 5937 S.Context.getTypeSize(ParamType)) { 5938 // Found a function, don't need the header hint. 5939 EmitHeaderHint = false; 5940 break; 5941 } 5942 } 5943 } 5944 } else { 5945 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 5946 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 5947 5948 if (HeaderName) { 5949 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 5950 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 5951 R.suppressDiagnostics(); 5952 S.LookupName(R, S.getCurScope()); 5953 5954 if (R.isSingleResult()) { 5955 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 5956 if (FD && FD->getBuiltinID() == AbsKind) { 5957 EmitHeaderHint = false; 5958 } else { 5959 return; 5960 } 5961 } else if (!R.empty()) { 5962 return; 5963 } 5964 } 5965 } 5966 5967 S.Diag(Loc, diag::note_replace_abs_function) 5968 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 5969 5970 if (!HeaderName) 5971 return; 5972 5973 if (!EmitHeaderHint) 5974 return; 5975 5976 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 5977 << FunctionName; 5978 } 5979 5980 static bool IsFunctionStdAbs(const FunctionDecl *FDecl) { 5981 if (!FDecl) 5982 return false; 5983 5984 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs")) 5985 return false; 5986 5987 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext()); 5988 5989 while (ND && ND->isInlineNamespace()) { 5990 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext()); 5991 } 5992 5993 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std")) 5994 return false; 5995 5996 if (!isa<TranslationUnitDecl>(ND->getDeclContext())) 5997 return false; 5998 5999 return true; 6000 } 6001 6002 // Warn when using the wrong abs() function. 6003 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 6004 const FunctionDecl *FDecl, 6005 IdentifierInfo *FnInfo) { 6006 if (Call->getNumArgs() != 1) 6007 return; 6008 6009 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 6010 bool IsStdAbs = IsFunctionStdAbs(FDecl); 6011 if (AbsKind == 0 && !IsStdAbs) 6012 return; 6013 6014 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 6015 QualType ParamType = Call->getArg(0)->getType(); 6016 6017 // Unsigned types cannot be negative. Suggest removing the absolute value 6018 // function call. 6019 if (ArgType->isUnsignedIntegerType()) { 6020 const char *FunctionName = 6021 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 6022 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 6023 Diag(Call->getExprLoc(), diag::note_remove_abs) 6024 << FunctionName 6025 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 6026 return; 6027 } 6028 6029 // Taking the absolute value of a pointer is very suspicious, they probably 6030 // wanted to index into an array, dereference a pointer, call a function, etc. 6031 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 6032 unsigned DiagType = 0; 6033 if (ArgType->isFunctionType()) 6034 DiagType = 1; 6035 else if (ArgType->isArrayType()) 6036 DiagType = 2; 6037 6038 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 6039 return; 6040 } 6041 6042 // std::abs has overloads which prevent most of the absolute value problems 6043 // from occurring. 6044 if (IsStdAbs) 6045 return; 6046 6047 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 6048 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 6049 6050 // The argument and parameter are the same kind. Check if they are the right 6051 // size. 6052 if (ArgValueKind == ParamValueKind) { 6053 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 6054 return; 6055 6056 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 6057 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 6058 << FDecl << ArgType << ParamType; 6059 6060 if (NewAbsKind == 0) 6061 return; 6062 6063 emitReplacement(*this, Call->getExprLoc(), 6064 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 6065 return; 6066 } 6067 6068 // ArgValueKind != ParamValueKind 6069 // The wrong type of absolute value function was used. Attempt to find the 6070 // proper one. 6071 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 6072 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 6073 if (NewAbsKind == 0) 6074 return; 6075 6076 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 6077 << FDecl << ParamValueKind << ArgValueKind; 6078 6079 emitReplacement(*this, Call->getExprLoc(), 6080 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 6081 } 6082 6083 //===--- CHECK: Standard memory functions ---------------------------------===// 6084 6085 /// \brief Takes the expression passed to the size_t parameter of functions 6086 /// such as memcmp, strncat, etc and warns if it's a comparison. 6087 /// 6088 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 6089 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 6090 IdentifierInfo *FnName, 6091 SourceLocation FnLoc, 6092 SourceLocation RParenLoc) { 6093 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 6094 if (!Size) 6095 return false; 6096 6097 // if E is binop and op is >, <, >=, <=, ==, &&, ||: 6098 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp()) 6099 return false; 6100 6101 SourceRange SizeRange = Size->getSourceRange(); 6102 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 6103 << SizeRange << FnName; 6104 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 6105 << FnName << FixItHint::CreateInsertion( 6106 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")") 6107 << FixItHint::CreateRemoval(RParenLoc); 6108 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 6109 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 6110 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 6111 ")"); 6112 6113 return true; 6114 } 6115 6116 /// \brief Determine whether the given type is or contains a dynamic class type 6117 /// (e.g., whether it has a vtable). 6118 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 6119 bool &IsContained) { 6120 // Look through array types while ignoring qualifiers. 6121 const Type *Ty = T->getBaseElementTypeUnsafe(); 6122 IsContained = false; 6123 6124 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 6125 RD = RD ? RD->getDefinition() : nullptr; 6126 if (!RD || RD->isInvalidDecl()) 6127 return nullptr; 6128 6129 if (RD->isDynamicClass()) 6130 return RD; 6131 6132 // Check all the fields. If any bases were dynamic, the class is dynamic. 6133 // It's impossible for a class to transitively contain itself by value, so 6134 // infinite recursion is impossible. 6135 for (auto *FD : RD->fields()) { 6136 bool SubContained; 6137 if (const CXXRecordDecl *ContainedRD = 6138 getContainedDynamicClass(FD->getType(), SubContained)) { 6139 IsContained = true; 6140 return ContainedRD; 6141 } 6142 } 6143 6144 return nullptr; 6145 } 6146 6147 /// \brief If E is a sizeof expression, returns its argument expression, 6148 /// otherwise returns NULL. 6149 static const Expr *getSizeOfExprArg(const Expr *E) { 6150 if (const UnaryExprOrTypeTraitExpr *SizeOf = 6151 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 6152 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType()) 6153 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 6154 6155 return nullptr; 6156 } 6157 6158 /// \brief If E is a sizeof expression, returns its argument type. 6159 static QualType getSizeOfArgType(const Expr *E) { 6160 if (const UnaryExprOrTypeTraitExpr *SizeOf = 6161 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 6162 if (SizeOf->getKind() == clang::UETT_SizeOf) 6163 return SizeOf->getTypeOfArgument(); 6164 6165 return QualType(); 6166 } 6167 6168 /// \brief Check for dangerous or invalid arguments to memset(). 6169 /// 6170 /// This issues warnings on known problematic, dangerous or unspecified 6171 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 6172 /// function calls. 6173 /// 6174 /// \param Call The call expression to diagnose. 6175 void Sema::CheckMemaccessArguments(const CallExpr *Call, 6176 unsigned BId, 6177 IdentifierInfo *FnName) { 6178 assert(BId != 0); 6179 6180 // It is possible to have a non-standard definition of memset. Validate 6181 // we have enough arguments, and if not, abort further checking. 6182 unsigned ExpectedNumArgs = 6183 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 6184 if (Call->getNumArgs() < ExpectedNumArgs) 6185 return; 6186 6187 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 6188 BId == Builtin::BIstrndup ? 1 : 2); 6189 unsigned LenArg = 6190 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 6191 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 6192 6193 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 6194 Call->getLocStart(), Call->getRParenLoc())) 6195 return; 6196 6197 // We have special checking when the length is a sizeof expression. 6198 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 6199 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 6200 llvm::FoldingSetNodeID SizeOfArgID; 6201 6202 // Although widely used, 'bzero' is not a standard function. Be more strict 6203 // with the argument types before allowing diagnostics and only allow the 6204 // form bzero(ptr, sizeof(...)). 6205 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 6206 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 6207 return; 6208 6209 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 6210 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 6211 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 6212 6213 QualType DestTy = Dest->getType(); 6214 QualType PointeeTy; 6215 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 6216 PointeeTy = DestPtrTy->getPointeeType(); 6217 6218 // Never warn about void type pointers. This can be used to suppress 6219 // false positives. 6220 if (PointeeTy->isVoidType()) 6221 continue; 6222 6223 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 6224 // actually comparing the expressions for equality. Because computing the 6225 // expression IDs can be expensive, we only do this if the diagnostic is 6226 // enabled. 6227 if (SizeOfArg && 6228 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 6229 SizeOfArg->getExprLoc())) { 6230 // We only compute IDs for expressions if the warning is enabled, and 6231 // cache the sizeof arg's ID. 6232 if (SizeOfArgID == llvm::FoldingSetNodeID()) 6233 SizeOfArg->Profile(SizeOfArgID, Context, true); 6234 llvm::FoldingSetNodeID DestID; 6235 Dest->Profile(DestID, Context, true); 6236 if (DestID == SizeOfArgID) { 6237 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 6238 // over sizeof(src) as well. 6239 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 6240 StringRef ReadableName = FnName->getName(); 6241 6242 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 6243 if (UnaryOp->getOpcode() == UO_AddrOf) 6244 ActionIdx = 1; // If its an address-of operator, just remove it. 6245 if (!PointeeTy->isIncompleteType() && 6246 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 6247 ActionIdx = 2; // If the pointee's size is sizeof(char), 6248 // suggest an explicit length. 6249 6250 // If the function is defined as a builtin macro, do not show macro 6251 // expansion. 6252 SourceLocation SL = SizeOfArg->getExprLoc(); 6253 SourceRange DSR = Dest->getSourceRange(); 6254 SourceRange SSR = SizeOfArg->getSourceRange(); 6255 SourceManager &SM = getSourceManager(); 6256 6257 if (SM.isMacroArgExpansion(SL)) { 6258 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 6259 SL = SM.getSpellingLoc(SL); 6260 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 6261 SM.getSpellingLoc(DSR.getEnd())); 6262 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 6263 SM.getSpellingLoc(SSR.getEnd())); 6264 } 6265 6266 DiagRuntimeBehavior(SL, SizeOfArg, 6267 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 6268 << ReadableName 6269 << PointeeTy 6270 << DestTy 6271 << DSR 6272 << SSR); 6273 DiagRuntimeBehavior(SL, SizeOfArg, 6274 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 6275 << ActionIdx 6276 << SSR); 6277 6278 break; 6279 } 6280 } 6281 6282 // Also check for cases where the sizeof argument is the exact same 6283 // type as the memory argument, and where it points to a user-defined 6284 // record type. 6285 if (SizeOfArgTy != QualType()) { 6286 if (PointeeTy->isRecordType() && 6287 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 6288 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 6289 PDiag(diag::warn_sizeof_pointer_type_memaccess) 6290 << FnName << SizeOfArgTy << ArgIdx 6291 << PointeeTy << Dest->getSourceRange() 6292 << LenExpr->getSourceRange()); 6293 break; 6294 } 6295 } 6296 } else if (DestTy->isArrayType()) { 6297 PointeeTy = DestTy; 6298 } 6299 6300 if (PointeeTy == QualType()) 6301 continue; 6302 6303 // Always complain about dynamic classes. 6304 bool IsContained; 6305 if (const CXXRecordDecl *ContainedRD = 6306 getContainedDynamicClass(PointeeTy, IsContained)) { 6307 6308 unsigned OperationType = 0; 6309 // "overwritten" if we're warning about the destination for any call 6310 // but memcmp; otherwise a verb appropriate to the call. 6311 if (ArgIdx != 0 || BId == Builtin::BImemcmp) { 6312 if (BId == Builtin::BImemcpy) 6313 OperationType = 1; 6314 else if(BId == Builtin::BImemmove) 6315 OperationType = 2; 6316 else if (BId == Builtin::BImemcmp) 6317 OperationType = 3; 6318 } 6319 6320 DiagRuntimeBehavior( 6321 Dest->getExprLoc(), Dest, 6322 PDiag(diag::warn_dyn_class_memaccess) 6323 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx) 6324 << FnName << IsContained << ContainedRD << OperationType 6325 << Call->getCallee()->getSourceRange()); 6326 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 6327 BId != Builtin::BImemset) 6328 DiagRuntimeBehavior( 6329 Dest->getExprLoc(), Dest, 6330 PDiag(diag::warn_arc_object_memaccess) 6331 << ArgIdx << FnName << PointeeTy 6332 << Call->getCallee()->getSourceRange()); 6333 else 6334 continue; 6335 6336 DiagRuntimeBehavior( 6337 Dest->getExprLoc(), Dest, 6338 PDiag(diag::note_bad_memaccess_silence) 6339 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 6340 break; 6341 } 6342 } 6343 6344 // A little helper routine: ignore addition and subtraction of integer literals. 6345 // This intentionally does not ignore all integer constant expressions because 6346 // we don't want to remove sizeof(). 6347 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 6348 Ex = Ex->IgnoreParenCasts(); 6349 6350 for (;;) { 6351 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 6352 if (!BO || !BO->isAdditiveOp()) 6353 break; 6354 6355 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 6356 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 6357 6358 if (isa<IntegerLiteral>(RHS)) 6359 Ex = LHS; 6360 else if (isa<IntegerLiteral>(LHS)) 6361 Ex = RHS; 6362 else 6363 break; 6364 } 6365 6366 return Ex; 6367 } 6368 6369 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 6370 ASTContext &Context) { 6371 // Only handle constant-sized or VLAs, but not flexible members. 6372 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 6373 // Only issue the FIXIT for arrays of size > 1. 6374 if (CAT->getSize().getSExtValue() <= 1) 6375 return false; 6376 } else if (!Ty->isVariableArrayType()) { 6377 return false; 6378 } 6379 return true; 6380 } 6381 6382 // Warn if the user has made the 'size' argument to strlcpy or strlcat 6383 // be the size of the source, instead of the destination. 6384 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 6385 IdentifierInfo *FnName) { 6386 6387 // Don't crash if the user has the wrong number of arguments 6388 unsigned NumArgs = Call->getNumArgs(); 6389 if ((NumArgs != 3) && (NumArgs != 4)) 6390 return; 6391 6392 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 6393 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 6394 const Expr *CompareWithSrc = nullptr; 6395 6396 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 6397 Call->getLocStart(), Call->getRParenLoc())) 6398 return; 6399 6400 // Look for 'strlcpy(dst, x, sizeof(x))' 6401 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 6402 CompareWithSrc = Ex; 6403 else { 6404 // Look for 'strlcpy(dst, x, strlen(x))' 6405 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 6406 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 6407 SizeCall->getNumArgs() == 1) 6408 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 6409 } 6410 } 6411 6412 if (!CompareWithSrc) 6413 return; 6414 6415 // Determine if the argument to sizeof/strlen is equal to the source 6416 // argument. In principle there's all kinds of things you could do 6417 // here, for instance creating an == expression and evaluating it with 6418 // EvaluateAsBooleanCondition, but this uses a more direct technique: 6419 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 6420 if (!SrcArgDRE) 6421 return; 6422 6423 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 6424 if (!CompareWithSrcDRE || 6425 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 6426 return; 6427 6428 const Expr *OriginalSizeArg = Call->getArg(2); 6429 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size) 6430 << OriginalSizeArg->getSourceRange() << FnName; 6431 6432 // Output a FIXIT hint if the destination is an array (rather than a 6433 // pointer to an array). This could be enhanced to handle some 6434 // pointers if we know the actual size, like if DstArg is 'array+2' 6435 // we could say 'sizeof(array)-2'. 6436 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 6437 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 6438 return; 6439 6440 SmallString<128> sizeString; 6441 llvm::raw_svector_ostream OS(sizeString); 6442 OS << "sizeof("; 6443 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 6444 OS << ")"; 6445 6446 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size) 6447 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 6448 OS.str()); 6449 } 6450 6451 /// Check if two expressions refer to the same declaration. 6452 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 6453 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 6454 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 6455 return D1->getDecl() == D2->getDecl(); 6456 return false; 6457 } 6458 6459 static const Expr *getStrlenExprArg(const Expr *E) { 6460 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 6461 const FunctionDecl *FD = CE->getDirectCallee(); 6462 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 6463 return nullptr; 6464 return CE->getArg(0)->IgnoreParenCasts(); 6465 } 6466 return nullptr; 6467 } 6468 6469 // Warn on anti-patterns as the 'size' argument to strncat. 6470 // The correct size argument should look like following: 6471 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 6472 void Sema::CheckStrncatArguments(const CallExpr *CE, 6473 IdentifierInfo *FnName) { 6474 // Don't crash if the user has the wrong number of arguments. 6475 if (CE->getNumArgs() < 3) 6476 return; 6477 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 6478 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 6479 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 6480 6481 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(), 6482 CE->getRParenLoc())) 6483 return; 6484 6485 // Identify common expressions, which are wrongly used as the size argument 6486 // to strncat and may lead to buffer overflows. 6487 unsigned PatternType = 0; 6488 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 6489 // - sizeof(dst) 6490 if (referToTheSameDecl(SizeOfArg, DstArg)) 6491 PatternType = 1; 6492 // - sizeof(src) 6493 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 6494 PatternType = 2; 6495 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 6496 if (BE->getOpcode() == BO_Sub) { 6497 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 6498 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 6499 // - sizeof(dst) - strlen(dst) 6500 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 6501 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 6502 PatternType = 1; 6503 // - sizeof(src) - (anything) 6504 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 6505 PatternType = 2; 6506 } 6507 } 6508 6509 if (PatternType == 0) 6510 return; 6511 6512 // Generate the diagnostic. 6513 SourceLocation SL = LenArg->getLocStart(); 6514 SourceRange SR = LenArg->getSourceRange(); 6515 SourceManager &SM = getSourceManager(); 6516 6517 // If the function is defined as a builtin macro, do not show macro expansion. 6518 if (SM.isMacroArgExpansion(SL)) { 6519 SL = SM.getSpellingLoc(SL); 6520 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 6521 SM.getSpellingLoc(SR.getEnd())); 6522 } 6523 6524 // Check if the destination is an array (rather than a pointer to an array). 6525 QualType DstTy = DstArg->getType(); 6526 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 6527 Context); 6528 if (!isKnownSizeArray) { 6529 if (PatternType == 1) 6530 Diag(SL, diag::warn_strncat_wrong_size) << SR; 6531 else 6532 Diag(SL, diag::warn_strncat_src_size) << SR; 6533 return; 6534 } 6535 6536 if (PatternType == 1) 6537 Diag(SL, diag::warn_strncat_large_size) << SR; 6538 else 6539 Diag(SL, diag::warn_strncat_src_size) << SR; 6540 6541 SmallString<128> sizeString; 6542 llvm::raw_svector_ostream OS(sizeString); 6543 OS << "sizeof("; 6544 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 6545 OS << ") - "; 6546 OS << "strlen("; 6547 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 6548 OS << ") - 1"; 6549 6550 Diag(SL, diag::note_strncat_wrong_size) 6551 << FixItHint::CreateReplacement(SR, OS.str()); 6552 } 6553 6554 //===--- CHECK: Return Address of Stack Variable --------------------------===// 6555 6556 static const Expr *EvalVal(const Expr *E, 6557 SmallVectorImpl<const DeclRefExpr *> &refVars, 6558 const Decl *ParentDecl); 6559 static const Expr *EvalAddr(const Expr *E, 6560 SmallVectorImpl<const DeclRefExpr *> &refVars, 6561 const Decl *ParentDecl); 6562 6563 /// CheckReturnStackAddr - Check if a return statement returns the address 6564 /// of a stack variable. 6565 static void 6566 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType, 6567 SourceLocation ReturnLoc) { 6568 6569 const Expr *stackE = nullptr; 6570 SmallVector<const DeclRefExpr *, 8> refVars; 6571 6572 // Perform checking for returned stack addresses, local blocks, 6573 // label addresses or references to temporaries. 6574 if (lhsType->isPointerType() || 6575 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) { 6576 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr); 6577 } else if (lhsType->isReferenceType()) { 6578 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr); 6579 } 6580 6581 if (!stackE) 6582 return; // Nothing suspicious was found. 6583 6584 // Parameters are initalized in the calling scope, so taking the address 6585 // of a parameter reference doesn't need a warning. 6586 for (auto *DRE : refVars) 6587 if (isa<ParmVarDecl>(DRE->getDecl())) 6588 return; 6589 6590 SourceLocation diagLoc; 6591 SourceRange diagRange; 6592 if (refVars.empty()) { 6593 diagLoc = stackE->getLocStart(); 6594 diagRange = stackE->getSourceRange(); 6595 } else { 6596 // We followed through a reference variable. 'stackE' contains the 6597 // problematic expression but we will warn at the return statement pointing 6598 // at the reference variable. We will later display the "trail" of 6599 // reference variables using notes. 6600 diagLoc = refVars[0]->getLocStart(); 6601 diagRange = refVars[0]->getSourceRange(); 6602 } 6603 6604 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { 6605 // address of local var 6606 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType() 6607 << DR->getDecl()->getDeclName() << diagRange; 6608 } else if (isa<BlockExpr>(stackE)) { // local block. 6609 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange; 6610 } else if (isa<AddrLabelExpr>(stackE)) { // address of label. 6611 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange; 6612 } else { // local temporary. 6613 // If there is an LValue->RValue conversion, then the value of the 6614 // reference type is used, not the reference. 6615 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) { 6616 if (ICE->getCastKind() == CK_LValueToRValue) { 6617 return; 6618 } 6619 } 6620 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref) 6621 << lhsType->isReferenceType() << diagRange; 6622 } 6623 6624 // Display the "trail" of reference variables that we followed until we 6625 // found the problematic expression using notes. 6626 for (unsigned i = 0, e = refVars.size(); i != e; ++i) { 6627 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl()); 6628 // If this var binds to another reference var, show the range of the next 6629 // var, otherwise the var binds to the problematic expression, in which case 6630 // show the range of the expression. 6631 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange() 6632 : stackE->getSourceRange(); 6633 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind) 6634 << VD->getDeclName() << range; 6635 } 6636 } 6637 6638 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that 6639 /// check if the expression in a return statement evaluates to an address 6640 /// to a location on the stack, a local block, an address of a label, or a 6641 /// reference to local temporary. The recursion is used to traverse the 6642 /// AST of the return expression, with recursion backtracking when we 6643 /// encounter a subexpression that (1) clearly does not lead to one of the 6644 /// above problematic expressions (2) is something we cannot determine leads to 6645 /// a problematic expression based on such local checking. 6646 /// 6647 /// Both EvalAddr and EvalVal follow through reference variables to evaluate 6648 /// the expression that they point to. Such variables are added to the 6649 /// 'refVars' vector so that we know what the reference variable "trail" was. 6650 /// 6651 /// EvalAddr processes expressions that are pointers that are used as 6652 /// references (and not L-values). EvalVal handles all other values. 6653 /// At the base case of the recursion is a check for the above problematic 6654 /// expressions. 6655 /// 6656 /// This implementation handles: 6657 /// 6658 /// * pointer-to-pointer casts 6659 /// * implicit conversions from array references to pointers 6660 /// * taking the address of fields 6661 /// * arbitrary interplay between "&" and "*" operators 6662 /// * pointer arithmetic from an address of a stack variable 6663 /// * taking the address of an array element where the array is on the stack 6664 static const Expr *EvalAddr(const Expr *E, 6665 SmallVectorImpl<const DeclRefExpr *> &refVars, 6666 const Decl *ParentDecl) { 6667 if (E->isTypeDependent()) 6668 return nullptr; 6669 6670 // We should only be called for evaluating pointer expressions. 6671 assert((E->getType()->isAnyPointerType() || 6672 E->getType()->isBlockPointerType() || 6673 E->getType()->isObjCQualifiedIdType()) && 6674 "EvalAddr only works on pointers"); 6675 6676 E = E->IgnoreParens(); 6677 6678 // Our "symbolic interpreter" is just a dispatch off the currently 6679 // viewed AST node. We then recursively traverse the AST by calling 6680 // EvalAddr and EvalVal appropriately. 6681 switch (E->getStmtClass()) { 6682 case Stmt::DeclRefExprClass: { 6683 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 6684 6685 // If we leave the immediate function, the lifetime isn't about to end. 6686 if (DR->refersToEnclosingVariableOrCapture()) 6687 return nullptr; 6688 6689 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) 6690 // If this is a reference variable, follow through to the expression that 6691 // it points to. 6692 if (V->hasLocalStorage() && 6693 V->getType()->isReferenceType() && V->hasInit()) { 6694 // Add the reference variable to the "trail". 6695 refVars.push_back(DR); 6696 return EvalAddr(V->getInit(), refVars, ParentDecl); 6697 } 6698 6699 return nullptr; 6700 } 6701 6702 case Stmt::UnaryOperatorClass: { 6703 // The only unary operator that make sense to handle here 6704 // is AddrOf. All others don't make sense as pointers. 6705 const UnaryOperator *U = cast<UnaryOperator>(E); 6706 6707 if (U->getOpcode() == UO_AddrOf) 6708 return EvalVal(U->getSubExpr(), refVars, ParentDecl); 6709 return nullptr; 6710 } 6711 6712 case Stmt::BinaryOperatorClass: { 6713 // Handle pointer arithmetic. All other binary operators are not valid 6714 // in this context. 6715 const BinaryOperator *B = cast<BinaryOperator>(E); 6716 BinaryOperatorKind op = B->getOpcode(); 6717 6718 if (op != BO_Add && op != BO_Sub) 6719 return nullptr; 6720 6721 const Expr *Base = B->getLHS(); 6722 6723 // Determine which argument is the real pointer base. It could be 6724 // the RHS argument instead of the LHS. 6725 if (!Base->getType()->isPointerType()) 6726 Base = B->getRHS(); 6727 6728 assert(Base->getType()->isPointerType()); 6729 return EvalAddr(Base, refVars, ParentDecl); 6730 } 6731 6732 // For conditional operators we need to see if either the LHS or RHS are 6733 // valid DeclRefExpr*s. If one of them is valid, we return it. 6734 case Stmt::ConditionalOperatorClass: { 6735 const ConditionalOperator *C = cast<ConditionalOperator>(E); 6736 6737 // Handle the GNU extension for missing LHS. 6738 // FIXME: That isn't a ConditionalOperator, so doesn't get here. 6739 if (const Expr *LHSExpr = C->getLHS()) { 6740 // In C++, we can have a throw-expression, which has 'void' type. 6741 if (!LHSExpr->getType()->isVoidType()) 6742 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl)) 6743 return LHS; 6744 } 6745 6746 // In C++, we can have a throw-expression, which has 'void' type. 6747 if (C->getRHS()->getType()->isVoidType()) 6748 return nullptr; 6749 6750 return EvalAddr(C->getRHS(), refVars, ParentDecl); 6751 } 6752 6753 case Stmt::BlockExprClass: 6754 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures()) 6755 return E; // local block. 6756 return nullptr; 6757 6758 case Stmt::AddrLabelExprClass: 6759 return E; // address of label. 6760 6761 case Stmt::ExprWithCleanupsClass: 6762 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars, 6763 ParentDecl); 6764 6765 // For casts, we need to handle conversions from arrays to 6766 // pointer values, and pointer-to-pointer conversions. 6767 case Stmt::ImplicitCastExprClass: 6768 case Stmt::CStyleCastExprClass: 6769 case Stmt::CXXFunctionalCastExprClass: 6770 case Stmt::ObjCBridgedCastExprClass: 6771 case Stmt::CXXStaticCastExprClass: 6772 case Stmt::CXXDynamicCastExprClass: 6773 case Stmt::CXXConstCastExprClass: 6774 case Stmt::CXXReinterpretCastExprClass: { 6775 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr(); 6776 switch (cast<CastExpr>(E)->getCastKind()) { 6777 case CK_LValueToRValue: 6778 case CK_NoOp: 6779 case CK_BaseToDerived: 6780 case CK_DerivedToBase: 6781 case CK_UncheckedDerivedToBase: 6782 case CK_Dynamic: 6783 case CK_CPointerToObjCPointerCast: 6784 case CK_BlockPointerToObjCPointerCast: 6785 case CK_AnyPointerToBlockPointerCast: 6786 return EvalAddr(SubExpr, refVars, ParentDecl); 6787 6788 case CK_ArrayToPointerDecay: 6789 return EvalVal(SubExpr, refVars, ParentDecl); 6790 6791 case CK_BitCast: 6792 if (SubExpr->getType()->isAnyPointerType() || 6793 SubExpr->getType()->isBlockPointerType() || 6794 SubExpr->getType()->isObjCQualifiedIdType()) 6795 return EvalAddr(SubExpr, refVars, ParentDecl); 6796 else 6797 return nullptr; 6798 6799 default: 6800 return nullptr; 6801 } 6802 } 6803 6804 case Stmt::MaterializeTemporaryExprClass: 6805 if (const Expr *Result = 6806 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 6807 refVars, ParentDecl)) 6808 return Result; 6809 return E; 6810 6811 // Everything else: we simply don't reason about them. 6812 default: 6813 return nullptr; 6814 } 6815 } 6816 6817 /// EvalVal - This function is complements EvalAddr in the mutual recursion. 6818 /// See the comments for EvalAddr for more details. 6819 static const Expr *EvalVal(const Expr *E, 6820 SmallVectorImpl<const DeclRefExpr *> &refVars, 6821 const Decl *ParentDecl) { 6822 do { 6823 // We should only be called for evaluating non-pointer expressions, or 6824 // expressions with a pointer type that are not used as references but 6825 // instead 6826 // are l-values (e.g., DeclRefExpr with a pointer type). 6827 6828 // Our "symbolic interpreter" is just a dispatch off the currently 6829 // viewed AST node. We then recursively traverse the AST by calling 6830 // EvalAddr and EvalVal appropriately. 6831 6832 E = E->IgnoreParens(); 6833 switch (E->getStmtClass()) { 6834 case Stmt::ImplicitCastExprClass: { 6835 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E); 6836 if (IE->getValueKind() == VK_LValue) { 6837 E = IE->getSubExpr(); 6838 continue; 6839 } 6840 return nullptr; 6841 } 6842 6843 case Stmt::ExprWithCleanupsClass: 6844 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars, 6845 ParentDecl); 6846 6847 case Stmt::DeclRefExprClass: { 6848 // When we hit a DeclRefExpr we are looking at code that refers to a 6849 // variable's name. If it's not a reference variable we check if it has 6850 // local storage within the function, and if so, return the expression. 6851 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 6852 6853 // If we leave the immediate function, the lifetime isn't about to end. 6854 if (DR->refersToEnclosingVariableOrCapture()) 6855 return nullptr; 6856 6857 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) { 6858 // Check if it refers to itself, e.g. "int& i = i;". 6859 if (V == ParentDecl) 6860 return DR; 6861 6862 if (V->hasLocalStorage()) { 6863 if (!V->getType()->isReferenceType()) 6864 return DR; 6865 6866 // Reference variable, follow through to the expression that 6867 // it points to. 6868 if (V->hasInit()) { 6869 // Add the reference variable to the "trail". 6870 refVars.push_back(DR); 6871 return EvalVal(V->getInit(), refVars, V); 6872 } 6873 } 6874 } 6875 6876 return nullptr; 6877 } 6878 6879 case Stmt::UnaryOperatorClass: { 6880 // The only unary operator that make sense to handle here 6881 // is Deref. All others don't resolve to a "name." This includes 6882 // handling all sorts of rvalues passed to a unary operator. 6883 const UnaryOperator *U = cast<UnaryOperator>(E); 6884 6885 if (U->getOpcode() == UO_Deref) 6886 return EvalAddr(U->getSubExpr(), refVars, ParentDecl); 6887 6888 return nullptr; 6889 } 6890 6891 case Stmt::ArraySubscriptExprClass: { 6892 // Array subscripts are potential references to data on the stack. We 6893 // retrieve the DeclRefExpr* for the array variable if it indeed 6894 // has local storage. 6895 const auto *ASE = cast<ArraySubscriptExpr>(E); 6896 if (ASE->isTypeDependent()) 6897 return nullptr; 6898 return EvalAddr(ASE->getBase(), refVars, ParentDecl); 6899 } 6900 6901 case Stmt::OMPArraySectionExprClass: { 6902 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars, 6903 ParentDecl); 6904 } 6905 6906 case Stmt::ConditionalOperatorClass: { 6907 // For conditional operators we need to see if either the LHS or RHS are 6908 // non-NULL Expr's. If one is non-NULL, we return it. 6909 const ConditionalOperator *C = cast<ConditionalOperator>(E); 6910 6911 // Handle the GNU extension for missing LHS. 6912 if (const Expr *LHSExpr = C->getLHS()) { 6913 // In C++, we can have a throw-expression, which has 'void' type. 6914 if (!LHSExpr->getType()->isVoidType()) 6915 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl)) 6916 return LHS; 6917 } 6918 6919 // In C++, we can have a throw-expression, which has 'void' type. 6920 if (C->getRHS()->getType()->isVoidType()) 6921 return nullptr; 6922 6923 return EvalVal(C->getRHS(), refVars, ParentDecl); 6924 } 6925 6926 // Accesses to members are potential references to data on the stack. 6927 case Stmt::MemberExprClass: { 6928 const MemberExpr *M = cast<MemberExpr>(E); 6929 6930 // Check for indirect access. We only want direct field accesses. 6931 if (M->isArrow()) 6932 return nullptr; 6933 6934 // Check whether the member type is itself a reference, in which case 6935 // we're not going to refer to the member, but to what the member refers 6936 // to. 6937 if (M->getMemberDecl()->getType()->isReferenceType()) 6938 return nullptr; 6939 6940 return EvalVal(M->getBase(), refVars, ParentDecl); 6941 } 6942 6943 case Stmt::MaterializeTemporaryExprClass: 6944 if (const Expr *Result = 6945 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 6946 refVars, ParentDecl)) 6947 return Result; 6948 return E; 6949 6950 default: 6951 // Check that we don't return or take the address of a reference to a 6952 // temporary. This is only useful in C++. 6953 if (!E->isTypeDependent() && E->isRValue()) 6954 return E; 6955 6956 // Everything else: we simply don't reason about them. 6957 return nullptr; 6958 } 6959 } while (true); 6960 } 6961 6962 void 6963 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 6964 SourceLocation ReturnLoc, 6965 bool isObjCMethod, 6966 const AttrVec *Attrs, 6967 const FunctionDecl *FD) { 6968 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc); 6969 6970 // Check if the return value is null but should not be. 6971 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 6972 (!isObjCMethod && isNonNullType(Context, lhsType))) && 6973 CheckNonNullExpr(*this, RetValExp)) 6974 Diag(ReturnLoc, diag::warn_null_ret) 6975 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 6976 6977 // C++11 [basic.stc.dynamic.allocation]p4: 6978 // If an allocation function declared with a non-throwing 6979 // exception-specification fails to allocate storage, it shall return 6980 // a null pointer. Any other allocation function that fails to allocate 6981 // storage shall indicate failure only by throwing an exception [...] 6982 if (FD) { 6983 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 6984 if (Op == OO_New || Op == OO_Array_New) { 6985 const FunctionProtoType *Proto 6986 = FD->getType()->castAs<FunctionProtoType>(); 6987 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) && 6988 CheckNonNullExpr(*this, RetValExp)) 6989 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 6990 << FD << getLangOpts().CPlusPlus11; 6991 } 6992 } 6993 } 6994 6995 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 6996 6997 /// Check for comparisons of floating point operands using != and ==. 6998 /// Issue a warning if these are no self-comparisons, as they are not likely 6999 /// to do what the programmer intended. 7000 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 7001 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 7002 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 7003 7004 // Special case: check for x == x (which is OK). 7005 // Do not emit warnings for such cases. 7006 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 7007 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 7008 if (DRL->getDecl() == DRR->getDecl()) 7009 return; 7010 7011 // Special case: check for comparisons against literals that can be exactly 7012 // represented by APFloat. In such cases, do not emit a warning. This 7013 // is a heuristic: often comparison against such literals are used to 7014 // detect if a value in a variable has not changed. This clearly can 7015 // lead to false negatives. 7016 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 7017 if (FLL->isExact()) 7018 return; 7019 } else 7020 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 7021 if (FLR->isExact()) 7022 return; 7023 7024 // Check for comparisons with builtin types. 7025 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 7026 if (CL->getBuiltinCallee()) 7027 return; 7028 7029 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 7030 if (CR->getBuiltinCallee()) 7031 return; 7032 7033 // Emit the diagnostic. 7034 Diag(Loc, diag::warn_floatingpoint_eq) 7035 << LHS->getSourceRange() << RHS->getSourceRange(); 7036 } 7037 7038 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 7039 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 7040 7041 namespace { 7042 7043 /// Structure recording the 'active' range of an integer-valued 7044 /// expression. 7045 struct IntRange { 7046 /// The number of bits active in the int. 7047 unsigned Width; 7048 7049 /// True if the int is known not to have negative values. 7050 bool NonNegative; 7051 7052 IntRange(unsigned Width, bool NonNegative) 7053 : Width(Width), NonNegative(NonNegative) 7054 {} 7055 7056 /// Returns the range of the bool type. 7057 static IntRange forBoolType() { 7058 return IntRange(1, true); 7059 } 7060 7061 /// Returns the range of an opaque value of the given integral type. 7062 static IntRange forValueOfType(ASTContext &C, QualType T) { 7063 return forValueOfCanonicalType(C, 7064 T->getCanonicalTypeInternal().getTypePtr()); 7065 } 7066 7067 /// Returns the range of an opaque value of a canonical integral type. 7068 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 7069 assert(T->isCanonicalUnqualified()); 7070 7071 if (const VectorType *VT = dyn_cast<VectorType>(T)) 7072 T = VT->getElementType().getTypePtr(); 7073 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 7074 T = CT->getElementType().getTypePtr(); 7075 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 7076 T = AT->getValueType().getTypePtr(); 7077 7078 // For enum types, use the known bit width of the enumerators. 7079 if (const EnumType *ET = dyn_cast<EnumType>(T)) { 7080 EnumDecl *Enum = ET->getDecl(); 7081 if (!Enum->isCompleteDefinition()) 7082 return IntRange(C.getIntWidth(QualType(T, 0)), false); 7083 7084 unsigned NumPositive = Enum->getNumPositiveBits(); 7085 unsigned NumNegative = Enum->getNumNegativeBits(); 7086 7087 if (NumNegative == 0) 7088 return IntRange(NumPositive, true/*NonNegative*/); 7089 else 7090 return IntRange(std::max(NumPositive + 1, NumNegative), 7091 false/*NonNegative*/); 7092 } 7093 7094 const BuiltinType *BT = cast<BuiltinType>(T); 7095 assert(BT->isInteger()); 7096 7097 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 7098 } 7099 7100 /// Returns the "target" range of a canonical integral type, i.e. 7101 /// the range of values expressible in the type. 7102 /// 7103 /// This matches forValueOfCanonicalType except that enums have the 7104 /// full range of their type, not the range of their enumerators. 7105 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 7106 assert(T->isCanonicalUnqualified()); 7107 7108 if (const VectorType *VT = dyn_cast<VectorType>(T)) 7109 T = VT->getElementType().getTypePtr(); 7110 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 7111 T = CT->getElementType().getTypePtr(); 7112 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 7113 T = AT->getValueType().getTypePtr(); 7114 if (const EnumType *ET = dyn_cast<EnumType>(T)) 7115 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 7116 7117 const BuiltinType *BT = cast<BuiltinType>(T); 7118 assert(BT->isInteger()); 7119 7120 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 7121 } 7122 7123 /// Returns the supremum of two ranges: i.e. their conservative merge. 7124 static IntRange join(IntRange L, IntRange R) { 7125 return IntRange(std::max(L.Width, R.Width), 7126 L.NonNegative && R.NonNegative); 7127 } 7128 7129 /// Returns the infinum of two ranges: i.e. their aggressive merge. 7130 static IntRange meet(IntRange L, IntRange R) { 7131 return IntRange(std::min(L.Width, R.Width), 7132 L.NonNegative || R.NonNegative); 7133 } 7134 }; 7135 7136 IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) { 7137 if (value.isSigned() && value.isNegative()) 7138 return IntRange(value.getMinSignedBits(), false); 7139 7140 if (value.getBitWidth() > MaxWidth) 7141 value = value.trunc(MaxWidth); 7142 7143 // isNonNegative() just checks the sign bit without considering 7144 // signedness. 7145 return IntRange(value.getActiveBits(), true); 7146 } 7147 7148 IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 7149 unsigned MaxWidth) { 7150 if (result.isInt()) 7151 return GetValueRange(C, result.getInt(), MaxWidth); 7152 7153 if (result.isVector()) { 7154 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 7155 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 7156 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 7157 R = IntRange::join(R, El); 7158 } 7159 return R; 7160 } 7161 7162 if (result.isComplexInt()) { 7163 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 7164 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 7165 return IntRange::join(R, I); 7166 } 7167 7168 // This can happen with lossless casts to intptr_t of "based" lvalues. 7169 // Assume it might use arbitrary bits. 7170 // FIXME: The only reason we need to pass the type in here is to get 7171 // the sign right on this one case. It would be nice if APValue 7172 // preserved this. 7173 assert(result.isLValue() || result.isAddrLabelDiff()); 7174 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 7175 } 7176 7177 QualType GetExprType(const Expr *E) { 7178 QualType Ty = E->getType(); 7179 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 7180 Ty = AtomicRHS->getValueType(); 7181 return Ty; 7182 } 7183 7184 /// Pseudo-evaluate the given integer expression, estimating the 7185 /// range of values it might take. 7186 /// 7187 /// \param MaxWidth - the width to which the value will be truncated 7188 IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) { 7189 E = E->IgnoreParens(); 7190 7191 // Try a full evaluation first. 7192 Expr::EvalResult result; 7193 if (E->EvaluateAsRValue(result, C)) 7194 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 7195 7196 // I think we only want to look through implicit casts here; if the 7197 // user has an explicit widening cast, we should treat the value as 7198 // being of the new, wider type. 7199 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 7200 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 7201 return GetExprRange(C, CE->getSubExpr(), MaxWidth); 7202 7203 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 7204 7205 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 7206 CE->getCastKind() == CK_BooleanToSignedIntegral; 7207 7208 // Assume that non-integer casts can span the full range of the type. 7209 if (!isIntegerCast) 7210 return OutputTypeRange; 7211 7212 IntRange SubRange 7213 = GetExprRange(C, CE->getSubExpr(), 7214 std::min(MaxWidth, OutputTypeRange.Width)); 7215 7216 // Bail out if the subexpr's range is as wide as the cast type. 7217 if (SubRange.Width >= OutputTypeRange.Width) 7218 return OutputTypeRange; 7219 7220 // Otherwise, we take the smaller width, and we're non-negative if 7221 // either the output type or the subexpr is. 7222 return IntRange(SubRange.Width, 7223 SubRange.NonNegative || OutputTypeRange.NonNegative); 7224 } 7225 7226 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 7227 // If we can fold the condition, just take that operand. 7228 bool CondResult; 7229 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 7230 return GetExprRange(C, CondResult ? CO->getTrueExpr() 7231 : CO->getFalseExpr(), 7232 MaxWidth); 7233 7234 // Otherwise, conservatively merge. 7235 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth); 7236 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth); 7237 return IntRange::join(L, R); 7238 } 7239 7240 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 7241 switch (BO->getOpcode()) { 7242 7243 // Boolean-valued operations are single-bit and positive. 7244 case BO_LAnd: 7245 case BO_LOr: 7246 case BO_LT: 7247 case BO_GT: 7248 case BO_LE: 7249 case BO_GE: 7250 case BO_EQ: 7251 case BO_NE: 7252 return IntRange::forBoolType(); 7253 7254 // The type of the assignments is the type of the LHS, so the RHS 7255 // is not necessarily the same type. 7256 case BO_MulAssign: 7257 case BO_DivAssign: 7258 case BO_RemAssign: 7259 case BO_AddAssign: 7260 case BO_SubAssign: 7261 case BO_XorAssign: 7262 case BO_OrAssign: 7263 // TODO: bitfields? 7264 return IntRange::forValueOfType(C, GetExprType(E)); 7265 7266 // Simple assignments just pass through the RHS, which will have 7267 // been coerced to the LHS type. 7268 case BO_Assign: 7269 // TODO: bitfields? 7270 return GetExprRange(C, BO->getRHS(), MaxWidth); 7271 7272 // Operations with opaque sources are black-listed. 7273 case BO_PtrMemD: 7274 case BO_PtrMemI: 7275 return IntRange::forValueOfType(C, GetExprType(E)); 7276 7277 // Bitwise-and uses the *infinum* of the two source ranges. 7278 case BO_And: 7279 case BO_AndAssign: 7280 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth), 7281 GetExprRange(C, BO->getRHS(), MaxWidth)); 7282 7283 // Left shift gets black-listed based on a judgement call. 7284 case BO_Shl: 7285 // ...except that we want to treat '1 << (blah)' as logically 7286 // positive. It's an important idiom. 7287 if (IntegerLiteral *I 7288 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 7289 if (I->getValue() == 1) { 7290 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 7291 return IntRange(R.Width, /*NonNegative*/ true); 7292 } 7293 } 7294 // fallthrough 7295 7296 case BO_ShlAssign: 7297 return IntRange::forValueOfType(C, GetExprType(E)); 7298 7299 // Right shift by a constant can narrow its left argument. 7300 case BO_Shr: 7301 case BO_ShrAssign: { 7302 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 7303 7304 // If the shift amount is a positive constant, drop the width by 7305 // that much. 7306 llvm::APSInt shift; 7307 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 7308 shift.isNonNegative()) { 7309 unsigned zext = shift.getZExtValue(); 7310 if (zext >= L.Width) 7311 L.Width = (L.NonNegative ? 0 : 1); 7312 else 7313 L.Width -= zext; 7314 } 7315 7316 return L; 7317 } 7318 7319 // Comma acts as its right operand. 7320 case BO_Comma: 7321 return GetExprRange(C, BO->getRHS(), MaxWidth); 7322 7323 // Black-list pointer subtractions. 7324 case BO_Sub: 7325 if (BO->getLHS()->getType()->isPointerType()) 7326 return IntRange::forValueOfType(C, GetExprType(E)); 7327 break; 7328 7329 // The width of a division result is mostly determined by the size 7330 // of the LHS. 7331 case BO_Div: { 7332 // Don't 'pre-truncate' the operands. 7333 unsigned opWidth = C.getIntWidth(GetExprType(E)); 7334 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 7335 7336 // If the divisor is constant, use that. 7337 llvm::APSInt divisor; 7338 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 7339 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 7340 if (log2 >= L.Width) 7341 L.Width = (L.NonNegative ? 0 : 1); 7342 else 7343 L.Width = std::min(L.Width - log2, MaxWidth); 7344 return L; 7345 } 7346 7347 // Otherwise, just use the LHS's width. 7348 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 7349 return IntRange(L.Width, L.NonNegative && R.NonNegative); 7350 } 7351 7352 // The result of a remainder can't be larger than the result of 7353 // either side. 7354 case BO_Rem: { 7355 // Don't 'pre-truncate' the operands. 7356 unsigned opWidth = C.getIntWidth(GetExprType(E)); 7357 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 7358 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 7359 7360 IntRange meet = IntRange::meet(L, R); 7361 meet.Width = std::min(meet.Width, MaxWidth); 7362 return meet; 7363 } 7364 7365 // The default behavior is okay for these. 7366 case BO_Mul: 7367 case BO_Add: 7368 case BO_Xor: 7369 case BO_Or: 7370 break; 7371 } 7372 7373 // The default case is to treat the operation as if it were closed 7374 // on the narrowest type that encompasses both operands. 7375 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 7376 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth); 7377 return IntRange::join(L, R); 7378 } 7379 7380 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 7381 switch (UO->getOpcode()) { 7382 // Boolean-valued operations are white-listed. 7383 case UO_LNot: 7384 return IntRange::forBoolType(); 7385 7386 // Operations with opaque sources are black-listed. 7387 case UO_Deref: 7388 case UO_AddrOf: // should be impossible 7389 return IntRange::forValueOfType(C, GetExprType(E)); 7390 7391 default: 7392 return GetExprRange(C, UO->getSubExpr(), MaxWidth); 7393 } 7394 } 7395 7396 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 7397 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth); 7398 7399 if (const auto *BitField = E->getSourceBitField()) 7400 return IntRange(BitField->getBitWidthValue(C), 7401 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 7402 7403 return IntRange::forValueOfType(C, GetExprType(E)); 7404 } 7405 7406 IntRange GetExprRange(ASTContext &C, const Expr *E) { 7407 return GetExprRange(C, E, C.getIntWidth(GetExprType(E))); 7408 } 7409 7410 /// Checks whether the given value, which currently has the given 7411 /// source semantics, has the same value when coerced through the 7412 /// target semantics. 7413 bool IsSameFloatAfterCast(const llvm::APFloat &value, 7414 const llvm::fltSemantics &Src, 7415 const llvm::fltSemantics &Tgt) { 7416 llvm::APFloat truncated = value; 7417 7418 bool ignored; 7419 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 7420 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 7421 7422 return truncated.bitwiseIsEqual(value); 7423 } 7424 7425 /// Checks whether the given value, which currently has the given 7426 /// source semantics, has the same value when coerced through the 7427 /// target semantics. 7428 /// 7429 /// The value might be a vector of floats (or a complex number). 7430 bool IsSameFloatAfterCast(const APValue &value, 7431 const llvm::fltSemantics &Src, 7432 const llvm::fltSemantics &Tgt) { 7433 if (value.isFloat()) 7434 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 7435 7436 if (value.isVector()) { 7437 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 7438 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 7439 return false; 7440 return true; 7441 } 7442 7443 assert(value.isComplexFloat()); 7444 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 7445 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 7446 } 7447 7448 void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC); 7449 7450 bool IsZero(Sema &S, Expr *E) { 7451 // Suppress cases where we are comparing against an enum constant. 7452 if (const DeclRefExpr *DR = 7453 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 7454 if (isa<EnumConstantDecl>(DR->getDecl())) 7455 return false; 7456 7457 // Suppress cases where the '0' value is expanded from a macro. 7458 if (E->getLocStart().isMacroID()) 7459 return false; 7460 7461 llvm::APSInt Value; 7462 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0; 7463 } 7464 7465 bool HasEnumType(Expr *E) { 7466 // Strip off implicit integral promotions. 7467 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 7468 if (ICE->getCastKind() != CK_IntegralCast && 7469 ICE->getCastKind() != CK_NoOp) 7470 break; 7471 E = ICE->getSubExpr(); 7472 } 7473 7474 return E->getType()->isEnumeralType(); 7475 } 7476 7477 void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) { 7478 // Disable warning in template instantiations. 7479 if (!S.ActiveTemplateInstantiations.empty()) 7480 return; 7481 7482 BinaryOperatorKind op = E->getOpcode(); 7483 if (E->isValueDependent()) 7484 return; 7485 7486 if (op == BO_LT && IsZero(S, E->getRHS())) { 7487 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 7488 << "< 0" << "false" << HasEnumType(E->getLHS()) 7489 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 7490 } else if (op == BO_GE && IsZero(S, E->getRHS())) { 7491 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 7492 << ">= 0" << "true" << HasEnumType(E->getLHS()) 7493 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 7494 } else if (op == BO_GT && IsZero(S, E->getLHS())) { 7495 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 7496 << "0 >" << "false" << HasEnumType(E->getRHS()) 7497 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 7498 } else if (op == BO_LE && IsZero(S, E->getLHS())) { 7499 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 7500 << "0 <=" << "true" << HasEnumType(E->getRHS()) 7501 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 7502 } 7503 } 7504 7505 void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant, 7506 Expr *Other, const llvm::APSInt &Value, 7507 bool RhsConstant) { 7508 // Disable warning in template instantiations. 7509 if (!S.ActiveTemplateInstantiations.empty()) 7510 return; 7511 7512 // TODO: Investigate using GetExprRange() to get tighter bounds 7513 // on the bit ranges. 7514 QualType OtherT = Other->getType(); 7515 if (const auto *AT = OtherT->getAs<AtomicType>()) 7516 OtherT = AT->getValueType(); 7517 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); 7518 unsigned OtherWidth = OtherRange.Width; 7519 7520 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue(); 7521 7522 // 0 values are handled later by CheckTrivialUnsignedComparison(). 7523 if ((Value == 0) && (!OtherIsBooleanType)) 7524 return; 7525 7526 BinaryOperatorKind op = E->getOpcode(); 7527 bool IsTrue = true; 7528 7529 // Used for diagnostic printout. 7530 enum { 7531 LiteralConstant = 0, 7532 CXXBoolLiteralTrue, 7533 CXXBoolLiteralFalse 7534 } LiteralOrBoolConstant = LiteralConstant; 7535 7536 if (!OtherIsBooleanType) { 7537 QualType ConstantT = Constant->getType(); 7538 QualType CommonT = E->getLHS()->getType(); 7539 7540 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT)) 7541 return; 7542 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) && 7543 "comparison with non-integer type"); 7544 7545 bool ConstantSigned = ConstantT->isSignedIntegerType(); 7546 bool CommonSigned = CommonT->isSignedIntegerType(); 7547 7548 bool EqualityOnly = false; 7549 7550 if (CommonSigned) { 7551 // The common type is signed, therefore no signed to unsigned conversion. 7552 if (!OtherRange.NonNegative) { 7553 // Check that the constant is representable in type OtherT. 7554 if (ConstantSigned) { 7555 if (OtherWidth >= Value.getMinSignedBits()) 7556 return; 7557 } else { // !ConstantSigned 7558 if (OtherWidth >= Value.getActiveBits() + 1) 7559 return; 7560 } 7561 } else { // !OtherSigned 7562 // Check that the constant is representable in type OtherT. 7563 // Negative values are out of range. 7564 if (ConstantSigned) { 7565 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits()) 7566 return; 7567 } else { // !ConstantSigned 7568 if (OtherWidth >= Value.getActiveBits()) 7569 return; 7570 } 7571 } 7572 } else { // !CommonSigned 7573 if (OtherRange.NonNegative) { 7574 if (OtherWidth >= Value.getActiveBits()) 7575 return; 7576 } else { // OtherSigned 7577 assert(!ConstantSigned && 7578 "Two signed types converted to unsigned types."); 7579 // Check to see if the constant is representable in OtherT. 7580 if (OtherWidth > Value.getActiveBits()) 7581 return; 7582 // Check to see if the constant is equivalent to a negative value 7583 // cast to CommonT. 7584 if (S.Context.getIntWidth(ConstantT) == 7585 S.Context.getIntWidth(CommonT) && 7586 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth) 7587 return; 7588 // The constant value rests between values that OtherT can represent 7589 // after conversion. Relational comparison still works, but equality 7590 // comparisons will be tautological. 7591 EqualityOnly = true; 7592 } 7593 } 7594 7595 bool PositiveConstant = !ConstantSigned || Value.isNonNegative(); 7596 7597 if (op == BO_EQ || op == BO_NE) { 7598 IsTrue = op == BO_NE; 7599 } else if (EqualityOnly) { 7600 return; 7601 } else if (RhsConstant) { 7602 if (op == BO_GT || op == BO_GE) 7603 IsTrue = !PositiveConstant; 7604 else // op == BO_LT || op == BO_LE 7605 IsTrue = PositiveConstant; 7606 } else { 7607 if (op == BO_LT || op == BO_LE) 7608 IsTrue = !PositiveConstant; 7609 else // op == BO_GT || op == BO_GE 7610 IsTrue = PositiveConstant; 7611 } 7612 } else { 7613 // Other isKnownToHaveBooleanValue 7614 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn }; 7615 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal }; 7616 enum ConstantSide { Lhs, Rhs, SizeOfConstSides }; 7617 7618 static const struct LinkedConditions { 7619 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal]; 7620 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal]; 7621 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal]; 7622 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal]; 7623 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal]; 7624 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal]; 7625 7626 } TruthTable = { 7627 // Constant on LHS. | Constant on RHS. | 7628 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One| 7629 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } }, 7630 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } }, 7631 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } }, 7632 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } }, 7633 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } }, 7634 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } } 7635 }; 7636 7637 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant); 7638 7639 enum ConstantValue ConstVal = Zero; 7640 if (Value.isUnsigned() || Value.isNonNegative()) { 7641 if (Value == 0) { 7642 LiteralOrBoolConstant = 7643 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant; 7644 ConstVal = Zero; 7645 } else if (Value == 1) { 7646 LiteralOrBoolConstant = 7647 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant; 7648 ConstVal = One; 7649 } else { 7650 LiteralOrBoolConstant = LiteralConstant; 7651 ConstVal = GT_One; 7652 } 7653 } else { 7654 ConstVal = LT_Zero; 7655 } 7656 7657 CompareBoolWithConstantResult CmpRes; 7658 7659 switch (op) { 7660 case BO_LT: 7661 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal]; 7662 break; 7663 case BO_GT: 7664 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal]; 7665 break; 7666 case BO_LE: 7667 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal]; 7668 break; 7669 case BO_GE: 7670 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal]; 7671 break; 7672 case BO_EQ: 7673 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal]; 7674 break; 7675 case BO_NE: 7676 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal]; 7677 break; 7678 default: 7679 CmpRes = Unkwn; 7680 break; 7681 } 7682 7683 if (CmpRes == AFals) { 7684 IsTrue = false; 7685 } else if (CmpRes == ATrue) { 7686 IsTrue = true; 7687 } else { 7688 return; 7689 } 7690 } 7691 7692 // If this is a comparison to an enum constant, include that 7693 // constant in the diagnostic. 7694 const EnumConstantDecl *ED = nullptr; 7695 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 7696 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 7697 7698 SmallString<64> PrettySourceValue; 7699 llvm::raw_svector_ostream OS(PrettySourceValue); 7700 if (ED) 7701 OS << '\'' << *ED << "' (" << Value << ")"; 7702 else 7703 OS << Value; 7704 7705 S.DiagRuntimeBehavior( 7706 E->getOperatorLoc(), E, 7707 S.PDiag(diag::warn_out_of_range_compare) 7708 << OS.str() << LiteralOrBoolConstant 7709 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue 7710 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 7711 } 7712 7713 /// Analyze the operands of the given comparison. Implements the 7714 /// fallback case from AnalyzeComparison. 7715 void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 7716 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 7717 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 7718 } 7719 7720 /// \brief Implements -Wsign-compare. 7721 /// 7722 /// \param E the binary operator to check for warnings 7723 void AnalyzeComparison(Sema &S, BinaryOperator *E) { 7724 // The type the comparison is being performed in. 7725 QualType T = E->getLHS()->getType(); 7726 7727 // Only analyze comparison operators where both sides have been converted to 7728 // the same type. 7729 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 7730 return AnalyzeImpConvsInComparison(S, E); 7731 7732 // Don't analyze value-dependent comparisons directly. 7733 if (E->isValueDependent()) 7734 return AnalyzeImpConvsInComparison(S, E); 7735 7736 Expr *LHS = E->getLHS()->IgnoreParenImpCasts(); 7737 Expr *RHS = E->getRHS()->IgnoreParenImpCasts(); 7738 7739 bool IsComparisonConstant = false; 7740 7741 // Check whether an integer constant comparison results in a value 7742 // of 'true' or 'false'. 7743 if (T->isIntegralType(S.Context)) { 7744 llvm::APSInt RHSValue; 7745 bool IsRHSIntegralLiteral = 7746 RHS->isIntegerConstantExpr(RHSValue, S.Context); 7747 llvm::APSInt LHSValue; 7748 bool IsLHSIntegralLiteral = 7749 LHS->isIntegerConstantExpr(LHSValue, S.Context); 7750 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral) 7751 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true); 7752 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral) 7753 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false); 7754 else 7755 IsComparisonConstant = 7756 (IsRHSIntegralLiteral && IsLHSIntegralLiteral); 7757 } else if (!T->hasUnsignedIntegerRepresentation()) 7758 IsComparisonConstant = E->isIntegerConstantExpr(S.Context); 7759 7760 // We don't do anything special if this isn't an unsigned integral 7761 // comparison: we're only interested in integral comparisons, and 7762 // signed comparisons only happen in cases we don't care to warn about. 7763 // 7764 // We also don't care about value-dependent expressions or expressions 7765 // whose result is a constant. 7766 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant) 7767 return AnalyzeImpConvsInComparison(S, E); 7768 7769 // Check to see if one of the (unmodified) operands is of different 7770 // signedness. 7771 Expr *signedOperand, *unsignedOperand; 7772 if (LHS->getType()->hasSignedIntegerRepresentation()) { 7773 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 7774 "unsigned comparison between two signed integer expressions?"); 7775 signedOperand = LHS; 7776 unsignedOperand = RHS; 7777 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 7778 signedOperand = RHS; 7779 unsignedOperand = LHS; 7780 } else { 7781 CheckTrivialUnsignedComparison(S, E); 7782 return AnalyzeImpConvsInComparison(S, E); 7783 } 7784 7785 // Otherwise, calculate the effective range of the signed operand. 7786 IntRange signedRange = GetExprRange(S.Context, signedOperand); 7787 7788 // Go ahead and analyze implicit conversions in the operands. Note 7789 // that we skip the implicit conversions on both sides. 7790 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 7791 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 7792 7793 // If the signed range is non-negative, -Wsign-compare won't fire, 7794 // but we should still check for comparisons which are always true 7795 // or false. 7796 if (signedRange.NonNegative) 7797 return CheckTrivialUnsignedComparison(S, E); 7798 7799 // For (in)equality comparisons, if the unsigned operand is a 7800 // constant which cannot collide with a overflowed signed operand, 7801 // then reinterpreting the signed operand as unsigned will not 7802 // change the result of the comparison. 7803 if (E->isEqualityOp()) { 7804 unsigned comparisonWidth = S.Context.getIntWidth(T); 7805 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand); 7806 7807 // We should never be unable to prove that the unsigned operand is 7808 // non-negative. 7809 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 7810 7811 if (unsignedRange.Width < comparisonWidth) 7812 return; 7813 } 7814 7815 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 7816 S.PDiag(diag::warn_mixed_sign_comparison) 7817 << LHS->getType() << RHS->getType() 7818 << LHS->getSourceRange() << RHS->getSourceRange()); 7819 } 7820 7821 /// Analyzes an attempt to assign the given value to a bitfield. 7822 /// 7823 /// Returns true if there was something fishy about the attempt. 7824 bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 7825 SourceLocation InitLoc) { 7826 assert(Bitfield->isBitField()); 7827 if (Bitfield->isInvalidDecl()) 7828 return false; 7829 7830 // White-list bool bitfields. 7831 if (Bitfield->getType()->isBooleanType()) 7832 return false; 7833 7834 // Ignore value- or type-dependent expressions. 7835 if (Bitfield->getBitWidth()->isValueDependent() || 7836 Bitfield->getBitWidth()->isTypeDependent() || 7837 Init->isValueDependent() || 7838 Init->isTypeDependent()) 7839 return false; 7840 7841 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 7842 7843 llvm::APSInt Value; 7844 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) 7845 return false; 7846 7847 unsigned OriginalWidth = Value.getBitWidth(); 7848 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 7849 7850 if (Value.isSigned() && Value.isNegative()) 7851 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 7852 if (UO->getOpcode() == UO_Minus) 7853 if (isa<IntegerLiteral>(UO->getSubExpr())) 7854 OriginalWidth = Value.getMinSignedBits(); 7855 7856 if (OriginalWidth <= FieldWidth) 7857 return false; 7858 7859 // Compute the value which the bitfield will contain. 7860 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 7861 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType()); 7862 7863 // Check whether the stored value is equal to the original value. 7864 TruncatedValue = TruncatedValue.extend(OriginalWidth); 7865 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 7866 return false; 7867 7868 // Special-case bitfields of width 1: booleans are naturally 0/1, and 7869 // therefore don't strictly fit into a signed bitfield of width 1. 7870 if (FieldWidth == 1 && Value == 1) 7871 return false; 7872 7873 std::string PrettyValue = Value.toString(10); 7874 std::string PrettyTrunc = TruncatedValue.toString(10); 7875 7876 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 7877 << PrettyValue << PrettyTrunc << OriginalInit->getType() 7878 << Init->getSourceRange(); 7879 7880 return true; 7881 } 7882 7883 /// Analyze the given simple or compound assignment for warning-worthy 7884 /// operations. 7885 void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 7886 // Just recurse on the LHS. 7887 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 7888 7889 // We want to recurse on the RHS as normal unless we're assigning to 7890 // a bitfield. 7891 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 7892 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 7893 E->getOperatorLoc())) { 7894 // Recurse, ignoring any implicit conversions on the RHS. 7895 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 7896 E->getOperatorLoc()); 7897 } 7898 } 7899 7900 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 7901 } 7902 7903 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 7904 void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 7905 SourceLocation CContext, unsigned diag, 7906 bool pruneControlFlow = false) { 7907 if (pruneControlFlow) { 7908 S.DiagRuntimeBehavior(E->getExprLoc(), E, 7909 S.PDiag(diag) 7910 << SourceType << T << E->getSourceRange() 7911 << SourceRange(CContext)); 7912 return; 7913 } 7914 S.Diag(E->getExprLoc(), diag) 7915 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 7916 } 7917 7918 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 7919 void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext, 7920 unsigned diag, bool pruneControlFlow = false) { 7921 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 7922 } 7923 7924 7925 /// Diagnose an implicit cast from a floating point value to an integer value. 7926 void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 7927 7928 SourceLocation CContext) { 7929 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 7930 const bool PruneWarnings = !S.ActiveTemplateInstantiations.empty(); 7931 7932 Expr *InnerE = E->IgnoreParenImpCasts(); 7933 // We also want to warn on, e.g., "int i = -1.234" 7934 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 7935 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 7936 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 7937 7938 const bool IsLiteral = 7939 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 7940 7941 llvm::APFloat Value(0.0); 7942 bool IsConstant = 7943 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 7944 if (!IsConstant) { 7945 return DiagnoseImpCast(S, E, T, CContext, 7946 diag::warn_impcast_float_integer, PruneWarnings); 7947 } 7948 7949 bool isExact = false; 7950 7951 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 7952 T->hasUnsignedIntegerRepresentation()); 7953 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero, 7954 &isExact) == llvm::APFloat::opOK && 7955 isExact) { 7956 if (IsLiteral) return; 7957 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 7958 PruneWarnings); 7959 } 7960 7961 unsigned DiagID = 0; 7962 if (IsLiteral) { 7963 // Warn on floating point literal to integer. 7964 DiagID = diag::warn_impcast_literal_float_to_integer; 7965 } else if (IntegerValue == 0) { 7966 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 7967 return DiagnoseImpCast(S, E, T, CContext, 7968 diag::warn_impcast_float_integer, PruneWarnings); 7969 } 7970 // Warn on non-zero to zero conversion. 7971 DiagID = diag::warn_impcast_float_to_integer_zero; 7972 } else { 7973 if (IntegerValue.isUnsigned()) { 7974 if (!IntegerValue.isMaxValue()) { 7975 return DiagnoseImpCast(S, E, T, CContext, 7976 diag::warn_impcast_float_integer, PruneWarnings); 7977 } 7978 } else { // IntegerValue.isSigned() 7979 if (!IntegerValue.isMaxSignedValue() && 7980 !IntegerValue.isMinSignedValue()) { 7981 return DiagnoseImpCast(S, E, T, CContext, 7982 diag::warn_impcast_float_integer, PruneWarnings); 7983 } 7984 } 7985 // Warn on evaluatable floating point expression to integer conversion. 7986 DiagID = diag::warn_impcast_float_to_integer; 7987 } 7988 7989 // FIXME: Force the precision of the source value down so we don't print 7990 // digits which are usually useless (we don't really care here if we 7991 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 7992 // would automatically print the shortest representation, but it's a bit 7993 // tricky to implement. 7994 SmallString<16> PrettySourceValue; 7995 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 7996 precision = (precision * 59 + 195) / 196; 7997 Value.toString(PrettySourceValue, precision); 7998 7999 SmallString<16> PrettyTargetValue; 8000 if (IsBool) 8001 PrettyTargetValue = Value.isZero() ? "false" : "true"; 8002 else 8003 IntegerValue.toString(PrettyTargetValue); 8004 8005 if (PruneWarnings) { 8006 S.DiagRuntimeBehavior(E->getExprLoc(), E, 8007 S.PDiag(DiagID) 8008 << E->getType() << T.getUnqualifiedType() 8009 << PrettySourceValue << PrettyTargetValue 8010 << E->getSourceRange() << SourceRange(CContext)); 8011 } else { 8012 S.Diag(E->getExprLoc(), DiagID) 8013 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 8014 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 8015 } 8016 } 8017 8018 std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) { 8019 if (!Range.Width) return "0"; 8020 8021 llvm::APSInt ValueInRange = Value; 8022 ValueInRange.setIsSigned(!Range.NonNegative); 8023 ValueInRange = ValueInRange.trunc(Range.Width); 8024 return ValueInRange.toString(10); 8025 } 8026 8027 bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 8028 if (!isa<ImplicitCastExpr>(Ex)) 8029 return false; 8030 8031 Expr *InnerE = Ex->IgnoreParenImpCasts(); 8032 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 8033 const Type *Source = 8034 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 8035 if (Target->isDependentType()) 8036 return false; 8037 8038 const BuiltinType *FloatCandidateBT = 8039 dyn_cast<BuiltinType>(ToBool ? Source : Target); 8040 const Type *BoolCandidateType = ToBool ? Target : Source; 8041 8042 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 8043 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 8044 } 8045 8046 void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 8047 SourceLocation CC) { 8048 unsigned NumArgs = TheCall->getNumArgs(); 8049 for (unsigned i = 0; i < NumArgs; ++i) { 8050 Expr *CurrA = TheCall->getArg(i); 8051 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 8052 continue; 8053 8054 bool IsSwapped = ((i > 0) && 8055 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 8056 IsSwapped |= ((i < (NumArgs - 1)) && 8057 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 8058 if (IsSwapped) { 8059 // Warn on this floating-point to bool conversion. 8060 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 8061 CurrA->getType(), CC, 8062 diag::warn_impcast_floating_point_to_bool); 8063 } 8064 } 8065 } 8066 8067 void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) { 8068 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 8069 E->getExprLoc())) 8070 return; 8071 8072 // Don't warn on functions which have return type nullptr_t. 8073 if (isa<CallExpr>(E)) 8074 return; 8075 8076 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 8077 const Expr::NullPointerConstantKind NullKind = 8078 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 8079 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 8080 return; 8081 8082 // Return if target type is a safe conversion. 8083 if (T->isAnyPointerType() || T->isBlockPointerType() || 8084 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 8085 return; 8086 8087 SourceLocation Loc = E->getSourceRange().getBegin(); 8088 8089 // Venture through the macro stacks to get to the source of macro arguments. 8090 // The new location is a better location than the complete location that was 8091 // passed in. 8092 while (S.SourceMgr.isMacroArgExpansion(Loc)) 8093 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc); 8094 8095 while (S.SourceMgr.isMacroArgExpansion(CC)) 8096 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC); 8097 8098 // __null is usually wrapped in a macro. Go up a macro if that is the case. 8099 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 8100 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 8101 Loc, S.SourceMgr, S.getLangOpts()); 8102 if (MacroName == "NULL") 8103 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first; 8104 } 8105 8106 // Only warn if the null and context location are in the same macro expansion. 8107 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 8108 return; 8109 8110 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 8111 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC) 8112 << FixItHint::CreateReplacement(Loc, 8113 S.getFixItZeroLiteralForType(T, Loc)); 8114 } 8115 8116 void checkObjCArrayLiteral(Sema &S, QualType TargetType, 8117 ObjCArrayLiteral *ArrayLiteral); 8118 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 8119 ObjCDictionaryLiteral *DictionaryLiteral); 8120 8121 /// Check a single element within a collection literal against the 8122 /// target element type. 8123 void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType, 8124 Expr *Element, unsigned ElementKind) { 8125 // Skip a bitcast to 'id' or qualified 'id'. 8126 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 8127 if (ICE->getCastKind() == CK_BitCast && 8128 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 8129 Element = ICE->getSubExpr(); 8130 } 8131 8132 QualType ElementType = Element->getType(); 8133 ExprResult ElementResult(Element); 8134 if (ElementType->getAs<ObjCObjectPointerType>() && 8135 S.CheckSingleAssignmentConstraints(TargetElementType, 8136 ElementResult, 8137 false, false) 8138 != Sema::Compatible) { 8139 S.Diag(Element->getLocStart(), 8140 diag::warn_objc_collection_literal_element) 8141 << ElementType << ElementKind << TargetElementType 8142 << Element->getSourceRange(); 8143 } 8144 8145 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 8146 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 8147 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 8148 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 8149 } 8150 8151 /// Check an Objective-C array literal being converted to the given 8152 /// target type. 8153 void checkObjCArrayLiteral(Sema &S, QualType TargetType, 8154 ObjCArrayLiteral *ArrayLiteral) { 8155 if (!S.NSArrayDecl) 8156 return; 8157 8158 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 8159 if (!TargetObjCPtr) 8160 return; 8161 8162 if (TargetObjCPtr->isUnspecialized() || 8163 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 8164 != S.NSArrayDecl->getCanonicalDecl()) 8165 return; 8166 8167 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 8168 if (TypeArgs.size() != 1) 8169 return; 8170 8171 QualType TargetElementType = TypeArgs[0]; 8172 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 8173 checkObjCCollectionLiteralElement(S, TargetElementType, 8174 ArrayLiteral->getElement(I), 8175 0); 8176 } 8177 } 8178 8179 /// Check an Objective-C dictionary literal being converted to the given 8180 /// target type. 8181 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 8182 ObjCDictionaryLiteral *DictionaryLiteral) { 8183 if (!S.NSDictionaryDecl) 8184 return; 8185 8186 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 8187 if (!TargetObjCPtr) 8188 return; 8189 8190 if (TargetObjCPtr->isUnspecialized() || 8191 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 8192 != S.NSDictionaryDecl->getCanonicalDecl()) 8193 return; 8194 8195 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 8196 if (TypeArgs.size() != 2) 8197 return; 8198 8199 QualType TargetKeyType = TypeArgs[0]; 8200 QualType TargetObjectType = TypeArgs[1]; 8201 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 8202 auto Element = DictionaryLiteral->getKeyValueElement(I); 8203 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 8204 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 8205 } 8206 } 8207 8208 // Helper function to filter out cases for constant width constant conversion. 8209 // Don't warn on char array initialization or for non-decimal values. 8210 bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 8211 SourceLocation CC) { 8212 // If initializing from a constant, and the constant starts with '0', 8213 // then it is a binary, octal, or hexadecimal. Allow these constants 8214 // to fill all the bits, even if there is a sign change. 8215 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 8216 const char FirstLiteralCharacter = 8217 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0]; 8218 if (FirstLiteralCharacter == '0') 8219 return false; 8220 } 8221 8222 // If the CC location points to a '{', and the type is char, then assume 8223 // assume it is an array initialization. 8224 if (CC.isValid() && T->isCharType()) { 8225 const char FirstContextCharacter = 8226 S.getSourceManager().getCharacterData(CC)[0]; 8227 if (FirstContextCharacter == '{') 8228 return false; 8229 } 8230 8231 return true; 8232 } 8233 8234 void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 8235 SourceLocation CC, bool *ICContext = nullptr) { 8236 if (E->isTypeDependent() || E->isValueDependent()) return; 8237 8238 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 8239 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 8240 if (Source == Target) return; 8241 if (Target->isDependentType()) return; 8242 8243 // If the conversion context location is invalid don't complain. We also 8244 // don't want to emit a warning if the issue occurs from the expansion of 8245 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 8246 // delay this check as long as possible. Once we detect we are in that 8247 // scenario, we just return. 8248 if (CC.isInvalid()) 8249 return; 8250 8251 // Diagnose implicit casts to bool. 8252 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 8253 if (isa<StringLiteral>(E)) 8254 // Warn on string literal to bool. Checks for string literals in logical 8255 // and expressions, for instance, assert(0 && "error here"), are 8256 // prevented by a check in AnalyzeImplicitConversions(). 8257 return DiagnoseImpCast(S, E, T, CC, 8258 diag::warn_impcast_string_literal_to_bool); 8259 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 8260 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 8261 // This covers the literal expressions that evaluate to Objective-C 8262 // objects. 8263 return DiagnoseImpCast(S, E, T, CC, 8264 diag::warn_impcast_objective_c_literal_to_bool); 8265 } 8266 if (Source->isPointerType() || Source->canDecayToPointerType()) { 8267 // Warn on pointer to bool conversion that is always true. 8268 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 8269 SourceRange(CC)); 8270 } 8271 } 8272 8273 // Check implicit casts from Objective-C collection literals to specialized 8274 // collection types, e.g., NSArray<NSString *> *. 8275 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 8276 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 8277 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 8278 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 8279 8280 // Strip vector types. 8281 if (isa<VectorType>(Source)) { 8282 if (!isa<VectorType>(Target)) { 8283 if (S.SourceMgr.isInSystemMacro(CC)) 8284 return; 8285 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 8286 } 8287 8288 // If the vector cast is cast between two vectors of the same size, it is 8289 // a bitcast, not a conversion. 8290 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 8291 return; 8292 8293 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 8294 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 8295 } 8296 if (auto VecTy = dyn_cast<VectorType>(Target)) 8297 Target = VecTy->getElementType().getTypePtr(); 8298 8299 // Strip complex types. 8300 if (isa<ComplexType>(Source)) { 8301 if (!isa<ComplexType>(Target)) { 8302 if (S.SourceMgr.isInSystemMacro(CC)) 8303 return; 8304 8305 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar); 8306 } 8307 8308 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 8309 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 8310 } 8311 8312 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 8313 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 8314 8315 // If the source is floating point... 8316 if (SourceBT && SourceBT->isFloatingPoint()) { 8317 // ...and the target is floating point... 8318 if (TargetBT && TargetBT->isFloatingPoint()) { 8319 // ...then warn if we're dropping FP rank. 8320 8321 // Builtin FP kinds are ordered by increasing FP rank. 8322 if (SourceBT->getKind() > TargetBT->getKind()) { 8323 // Don't warn about float constants that are precisely 8324 // representable in the target type. 8325 Expr::EvalResult result; 8326 if (E->EvaluateAsRValue(result, S.Context)) { 8327 // Value might be a float, a float vector, or a float complex. 8328 if (IsSameFloatAfterCast(result.Val, 8329 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 8330 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 8331 return; 8332 } 8333 8334 if (S.SourceMgr.isInSystemMacro(CC)) 8335 return; 8336 8337 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 8338 } 8339 // ... or possibly if we're increasing rank, too 8340 else if (TargetBT->getKind() > SourceBT->getKind()) { 8341 if (S.SourceMgr.isInSystemMacro(CC)) 8342 return; 8343 8344 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 8345 } 8346 return; 8347 } 8348 8349 // If the target is integral, always warn. 8350 if (TargetBT && TargetBT->isInteger()) { 8351 if (S.SourceMgr.isInSystemMacro(CC)) 8352 return; 8353 8354 DiagnoseFloatingImpCast(S, E, T, CC); 8355 } 8356 8357 // Detect the case where a call result is converted from floating-point to 8358 // to bool, and the final argument to the call is converted from bool, to 8359 // discover this typo: 8360 // 8361 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 8362 // 8363 // FIXME: This is an incredibly special case; is there some more general 8364 // way to detect this class of misplaced-parentheses bug? 8365 if (Target->isBooleanType() && isa<CallExpr>(E)) { 8366 // Check last argument of function call to see if it is an 8367 // implicit cast from a type matching the type the result 8368 // is being cast to. 8369 CallExpr *CEx = cast<CallExpr>(E); 8370 if (unsigned NumArgs = CEx->getNumArgs()) { 8371 Expr *LastA = CEx->getArg(NumArgs - 1); 8372 Expr *InnerE = LastA->IgnoreParenImpCasts(); 8373 if (isa<ImplicitCastExpr>(LastA) && 8374 InnerE->getType()->isBooleanType()) { 8375 // Warn on this floating-point to bool conversion 8376 DiagnoseImpCast(S, E, T, CC, 8377 diag::warn_impcast_floating_point_to_bool); 8378 } 8379 } 8380 } 8381 return; 8382 } 8383 8384 DiagnoseNullConversion(S, E, T, CC); 8385 8386 S.DiscardMisalignedMemberAddress(Target, E); 8387 8388 if (!Source->isIntegerType() || !Target->isIntegerType()) 8389 return; 8390 8391 // TODO: remove this early return once the false positives for constant->bool 8392 // in templates, macros, etc, are reduced or removed. 8393 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 8394 return; 8395 8396 IntRange SourceRange = GetExprRange(S.Context, E); 8397 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 8398 8399 if (SourceRange.Width > TargetRange.Width) { 8400 // If the source is a constant, use a default-on diagnostic. 8401 // TODO: this should happen for bitfield stores, too. 8402 llvm::APSInt Value(32); 8403 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) { 8404 if (S.SourceMgr.isInSystemMacro(CC)) 8405 return; 8406 8407 std::string PrettySourceValue = Value.toString(10); 8408 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 8409 8410 S.DiagRuntimeBehavior(E->getExprLoc(), E, 8411 S.PDiag(diag::warn_impcast_integer_precision_constant) 8412 << PrettySourceValue << PrettyTargetValue 8413 << E->getType() << T << E->getSourceRange() 8414 << clang::SourceRange(CC)); 8415 return; 8416 } 8417 8418 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 8419 if (S.SourceMgr.isInSystemMacro(CC)) 8420 return; 8421 8422 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 8423 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 8424 /* pruneControlFlow */ true); 8425 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 8426 } 8427 8428 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative && 8429 SourceRange.NonNegative && Source->isSignedIntegerType()) { 8430 // Warn when doing a signed to signed conversion, warn if the positive 8431 // source value is exactly the width of the target type, which will 8432 // cause a negative value to be stored. 8433 8434 llvm::APSInt Value; 8435 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) && 8436 !S.SourceMgr.isInSystemMacro(CC)) { 8437 if (isSameWidthConstantConversion(S, E, T, CC)) { 8438 std::string PrettySourceValue = Value.toString(10); 8439 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 8440 8441 S.DiagRuntimeBehavior( 8442 E->getExprLoc(), E, 8443 S.PDiag(diag::warn_impcast_integer_precision_constant) 8444 << PrettySourceValue << PrettyTargetValue << E->getType() << T 8445 << E->getSourceRange() << clang::SourceRange(CC)); 8446 return; 8447 } 8448 } 8449 8450 // Fall through for non-constants to give a sign conversion warning. 8451 } 8452 8453 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 8454 (!TargetRange.NonNegative && SourceRange.NonNegative && 8455 SourceRange.Width == TargetRange.Width)) { 8456 if (S.SourceMgr.isInSystemMacro(CC)) 8457 return; 8458 8459 unsigned DiagID = diag::warn_impcast_integer_sign; 8460 8461 // Traditionally, gcc has warned about this under -Wsign-compare. 8462 // We also want to warn about it in -Wconversion. 8463 // So if -Wconversion is off, use a completely identical diagnostic 8464 // in the sign-compare group. 8465 // The conditional-checking code will 8466 if (ICContext) { 8467 DiagID = diag::warn_impcast_integer_sign_conditional; 8468 *ICContext = true; 8469 } 8470 8471 return DiagnoseImpCast(S, E, T, CC, DiagID); 8472 } 8473 8474 // Diagnose conversions between different enumeration types. 8475 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 8476 // type, to give us better diagnostics. 8477 QualType SourceType = E->getType(); 8478 if (!S.getLangOpts().CPlusPlus) { 8479 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 8480 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 8481 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 8482 SourceType = S.Context.getTypeDeclType(Enum); 8483 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 8484 } 8485 } 8486 8487 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 8488 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 8489 if (SourceEnum->getDecl()->hasNameForLinkage() && 8490 TargetEnum->getDecl()->hasNameForLinkage() && 8491 SourceEnum != TargetEnum) { 8492 if (S.SourceMgr.isInSystemMacro(CC)) 8493 return; 8494 8495 return DiagnoseImpCast(S, E, SourceType, T, CC, 8496 diag::warn_impcast_different_enum_types); 8497 } 8498 } 8499 8500 void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 8501 SourceLocation CC, QualType T); 8502 8503 void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 8504 SourceLocation CC, bool &ICContext) { 8505 E = E->IgnoreParenImpCasts(); 8506 8507 if (isa<ConditionalOperator>(E)) 8508 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T); 8509 8510 AnalyzeImplicitConversions(S, E, CC); 8511 if (E->getType() != T) 8512 return CheckImplicitConversion(S, E, T, CC, &ICContext); 8513 } 8514 8515 void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 8516 SourceLocation CC, QualType T) { 8517 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 8518 8519 bool Suspicious = false; 8520 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 8521 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 8522 8523 // If -Wconversion would have warned about either of the candidates 8524 // for a signedness conversion to the context type... 8525 if (!Suspicious) return; 8526 8527 // ...but it's currently ignored... 8528 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 8529 return; 8530 8531 // ...then check whether it would have warned about either of the 8532 // candidates for a signedness conversion to the condition type. 8533 if (E->getType() == T) return; 8534 8535 Suspicious = false; 8536 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 8537 E->getType(), CC, &Suspicious); 8538 if (!Suspicious) 8539 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 8540 E->getType(), CC, &Suspicious); 8541 } 8542 8543 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 8544 /// Input argument E is a logical expression. 8545 void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 8546 if (S.getLangOpts().Bool) 8547 return; 8548 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 8549 } 8550 8551 /// AnalyzeImplicitConversions - Find and report any interesting 8552 /// implicit conversions in the given expression. There are a couple 8553 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 8554 void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) { 8555 QualType T = OrigE->getType(); 8556 Expr *E = OrigE->IgnoreParenImpCasts(); 8557 8558 if (E->isTypeDependent() || E->isValueDependent()) 8559 return; 8560 8561 // For conditional operators, we analyze the arguments as if they 8562 // were being fed directly into the output. 8563 if (isa<ConditionalOperator>(E)) { 8564 ConditionalOperator *CO = cast<ConditionalOperator>(E); 8565 CheckConditionalOperator(S, CO, CC, T); 8566 return; 8567 } 8568 8569 // Check implicit argument conversions for function calls. 8570 if (CallExpr *Call = dyn_cast<CallExpr>(E)) 8571 CheckImplicitArgumentConversions(S, Call, CC); 8572 8573 // Go ahead and check any implicit conversions we might have skipped. 8574 // The non-canonical typecheck is just an optimization; 8575 // CheckImplicitConversion will filter out dead implicit conversions. 8576 if (E->getType() != T) 8577 CheckImplicitConversion(S, E, T, CC); 8578 8579 // Now continue drilling into this expression. 8580 8581 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 8582 // The bound subexpressions in a PseudoObjectExpr are not reachable 8583 // as transitive children. 8584 // FIXME: Use a more uniform representation for this. 8585 for (auto *SE : POE->semantics()) 8586 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 8587 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC); 8588 } 8589 8590 // Skip past explicit casts. 8591 if (isa<ExplicitCastExpr>(E)) { 8592 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts(); 8593 return AnalyzeImplicitConversions(S, E, CC); 8594 } 8595 8596 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 8597 // Do a somewhat different check with comparison operators. 8598 if (BO->isComparisonOp()) 8599 return AnalyzeComparison(S, BO); 8600 8601 // And with simple assignments. 8602 if (BO->getOpcode() == BO_Assign) 8603 return AnalyzeAssignment(S, BO); 8604 } 8605 8606 // These break the otherwise-useful invariant below. Fortunately, 8607 // we don't really need to recurse into them, because any internal 8608 // expressions should have been analyzed already when they were 8609 // built into statements. 8610 if (isa<StmtExpr>(E)) return; 8611 8612 // Don't descend into unevaluated contexts. 8613 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 8614 8615 // Now just recurse over the expression's children. 8616 CC = E->getExprLoc(); 8617 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 8618 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 8619 for (Stmt *SubStmt : E->children()) { 8620 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 8621 if (!ChildExpr) 8622 continue; 8623 8624 if (IsLogicalAndOperator && 8625 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 8626 // Ignore checking string literals that are in logical and operators. 8627 // This is a common pattern for asserts. 8628 continue; 8629 AnalyzeImplicitConversions(S, ChildExpr, CC); 8630 } 8631 8632 if (BO && BO->isLogicalOp()) { 8633 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 8634 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 8635 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 8636 8637 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 8638 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 8639 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 8640 } 8641 8642 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) 8643 if (U->getOpcode() == UO_LNot) 8644 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 8645 } 8646 8647 } // end anonymous namespace 8648 8649 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 8650 unsigned Start, unsigned End) { 8651 bool IllegalParams = false; 8652 for (unsigned I = Start; I <= End; ++I) { 8653 QualType Ty = TheCall->getArg(I)->getType(); 8654 // Taking into account implicit conversions, 8655 // allow any integer within 32 bits range 8656 if (!Ty->isIntegerType() || 8657 S.Context.getTypeSizeInChars(Ty).getQuantity() > 4) { 8658 S.Diag(TheCall->getArg(I)->getLocStart(), 8659 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 8660 IllegalParams = true; 8661 } 8662 // Potentially emit standard warnings for implicit conversions if enabled 8663 // using -Wconversion. 8664 CheckImplicitConversion(S, TheCall->getArg(I), S.Context.UnsignedIntTy, 8665 TheCall->getArg(I)->getLocStart()); 8666 } 8667 return IllegalParams; 8668 } 8669 8670 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 8671 // Returns true when emitting a warning about taking the address of a reference. 8672 static bool CheckForReference(Sema &SemaRef, const Expr *E, 8673 const PartialDiagnostic &PD) { 8674 E = E->IgnoreParenImpCasts(); 8675 8676 const FunctionDecl *FD = nullptr; 8677 8678 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 8679 if (!DRE->getDecl()->getType()->isReferenceType()) 8680 return false; 8681 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 8682 if (!M->getMemberDecl()->getType()->isReferenceType()) 8683 return false; 8684 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 8685 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 8686 return false; 8687 FD = Call->getDirectCallee(); 8688 } else { 8689 return false; 8690 } 8691 8692 SemaRef.Diag(E->getExprLoc(), PD); 8693 8694 // If possible, point to location of function. 8695 if (FD) { 8696 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 8697 } 8698 8699 return true; 8700 } 8701 8702 // Returns true if the SourceLocation is expanded from any macro body. 8703 // Returns false if the SourceLocation is invalid, is from not in a macro 8704 // expansion, or is from expanded from a top-level macro argument. 8705 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 8706 if (Loc.isInvalid()) 8707 return false; 8708 8709 while (Loc.isMacroID()) { 8710 if (SM.isMacroBodyExpansion(Loc)) 8711 return true; 8712 Loc = SM.getImmediateMacroCallerLoc(Loc); 8713 } 8714 8715 return false; 8716 } 8717 8718 /// \brief Diagnose pointers that are always non-null. 8719 /// \param E the expression containing the pointer 8720 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 8721 /// compared to a null pointer 8722 /// \param IsEqual True when the comparison is equal to a null pointer 8723 /// \param Range Extra SourceRange to highlight in the diagnostic 8724 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 8725 Expr::NullPointerConstantKind NullKind, 8726 bool IsEqual, SourceRange Range) { 8727 if (!E) 8728 return; 8729 8730 // Don't warn inside macros. 8731 if (E->getExprLoc().isMacroID()) { 8732 const SourceManager &SM = getSourceManager(); 8733 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 8734 IsInAnyMacroBody(SM, Range.getBegin())) 8735 return; 8736 } 8737 E = E->IgnoreImpCasts(); 8738 8739 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 8740 8741 if (isa<CXXThisExpr>(E)) { 8742 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 8743 : diag::warn_this_bool_conversion; 8744 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 8745 return; 8746 } 8747 8748 bool IsAddressOf = false; 8749 8750 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 8751 if (UO->getOpcode() != UO_AddrOf) 8752 return; 8753 IsAddressOf = true; 8754 E = UO->getSubExpr(); 8755 } 8756 8757 if (IsAddressOf) { 8758 unsigned DiagID = IsCompare 8759 ? diag::warn_address_of_reference_null_compare 8760 : diag::warn_address_of_reference_bool_conversion; 8761 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 8762 << IsEqual; 8763 if (CheckForReference(*this, E, PD)) { 8764 return; 8765 } 8766 } 8767 8768 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 8769 bool IsParam = isa<NonNullAttr>(NonnullAttr); 8770 std::string Str; 8771 llvm::raw_string_ostream S(Str); 8772 E->printPretty(S, nullptr, getPrintingPolicy()); 8773 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 8774 : diag::warn_cast_nonnull_to_bool; 8775 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 8776 << E->getSourceRange() << Range << IsEqual; 8777 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 8778 }; 8779 8780 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 8781 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 8782 if (auto *Callee = Call->getDirectCallee()) { 8783 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 8784 ComplainAboutNonnullParamOrCall(A); 8785 return; 8786 } 8787 } 8788 } 8789 8790 // Expect to find a single Decl. Skip anything more complicated. 8791 ValueDecl *D = nullptr; 8792 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 8793 D = R->getDecl(); 8794 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 8795 D = M->getMemberDecl(); 8796 } 8797 8798 // Weak Decls can be null. 8799 if (!D || D->isWeak()) 8800 return; 8801 8802 // Check for parameter decl with nonnull attribute 8803 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 8804 if (getCurFunction() && 8805 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 8806 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 8807 ComplainAboutNonnullParamOrCall(A); 8808 return; 8809 } 8810 8811 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 8812 auto ParamIter = llvm::find(FD->parameters(), PV); 8813 assert(ParamIter != FD->param_end()); 8814 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 8815 8816 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 8817 if (!NonNull->args_size()) { 8818 ComplainAboutNonnullParamOrCall(NonNull); 8819 return; 8820 } 8821 8822 for (unsigned ArgNo : NonNull->args()) { 8823 if (ArgNo == ParamNo) { 8824 ComplainAboutNonnullParamOrCall(NonNull); 8825 return; 8826 } 8827 } 8828 } 8829 } 8830 } 8831 } 8832 8833 QualType T = D->getType(); 8834 const bool IsArray = T->isArrayType(); 8835 const bool IsFunction = T->isFunctionType(); 8836 8837 // Address of function is used to silence the function warning. 8838 if (IsAddressOf && IsFunction) { 8839 return; 8840 } 8841 8842 // Found nothing. 8843 if (!IsAddressOf && !IsFunction && !IsArray) 8844 return; 8845 8846 // Pretty print the expression for the diagnostic. 8847 std::string Str; 8848 llvm::raw_string_ostream S(Str); 8849 E->printPretty(S, nullptr, getPrintingPolicy()); 8850 8851 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 8852 : diag::warn_impcast_pointer_to_bool; 8853 enum { 8854 AddressOf, 8855 FunctionPointer, 8856 ArrayPointer 8857 } DiagType; 8858 if (IsAddressOf) 8859 DiagType = AddressOf; 8860 else if (IsFunction) 8861 DiagType = FunctionPointer; 8862 else if (IsArray) 8863 DiagType = ArrayPointer; 8864 else 8865 llvm_unreachable("Could not determine diagnostic."); 8866 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 8867 << Range << IsEqual; 8868 8869 if (!IsFunction) 8870 return; 8871 8872 // Suggest '&' to silence the function warning. 8873 Diag(E->getExprLoc(), diag::note_function_warning_silence) 8874 << FixItHint::CreateInsertion(E->getLocStart(), "&"); 8875 8876 // Check to see if '()' fixit should be emitted. 8877 QualType ReturnType; 8878 UnresolvedSet<4> NonTemplateOverloads; 8879 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 8880 if (ReturnType.isNull()) 8881 return; 8882 8883 if (IsCompare) { 8884 // There are two cases here. If there is null constant, the only suggest 8885 // for a pointer return type. If the null is 0, then suggest if the return 8886 // type is a pointer or an integer type. 8887 if (!ReturnType->isPointerType()) { 8888 if (NullKind == Expr::NPCK_ZeroExpression || 8889 NullKind == Expr::NPCK_ZeroLiteral) { 8890 if (!ReturnType->isIntegerType()) 8891 return; 8892 } else { 8893 return; 8894 } 8895 } 8896 } else { // !IsCompare 8897 // For function to bool, only suggest if the function pointer has bool 8898 // return type. 8899 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 8900 return; 8901 } 8902 Diag(E->getExprLoc(), diag::note_function_to_function_call) 8903 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()"); 8904 } 8905 8906 /// Diagnoses "dangerous" implicit conversions within the given 8907 /// expression (which is a full expression). Implements -Wconversion 8908 /// and -Wsign-compare. 8909 /// 8910 /// \param CC the "context" location of the implicit conversion, i.e. 8911 /// the most location of the syntactic entity requiring the implicit 8912 /// conversion 8913 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 8914 // Don't diagnose in unevaluated contexts. 8915 if (isUnevaluatedContext()) 8916 return; 8917 8918 // Don't diagnose for value- or type-dependent expressions. 8919 if (E->isTypeDependent() || E->isValueDependent()) 8920 return; 8921 8922 // Check for array bounds violations in cases where the check isn't triggered 8923 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 8924 // ArraySubscriptExpr is on the RHS of a variable initialization. 8925 CheckArrayAccess(E); 8926 8927 // This is not the right CC for (e.g.) a variable initialization. 8928 AnalyzeImplicitConversions(*this, E, CC); 8929 } 8930 8931 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 8932 /// Input argument E is a logical expression. 8933 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 8934 ::CheckBoolLikeConversion(*this, E, CC); 8935 } 8936 8937 /// Diagnose when expression is an integer constant expression and its evaluation 8938 /// results in integer overflow 8939 void Sema::CheckForIntOverflow (Expr *E) { 8940 // Use a work list to deal with nested struct initializers. 8941 SmallVector<Expr *, 2> Exprs(1, E); 8942 8943 do { 8944 Expr *E = Exprs.pop_back_val(); 8945 8946 if (isa<BinaryOperator>(E->IgnoreParenCasts())) { 8947 E->IgnoreParenCasts()->EvaluateForOverflow(Context); 8948 continue; 8949 } 8950 8951 if (auto InitList = dyn_cast<InitListExpr>(E)) 8952 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 8953 } while (!Exprs.empty()); 8954 } 8955 8956 namespace { 8957 /// \brief Visitor for expressions which looks for unsequenced operations on the 8958 /// same object. 8959 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> { 8960 typedef EvaluatedExprVisitor<SequenceChecker> Base; 8961 8962 /// \brief A tree of sequenced regions within an expression. Two regions are 8963 /// unsequenced if one is an ancestor or a descendent of the other. When we 8964 /// finish processing an expression with sequencing, such as a comma 8965 /// expression, we fold its tree nodes into its parent, since they are 8966 /// unsequenced with respect to nodes we will visit later. 8967 class SequenceTree { 8968 struct Value { 8969 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 8970 unsigned Parent : 31; 8971 unsigned Merged : 1; 8972 }; 8973 SmallVector<Value, 8> Values; 8974 8975 public: 8976 /// \brief A region within an expression which may be sequenced with respect 8977 /// to some other region. 8978 class Seq { 8979 explicit Seq(unsigned N) : Index(N) {} 8980 unsigned Index; 8981 friend class SequenceTree; 8982 public: 8983 Seq() : Index(0) {} 8984 }; 8985 8986 SequenceTree() { Values.push_back(Value(0)); } 8987 Seq root() const { return Seq(0); } 8988 8989 /// \brief Create a new sequence of operations, which is an unsequenced 8990 /// subset of \p Parent. This sequence of operations is sequenced with 8991 /// respect to other children of \p Parent. 8992 Seq allocate(Seq Parent) { 8993 Values.push_back(Value(Parent.Index)); 8994 return Seq(Values.size() - 1); 8995 } 8996 8997 /// \brief Merge a sequence of operations into its parent. 8998 void merge(Seq S) { 8999 Values[S.Index].Merged = true; 9000 } 9001 9002 /// \brief Determine whether two operations are unsequenced. This operation 9003 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 9004 /// should have been merged into its parent as appropriate. 9005 bool isUnsequenced(Seq Cur, Seq Old) { 9006 unsigned C = representative(Cur.Index); 9007 unsigned Target = representative(Old.Index); 9008 while (C >= Target) { 9009 if (C == Target) 9010 return true; 9011 C = Values[C].Parent; 9012 } 9013 return false; 9014 } 9015 9016 private: 9017 /// \brief Pick a representative for a sequence. 9018 unsigned representative(unsigned K) { 9019 if (Values[K].Merged) 9020 // Perform path compression as we go. 9021 return Values[K].Parent = representative(Values[K].Parent); 9022 return K; 9023 } 9024 }; 9025 9026 /// An object for which we can track unsequenced uses. 9027 typedef NamedDecl *Object; 9028 9029 /// Different flavors of object usage which we track. We only track the 9030 /// least-sequenced usage of each kind. 9031 enum UsageKind { 9032 /// A read of an object. Multiple unsequenced reads are OK. 9033 UK_Use, 9034 /// A modification of an object which is sequenced before the value 9035 /// computation of the expression, such as ++n in C++. 9036 UK_ModAsValue, 9037 /// A modification of an object which is not sequenced before the value 9038 /// computation of the expression, such as n++. 9039 UK_ModAsSideEffect, 9040 9041 UK_Count = UK_ModAsSideEffect + 1 9042 }; 9043 9044 struct Usage { 9045 Usage() : Use(nullptr), Seq() {} 9046 Expr *Use; 9047 SequenceTree::Seq Seq; 9048 }; 9049 9050 struct UsageInfo { 9051 UsageInfo() : Diagnosed(false) {} 9052 Usage Uses[UK_Count]; 9053 /// Have we issued a diagnostic for this variable already? 9054 bool Diagnosed; 9055 }; 9056 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap; 9057 9058 Sema &SemaRef; 9059 /// Sequenced regions within the expression. 9060 SequenceTree Tree; 9061 /// Declaration modifications and references which we have seen. 9062 UsageInfoMap UsageMap; 9063 /// The region we are currently within. 9064 SequenceTree::Seq Region; 9065 /// Filled in with declarations which were modified as a side-effect 9066 /// (that is, post-increment operations). 9067 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect; 9068 /// Expressions to check later. We defer checking these to reduce 9069 /// stack usage. 9070 SmallVectorImpl<Expr *> &WorkList; 9071 9072 /// RAII object wrapping the visitation of a sequenced subexpression of an 9073 /// expression. At the end of this process, the side-effects of the evaluation 9074 /// become sequenced with respect to the value computation of the result, so 9075 /// we downgrade any UK_ModAsSideEffect within the evaluation to 9076 /// UK_ModAsValue. 9077 struct SequencedSubexpression { 9078 SequencedSubexpression(SequenceChecker &Self) 9079 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 9080 Self.ModAsSideEffect = &ModAsSideEffect; 9081 } 9082 ~SequencedSubexpression() { 9083 for (auto &M : llvm::reverse(ModAsSideEffect)) { 9084 UsageInfo &U = Self.UsageMap[M.first]; 9085 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect]; 9086 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue); 9087 SideEffectUsage = M.second; 9088 } 9089 Self.ModAsSideEffect = OldModAsSideEffect; 9090 } 9091 9092 SequenceChecker &Self; 9093 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 9094 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect; 9095 }; 9096 9097 /// RAII object wrapping the visitation of a subexpression which we might 9098 /// choose to evaluate as a constant. If any subexpression is evaluated and 9099 /// found to be non-constant, this allows us to suppress the evaluation of 9100 /// the outer expression. 9101 class EvaluationTracker { 9102 public: 9103 EvaluationTracker(SequenceChecker &Self) 9104 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) { 9105 Self.EvalTracker = this; 9106 } 9107 ~EvaluationTracker() { 9108 Self.EvalTracker = Prev; 9109 if (Prev) 9110 Prev->EvalOK &= EvalOK; 9111 } 9112 9113 bool evaluate(const Expr *E, bool &Result) { 9114 if (!EvalOK || E->isValueDependent()) 9115 return false; 9116 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context); 9117 return EvalOK; 9118 } 9119 9120 private: 9121 SequenceChecker &Self; 9122 EvaluationTracker *Prev; 9123 bool EvalOK; 9124 } *EvalTracker; 9125 9126 /// \brief Find the object which is produced by the specified expression, 9127 /// if any. 9128 Object getObject(Expr *E, bool Mod) const { 9129 E = E->IgnoreParenCasts(); 9130 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 9131 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 9132 return getObject(UO->getSubExpr(), Mod); 9133 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 9134 if (BO->getOpcode() == BO_Comma) 9135 return getObject(BO->getRHS(), Mod); 9136 if (Mod && BO->isAssignmentOp()) 9137 return getObject(BO->getLHS(), Mod); 9138 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 9139 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 9140 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 9141 return ME->getMemberDecl(); 9142 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 9143 // FIXME: If this is a reference, map through to its value. 9144 return DRE->getDecl(); 9145 return nullptr; 9146 } 9147 9148 /// \brief Note that an object was modified or used by an expression. 9149 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) { 9150 Usage &U = UI.Uses[UK]; 9151 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) { 9152 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 9153 ModAsSideEffect->push_back(std::make_pair(O, U)); 9154 U.Use = Ref; 9155 U.Seq = Region; 9156 } 9157 } 9158 /// \brief Check whether a modification or use conflicts with a prior usage. 9159 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind, 9160 bool IsModMod) { 9161 if (UI.Diagnosed) 9162 return; 9163 9164 const Usage &U = UI.Uses[OtherKind]; 9165 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) 9166 return; 9167 9168 Expr *Mod = U.Use; 9169 Expr *ModOrUse = Ref; 9170 if (OtherKind == UK_Use) 9171 std::swap(Mod, ModOrUse); 9172 9173 SemaRef.Diag(Mod->getExprLoc(), 9174 IsModMod ? diag::warn_unsequenced_mod_mod 9175 : diag::warn_unsequenced_mod_use) 9176 << O << SourceRange(ModOrUse->getExprLoc()); 9177 UI.Diagnosed = true; 9178 } 9179 9180 void notePreUse(Object O, Expr *Use) { 9181 UsageInfo &U = UsageMap[O]; 9182 // Uses conflict with other modifications. 9183 checkUsage(O, U, Use, UK_ModAsValue, false); 9184 } 9185 void notePostUse(Object O, Expr *Use) { 9186 UsageInfo &U = UsageMap[O]; 9187 checkUsage(O, U, Use, UK_ModAsSideEffect, false); 9188 addUsage(U, O, Use, UK_Use); 9189 } 9190 9191 void notePreMod(Object O, Expr *Mod) { 9192 UsageInfo &U = UsageMap[O]; 9193 // Modifications conflict with other modifications and with uses. 9194 checkUsage(O, U, Mod, UK_ModAsValue, true); 9195 checkUsage(O, U, Mod, UK_Use, false); 9196 } 9197 void notePostMod(Object O, Expr *Use, UsageKind UK) { 9198 UsageInfo &U = UsageMap[O]; 9199 checkUsage(O, U, Use, UK_ModAsSideEffect, true); 9200 addUsage(U, O, Use, UK); 9201 } 9202 9203 public: 9204 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList) 9205 : Base(S.Context), SemaRef(S), Region(Tree.root()), 9206 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) { 9207 Visit(E); 9208 } 9209 9210 void VisitStmt(Stmt *S) { 9211 // Skip all statements which aren't expressions for now. 9212 } 9213 9214 void VisitExpr(Expr *E) { 9215 // By default, just recurse to evaluated subexpressions. 9216 Base::VisitStmt(E); 9217 } 9218 9219 void VisitCastExpr(CastExpr *E) { 9220 Object O = Object(); 9221 if (E->getCastKind() == CK_LValueToRValue) 9222 O = getObject(E->getSubExpr(), false); 9223 9224 if (O) 9225 notePreUse(O, E); 9226 VisitExpr(E); 9227 if (O) 9228 notePostUse(O, E); 9229 } 9230 9231 void VisitBinComma(BinaryOperator *BO) { 9232 // C++11 [expr.comma]p1: 9233 // Every value computation and side effect associated with the left 9234 // expression is sequenced before every value computation and side 9235 // effect associated with the right expression. 9236 SequenceTree::Seq LHS = Tree.allocate(Region); 9237 SequenceTree::Seq RHS = Tree.allocate(Region); 9238 SequenceTree::Seq OldRegion = Region; 9239 9240 { 9241 SequencedSubexpression SeqLHS(*this); 9242 Region = LHS; 9243 Visit(BO->getLHS()); 9244 } 9245 9246 Region = RHS; 9247 Visit(BO->getRHS()); 9248 9249 Region = OldRegion; 9250 9251 // Forget that LHS and RHS are sequenced. They are both unsequenced 9252 // with respect to other stuff. 9253 Tree.merge(LHS); 9254 Tree.merge(RHS); 9255 } 9256 9257 void VisitBinAssign(BinaryOperator *BO) { 9258 // The modification is sequenced after the value computation of the LHS 9259 // and RHS, so check it before inspecting the operands and update the 9260 // map afterwards. 9261 Object O = getObject(BO->getLHS(), true); 9262 if (!O) 9263 return VisitExpr(BO); 9264 9265 notePreMod(O, BO); 9266 9267 // C++11 [expr.ass]p7: 9268 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated 9269 // only once. 9270 // 9271 // Therefore, for a compound assignment operator, O is considered used 9272 // everywhere except within the evaluation of E1 itself. 9273 if (isa<CompoundAssignOperator>(BO)) 9274 notePreUse(O, BO); 9275 9276 Visit(BO->getLHS()); 9277 9278 if (isa<CompoundAssignOperator>(BO)) 9279 notePostUse(O, BO); 9280 9281 Visit(BO->getRHS()); 9282 9283 // C++11 [expr.ass]p1: 9284 // the assignment is sequenced [...] before the value computation of the 9285 // assignment expression. 9286 // C11 6.5.16/3 has no such rule. 9287 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 9288 : UK_ModAsSideEffect); 9289 } 9290 9291 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) { 9292 VisitBinAssign(CAO); 9293 } 9294 9295 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 9296 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 9297 void VisitUnaryPreIncDec(UnaryOperator *UO) { 9298 Object O = getObject(UO->getSubExpr(), true); 9299 if (!O) 9300 return VisitExpr(UO); 9301 9302 notePreMod(O, UO); 9303 Visit(UO->getSubExpr()); 9304 // C++11 [expr.pre.incr]p1: 9305 // the expression ++x is equivalent to x+=1 9306 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 9307 : UK_ModAsSideEffect); 9308 } 9309 9310 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 9311 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 9312 void VisitUnaryPostIncDec(UnaryOperator *UO) { 9313 Object O = getObject(UO->getSubExpr(), true); 9314 if (!O) 9315 return VisitExpr(UO); 9316 9317 notePreMod(O, UO); 9318 Visit(UO->getSubExpr()); 9319 notePostMod(O, UO, UK_ModAsSideEffect); 9320 } 9321 9322 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated. 9323 void VisitBinLOr(BinaryOperator *BO) { 9324 // The side-effects of the LHS of an '&&' are sequenced before the 9325 // value computation of the RHS, and hence before the value computation 9326 // of the '&&' itself, unless the LHS evaluates to zero. We treat them 9327 // as if they were unconditionally sequenced. 9328 EvaluationTracker Eval(*this); 9329 { 9330 SequencedSubexpression Sequenced(*this); 9331 Visit(BO->getLHS()); 9332 } 9333 9334 bool Result; 9335 if (Eval.evaluate(BO->getLHS(), Result)) { 9336 if (!Result) 9337 Visit(BO->getRHS()); 9338 } else { 9339 // Check for unsequenced operations in the RHS, treating it as an 9340 // entirely separate evaluation. 9341 // 9342 // FIXME: If there are operations in the RHS which are unsequenced 9343 // with respect to operations outside the RHS, and those operations 9344 // are unconditionally evaluated, diagnose them. 9345 WorkList.push_back(BO->getRHS()); 9346 } 9347 } 9348 void VisitBinLAnd(BinaryOperator *BO) { 9349 EvaluationTracker Eval(*this); 9350 { 9351 SequencedSubexpression Sequenced(*this); 9352 Visit(BO->getLHS()); 9353 } 9354 9355 bool Result; 9356 if (Eval.evaluate(BO->getLHS(), Result)) { 9357 if (Result) 9358 Visit(BO->getRHS()); 9359 } else { 9360 WorkList.push_back(BO->getRHS()); 9361 } 9362 } 9363 9364 // Only visit the condition, unless we can be sure which subexpression will 9365 // be chosen. 9366 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) { 9367 EvaluationTracker Eval(*this); 9368 { 9369 SequencedSubexpression Sequenced(*this); 9370 Visit(CO->getCond()); 9371 } 9372 9373 bool Result; 9374 if (Eval.evaluate(CO->getCond(), Result)) 9375 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr()); 9376 else { 9377 WorkList.push_back(CO->getTrueExpr()); 9378 WorkList.push_back(CO->getFalseExpr()); 9379 } 9380 } 9381 9382 void VisitCallExpr(CallExpr *CE) { 9383 // C++11 [intro.execution]p15: 9384 // When calling a function [...], every value computation and side effect 9385 // associated with any argument expression, or with the postfix expression 9386 // designating the called function, is sequenced before execution of every 9387 // expression or statement in the body of the function [and thus before 9388 // the value computation of its result]. 9389 SequencedSubexpression Sequenced(*this); 9390 Base::VisitCallExpr(CE); 9391 9392 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 9393 } 9394 9395 void VisitCXXConstructExpr(CXXConstructExpr *CCE) { 9396 // This is a call, so all subexpressions are sequenced before the result. 9397 SequencedSubexpression Sequenced(*this); 9398 9399 if (!CCE->isListInitialization()) 9400 return VisitExpr(CCE); 9401 9402 // In C++11, list initializations are sequenced. 9403 SmallVector<SequenceTree::Seq, 32> Elts; 9404 SequenceTree::Seq Parent = Region; 9405 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(), 9406 E = CCE->arg_end(); 9407 I != E; ++I) { 9408 Region = Tree.allocate(Parent); 9409 Elts.push_back(Region); 9410 Visit(*I); 9411 } 9412 9413 // Forget that the initializers are sequenced. 9414 Region = Parent; 9415 for (unsigned I = 0; I < Elts.size(); ++I) 9416 Tree.merge(Elts[I]); 9417 } 9418 9419 void VisitInitListExpr(InitListExpr *ILE) { 9420 if (!SemaRef.getLangOpts().CPlusPlus11) 9421 return VisitExpr(ILE); 9422 9423 // In C++11, list initializations are sequenced. 9424 SmallVector<SequenceTree::Seq, 32> Elts; 9425 SequenceTree::Seq Parent = Region; 9426 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 9427 Expr *E = ILE->getInit(I); 9428 if (!E) continue; 9429 Region = Tree.allocate(Parent); 9430 Elts.push_back(Region); 9431 Visit(E); 9432 } 9433 9434 // Forget that the initializers are sequenced. 9435 Region = Parent; 9436 for (unsigned I = 0; I < Elts.size(); ++I) 9437 Tree.merge(Elts[I]); 9438 } 9439 }; 9440 } // end anonymous namespace 9441 9442 void Sema::CheckUnsequencedOperations(Expr *E) { 9443 SmallVector<Expr *, 8> WorkList; 9444 WorkList.push_back(E); 9445 while (!WorkList.empty()) { 9446 Expr *Item = WorkList.pop_back_val(); 9447 SequenceChecker(*this, Item, WorkList); 9448 } 9449 } 9450 9451 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 9452 bool IsConstexpr) { 9453 CheckImplicitConversions(E, CheckLoc); 9454 if (!E->isInstantiationDependent()) 9455 CheckUnsequencedOperations(E); 9456 if (!IsConstexpr && !E->isValueDependent()) 9457 CheckForIntOverflow(E); 9458 DiagnoseMisalignedMembers(); 9459 } 9460 9461 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 9462 FieldDecl *BitField, 9463 Expr *Init) { 9464 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 9465 } 9466 9467 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 9468 SourceLocation Loc) { 9469 if (!PType->isVariablyModifiedType()) 9470 return; 9471 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 9472 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 9473 return; 9474 } 9475 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 9476 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 9477 return; 9478 } 9479 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 9480 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 9481 return; 9482 } 9483 9484 const ArrayType *AT = S.Context.getAsArrayType(PType); 9485 if (!AT) 9486 return; 9487 9488 if (AT->getSizeModifier() != ArrayType::Star) { 9489 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 9490 return; 9491 } 9492 9493 S.Diag(Loc, diag::err_array_star_in_function_definition); 9494 } 9495 9496 /// CheckParmsForFunctionDef - Check that the parameters of the given 9497 /// function are appropriate for the definition of a function. This 9498 /// takes care of any checks that cannot be performed on the 9499 /// declaration itself, e.g., that the types of each of the function 9500 /// parameters are complete. 9501 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 9502 bool CheckParameterNames) { 9503 bool HasInvalidParm = false; 9504 for (ParmVarDecl *Param : Parameters) { 9505 // C99 6.7.5.3p4: the parameters in a parameter type list in a 9506 // function declarator that is part of a function definition of 9507 // that function shall not have incomplete type. 9508 // 9509 // This is also C++ [dcl.fct]p6. 9510 if (!Param->isInvalidDecl() && 9511 RequireCompleteType(Param->getLocation(), Param->getType(), 9512 diag::err_typecheck_decl_incomplete_type)) { 9513 Param->setInvalidDecl(); 9514 HasInvalidParm = true; 9515 } 9516 9517 // C99 6.9.1p5: If the declarator includes a parameter type list, the 9518 // declaration of each parameter shall include an identifier. 9519 if (CheckParameterNames && 9520 Param->getIdentifier() == nullptr && 9521 !Param->isImplicit() && 9522 !getLangOpts().CPlusPlus) 9523 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 9524 9525 // C99 6.7.5.3p12: 9526 // If the function declarator is not part of a definition of that 9527 // function, parameters may have incomplete type and may use the [*] 9528 // notation in their sequences of declarator specifiers to specify 9529 // variable length array types. 9530 QualType PType = Param->getOriginalType(); 9531 // FIXME: This diagnostic should point the '[*]' if source-location 9532 // information is added for it. 9533 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 9534 9535 // MSVC destroys objects passed by value in the callee. Therefore a 9536 // function definition which takes such a parameter must be able to call the 9537 // object's destructor. However, we don't perform any direct access check 9538 // on the dtor. 9539 if (getLangOpts().CPlusPlus && Context.getTargetInfo() 9540 .getCXXABI() 9541 .areArgsDestroyedLeftToRightInCallee()) { 9542 if (!Param->isInvalidDecl()) { 9543 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) { 9544 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 9545 if (!ClassDecl->isInvalidDecl() && 9546 !ClassDecl->hasIrrelevantDestructor() && 9547 !ClassDecl->isDependentContext()) { 9548 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 9549 MarkFunctionReferenced(Param->getLocation(), Destructor); 9550 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 9551 } 9552 } 9553 } 9554 } 9555 9556 // Parameters with the pass_object_size attribute only need to be marked 9557 // constant at function definitions. Because we lack information about 9558 // whether we're on a declaration or definition when we're instantiating the 9559 // attribute, we need to check for constness here. 9560 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 9561 if (!Param->getType().isConstQualified()) 9562 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 9563 << Attr->getSpelling() << 1; 9564 } 9565 9566 return HasInvalidParm; 9567 } 9568 9569 /// CheckCastAlign - Implements -Wcast-align, which warns when a 9570 /// pointer cast increases the alignment requirements. 9571 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 9572 // This is actually a lot of work to potentially be doing on every 9573 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 9574 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 9575 return; 9576 9577 // Ignore dependent types. 9578 if (T->isDependentType() || Op->getType()->isDependentType()) 9579 return; 9580 9581 // Require that the destination be a pointer type. 9582 const PointerType *DestPtr = T->getAs<PointerType>(); 9583 if (!DestPtr) return; 9584 9585 // If the destination has alignment 1, we're done. 9586 QualType DestPointee = DestPtr->getPointeeType(); 9587 if (DestPointee->isIncompleteType()) return; 9588 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 9589 if (DestAlign.isOne()) return; 9590 9591 // Require that the source be a pointer type. 9592 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 9593 if (!SrcPtr) return; 9594 QualType SrcPointee = SrcPtr->getPointeeType(); 9595 9596 // Whitelist casts from cv void*. We already implicitly 9597 // whitelisted casts to cv void*, since they have alignment 1. 9598 // Also whitelist casts involving incomplete types, which implicitly 9599 // includes 'void'. 9600 if (SrcPointee->isIncompleteType()) return; 9601 9602 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee); 9603 if (SrcAlign >= DestAlign) return; 9604 9605 Diag(TRange.getBegin(), diag::warn_cast_align) 9606 << Op->getType() << T 9607 << static_cast<unsigned>(SrcAlign.getQuantity()) 9608 << static_cast<unsigned>(DestAlign.getQuantity()) 9609 << TRange << Op->getSourceRange(); 9610 } 9611 9612 /// \brief Check whether this array fits the idiom of a size-one tail padded 9613 /// array member of a struct. 9614 /// 9615 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 9616 /// commonly used to emulate flexible arrays in C89 code. 9617 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 9618 const NamedDecl *ND) { 9619 if (Size != 1 || !ND) return false; 9620 9621 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 9622 if (!FD) return false; 9623 9624 // Don't consider sizes resulting from macro expansions or template argument 9625 // substitution to form C89 tail-padded arrays. 9626 9627 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 9628 while (TInfo) { 9629 TypeLoc TL = TInfo->getTypeLoc(); 9630 // Look through typedefs. 9631 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 9632 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 9633 TInfo = TDL->getTypeSourceInfo(); 9634 continue; 9635 } 9636 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 9637 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 9638 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 9639 return false; 9640 } 9641 break; 9642 } 9643 9644 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 9645 if (!RD) return false; 9646 if (RD->isUnion()) return false; 9647 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 9648 if (!CRD->isStandardLayout()) return false; 9649 } 9650 9651 // See if this is the last field decl in the record. 9652 const Decl *D = FD; 9653 while ((D = D->getNextDeclInContext())) 9654 if (isa<FieldDecl>(D)) 9655 return false; 9656 return true; 9657 } 9658 9659 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 9660 const ArraySubscriptExpr *ASE, 9661 bool AllowOnePastEnd, bool IndexNegated) { 9662 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 9663 if (IndexExpr->isValueDependent()) 9664 return; 9665 9666 const Type *EffectiveType = 9667 BaseExpr->getType()->getPointeeOrArrayElementType(); 9668 BaseExpr = BaseExpr->IgnoreParenCasts(); 9669 const ConstantArrayType *ArrayTy = 9670 Context.getAsConstantArrayType(BaseExpr->getType()); 9671 if (!ArrayTy) 9672 return; 9673 9674 llvm::APSInt index; 9675 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects)) 9676 return; 9677 if (IndexNegated) 9678 index = -index; 9679 9680 const NamedDecl *ND = nullptr; 9681 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 9682 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 9683 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 9684 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 9685 9686 if (index.isUnsigned() || !index.isNegative()) { 9687 llvm::APInt size = ArrayTy->getSize(); 9688 if (!size.isStrictlyPositive()) 9689 return; 9690 9691 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType(); 9692 if (BaseType != EffectiveType) { 9693 // Make sure we're comparing apples to apples when comparing index to size 9694 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 9695 uint64_t array_typesize = Context.getTypeSize(BaseType); 9696 // Handle ptrarith_typesize being zero, such as when casting to void* 9697 if (!ptrarith_typesize) ptrarith_typesize = 1; 9698 if (ptrarith_typesize != array_typesize) { 9699 // There's a cast to a different size type involved 9700 uint64_t ratio = array_typesize / ptrarith_typesize; 9701 // TODO: Be smarter about handling cases where array_typesize is not a 9702 // multiple of ptrarith_typesize 9703 if (ptrarith_typesize * ratio == array_typesize) 9704 size *= llvm::APInt(size.getBitWidth(), ratio); 9705 } 9706 } 9707 9708 if (size.getBitWidth() > index.getBitWidth()) 9709 index = index.zext(size.getBitWidth()); 9710 else if (size.getBitWidth() < index.getBitWidth()) 9711 size = size.zext(index.getBitWidth()); 9712 9713 // For array subscripting the index must be less than size, but for pointer 9714 // arithmetic also allow the index (offset) to be equal to size since 9715 // computing the next address after the end of the array is legal and 9716 // commonly done e.g. in C++ iterators and range-based for loops. 9717 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 9718 return; 9719 9720 // Also don't warn for arrays of size 1 which are members of some 9721 // structure. These are often used to approximate flexible arrays in C89 9722 // code. 9723 if (IsTailPaddedMemberArray(*this, size, ND)) 9724 return; 9725 9726 // Suppress the warning if the subscript expression (as identified by the 9727 // ']' location) and the index expression are both from macro expansions 9728 // within a system header. 9729 if (ASE) { 9730 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 9731 ASE->getRBracketLoc()); 9732 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 9733 SourceLocation IndexLoc = SourceMgr.getSpellingLoc( 9734 IndexExpr->getLocStart()); 9735 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 9736 return; 9737 } 9738 } 9739 9740 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 9741 if (ASE) 9742 DiagID = diag::warn_array_index_exceeds_bounds; 9743 9744 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 9745 PDiag(DiagID) << index.toString(10, true) 9746 << size.toString(10, true) 9747 << (unsigned)size.getLimitedValue(~0U) 9748 << IndexExpr->getSourceRange()); 9749 } else { 9750 unsigned DiagID = diag::warn_array_index_precedes_bounds; 9751 if (!ASE) { 9752 DiagID = diag::warn_ptr_arith_precedes_bounds; 9753 if (index.isNegative()) index = -index; 9754 } 9755 9756 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 9757 PDiag(DiagID) << index.toString(10, true) 9758 << IndexExpr->getSourceRange()); 9759 } 9760 9761 if (!ND) { 9762 // Try harder to find a NamedDecl to point at in the note. 9763 while (const ArraySubscriptExpr *ASE = 9764 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 9765 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 9766 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 9767 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 9768 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 9769 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 9770 } 9771 9772 if (ND) 9773 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr, 9774 PDiag(diag::note_array_index_out_of_bounds) 9775 << ND->getDeclName()); 9776 } 9777 9778 void Sema::CheckArrayAccess(const Expr *expr) { 9779 int AllowOnePastEnd = 0; 9780 while (expr) { 9781 expr = expr->IgnoreParenImpCasts(); 9782 switch (expr->getStmtClass()) { 9783 case Stmt::ArraySubscriptExprClass: { 9784 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 9785 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 9786 AllowOnePastEnd > 0); 9787 return; 9788 } 9789 case Stmt::OMPArraySectionExprClass: { 9790 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 9791 if (ASE->getLowerBound()) 9792 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 9793 /*ASE=*/nullptr, AllowOnePastEnd > 0); 9794 return; 9795 } 9796 case Stmt::UnaryOperatorClass: { 9797 // Only unwrap the * and & unary operators 9798 const UnaryOperator *UO = cast<UnaryOperator>(expr); 9799 expr = UO->getSubExpr(); 9800 switch (UO->getOpcode()) { 9801 case UO_AddrOf: 9802 AllowOnePastEnd++; 9803 break; 9804 case UO_Deref: 9805 AllowOnePastEnd--; 9806 break; 9807 default: 9808 return; 9809 } 9810 break; 9811 } 9812 case Stmt::ConditionalOperatorClass: { 9813 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 9814 if (const Expr *lhs = cond->getLHS()) 9815 CheckArrayAccess(lhs); 9816 if (const Expr *rhs = cond->getRHS()) 9817 CheckArrayAccess(rhs); 9818 return; 9819 } 9820 default: 9821 return; 9822 } 9823 } 9824 } 9825 9826 //===--- CHECK: Objective-C retain cycles ----------------------------------// 9827 9828 namespace { 9829 struct RetainCycleOwner { 9830 RetainCycleOwner() : Variable(nullptr), Indirect(false) {} 9831 VarDecl *Variable; 9832 SourceRange Range; 9833 SourceLocation Loc; 9834 bool Indirect; 9835 9836 void setLocsFrom(Expr *e) { 9837 Loc = e->getExprLoc(); 9838 Range = e->getSourceRange(); 9839 } 9840 }; 9841 } // end anonymous namespace 9842 9843 /// Consider whether capturing the given variable can possibly lead to 9844 /// a retain cycle. 9845 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 9846 // In ARC, it's captured strongly iff the variable has __strong 9847 // lifetime. In MRR, it's captured strongly if the variable is 9848 // __block and has an appropriate type. 9849 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 9850 return false; 9851 9852 owner.Variable = var; 9853 if (ref) 9854 owner.setLocsFrom(ref); 9855 return true; 9856 } 9857 9858 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 9859 while (true) { 9860 e = e->IgnoreParens(); 9861 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 9862 switch (cast->getCastKind()) { 9863 case CK_BitCast: 9864 case CK_LValueBitCast: 9865 case CK_LValueToRValue: 9866 case CK_ARCReclaimReturnedObject: 9867 e = cast->getSubExpr(); 9868 continue; 9869 9870 default: 9871 return false; 9872 } 9873 } 9874 9875 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 9876 ObjCIvarDecl *ivar = ref->getDecl(); 9877 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 9878 return false; 9879 9880 // Try to find a retain cycle in the base. 9881 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 9882 return false; 9883 9884 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 9885 owner.Indirect = true; 9886 return true; 9887 } 9888 9889 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 9890 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 9891 if (!var) return false; 9892 return considerVariable(var, ref, owner); 9893 } 9894 9895 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 9896 if (member->isArrow()) return false; 9897 9898 // Don't count this as an indirect ownership. 9899 e = member->getBase(); 9900 continue; 9901 } 9902 9903 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 9904 // Only pay attention to pseudo-objects on property references. 9905 ObjCPropertyRefExpr *pre 9906 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 9907 ->IgnoreParens()); 9908 if (!pre) return false; 9909 if (pre->isImplicitProperty()) return false; 9910 ObjCPropertyDecl *property = pre->getExplicitProperty(); 9911 if (!property->isRetaining() && 9912 !(property->getPropertyIvarDecl() && 9913 property->getPropertyIvarDecl()->getType() 9914 .getObjCLifetime() == Qualifiers::OCL_Strong)) 9915 return false; 9916 9917 owner.Indirect = true; 9918 if (pre->isSuperReceiver()) { 9919 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 9920 if (!owner.Variable) 9921 return false; 9922 owner.Loc = pre->getLocation(); 9923 owner.Range = pre->getSourceRange(); 9924 return true; 9925 } 9926 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 9927 ->getSourceExpr()); 9928 continue; 9929 } 9930 9931 // Array ivars? 9932 9933 return false; 9934 } 9935 } 9936 9937 namespace { 9938 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 9939 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 9940 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 9941 Context(Context), Variable(variable), Capturer(nullptr), 9942 VarWillBeReased(false) {} 9943 ASTContext &Context; 9944 VarDecl *Variable; 9945 Expr *Capturer; 9946 bool VarWillBeReased; 9947 9948 void VisitDeclRefExpr(DeclRefExpr *ref) { 9949 if (ref->getDecl() == Variable && !Capturer) 9950 Capturer = ref; 9951 } 9952 9953 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 9954 if (Capturer) return; 9955 Visit(ref->getBase()); 9956 if (Capturer && ref->isFreeIvar()) 9957 Capturer = ref; 9958 } 9959 9960 void VisitBlockExpr(BlockExpr *block) { 9961 // Look inside nested blocks 9962 if (block->getBlockDecl()->capturesVariable(Variable)) 9963 Visit(block->getBlockDecl()->getBody()); 9964 } 9965 9966 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 9967 if (Capturer) return; 9968 if (OVE->getSourceExpr()) 9969 Visit(OVE->getSourceExpr()); 9970 } 9971 void VisitBinaryOperator(BinaryOperator *BinOp) { 9972 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 9973 return; 9974 Expr *LHS = BinOp->getLHS(); 9975 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 9976 if (DRE->getDecl() != Variable) 9977 return; 9978 if (Expr *RHS = BinOp->getRHS()) { 9979 RHS = RHS->IgnoreParenCasts(); 9980 llvm::APSInt Value; 9981 VarWillBeReased = 9982 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0); 9983 } 9984 } 9985 } 9986 }; 9987 } // end anonymous namespace 9988 9989 /// Check whether the given argument is a block which captures a 9990 /// variable. 9991 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 9992 assert(owner.Variable && owner.Loc.isValid()); 9993 9994 e = e->IgnoreParenCasts(); 9995 9996 // Look through [^{...} copy] and Block_copy(^{...}). 9997 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 9998 Selector Cmd = ME->getSelector(); 9999 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 10000 e = ME->getInstanceReceiver(); 10001 if (!e) 10002 return nullptr; 10003 e = e->IgnoreParenCasts(); 10004 } 10005 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 10006 if (CE->getNumArgs() == 1) { 10007 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 10008 if (Fn) { 10009 const IdentifierInfo *FnI = Fn->getIdentifier(); 10010 if (FnI && FnI->isStr("_Block_copy")) { 10011 e = CE->getArg(0)->IgnoreParenCasts(); 10012 } 10013 } 10014 } 10015 } 10016 10017 BlockExpr *block = dyn_cast<BlockExpr>(e); 10018 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 10019 return nullptr; 10020 10021 FindCaptureVisitor visitor(S.Context, owner.Variable); 10022 visitor.Visit(block->getBlockDecl()->getBody()); 10023 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 10024 } 10025 10026 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 10027 RetainCycleOwner &owner) { 10028 assert(capturer); 10029 assert(owner.Variable && owner.Loc.isValid()); 10030 10031 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 10032 << owner.Variable << capturer->getSourceRange(); 10033 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 10034 << owner.Indirect << owner.Range; 10035 } 10036 10037 /// Check for a keyword selector that starts with the word 'add' or 10038 /// 'set'. 10039 static bool isSetterLikeSelector(Selector sel) { 10040 if (sel.isUnarySelector()) return false; 10041 10042 StringRef str = sel.getNameForSlot(0); 10043 while (!str.empty() && str.front() == '_') str = str.substr(1); 10044 if (str.startswith("set")) 10045 str = str.substr(3); 10046 else if (str.startswith("add")) { 10047 // Specially whitelist 'addOperationWithBlock:'. 10048 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 10049 return false; 10050 str = str.substr(3); 10051 } 10052 else 10053 return false; 10054 10055 if (str.empty()) return true; 10056 return !isLowercase(str.front()); 10057 } 10058 10059 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 10060 ObjCMessageExpr *Message) { 10061 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 10062 Message->getReceiverInterface(), 10063 NSAPI::ClassId_NSMutableArray); 10064 if (!IsMutableArray) { 10065 return None; 10066 } 10067 10068 Selector Sel = Message->getSelector(); 10069 10070 Optional<NSAPI::NSArrayMethodKind> MKOpt = 10071 S.NSAPIObj->getNSArrayMethodKind(Sel); 10072 if (!MKOpt) { 10073 return None; 10074 } 10075 10076 NSAPI::NSArrayMethodKind MK = *MKOpt; 10077 10078 switch (MK) { 10079 case NSAPI::NSMutableArr_addObject: 10080 case NSAPI::NSMutableArr_insertObjectAtIndex: 10081 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 10082 return 0; 10083 case NSAPI::NSMutableArr_replaceObjectAtIndex: 10084 return 1; 10085 10086 default: 10087 return None; 10088 } 10089 10090 return None; 10091 } 10092 10093 static 10094 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 10095 ObjCMessageExpr *Message) { 10096 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 10097 Message->getReceiverInterface(), 10098 NSAPI::ClassId_NSMutableDictionary); 10099 if (!IsMutableDictionary) { 10100 return None; 10101 } 10102 10103 Selector Sel = Message->getSelector(); 10104 10105 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 10106 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 10107 if (!MKOpt) { 10108 return None; 10109 } 10110 10111 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 10112 10113 switch (MK) { 10114 case NSAPI::NSMutableDict_setObjectForKey: 10115 case NSAPI::NSMutableDict_setValueForKey: 10116 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 10117 return 0; 10118 10119 default: 10120 return None; 10121 } 10122 10123 return None; 10124 } 10125 10126 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 10127 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 10128 Message->getReceiverInterface(), 10129 NSAPI::ClassId_NSMutableSet); 10130 10131 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 10132 Message->getReceiverInterface(), 10133 NSAPI::ClassId_NSMutableOrderedSet); 10134 if (!IsMutableSet && !IsMutableOrderedSet) { 10135 return None; 10136 } 10137 10138 Selector Sel = Message->getSelector(); 10139 10140 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 10141 if (!MKOpt) { 10142 return None; 10143 } 10144 10145 NSAPI::NSSetMethodKind MK = *MKOpt; 10146 10147 switch (MK) { 10148 case NSAPI::NSMutableSet_addObject: 10149 case NSAPI::NSOrderedSet_setObjectAtIndex: 10150 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 10151 case NSAPI::NSOrderedSet_insertObjectAtIndex: 10152 return 0; 10153 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 10154 return 1; 10155 } 10156 10157 return None; 10158 } 10159 10160 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 10161 if (!Message->isInstanceMessage()) { 10162 return; 10163 } 10164 10165 Optional<int> ArgOpt; 10166 10167 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 10168 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 10169 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 10170 return; 10171 } 10172 10173 int ArgIndex = *ArgOpt; 10174 10175 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 10176 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 10177 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 10178 } 10179 10180 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 10181 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 10182 if (ArgRE->isObjCSelfExpr()) { 10183 Diag(Message->getSourceRange().getBegin(), 10184 diag::warn_objc_circular_container) 10185 << ArgRE->getDecl()->getName() << StringRef("super"); 10186 } 10187 } 10188 } else { 10189 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 10190 10191 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 10192 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 10193 } 10194 10195 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 10196 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 10197 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 10198 ValueDecl *Decl = ReceiverRE->getDecl(); 10199 Diag(Message->getSourceRange().getBegin(), 10200 diag::warn_objc_circular_container) 10201 << Decl->getName() << Decl->getName(); 10202 if (!ArgRE->isObjCSelfExpr()) { 10203 Diag(Decl->getLocation(), 10204 diag::note_objc_circular_container_declared_here) 10205 << Decl->getName(); 10206 } 10207 } 10208 } 10209 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 10210 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 10211 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 10212 ObjCIvarDecl *Decl = IvarRE->getDecl(); 10213 Diag(Message->getSourceRange().getBegin(), 10214 diag::warn_objc_circular_container) 10215 << Decl->getName() << Decl->getName(); 10216 Diag(Decl->getLocation(), 10217 diag::note_objc_circular_container_declared_here) 10218 << Decl->getName(); 10219 } 10220 } 10221 } 10222 } 10223 } 10224 10225 /// Check a message send to see if it's likely to cause a retain cycle. 10226 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 10227 // Only check instance methods whose selector looks like a setter. 10228 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 10229 return; 10230 10231 // Try to find a variable that the receiver is strongly owned by. 10232 RetainCycleOwner owner; 10233 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 10234 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 10235 return; 10236 } else { 10237 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 10238 owner.Variable = getCurMethodDecl()->getSelfDecl(); 10239 owner.Loc = msg->getSuperLoc(); 10240 owner.Range = msg->getSuperLoc(); 10241 } 10242 10243 // Check whether the receiver is captured by any of the arguments. 10244 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) 10245 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) 10246 return diagnoseRetainCycle(*this, capturer, owner); 10247 } 10248 10249 /// Check a property assign to see if it's likely to cause a retain cycle. 10250 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 10251 RetainCycleOwner owner; 10252 if (!findRetainCycleOwner(*this, receiver, owner)) 10253 return; 10254 10255 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 10256 diagnoseRetainCycle(*this, capturer, owner); 10257 } 10258 10259 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 10260 RetainCycleOwner Owner; 10261 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 10262 return; 10263 10264 // Because we don't have an expression for the variable, we have to set the 10265 // location explicitly here. 10266 Owner.Loc = Var->getLocation(); 10267 Owner.Range = Var->getSourceRange(); 10268 10269 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 10270 diagnoseRetainCycle(*this, Capturer, Owner); 10271 } 10272 10273 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 10274 Expr *RHS, bool isProperty) { 10275 // Check if RHS is an Objective-C object literal, which also can get 10276 // immediately zapped in a weak reference. Note that we explicitly 10277 // allow ObjCStringLiterals, since those are designed to never really die. 10278 RHS = RHS->IgnoreParenImpCasts(); 10279 10280 // This enum needs to match with the 'select' in 10281 // warn_objc_arc_literal_assign (off-by-1). 10282 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 10283 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 10284 return false; 10285 10286 S.Diag(Loc, diag::warn_arc_literal_assign) 10287 << (unsigned) Kind 10288 << (isProperty ? 0 : 1) 10289 << RHS->getSourceRange(); 10290 10291 return true; 10292 } 10293 10294 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 10295 Qualifiers::ObjCLifetime LT, 10296 Expr *RHS, bool isProperty) { 10297 // Strip off any implicit cast added to get to the one ARC-specific. 10298 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 10299 if (cast->getCastKind() == CK_ARCConsumeObject) { 10300 S.Diag(Loc, diag::warn_arc_retained_assign) 10301 << (LT == Qualifiers::OCL_ExplicitNone) 10302 << (isProperty ? 0 : 1) 10303 << RHS->getSourceRange(); 10304 return true; 10305 } 10306 RHS = cast->getSubExpr(); 10307 } 10308 10309 if (LT == Qualifiers::OCL_Weak && 10310 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 10311 return true; 10312 10313 return false; 10314 } 10315 10316 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 10317 QualType LHS, Expr *RHS) { 10318 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 10319 10320 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 10321 return false; 10322 10323 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 10324 return true; 10325 10326 return false; 10327 } 10328 10329 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 10330 Expr *LHS, Expr *RHS) { 10331 QualType LHSType; 10332 // PropertyRef on LHS type need be directly obtained from 10333 // its declaration as it has a PseudoType. 10334 ObjCPropertyRefExpr *PRE 10335 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 10336 if (PRE && !PRE->isImplicitProperty()) { 10337 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 10338 if (PD) 10339 LHSType = PD->getType(); 10340 } 10341 10342 if (LHSType.isNull()) 10343 LHSType = LHS->getType(); 10344 10345 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 10346 10347 if (LT == Qualifiers::OCL_Weak) { 10348 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 10349 getCurFunction()->markSafeWeakUse(LHS); 10350 } 10351 10352 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 10353 return; 10354 10355 // FIXME. Check for other life times. 10356 if (LT != Qualifiers::OCL_None) 10357 return; 10358 10359 if (PRE) { 10360 if (PRE->isImplicitProperty()) 10361 return; 10362 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 10363 if (!PD) 10364 return; 10365 10366 unsigned Attributes = PD->getPropertyAttributes(); 10367 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) { 10368 // when 'assign' attribute was not explicitly specified 10369 // by user, ignore it and rely on property type itself 10370 // for lifetime info. 10371 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 10372 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) && 10373 LHSType->isObjCRetainableType()) 10374 return; 10375 10376 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 10377 if (cast->getCastKind() == CK_ARCConsumeObject) { 10378 Diag(Loc, diag::warn_arc_retained_property_assign) 10379 << RHS->getSourceRange(); 10380 return; 10381 } 10382 RHS = cast->getSubExpr(); 10383 } 10384 } 10385 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) { 10386 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 10387 return; 10388 } 10389 } 10390 } 10391 10392 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 10393 10394 namespace { 10395 bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 10396 SourceLocation StmtLoc, 10397 const NullStmt *Body) { 10398 // Do not warn if the body is a macro that expands to nothing, e.g: 10399 // 10400 // #define CALL(x) 10401 // if (condition) 10402 // CALL(0); 10403 // 10404 if (Body->hasLeadingEmptyMacro()) 10405 return false; 10406 10407 // Get line numbers of statement and body. 10408 bool StmtLineInvalid; 10409 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 10410 &StmtLineInvalid); 10411 if (StmtLineInvalid) 10412 return false; 10413 10414 bool BodyLineInvalid; 10415 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 10416 &BodyLineInvalid); 10417 if (BodyLineInvalid) 10418 return false; 10419 10420 // Warn if null statement and body are on the same line. 10421 if (StmtLine != BodyLine) 10422 return false; 10423 10424 return true; 10425 } 10426 } // end anonymous namespace 10427 10428 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 10429 const Stmt *Body, 10430 unsigned DiagID) { 10431 // Since this is a syntactic check, don't emit diagnostic for template 10432 // instantiations, this just adds noise. 10433 if (CurrentInstantiationScope) 10434 return; 10435 10436 // The body should be a null statement. 10437 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 10438 if (!NBody) 10439 return; 10440 10441 // Do the usual checks. 10442 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 10443 return; 10444 10445 Diag(NBody->getSemiLoc(), DiagID); 10446 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 10447 } 10448 10449 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 10450 const Stmt *PossibleBody) { 10451 assert(!CurrentInstantiationScope); // Ensured by caller 10452 10453 SourceLocation StmtLoc; 10454 const Stmt *Body; 10455 unsigned DiagID; 10456 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 10457 StmtLoc = FS->getRParenLoc(); 10458 Body = FS->getBody(); 10459 DiagID = diag::warn_empty_for_body; 10460 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 10461 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 10462 Body = WS->getBody(); 10463 DiagID = diag::warn_empty_while_body; 10464 } else 10465 return; // Neither `for' nor `while'. 10466 10467 // The body should be a null statement. 10468 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 10469 if (!NBody) 10470 return; 10471 10472 // Skip expensive checks if diagnostic is disabled. 10473 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 10474 return; 10475 10476 // Do the usual checks. 10477 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 10478 return; 10479 10480 // `for(...);' and `while(...);' are popular idioms, so in order to keep 10481 // noise level low, emit diagnostics only if for/while is followed by a 10482 // CompoundStmt, e.g.: 10483 // for (int i = 0; i < n; i++); 10484 // { 10485 // a(i); 10486 // } 10487 // or if for/while is followed by a statement with more indentation 10488 // than for/while itself: 10489 // for (int i = 0; i < n; i++); 10490 // a(i); 10491 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 10492 if (!ProbableTypo) { 10493 bool BodyColInvalid; 10494 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 10495 PossibleBody->getLocStart(), 10496 &BodyColInvalid); 10497 if (BodyColInvalid) 10498 return; 10499 10500 bool StmtColInvalid; 10501 unsigned StmtCol = SourceMgr.getPresumedColumnNumber( 10502 S->getLocStart(), 10503 &StmtColInvalid); 10504 if (StmtColInvalid) 10505 return; 10506 10507 if (BodyCol > StmtCol) 10508 ProbableTypo = true; 10509 } 10510 10511 if (ProbableTypo) { 10512 Diag(NBody->getSemiLoc(), DiagID); 10513 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 10514 } 10515 } 10516 10517 //===--- CHECK: Warn on self move with std::move. -------------------------===// 10518 10519 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 10520 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 10521 SourceLocation OpLoc) { 10522 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 10523 return; 10524 10525 if (!ActiveTemplateInstantiations.empty()) 10526 return; 10527 10528 // Strip parens and casts away. 10529 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 10530 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 10531 10532 // Check for a call expression 10533 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 10534 if (!CE || CE->getNumArgs() != 1) 10535 return; 10536 10537 // Check for a call to std::move 10538 const FunctionDecl *FD = CE->getDirectCallee(); 10539 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() || 10540 !FD->getIdentifier()->isStr("move")) 10541 return; 10542 10543 // Get argument from std::move 10544 RHSExpr = CE->getArg(0); 10545 10546 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 10547 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 10548 10549 // Two DeclRefExpr's, check that the decls are the same. 10550 if (LHSDeclRef && RHSDeclRef) { 10551 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 10552 return; 10553 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 10554 RHSDeclRef->getDecl()->getCanonicalDecl()) 10555 return; 10556 10557 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 10558 << LHSExpr->getSourceRange() 10559 << RHSExpr->getSourceRange(); 10560 return; 10561 } 10562 10563 // Member variables require a different approach to check for self moves. 10564 // MemberExpr's are the same if every nested MemberExpr refers to the same 10565 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 10566 // the base Expr's are CXXThisExpr's. 10567 const Expr *LHSBase = LHSExpr; 10568 const Expr *RHSBase = RHSExpr; 10569 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 10570 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 10571 if (!LHSME || !RHSME) 10572 return; 10573 10574 while (LHSME && RHSME) { 10575 if (LHSME->getMemberDecl()->getCanonicalDecl() != 10576 RHSME->getMemberDecl()->getCanonicalDecl()) 10577 return; 10578 10579 LHSBase = LHSME->getBase(); 10580 RHSBase = RHSME->getBase(); 10581 LHSME = dyn_cast<MemberExpr>(LHSBase); 10582 RHSME = dyn_cast<MemberExpr>(RHSBase); 10583 } 10584 10585 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 10586 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 10587 if (LHSDeclRef && RHSDeclRef) { 10588 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 10589 return; 10590 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 10591 RHSDeclRef->getDecl()->getCanonicalDecl()) 10592 return; 10593 10594 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 10595 << LHSExpr->getSourceRange() 10596 << RHSExpr->getSourceRange(); 10597 return; 10598 } 10599 10600 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 10601 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 10602 << LHSExpr->getSourceRange() 10603 << RHSExpr->getSourceRange(); 10604 } 10605 10606 //===--- Layout compatibility ----------------------------------------------// 10607 10608 namespace { 10609 10610 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 10611 10612 /// \brief Check if two enumeration types are layout-compatible. 10613 bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 10614 // C++11 [dcl.enum] p8: 10615 // Two enumeration types are layout-compatible if they have the same 10616 // underlying type. 10617 return ED1->isComplete() && ED2->isComplete() && 10618 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 10619 } 10620 10621 /// \brief Check if two fields are layout-compatible. 10622 bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) { 10623 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 10624 return false; 10625 10626 if (Field1->isBitField() != Field2->isBitField()) 10627 return false; 10628 10629 if (Field1->isBitField()) { 10630 // Make sure that the bit-fields are the same length. 10631 unsigned Bits1 = Field1->getBitWidthValue(C); 10632 unsigned Bits2 = Field2->getBitWidthValue(C); 10633 10634 if (Bits1 != Bits2) 10635 return false; 10636 } 10637 10638 return true; 10639 } 10640 10641 /// \brief Check if two standard-layout structs are layout-compatible. 10642 /// (C++11 [class.mem] p17) 10643 bool isLayoutCompatibleStruct(ASTContext &C, 10644 RecordDecl *RD1, 10645 RecordDecl *RD2) { 10646 // If both records are C++ classes, check that base classes match. 10647 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 10648 // If one of records is a CXXRecordDecl we are in C++ mode, 10649 // thus the other one is a CXXRecordDecl, too. 10650 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 10651 // Check number of base classes. 10652 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 10653 return false; 10654 10655 // Check the base classes. 10656 for (CXXRecordDecl::base_class_const_iterator 10657 Base1 = D1CXX->bases_begin(), 10658 BaseEnd1 = D1CXX->bases_end(), 10659 Base2 = D2CXX->bases_begin(); 10660 Base1 != BaseEnd1; 10661 ++Base1, ++Base2) { 10662 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 10663 return false; 10664 } 10665 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 10666 // If only RD2 is a C++ class, it should have zero base classes. 10667 if (D2CXX->getNumBases() > 0) 10668 return false; 10669 } 10670 10671 // Check the fields. 10672 RecordDecl::field_iterator Field2 = RD2->field_begin(), 10673 Field2End = RD2->field_end(), 10674 Field1 = RD1->field_begin(), 10675 Field1End = RD1->field_end(); 10676 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 10677 if (!isLayoutCompatible(C, *Field1, *Field2)) 10678 return false; 10679 } 10680 if (Field1 != Field1End || Field2 != Field2End) 10681 return false; 10682 10683 return true; 10684 } 10685 10686 /// \brief Check if two standard-layout unions are layout-compatible. 10687 /// (C++11 [class.mem] p18) 10688 bool isLayoutCompatibleUnion(ASTContext &C, 10689 RecordDecl *RD1, 10690 RecordDecl *RD2) { 10691 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 10692 for (auto *Field2 : RD2->fields()) 10693 UnmatchedFields.insert(Field2); 10694 10695 for (auto *Field1 : RD1->fields()) { 10696 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 10697 I = UnmatchedFields.begin(), 10698 E = UnmatchedFields.end(); 10699 10700 for ( ; I != E; ++I) { 10701 if (isLayoutCompatible(C, Field1, *I)) { 10702 bool Result = UnmatchedFields.erase(*I); 10703 (void) Result; 10704 assert(Result); 10705 break; 10706 } 10707 } 10708 if (I == E) 10709 return false; 10710 } 10711 10712 return UnmatchedFields.empty(); 10713 } 10714 10715 bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) { 10716 if (RD1->isUnion() != RD2->isUnion()) 10717 return false; 10718 10719 if (RD1->isUnion()) 10720 return isLayoutCompatibleUnion(C, RD1, RD2); 10721 else 10722 return isLayoutCompatibleStruct(C, RD1, RD2); 10723 } 10724 10725 /// \brief Check if two types are layout-compatible in C++11 sense. 10726 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 10727 if (T1.isNull() || T2.isNull()) 10728 return false; 10729 10730 // C++11 [basic.types] p11: 10731 // If two types T1 and T2 are the same type, then T1 and T2 are 10732 // layout-compatible types. 10733 if (C.hasSameType(T1, T2)) 10734 return true; 10735 10736 T1 = T1.getCanonicalType().getUnqualifiedType(); 10737 T2 = T2.getCanonicalType().getUnqualifiedType(); 10738 10739 const Type::TypeClass TC1 = T1->getTypeClass(); 10740 const Type::TypeClass TC2 = T2->getTypeClass(); 10741 10742 if (TC1 != TC2) 10743 return false; 10744 10745 if (TC1 == Type::Enum) { 10746 return isLayoutCompatible(C, 10747 cast<EnumType>(T1)->getDecl(), 10748 cast<EnumType>(T2)->getDecl()); 10749 } else if (TC1 == Type::Record) { 10750 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 10751 return false; 10752 10753 return isLayoutCompatible(C, 10754 cast<RecordType>(T1)->getDecl(), 10755 cast<RecordType>(T2)->getDecl()); 10756 } 10757 10758 return false; 10759 } 10760 } // end anonymous namespace 10761 10762 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 10763 10764 namespace { 10765 /// \brief Given a type tag expression find the type tag itself. 10766 /// 10767 /// \param TypeExpr Type tag expression, as it appears in user's code. 10768 /// 10769 /// \param VD Declaration of an identifier that appears in a type tag. 10770 /// 10771 /// \param MagicValue Type tag magic value. 10772 bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 10773 const ValueDecl **VD, uint64_t *MagicValue) { 10774 while(true) { 10775 if (!TypeExpr) 10776 return false; 10777 10778 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 10779 10780 switch (TypeExpr->getStmtClass()) { 10781 case Stmt::UnaryOperatorClass: { 10782 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 10783 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 10784 TypeExpr = UO->getSubExpr(); 10785 continue; 10786 } 10787 return false; 10788 } 10789 10790 case Stmt::DeclRefExprClass: { 10791 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 10792 *VD = DRE->getDecl(); 10793 return true; 10794 } 10795 10796 case Stmt::IntegerLiteralClass: { 10797 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 10798 llvm::APInt MagicValueAPInt = IL->getValue(); 10799 if (MagicValueAPInt.getActiveBits() <= 64) { 10800 *MagicValue = MagicValueAPInt.getZExtValue(); 10801 return true; 10802 } else 10803 return false; 10804 } 10805 10806 case Stmt::BinaryConditionalOperatorClass: 10807 case Stmt::ConditionalOperatorClass: { 10808 const AbstractConditionalOperator *ACO = 10809 cast<AbstractConditionalOperator>(TypeExpr); 10810 bool Result; 10811 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) { 10812 if (Result) 10813 TypeExpr = ACO->getTrueExpr(); 10814 else 10815 TypeExpr = ACO->getFalseExpr(); 10816 continue; 10817 } 10818 return false; 10819 } 10820 10821 case Stmt::BinaryOperatorClass: { 10822 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 10823 if (BO->getOpcode() == BO_Comma) { 10824 TypeExpr = BO->getRHS(); 10825 continue; 10826 } 10827 return false; 10828 } 10829 10830 default: 10831 return false; 10832 } 10833 } 10834 } 10835 10836 /// \brief Retrieve the C type corresponding to type tag TypeExpr. 10837 /// 10838 /// \param TypeExpr Expression that specifies a type tag. 10839 /// 10840 /// \param MagicValues Registered magic values. 10841 /// 10842 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 10843 /// kind. 10844 /// 10845 /// \param TypeInfo Information about the corresponding C type. 10846 /// 10847 /// \returns true if the corresponding C type was found. 10848 bool GetMatchingCType( 10849 const IdentifierInfo *ArgumentKind, 10850 const Expr *TypeExpr, const ASTContext &Ctx, 10851 const llvm::DenseMap<Sema::TypeTagMagicValue, 10852 Sema::TypeTagData> *MagicValues, 10853 bool &FoundWrongKind, 10854 Sema::TypeTagData &TypeInfo) { 10855 FoundWrongKind = false; 10856 10857 // Variable declaration that has type_tag_for_datatype attribute. 10858 const ValueDecl *VD = nullptr; 10859 10860 uint64_t MagicValue; 10861 10862 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue)) 10863 return false; 10864 10865 if (VD) { 10866 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 10867 if (I->getArgumentKind() != ArgumentKind) { 10868 FoundWrongKind = true; 10869 return false; 10870 } 10871 TypeInfo.Type = I->getMatchingCType(); 10872 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 10873 TypeInfo.MustBeNull = I->getMustBeNull(); 10874 return true; 10875 } 10876 return false; 10877 } 10878 10879 if (!MagicValues) 10880 return false; 10881 10882 llvm::DenseMap<Sema::TypeTagMagicValue, 10883 Sema::TypeTagData>::const_iterator I = 10884 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 10885 if (I == MagicValues->end()) 10886 return false; 10887 10888 TypeInfo = I->second; 10889 return true; 10890 } 10891 } // end anonymous namespace 10892 10893 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 10894 uint64_t MagicValue, QualType Type, 10895 bool LayoutCompatible, 10896 bool MustBeNull) { 10897 if (!TypeTagForDatatypeMagicValues) 10898 TypeTagForDatatypeMagicValues.reset( 10899 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 10900 10901 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 10902 (*TypeTagForDatatypeMagicValues)[Magic] = 10903 TypeTagData(Type, LayoutCompatible, MustBeNull); 10904 } 10905 10906 namespace { 10907 bool IsSameCharType(QualType T1, QualType T2) { 10908 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 10909 if (!BT1) 10910 return false; 10911 10912 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 10913 if (!BT2) 10914 return false; 10915 10916 BuiltinType::Kind T1Kind = BT1->getKind(); 10917 BuiltinType::Kind T2Kind = BT2->getKind(); 10918 10919 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 10920 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 10921 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 10922 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 10923 } 10924 } // end anonymous namespace 10925 10926 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 10927 const Expr * const *ExprArgs) { 10928 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 10929 bool IsPointerAttr = Attr->getIsPointer(); 10930 10931 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()]; 10932 bool FoundWrongKind; 10933 TypeTagData TypeInfo; 10934 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 10935 TypeTagForDatatypeMagicValues.get(), 10936 FoundWrongKind, TypeInfo)) { 10937 if (FoundWrongKind) 10938 Diag(TypeTagExpr->getExprLoc(), 10939 diag::warn_type_tag_for_datatype_wrong_kind) 10940 << TypeTagExpr->getSourceRange(); 10941 return; 10942 } 10943 10944 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()]; 10945 if (IsPointerAttr) { 10946 // Skip implicit cast of pointer to `void *' (as a function argument). 10947 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 10948 if (ICE->getType()->isVoidPointerType() && 10949 ICE->getCastKind() == CK_BitCast) 10950 ArgumentExpr = ICE->getSubExpr(); 10951 } 10952 QualType ArgumentType = ArgumentExpr->getType(); 10953 10954 // Passing a `void*' pointer shouldn't trigger a warning. 10955 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 10956 return; 10957 10958 if (TypeInfo.MustBeNull) { 10959 // Type tag with matching void type requires a null pointer. 10960 if (!ArgumentExpr->isNullPointerConstant(Context, 10961 Expr::NPC_ValueDependentIsNotNull)) { 10962 Diag(ArgumentExpr->getExprLoc(), 10963 diag::warn_type_safety_null_pointer_required) 10964 << ArgumentKind->getName() 10965 << ArgumentExpr->getSourceRange() 10966 << TypeTagExpr->getSourceRange(); 10967 } 10968 return; 10969 } 10970 10971 QualType RequiredType = TypeInfo.Type; 10972 if (IsPointerAttr) 10973 RequiredType = Context.getPointerType(RequiredType); 10974 10975 bool mismatch = false; 10976 if (!TypeInfo.LayoutCompatible) { 10977 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 10978 10979 // C++11 [basic.fundamental] p1: 10980 // Plain char, signed char, and unsigned char are three distinct types. 10981 // 10982 // But we treat plain `char' as equivalent to `signed char' or `unsigned 10983 // char' depending on the current char signedness mode. 10984 if (mismatch) 10985 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 10986 RequiredType->getPointeeType())) || 10987 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 10988 mismatch = false; 10989 } else 10990 if (IsPointerAttr) 10991 mismatch = !isLayoutCompatible(Context, 10992 ArgumentType->getPointeeType(), 10993 RequiredType->getPointeeType()); 10994 else 10995 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 10996 10997 if (mismatch) 10998 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 10999 << ArgumentType << ArgumentKind 11000 << TypeInfo.LayoutCompatible << RequiredType 11001 << ArgumentExpr->getSourceRange() 11002 << TypeTagExpr->getSourceRange(); 11003 } 11004 11005 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 11006 CharUnits Alignment) { 11007 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 11008 } 11009 11010 void Sema::DiagnoseMisalignedMembers() { 11011 for (MisalignedMember &m : MisalignedMembers) { 11012 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member) 11013 << m.MD << m.RD << m.E->getSourceRange(); 11014 } 11015 MisalignedMembers.clear(); 11016 } 11017 11018 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 11019 if (!T->isPointerType()) 11020 return; 11021 if (isa<UnaryOperator>(E) && 11022 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 11023 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 11024 if (isa<MemberExpr>(Op)) { 11025 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(), 11026 MisalignedMember(Op)); 11027 if (MA != MisalignedMembers.end() && 11028 Context.getTypeAlignInChars(T->getPointeeType()) <= MA->Alignment) 11029 MisalignedMembers.erase(MA); 11030 } 11031 } 11032 } 11033 11034 void Sema::RefersToMemberWithReducedAlignment( 11035 Expr *E, 11036 std::function<void(Expr *, RecordDecl *, ValueDecl *, CharUnits)> Action) { 11037 const auto *ME = dyn_cast<MemberExpr>(E); 11038 while (ME && isa<FieldDecl>(ME->getMemberDecl())) { 11039 QualType BaseType = ME->getBase()->getType(); 11040 if (ME->isArrow()) 11041 BaseType = BaseType->getPointeeType(); 11042 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl(); 11043 11044 ValueDecl *MD = ME->getMemberDecl(); 11045 bool ByteAligned = Context.getTypeAlignInChars(MD->getType()).isOne(); 11046 if (ByteAligned) // Attribute packed does not have any effect. 11047 break; 11048 11049 if (!ByteAligned && 11050 (RD->hasAttr<PackedAttr>() || (MD->hasAttr<PackedAttr>()))) { 11051 CharUnits Alignment = std::min(Context.getTypeAlignInChars(MD->getType()), 11052 Context.getTypeAlignInChars(BaseType)); 11053 // Notify that this expression designates a member with reduced alignment 11054 Action(E, RD, MD, Alignment); 11055 break; 11056 } 11057 ME = dyn_cast<MemberExpr>(ME->getBase()); 11058 } 11059 } 11060 11061 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 11062 using namespace std::placeholders; 11063 RefersToMemberWithReducedAlignment( 11064 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 11065 _2, _3, _4)); 11066 } 11067 11068