1 //===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements extra semantic analysis beyond what is enforced
11 // by the C type system.
13 //===----------------------------------------------------------------------===//
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"
44 using namespace clang;
47 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
48 unsigned ByteNo) const {
49 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
50 Context.getTargetInfo());
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;
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();
64 // Highlight all the excess arguments.
65 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
66 call->getArg(argCount - 1)->getLocEnd());
68 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
69 << 0 /*function call*/ << desiredArgCount << argCount
70 << call->getArg(1)->getSourceRange();
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))
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();
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();
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))
107 ExprResult Arg(TheCall->getArg(0));
108 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
109 if (ResultType.isNull())
112 TheCall->setArg(0, Arg.get());
113 TheCall->setType(ResultType);
117 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
118 if (checkArgCount(S, TheCall, 3))
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();
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.
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();
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)
157 const Expr *SizeArg = TheCall->getArg(SizeIdx);
158 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
160 llvm::APSInt Size, DstSize;
162 // find out if both sizes are known at compile time
163 if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
164 !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
167 if (Size.ule(DstSize))
170 // confirmed overflow so generate the diagnostic.
171 IdentifierInfo *FnName = FDecl->getIdentifier();
172 SourceLocation SL = TheCall->getLocStart();
173 SourceRange SR = TheCall->getSourceRange();
175 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
178 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
179 if (checkArgCount(S, BuiltinCall, 2))
182 SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
183 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
184 Expr *Call = BuiltinCall->getArg(0);
185 Expr *Chain = BuiltinCall->getArg(1);
187 if (Call->getStmtClass() != Stmt::CallExprClass) {
188 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
189 << Call->getSourceRange();
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();
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();
208 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
209 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
210 << Call->getSourceRange();
214 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
215 if (ChainResult.isInvalid())
217 if (!ChainResult.get()->getType()->isPointerType()) {
218 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
219 << Chain->getSourceRange();
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);
230 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
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());
241 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
242 Scope::ScopeFlags NeededScopeFlags,
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())
250 Scope *S = SemaRef.getCurScope();
251 while (S && !S->isSEHExceptScope())
253 if (!S || !(S->getFlags() & NeededScopeFlags)) {
254 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
255 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
256 << DRE->getDecl()->getIdentifier();
263 static inline bool isBlockPointer(Expr *Arg) {
264 return Arg->getType()->isBlockPointerType();
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();
294 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
295 IllegalParams = true;
299 return IllegalParams;
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))
309 Expr *BlockArg = TheCall->getArg(0);
310 if (!isBlockPointer(BlockArg)) {
311 S.Diag(BlockArg->getLocStart(),
312 diag::err_opencl_enqueue_kernel_expected_type) << "block";
315 return checkOpenCLBlockArgs(S, BlockArg);
318 /// Diagnose integer type and any valid implicit convertion to it.
319 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
320 const QualType &IntType);
322 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
323 unsigned Start, unsigned End) {
324 bool IllegalParams = false;
325 for (unsigned I = Start; I <= End; ++I)
326 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
327 S.Context.getSizeType());
328 return IllegalParams;
331 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
332 /// 'local void*' parameter of passed block.
333 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
335 unsigned NumNonVarArgs) {
336 const BlockPointerType *BPT =
337 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
338 unsigned NumBlockParams =
339 BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
340 unsigned TotalNumArgs = TheCall->getNumArgs();
342 // For each argument passed to the block, a corresponding uint needs to
343 // be passed to describe the size of the local memory.
344 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
345 S.Diag(TheCall->getLocStart(),
346 diag::err_opencl_enqueue_kernel_local_size_args);
350 // Check that the sizes of the local memory are specified by integers.
351 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
355 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
356 /// overload formats specified in Table 6.13.17.1.
357 /// int enqueue_kernel(queue_t queue,
358 /// kernel_enqueue_flags_t flags,
359 /// const ndrange_t ndrange,
360 /// void (^block)(void))
361 /// int enqueue_kernel(queue_t queue,
362 /// kernel_enqueue_flags_t flags,
363 /// const ndrange_t ndrange,
364 /// uint num_events_in_wait_list,
365 /// clk_event_t *event_wait_list,
366 /// clk_event_t *event_ret,
367 /// void (^block)(void))
368 /// int enqueue_kernel(queue_t queue,
369 /// kernel_enqueue_flags_t flags,
370 /// const ndrange_t ndrange,
371 /// void (^block)(local void*, ...),
373 /// int enqueue_kernel(queue_t queue,
374 /// kernel_enqueue_flags_t flags,
375 /// const ndrange_t ndrange,
376 /// uint num_events_in_wait_list,
377 /// clk_event_t *event_wait_list,
378 /// clk_event_t *event_ret,
379 /// void (^block)(local void*, ...),
381 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
382 unsigned NumArgs = TheCall->getNumArgs();
385 S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args);
389 Expr *Arg0 = TheCall->getArg(0);
390 Expr *Arg1 = TheCall->getArg(1);
391 Expr *Arg2 = TheCall->getArg(2);
392 Expr *Arg3 = TheCall->getArg(3);
394 // First argument always needs to be a queue_t type.
395 if (!Arg0->getType()->isQueueT()) {
396 S.Diag(TheCall->getArg(0)->getLocStart(),
397 diag::err_opencl_enqueue_kernel_expected_type)
398 << S.Context.OCLQueueTy;
402 // Second argument always needs to be a kernel_enqueue_flags_t enum value.
403 if (!Arg1->getType()->isIntegerType()) {
404 S.Diag(TheCall->getArg(1)->getLocStart(),
405 diag::err_opencl_enqueue_kernel_expected_type)
406 << "'kernel_enqueue_flags_t' (i.e. uint)";
410 // Third argument is always an ndrange_t type.
411 if (!Arg2->getType()->isNDRangeT()) {
412 S.Diag(TheCall->getArg(2)->getLocStart(),
413 diag::err_opencl_enqueue_kernel_expected_type)
414 << S.Context.OCLNDRangeTy;
418 // With four arguments, there is only one form that the function could be
419 // called in: no events and no variable arguments.
421 // check that the last argument is the right block type.
422 if (!isBlockPointer(Arg3)) {
423 S.Diag(Arg3->getLocStart(), diag::err_opencl_enqueue_kernel_expected_type)
427 // we have a block type, check the prototype
428 const BlockPointerType *BPT =
429 cast<BlockPointerType>(Arg3->getType().getCanonicalType());
430 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
431 S.Diag(Arg3->getLocStart(),
432 diag::err_opencl_enqueue_kernel_blocks_no_args);
437 // we can have block + varargs.
438 if (isBlockPointer(Arg3))
439 return (checkOpenCLBlockArgs(S, Arg3) ||
440 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
441 // last two cases with either exactly 7 args or 7 args and varargs.
443 // check common block argument.
444 Expr *Arg6 = TheCall->getArg(6);
445 if (!isBlockPointer(Arg6)) {
446 S.Diag(Arg6->getLocStart(), diag::err_opencl_enqueue_kernel_expected_type)
450 if (checkOpenCLBlockArgs(S, Arg6))
453 // Forth argument has to be any integer type.
454 if (!Arg3->getType()->isIntegerType()) {
455 S.Diag(TheCall->getArg(3)->getLocStart(),
456 diag::err_opencl_enqueue_kernel_expected_type)
460 // check remaining common arguments.
461 Expr *Arg4 = TheCall->getArg(4);
462 Expr *Arg5 = TheCall->getArg(5);
464 // Fifth argument is always passed as a pointer to clk_event_t.
465 if (!Arg4->isNullPointerConstant(S.Context,
466 Expr::NPC_ValueDependentIsNotNull) &&
467 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
468 S.Diag(TheCall->getArg(4)->getLocStart(),
469 diag::err_opencl_enqueue_kernel_expected_type)
470 << S.Context.getPointerType(S.Context.OCLClkEventTy);
474 // Sixth argument is always passed as a pointer to clk_event_t.
475 if (!Arg5->isNullPointerConstant(S.Context,
476 Expr::NPC_ValueDependentIsNotNull) &&
477 !(Arg5->getType()->isPointerType() &&
478 Arg5->getType()->getPointeeType()->isClkEventT())) {
479 S.Diag(TheCall->getArg(5)->getLocStart(),
480 diag::err_opencl_enqueue_kernel_expected_type)
481 << S.Context.getPointerType(S.Context.OCLClkEventTy);
488 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
491 // None of the specific case has been detected, give generic error
492 S.Diag(TheCall->getLocStart(),
493 diag::err_opencl_enqueue_kernel_incorrect_args);
497 /// Returns OpenCL access qual.
498 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
499 return D->getAttr<OpenCLAccessAttr>();
502 /// Returns true if pipe element type is different from the pointer.
503 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
504 const Expr *Arg0 = Call->getArg(0);
505 // First argument type should always be pipe.
506 if (!Arg0->getType()->isPipeType()) {
507 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
508 << Call->getDirectCallee() << Arg0->getSourceRange();
511 OpenCLAccessAttr *AccessQual =
512 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
513 // Validates the access qualifier is compatible with the call.
514 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
515 // read_only and write_only, and assumed to be read_only if no qualifier is
517 switch (Call->getDirectCallee()->getBuiltinID()) {
518 case Builtin::BIread_pipe:
519 case Builtin::BIreserve_read_pipe:
520 case Builtin::BIcommit_read_pipe:
521 case Builtin::BIwork_group_reserve_read_pipe:
522 case Builtin::BIsub_group_reserve_read_pipe:
523 case Builtin::BIwork_group_commit_read_pipe:
524 case Builtin::BIsub_group_commit_read_pipe:
525 if (!(!AccessQual || AccessQual->isReadOnly())) {
526 S.Diag(Arg0->getLocStart(),
527 diag::err_opencl_builtin_pipe_invalid_access_modifier)
528 << "read_only" << Arg0->getSourceRange();
532 case Builtin::BIwrite_pipe:
533 case Builtin::BIreserve_write_pipe:
534 case Builtin::BIcommit_write_pipe:
535 case Builtin::BIwork_group_reserve_write_pipe:
536 case Builtin::BIsub_group_reserve_write_pipe:
537 case Builtin::BIwork_group_commit_write_pipe:
538 case Builtin::BIsub_group_commit_write_pipe:
539 if (!(AccessQual && AccessQual->isWriteOnly())) {
540 S.Diag(Arg0->getLocStart(),
541 diag::err_opencl_builtin_pipe_invalid_access_modifier)
542 << "write_only" << Arg0->getSourceRange();
552 /// Returns true if pipe element type is different from the pointer.
553 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
554 const Expr *Arg0 = Call->getArg(0);
555 const Expr *ArgIdx = Call->getArg(Idx);
556 const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
557 const QualType EltTy = PipeTy->getElementType();
558 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
559 // The Idx argument should be a pointer and the type of the pointer and
560 // the type of pipe element should also be the same.
562 !S.Context.hasSameType(
563 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
564 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
565 << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
566 << ArgIdx->getType() << ArgIdx->getSourceRange();
572 // \brief Performs semantic analysis for the read/write_pipe call.
573 // \param S Reference to the semantic analyzer.
574 // \param Call A pointer to the builtin call.
575 // \return True if a semantic error has been found, false otherwise.
576 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
577 // OpenCL v2.0 s6.13.16.2 - The built-in read/write
578 // functions have two forms.
579 switch (Call->getNumArgs()) {
581 if (checkOpenCLPipeArg(S, Call))
583 // The call with 2 arguments should be
584 // read/write_pipe(pipe T, T*).
585 // Check packet type T.
586 if (checkOpenCLPipePacketType(S, Call, 1))
591 if (checkOpenCLPipeArg(S, Call))
593 // The call with 4 arguments should be
594 // read/write_pipe(pipe T, reserve_id_t, uint, T*).
595 // Check reserve_id_t.
596 if (!Call->getArg(1)->getType()->isReserveIDT()) {
597 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
598 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
599 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
604 const Expr *Arg2 = Call->getArg(2);
605 if (!Arg2->getType()->isIntegerType() &&
606 !Arg2->getType()->isUnsignedIntegerType()) {
607 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
608 << Call->getDirectCallee() << S.Context.UnsignedIntTy
609 << Arg2->getType() << Arg2->getSourceRange();
613 // Check packet type T.
614 if (checkOpenCLPipePacketType(S, Call, 3))
618 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
619 << Call->getDirectCallee() << Call->getSourceRange();
626 // \brief Performs a semantic analysis on the {work_group_/sub_group_
627 // /_}reserve_{read/write}_pipe
628 // \param S Reference to the semantic analyzer.
629 // \param Call The call to the builtin function to be analyzed.
630 // \return True if a semantic error was found, false otherwise.
631 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
632 if (checkArgCount(S, Call, 2))
635 if (checkOpenCLPipeArg(S, Call))
638 // Check the reserve size.
639 if (!Call->getArg(1)->getType()->isIntegerType() &&
640 !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
641 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
642 << Call->getDirectCallee() << S.Context.UnsignedIntTy
643 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
650 // \brief Performs a semantic analysis on {work_group_/sub_group_
651 // /_}commit_{read/write}_pipe
652 // \param S Reference to the semantic analyzer.
653 // \param Call The call to the builtin function to be analyzed.
654 // \return True if a semantic error was found, false otherwise.
655 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
656 if (checkArgCount(S, Call, 2))
659 if (checkOpenCLPipeArg(S, Call))
662 // Check reserve_id_t.
663 if (!Call->getArg(1)->getType()->isReserveIDT()) {
664 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
665 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
666 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
673 // \brief Performs a semantic analysis on the call to built-in Pipe
675 // \param S Reference to the semantic analyzer.
676 // \param Call The call to the builtin function to be analyzed.
677 // \return True if a semantic error was found, false otherwise.
678 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
679 if (checkArgCount(S, Call, 1))
682 if (!Call->getArg(0)->getType()->isPipeType()) {
683 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
684 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
690 // \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions.
691 // \brief Performs semantic analysis for the to_global/local/private call.
692 // \param S Reference to the semantic analyzer.
693 // \param BuiltinID ID of the builtin function.
694 // \param Call A pointer to the builtin call.
695 // \return True if a semantic error has been found, false otherwise.
696 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
698 if (Call->getNumArgs() != 1) {
699 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num)
700 << Call->getDirectCallee() << Call->getSourceRange();
704 auto RT = Call->getArg(0)->getType();
705 if (!RT->isPointerType() || RT->getPointeeType()
706 .getAddressSpace() == LangAS::opencl_constant) {
707 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
708 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
712 RT = RT->getPointeeType();
713 auto Qual = RT.getQualifiers();
715 case Builtin::BIto_global:
716 Qual.setAddressSpace(LangAS::opencl_global);
718 case Builtin::BIto_local:
719 Qual.setAddressSpace(LangAS::opencl_local);
722 Qual.removeAddressSpace();
724 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
725 RT.getUnqualifiedType(), Qual)));
731 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
733 ExprResult TheCallResult(TheCall);
735 // Find out if any arguments are required to be integer constant expressions.
736 unsigned ICEArguments = 0;
737 ASTContext::GetBuiltinTypeError Error;
738 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
739 if (Error != ASTContext::GE_None)
740 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
742 // If any arguments are required to be ICE's, check and diagnose.
743 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
744 // Skip arguments not required to be ICE's.
745 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
748 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
750 ICEArguments &= ~(1 << ArgNo);
754 case Builtin::BI__builtin___CFStringMakeConstantString:
755 assert(TheCall->getNumArgs() == 1 &&
756 "Wrong # arguments to builtin CFStringMakeConstantString");
757 if (CheckObjCString(TheCall->getArg(0)))
760 case Builtin::BI__builtin_stdarg_start:
761 case Builtin::BI__builtin_va_start:
762 if (SemaBuiltinVAStart(TheCall))
765 case Builtin::BI__va_start: {
766 switch (Context.getTargetInfo().getTriple().getArch()) {
767 case llvm::Triple::arm:
768 case llvm::Triple::thumb:
769 if (SemaBuiltinVAStartARM(TheCall))
773 if (SemaBuiltinVAStart(TheCall))
779 case Builtin::BI__builtin_isgreater:
780 case Builtin::BI__builtin_isgreaterequal:
781 case Builtin::BI__builtin_isless:
782 case Builtin::BI__builtin_islessequal:
783 case Builtin::BI__builtin_islessgreater:
784 case Builtin::BI__builtin_isunordered:
785 if (SemaBuiltinUnorderedCompare(TheCall))
788 case Builtin::BI__builtin_fpclassify:
789 if (SemaBuiltinFPClassification(TheCall, 6))
792 case Builtin::BI__builtin_isfinite:
793 case Builtin::BI__builtin_isinf:
794 case Builtin::BI__builtin_isinf_sign:
795 case Builtin::BI__builtin_isnan:
796 case Builtin::BI__builtin_isnormal:
797 if (SemaBuiltinFPClassification(TheCall, 1))
800 case Builtin::BI__builtin_shufflevector:
801 return SemaBuiltinShuffleVector(TheCall);
802 // TheCall will be freed by the smart pointer here, but that's fine, since
803 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
804 case Builtin::BI__builtin_prefetch:
805 if (SemaBuiltinPrefetch(TheCall))
808 case Builtin::BI__builtin_alloca_with_align:
809 if (SemaBuiltinAllocaWithAlign(TheCall))
812 case Builtin::BI__assume:
813 case Builtin::BI__builtin_assume:
814 if (SemaBuiltinAssume(TheCall))
817 case Builtin::BI__builtin_assume_aligned:
818 if (SemaBuiltinAssumeAligned(TheCall))
821 case Builtin::BI__builtin_object_size:
822 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
825 case Builtin::BI__builtin_longjmp:
826 if (SemaBuiltinLongjmp(TheCall))
829 case Builtin::BI__builtin_setjmp:
830 if (SemaBuiltinSetjmp(TheCall))
833 case Builtin::BI_setjmp:
834 case Builtin::BI_setjmpex:
835 if (checkArgCount(*this, TheCall, 1))
839 case Builtin::BI__builtin_classify_type:
840 if (checkArgCount(*this, TheCall, 1)) return true;
841 TheCall->setType(Context.IntTy);
843 case Builtin::BI__builtin_constant_p:
844 if (checkArgCount(*this, TheCall, 1)) return true;
845 TheCall->setType(Context.IntTy);
847 case Builtin::BI__sync_fetch_and_add:
848 case Builtin::BI__sync_fetch_and_add_1:
849 case Builtin::BI__sync_fetch_and_add_2:
850 case Builtin::BI__sync_fetch_and_add_4:
851 case Builtin::BI__sync_fetch_and_add_8:
852 case Builtin::BI__sync_fetch_and_add_16:
853 case Builtin::BI__sync_fetch_and_sub:
854 case Builtin::BI__sync_fetch_and_sub_1:
855 case Builtin::BI__sync_fetch_and_sub_2:
856 case Builtin::BI__sync_fetch_and_sub_4:
857 case Builtin::BI__sync_fetch_and_sub_8:
858 case Builtin::BI__sync_fetch_and_sub_16:
859 case Builtin::BI__sync_fetch_and_or:
860 case Builtin::BI__sync_fetch_and_or_1:
861 case Builtin::BI__sync_fetch_and_or_2:
862 case Builtin::BI__sync_fetch_and_or_4:
863 case Builtin::BI__sync_fetch_and_or_8:
864 case Builtin::BI__sync_fetch_and_or_16:
865 case Builtin::BI__sync_fetch_and_and:
866 case Builtin::BI__sync_fetch_and_and_1:
867 case Builtin::BI__sync_fetch_and_and_2:
868 case Builtin::BI__sync_fetch_and_and_4:
869 case Builtin::BI__sync_fetch_and_and_8:
870 case Builtin::BI__sync_fetch_and_and_16:
871 case Builtin::BI__sync_fetch_and_xor:
872 case Builtin::BI__sync_fetch_and_xor_1:
873 case Builtin::BI__sync_fetch_and_xor_2:
874 case Builtin::BI__sync_fetch_and_xor_4:
875 case Builtin::BI__sync_fetch_and_xor_8:
876 case Builtin::BI__sync_fetch_and_xor_16:
877 case Builtin::BI__sync_fetch_and_nand:
878 case Builtin::BI__sync_fetch_and_nand_1:
879 case Builtin::BI__sync_fetch_and_nand_2:
880 case Builtin::BI__sync_fetch_and_nand_4:
881 case Builtin::BI__sync_fetch_and_nand_8:
882 case Builtin::BI__sync_fetch_and_nand_16:
883 case Builtin::BI__sync_add_and_fetch:
884 case Builtin::BI__sync_add_and_fetch_1:
885 case Builtin::BI__sync_add_and_fetch_2:
886 case Builtin::BI__sync_add_and_fetch_4:
887 case Builtin::BI__sync_add_and_fetch_8:
888 case Builtin::BI__sync_add_and_fetch_16:
889 case Builtin::BI__sync_sub_and_fetch:
890 case Builtin::BI__sync_sub_and_fetch_1:
891 case Builtin::BI__sync_sub_and_fetch_2:
892 case Builtin::BI__sync_sub_and_fetch_4:
893 case Builtin::BI__sync_sub_and_fetch_8:
894 case Builtin::BI__sync_sub_and_fetch_16:
895 case Builtin::BI__sync_and_and_fetch:
896 case Builtin::BI__sync_and_and_fetch_1:
897 case Builtin::BI__sync_and_and_fetch_2:
898 case Builtin::BI__sync_and_and_fetch_4:
899 case Builtin::BI__sync_and_and_fetch_8:
900 case Builtin::BI__sync_and_and_fetch_16:
901 case Builtin::BI__sync_or_and_fetch:
902 case Builtin::BI__sync_or_and_fetch_1:
903 case Builtin::BI__sync_or_and_fetch_2:
904 case Builtin::BI__sync_or_and_fetch_4:
905 case Builtin::BI__sync_or_and_fetch_8:
906 case Builtin::BI__sync_or_and_fetch_16:
907 case Builtin::BI__sync_xor_and_fetch:
908 case Builtin::BI__sync_xor_and_fetch_1:
909 case Builtin::BI__sync_xor_and_fetch_2:
910 case Builtin::BI__sync_xor_and_fetch_4:
911 case Builtin::BI__sync_xor_and_fetch_8:
912 case Builtin::BI__sync_xor_and_fetch_16:
913 case Builtin::BI__sync_nand_and_fetch:
914 case Builtin::BI__sync_nand_and_fetch_1:
915 case Builtin::BI__sync_nand_and_fetch_2:
916 case Builtin::BI__sync_nand_and_fetch_4:
917 case Builtin::BI__sync_nand_and_fetch_8:
918 case Builtin::BI__sync_nand_and_fetch_16:
919 case Builtin::BI__sync_val_compare_and_swap:
920 case Builtin::BI__sync_val_compare_and_swap_1:
921 case Builtin::BI__sync_val_compare_and_swap_2:
922 case Builtin::BI__sync_val_compare_and_swap_4:
923 case Builtin::BI__sync_val_compare_and_swap_8:
924 case Builtin::BI__sync_val_compare_and_swap_16:
925 case Builtin::BI__sync_bool_compare_and_swap:
926 case Builtin::BI__sync_bool_compare_and_swap_1:
927 case Builtin::BI__sync_bool_compare_and_swap_2:
928 case Builtin::BI__sync_bool_compare_and_swap_4:
929 case Builtin::BI__sync_bool_compare_and_swap_8:
930 case Builtin::BI__sync_bool_compare_and_swap_16:
931 case Builtin::BI__sync_lock_test_and_set:
932 case Builtin::BI__sync_lock_test_and_set_1:
933 case Builtin::BI__sync_lock_test_and_set_2:
934 case Builtin::BI__sync_lock_test_and_set_4:
935 case Builtin::BI__sync_lock_test_and_set_8:
936 case Builtin::BI__sync_lock_test_and_set_16:
937 case Builtin::BI__sync_lock_release:
938 case Builtin::BI__sync_lock_release_1:
939 case Builtin::BI__sync_lock_release_2:
940 case Builtin::BI__sync_lock_release_4:
941 case Builtin::BI__sync_lock_release_8:
942 case Builtin::BI__sync_lock_release_16:
943 case Builtin::BI__sync_swap:
944 case Builtin::BI__sync_swap_1:
945 case Builtin::BI__sync_swap_2:
946 case Builtin::BI__sync_swap_4:
947 case Builtin::BI__sync_swap_8:
948 case Builtin::BI__sync_swap_16:
949 return SemaBuiltinAtomicOverloaded(TheCallResult);
950 case Builtin::BI__builtin_nontemporal_load:
951 case Builtin::BI__builtin_nontemporal_store:
952 return SemaBuiltinNontemporalOverloaded(TheCallResult);
953 #define BUILTIN(ID, TYPE, ATTRS)
954 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
955 case Builtin::BI##ID: \
956 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
957 #include "clang/Basic/Builtins.def"
958 case Builtin::BI__builtin_annotation:
959 if (SemaBuiltinAnnotation(*this, TheCall))
962 case Builtin::BI__builtin_addressof:
963 if (SemaBuiltinAddressof(*this, TheCall))
966 case Builtin::BI__builtin_add_overflow:
967 case Builtin::BI__builtin_sub_overflow:
968 case Builtin::BI__builtin_mul_overflow:
969 if (SemaBuiltinOverflow(*this, TheCall))
972 case Builtin::BI__builtin_operator_new:
973 case Builtin::BI__builtin_operator_delete:
974 if (!getLangOpts().CPlusPlus) {
975 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
976 << (BuiltinID == Builtin::BI__builtin_operator_new
977 ? "__builtin_operator_new"
978 : "__builtin_operator_delete")
982 // CodeGen assumes it can find the global new and delete to call,
983 // so ensure that they are declared.
984 DeclareGlobalNewDelete();
987 // check secure string manipulation functions where overflows
988 // are detectable at compile time
989 case Builtin::BI__builtin___memcpy_chk:
990 case Builtin::BI__builtin___memmove_chk:
991 case Builtin::BI__builtin___memset_chk:
992 case Builtin::BI__builtin___strlcat_chk:
993 case Builtin::BI__builtin___strlcpy_chk:
994 case Builtin::BI__builtin___strncat_chk:
995 case Builtin::BI__builtin___strncpy_chk:
996 case Builtin::BI__builtin___stpncpy_chk:
997 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
999 case Builtin::BI__builtin___memccpy_chk:
1000 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
1002 case Builtin::BI__builtin___snprintf_chk:
1003 case Builtin::BI__builtin___vsnprintf_chk:
1004 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
1006 case Builtin::BI__builtin_call_with_static_chain:
1007 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1010 case Builtin::BI__exception_code:
1011 case Builtin::BI_exception_code:
1012 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1013 diag::err_seh___except_block))
1016 case Builtin::BI__exception_info:
1017 case Builtin::BI_exception_info:
1018 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1019 diag::err_seh___except_filter))
1022 case Builtin::BI__GetExceptionInfo:
1023 if (checkArgCount(*this, TheCall, 1))
1026 if (CheckCXXThrowOperand(
1027 TheCall->getLocStart(),
1028 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1032 TheCall->setType(Context.VoidPtrTy);
1034 // OpenCL v2.0, s6.13.16 - Pipe functions
1035 case Builtin::BIread_pipe:
1036 case Builtin::BIwrite_pipe:
1037 // Since those two functions are declared with var args, we need a semantic
1038 // check for the argument.
1039 if (SemaBuiltinRWPipe(*this, TheCall))
1041 TheCall->setType(Context.IntTy);
1043 case Builtin::BIreserve_read_pipe:
1044 case Builtin::BIreserve_write_pipe:
1045 case Builtin::BIwork_group_reserve_read_pipe:
1046 case Builtin::BIwork_group_reserve_write_pipe:
1047 case Builtin::BIsub_group_reserve_read_pipe:
1048 case Builtin::BIsub_group_reserve_write_pipe:
1049 if (SemaBuiltinReserveRWPipe(*this, TheCall))
1051 // Since return type of reserve_read/write_pipe built-in function is
1052 // reserve_id_t, which is not defined in the builtin def file , we used int
1053 // as return type and need to override the return type of these functions.
1054 TheCall->setType(Context.OCLReserveIDTy);
1056 case Builtin::BIcommit_read_pipe:
1057 case Builtin::BIcommit_write_pipe:
1058 case Builtin::BIwork_group_commit_read_pipe:
1059 case Builtin::BIwork_group_commit_write_pipe:
1060 case Builtin::BIsub_group_commit_read_pipe:
1061 case Builtin::BIsub_group_commit_write_pipe:
1062 if (SemaBuiltinCommitRWPipe(*this, TheCall))
1065 case Builtin::BIget_pipe_num_packets:
1066 case Builtin::BIget_pipe_max_packets:
1067 if (SemaBuiltinPipePackets(*this, TheCall))
1069 TheCall->setType(Context.UnsignedIntTy);
1071 case Builtin::BIto_global:
1072 case Builtin::BIto_local:
1073 case Builtin::BIto_private:
1074 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1077 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1078 case Builtin::BIenqueue_kernel:
1079 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1082 case Builtin::BIget_kernel_work_group_size:
1083 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1084 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1087 case Builtin::BI__builtin_os_log_format:
1088 case Builtin::BI__builtin_os_log_format_buffer_size:
1089 if (SemaBuiltinOSLogFormat(TheCall)) {
1095 // Since the target specific builtins for each arch overlap, only check those
1096 // of the arch we are compiling for.
1097 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1098 switch (Context.getTargetInfo().getTriple().getArch()) {
1099 case llvm::Triple::arm:
1100 case llvm::Triple::armeb:
1101 case llvm::Triple::thumb:
1102 case llvm::Triple::thumbeb:
1103 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1106 case llvm::Triple::aarch64:
1107 case llvm::Triple::aarch64_be:
1108 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
1111 case llvm::Triple::mips:
1112 case llvm::Triple::mipsel:
1113 case llvm::Triple::mips64:
1114 case llvm::Triple::mips64el:
1115 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1118 case llvm::Triple::systemz:
1119 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1122 case llvm::Triple::x86:
1123 case llvm::Triple::x86_64:
1124 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1127 case llvm::Triple::ppc:
1128 case llvm::Triple::ppc64:
1129 case llvm::Triple::ppc64le:
1130 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1138 return TheCallResult;
1141 // Get the valid immediate range for the specified NEON type code.
1142 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1143 NeonTypeFlags Type(t);
1144 int IsQuad = ForceQuad ? true : Type.isQuad();
1145 switch (Type.getEltType()) {
1146 case NeonTypeFlags::Int8:
1147 case NeonTypeFlags::Poly8:
1148 return shift ? 7 : (8 << IsQuad) - 1;
1149 case NeonTypeFlags::Int16:
1150 case NeonTypeFlags::Poly16:
1151 return shift ? 15 : (4 << IsQuad) - 1;
1152 case NeonTypeFlags::Int32:
1153 return shift ? 31 : (2 << IsQuad) - 1;
1154 case NeonTypeFlags::Int64:
1155 case NeonTypeFlags::Poly64:
1156 return shift ? 63 : (1 << IsQuad) - 1;
1157 case NeonTypeFlags::Poly128:
1158 return shift ? 127 : (1 << IsQuad) - 1;
1159 case NeonTypeFlags::Float16:
1160 assert(!shift && "cannot shift float types!");
1161 return (4 << IsQuad) - 1;
1162 case NeonTypeFlags::Float32:
1163 assert(!shift && "cannot shift float types!");
1164 return (2 << IsQuad) - 1;
1165 case NeonTypeFlags::Float64:
1166 assert(!shift && "cannot shift float types!");
1167 return (1 << IsQuad) - 1;
1169 llvm_unreachable("Invalid NeonTypeFlag!");
1172 /// getNeonEltType - Return the QualType corresponding to the elements of
1173 /// the vector type specified by the NeonTypeFlags. This is used to check
1174 /// the pointer arguments for Neon load/store intrinsics.
1175 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
1176 bool IsPolyUnsigned, bool IsInt64Long) {
1177 switch (Flags.getEltType()) {
1178 case NeonTypeFlags::Int8:
1179 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1180 case NeonTypeFlags::Int16:
1181 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1182 case NeonTypeFlags::Int32:
1183 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1184 case NeonTypeFlags::Int64:
1186 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1188 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1189 : Context.LongLongTy;
1190 case NeonTypeFlags::Poly8:
1191 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
1192 case NeonTypeFlags::Poly16:
1193 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
1194 case NeonTypeFlags::Poly64:
1196 return Context.UnsignedLongTy;
1198 return Context.UnsignedLongLongTy;
1199 case NeonTypeFlags::Poly128:
1201 case NeonTypeFlags::Float16:
1202 return Context.HalfTy;
1203 case NeonTypeFlags::Float32:
1204 return Context.FloatTy;
1205 case NeonTypeFlags::Float64:
1206 return Context.DoubleTy;
1208 llvm_unreachable("Invalid NeonTypeFlag!");
1211 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1212 llvm::APSInt Result;
1216 bool HasConstPtr = false;
1217 switch (BuiltinID) {
1218 #define GET_NEON_OVERLOAD_CHECK
1219 #include "clang/Basic/arm_neon.inc"
1220 #undef GET_NEON_OVERLOAD_CHECK
1223 // For NEON intrinsics which are overloaded on vector element type, validate
1224 // the immediate which specifies which variant to emit.
1225 unsigned ImmArg = TheCall->getNumArgs()-1;
1227 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1230 TV = Result.getLimitedValue(64);
1231 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1232 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
1233 << TheCall->getArg(ImmArg)->getSourceRange();
1236 if (PtrArgNum >= 0) {
1237 // Check that pointer arguments have the specified type.
1238 Expr *Arg = TheCall->getArg(PtrArgNum);
1239 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1240 Arg = ICE->getSubExpr();
1241 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1242 QualType RHSTy = RHS.get()->getType();
1244 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
1245 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
1247 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1249 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
1251 EltTy = EltTy.withConst();
1252 QualType LHSTy = Context.getPointerType(EltTy);
1253 AssignConvertType ConvTy;
1254 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1255 if (RHS.isInvalid())
1257 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1258 RHS.get(), AA_Assigning))
1262 // For NEON intrinsics which take an immediate value as part of the
1263 // instruction, range check them here.
1264 unsigned i = 0, l = 0, u = 0;
1265 switch (BuiltinID) {
1268 #define GET_NEON_IMMEDIATE_CHECK
1269 #include "clang/Basic/arm_neon.inc"
1270 #undef GET_NEON_IMMEDIATE_CHECK
1273 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1276 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1277 unsigned MaxWidth) {
1278 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
1279 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1280 BuiltinID == ARM::BI__builtin_arm_strex ||
1281 BuiltinID == ARM::BI__builtin_arm_stlex ||
1282 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1283 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1284 BuiltinID == AArch64::BI__builtin_arm_strex ||
1285 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
1286 "unexpected ARM builtin");
1287 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
1288 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1289 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1290 BuiltinID == AArch64::BI__builtin_arm_ldaex;
1292 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1294 // Ensure that we have the proper number of arguments.
1295 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1298 // Inspect the pointer argument of the atomic builtin. This should always be
1299 // a pointer type, whose element is an integral scalar or pointer type.
1300 // Because it is a pointer type, we don't have to worry about any implicit
1302 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1303 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1304 if (PointerArgRes.isInvalid())
1306 PointerArg = PointerArgRes.get();
1308 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1310 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1311 << PointerArg->getType() << PointerArg->getSourceRange();
1315 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1316 // task is to insert the appropriate casts into the AST. First work out just
1317 // what the appropriate type is.
1318 QualType ValType = pointerType->getPointeeType();
1319 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1321 AddrType.addConst();
1323 // Issue a warning if the cast is dodgy.
1324 CastKind CastNeeded = CK_NoOp;
1325 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1326 CastNeeded = CK_BitCast;
1327 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1328 << PointerArg->getType()
1329 << Context.getPointerType(AddrType)
1330 << AA_Passing << PointerArg->getSourceRange();
1333 // Finally, do the cast and replace the argument with the corrected version.
1334 AddrType = Context.getPointerType(AddrType);
1335 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1336 if (PointerArgRes.isInvalid())
1338 PointerArg = PointerArgRes.get();
1340 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1342 // In general, we allow ints, floats and pointers to be loaded and stored.
1343 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1344 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1345 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1346 << PointerArg->getType() << PointerArg->getSourceRange();
1350 // But ARM doesn't have instructions to deal with 128-bit versions.
1351 if (Context.getTypeSize(ValType) > MaxWidth) {
1352 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
1353 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1354 << PointerArg->getType() << PointerArg->getSourceRange();
1358 switch (ValType.getObjCLifetime()) {
1359 case Qualifiers::OCL_None:
1360 case Qualifiers::OCL_ExplicitNone:
1364 case Qualifiers::OCL_Weak:
1365 case Qualifiers::OCL_Strong:
1366 case Qualifiers::OCL_Autoreleasing:
1367 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1368 << ValType << PointerArg->getSourceRange();
1373 TheCall->setType(ValType);
1377 // Initialize the argument to be stored.
1378 ExprResult ValArg = TheCall->getArg(0);
1379 InitializedEntity Entity = InitializedEntity::InitializeParameter(
1380 Context, ValType, /*consume*/ false);
1381 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1382 if (ValArg.isInvalid())
1384 TheCall->setArg(0, ValArg.get());
1386 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1387 // but the custom checker bypasses all default analysis.
1388 TheCall->setType(Context.IntTy);
1392 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1393 llvm::APSInt Result;
1395 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
1396 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1397 BuiltinID == ARM::BI__builtin_arm_strex ||
1398 BuiltinID == ARM::BI__builtin_arm_stlex) {
1399 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
1402 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1403 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1404 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1407 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1408 BuiltinID == ARM::BI__builtin_arm_wsr64)
1409 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1411 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1412 BuiltinID == ARM::BI__builtin_arm_rsrp ||
1413 BuiltinID == ARM::BI__builtin_arm_wsr ||
1414 BuiltinID == ARM::BI__builtin_arm_wsrp)
1415 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1417 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1420 // For intrinsics which take an immediate value as part of the instruction,
1421 // range check them here.
1422 unsigned i = 0, l = 0, u = 0;
1423 switch (BuiltinID) {
1424 default: return false;
1425 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
1426 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
1427 case ARM::BI__builtin_arm_vcvtr_f:
1428 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
1429 case ARM::BI__builtin_arm_dmb:
1430 case ARM::BI__builtin_arm_dsb:
1431 case ARM::BI__builtin_arm_isb:
1432 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
1435 // FIXME: VFP Intrinsics should error if VFP not present.
1436 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1439 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
1440 CallExpr *TheCall) {
1441 llvm::APSInt Result;
1443 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1444 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1445 BuiltinID == AArch64::BI__builtin_arm_strex ||
1446 BuiltinID == AArch64::BI__builtin_arm_stlex) {
1447 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1450 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1451 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1452 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1453 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1454 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1457 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1458 BuiltinID == AArch64::BI__builtin_arm_wsr64)
1459 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1461 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1462 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1463 BuiltinID == AArch64::BI__builtin_arm_wsr ||
1464 BuiltinID == AArch64::BI__builtin_arm_wsrp)
1465 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1467 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1470 // For intrinsics which take an immediate value as part of the instruction,
1471 // range check them here.
1472 unsigned i = 0, l = 0, u = 0;
1473 switch (BuiltinID) {
1474 default: return false;
1475 case AArch64::BI__builtin_arm_dmb:
1476 case AArch64::BI__builtin_arm_dsb:
1477 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1480 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1483 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
1484 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
1485 // ordering for DSP is unspecified. MSA is ordered by the data format used
1486 // by the underlying instruction i.e., df/m, df/n and then by size.
1488 // FIXME: The size tests here should instead be tablegen'd along with the
1489 // definitions from include/clang/Basic/BuiltinsMips.def.
1490 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
1492 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1493 unsigned i = 0, l = 0, u = 0, m = 0;
1494 switch (BuiltinID) {
1495 default: return false;
1496 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1497 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
1498 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1499 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1500 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1501 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1502 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
1503 // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
1505 // These intrinsics take an unsigned 3 bit immediate.
1506 case Mips::BI__builtin_msa_bclri_b:
1507 case Mips::BI__builtin_msa_bnegi_b:
1508 case Mips::BI__builtin_msa_bseti_b:
1509 case Mips::BI__builtin_msa_sat_s_b:
1510 case Mips::BI__builtin_msa_sat_u_b:
1511 case Mips::BI__builtin_msa_slli_b:
1512 case Mips::BI__builtin_msa_srai_b:
1513 case Mips::BI__builtin_msa_srari_b:
1514 case Mips::BI__builtin_msa_srli_b:
1515 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
1516 case Mips::BI__builtin_msa_binsli_b:
1517 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
1518 // These intrinsics take an unsigned 4 bit immediate.
1519 case Mips::BI__builtin_msa_bclri_h:
1520 case Mips::BI__builtin_msa_bnegi_h:
1521 case Mips::BI__builtin_msa_bseti_h:
1522 case Mips::BI__builtin_msa_sat_s_h:
1523 case Mips::BI__builtin_msa_sat_u_h:
1524 case Mips::BI__builtin_msa_slli_h:
1525 case Mips::BI__builtin_msa_srai_h:
1526 case Mips::BI__builtin_msa_srari_h:
1527 case Mips::BI__builtin_msa_srli_h:
1528 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
1529 case Mips::BI__builtin_msa_binsli_h:
1530 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
1531 // These intrinsics take an unsigned 5 bit immedate.
1532 // The first block of intrinsics actually have an unsigned 5 bit field,
1533 // not a df/n field.
1534 case Mips::BI__builtin_msa_clei_u_b:
1535 case Mips::BI__builtin_msa_clei_u_h:
1536 case Mips::BI__builtin_msa_clei_u_w:
1537 case Mips::BI__builtin_msa_clei_u_d:
1538 case Mips::BI__builtin_msa_clti_u_b:
1539 case Mips::BI__builtin_msa_clti_u_h:
1540 case Mips::BI__builtin_msa_clti_u_w:
1541 case Mips::BI__builtin_msa_clti_u_d:
1542 case Mips::BI__builtin_msa_maxi_u_b:
1543 case Mips::BI__builtin_msa_maxi_u_h:
1544 case Mips::BI__builtin_msa_maxi_u_w:
1545 case Mips::BI__builtin_msa_maxi_u_d:
1546 case Mips::BI__builtin_msa_mini_u_b:
1547 case Mips::BI__builtin_msa_mini_u_h:
1548 case Mips::BI__builtin_msa_mini_u_w:
1549 case Mips::BI__builtin_msa_mini_u_d:
1550 case Mips::BI__builtin_msa_addvi_b:
1551 case Mips::BI__builtin_msa_addvi_h:
1552 case Mips::BI__builtin_msa_addvi_w:
1553 case Mips::BI__builtin_msa_addvi_d:
1554 case Mips::BI__builtin_msa_bclri_w:
1555 case Mips::BI__builtin_msa_bnegi_w:
1556 case Mips::BI__builtin_msa_bseti_w:
1557 case Mips::BI__builtin_msa_sat_s_w:
1558 case Mips::BI__builtin_msa_sat_u_w:
1559 case Mips::BI__builtin_msa_slli_w:
1560 case Mips::BI__builtin_msa_srai_w:
1561 case Mips::BI__builtin_msa_srari_w:
1562 case Mips::BI__builtin_msa_srli_w:
1563 case Mips::BI__builtin_msa_srlri_w:
1564 case Mips::BI__builtin_msa_subvi_b:
1565 case Mips::BI__builtin_msa_subvi_h:
1566 case Mips::BI__builtin_msa_subvi_w:
1567 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
1568 case Mips::BI__builtin_msa_binsli_w:
1569 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
1570 // These intrinsics take an unsigned 6 bit immediate.
1571 case Mips::BI__builtin_msa_bclri_d:
1572 case Mips::BI__builtin_msa_bnegi_d:
1573 case Mips::BI__builtin_msa_bseti_d:
1574 case Mips::BI__builtin_msa_sat_s_d:
1575 case Mips::BI__builtin_msa_sat_u_d:
1576 case Mips::BI__builtin_msa_slli_d:
1577 case Mips::BI__builtin_msa_srai_d:
1578 case Mips::BI__builtin_msa_srari_d:
1579 case Mips::BI__builtin_msa_srli_d:
1580 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
1581 case Mips::BI__builtin_msa_binsli_d:
1582 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
1583 // These intrinsics take a signed 5 bit immediate.
1584 case Mips::BI__builtin_msa_ceqi_b:
1585 case Mips::BI__builtin_msa_ceqi_h:
1586 case Mips::BI__builtin_msa_ceqi_w:
1587 case Mips::BI__builtin_msa_ceqi_d:
1588 case Mips::BI__builtin_msa_clti_s_b:
1589 case Mips::BI__builtin_msa_clti_s_h:
1590 case Mips::BI__builtin_msa_clti_s_w:
1591 case Mips::BI__builtin_msa_clti_s_d:
1592 case Mips::BI__builtin_msa_clei_s_b:
1593 case Mips::BI__builtin_msa_clei_s_h:
1594 case Mips::BI__builtin_msa_clei_s_w:
1595 case Mips::BI__builtin_msa_clei_s_d:
1596 case Mips::BI__builtin_msa_maxi_s_b:
1597 case Mips::BI__builtin_msa_maxi_s_h:
1598 case Mips::BI__builtin_msa_maxi_s_w:
1599 case Mips::BI__builtin_msa_maxi_s_d:
1600 case Mips::BI__builtin_msa_mini_s_b:
1601 case Mips::BI__builtin_msa_mini_s_h:
1602 case Mips::BI__builtin_msa_mini_s_w:
1603 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
1604 // These intrinsics take an unsigned 8 bit immediate.
1605 case Mips::BI__builtin_msa_andi_b:
1606 case Mips::BI__builtin_msa_nori_b:
1607 case Mips::BI__builtin_msa_ori_b:
1608 case Mips::BI__builtin_msa_shf_b:
1609 case Mips::BI__builtin_msa_shf_h:
1610 case Mips::BI__builtin_msa_shf_w:
1611 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
1612 case Mips::BI__builtin_msa_bseli_b:
1613 case Mips::BI__builtin_msa_bmnzi_b:
1614 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
1616 // These intrinsics take an unsigned 4 bit immediate.
1617 case Mips::BI__builtin_msa_copy_s_b:
1618 case Mips::BI__builtin_msa_copy_u_b:
1619 case Mips::BI__builtin_msa_insve_b:
1620 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
1621 case Mips::BI__builtin_msa_sld_b:
1622 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
1623 // These intrinsics take an unsigned 3 bit immediate.
1624 case Mips::BI__builtin_msa_copy_s_h:
1625 case Mips::BI__builtin_msa_copy_u_h:
1626 case Mips::BI__builtin_msa_insve_h:
1627 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
1628 case Mips::BI__builtin_msa_sld_h:
1629 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
1630 // These intrinsics take an unsigned 2 bit immediate.
1631 case Mips::BI__builtin_msa_copy_s_w:
1632 case Mips::BI__builtin_msa_copy_u_w:
1633 case Mips::BI__builtin_msa_insve_w:
1634 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
1635 case Mips::BI__builtin_msa_sld_w:
1636 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
1637 // These intrinsics take an unsigned 1 bit immediate.
1638 case Mips::BI__builtin_msa_copy_s_d:
1639 case Mips::BI__builtin_msa_copy_u_d:
1640 case Mips::BI__builtin_msa_insve_d:
1641 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
1642 case Mips::BI__builtin_msa_sld_d:
1643 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
1644 // Memory offsets and immediate loads.
1645 // These intrinsics take a signed 10 bit immediate.
1646 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 127; break;
1647 case Mips::BI__builtin_msa_ldi_h:
1648 case Mips::BI__builtin_msa_ldi_w:
1649 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
1650 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
1651 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
1652 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
1653 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
1654 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
1655 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
1656 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
1657 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
1661 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1663 return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
1664 SemaBuiltinConstantArgMultiple(TheCall, i, m);
1667 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1668 unsigned i = 0, l = 0, u = 0;
1669 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1670 BuiltinID == PPC::BI__builtin_divdeu ||
1671 BuiltinID == PPC::BI__builtin_bpermd;
1672 bool IsTarget64Bit = Context.getTargetInfo()
1673 .getTypeWidth(Context
1675 .getIntPtrType()) == 64;
1676 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1677 BuiltinID == PPC::BI__builtin_divweu ||
1678 BuiltinID == PPC::BI__builtin_divde ||
1679 BuiltinID == PPC::BI__builtin_divdeu;
1681 if (Is64BitBltin && !IsTarget64Bit)
1682 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1683 << TheCall->getSourceRange();
1685 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1686 (BuiltinID == PPC::BI__builtin_bpermd &&
1687 !Context.getTargetInfo().hasFeature("bpermd")))
1688 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1689 << TheCall->getSourceRange();
1691 switch (BuiltinID) {
1692 default: return false;
1693 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1694 case PPC::BI__builtin_altivec_crypto_vshasigmad:
1695 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1696 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1697 case PPC::BI__builtin_tbegin:
1698 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1699 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1700 case PPC::BI__builtin_tabortwc:
1701 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1702 case PPC::BI__builtin_tabortwci:
1703 case PPC::BI__builtin_tabortdci:
1704 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1705 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
1707 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1710 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1711 CallExpr *TheCall) {
1712 if (BuiltinID == SystemZ::BI__builtin_tabort) {
1713 Expr *Arg = TheCall->getArg(0);
1714 llvm::APSInt AbortCode(32);
1715 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1716 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1717 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1718 << Arg->getSourceRange();
1721 // For intrinsics which take an immediate value as part of the instruction,
1722 // range check them here.
1723 unsigned i = 0, l = 0, u = 0;
1724 switch (BuiltinID) {
1725 default: return false;
1726 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1727 case SystemZ::BI__builtin_s390_verimb:
1728 case SystemZ::BI__builtin_s390_verimh:
1729 case SystemZ::BI__builtin_s390_verimf:
1730 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1731 case SystemZ::BI__builtin_s390_vfaeb:
1732 case SystemZ::BI__builtin_s390_vfaeh:
1733 case SystemZ::BI__builtin_s390_vfaef:
1734 case SystemZ::BI__builtin_s390_vfaebs:
1735 case SystemZ::BI__builtin_s390_vfaehs:
1736 case SystemZ::BI__builtin_s390_vfaefs:
1737 case SystemZ::BI__builtin_s390_vfaezb:
1738 case SystemZ::BI__builtin_s390_vfaezh:
1739 case SystemZ::BI__builtin_s390_vfaezf:
1740 case SystemZ::BI__builtin_s390_vfaezbs:
1741 case SystemZ::BI__builtin_s390_vfaezhs:
1742 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1743 case SystemZ::BI__builtin_s390_vfidb:
1744 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1745 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1746 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1747 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1748 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1749 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1750 case SystemZ::BI__builtin_s390_vstrcb:
1751 case SystemZ::BI__builtin_s390_vstrch:
1752 case SystemZ::BI__builtin_s390_vstrcf:
1753 case SystemZ::BI__builtin_s390_vstrczb:
1754 case SystemZ::BI__builtin_s390_vstrczh:
1755 case SystemZ::BI__builtin_s390_vstrczf:
1756 case SystemZ::BI__builtin_s390_vstrcbs:
1757 case SystemZ::BI__builtin_s390_vstrchs:
1758 case SystemZ::BI__builtin_s390_vstrcfs:
1759 case SystemZ::BI__builtin_s390_vstrczbs:
1760 case SystemZ::BI__builtin_s390_vstrczhs:
1761 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1763 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1766 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1767 /// This checks that the target supports __builtin_cpu_supports and
1768 /// that the string argument is constant and valid.
1769 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1770 Expr *Arg = TheCall->getArg(0);
1772 // Check if the argument is a string literal.
1773 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1774 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1775 << Arg->getSourceRange();
1777 // Check the contents of the string.
1779 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1780 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1781 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1782 << Arg->getSourceRange();
1786 // Check if the rounding mode is legal.
1787 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
1788 // Indicates if this instruction has rounding control or just SAE.
1791 unsigned ArgNum = 0;
1792 switch (BuiltinID) {
1795 case X86::BI__builtin_ia32_vcvttsd2si32:
1796 case X86::BI__builtin_ia32_vcvttsd2si64:
1797 case X86::BI__builtin_ia32_vcvttsd2usi32:
1798 case X86::BI__builtin_ia32_vcvttsd2usi64:
1799 case X86::BI__builtin_ia32_vcvttss2si32:
1800 case X86::BI__builtin_ia32_vcvttss2si64:
1801 case X86::BI__builtin_ia32_vcvttss2usi32:
1802 case X86::BI__builtin_ia32_vcvttss2usi64:
1805 case X86::BI__builtin_ia32_cvtps2pd512_mask:
1806 case X86::BI__builtin_ia32_cvttpd2dq512_mask:
1807 case X86::BI__builtin_ia32_cvttpd2qq512_mask:
1808 case X86::BI__builtin_ia32_cvttpd2udq512_mask:
1809 case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
1810 case X86::BI__builtin_ia32_cvttps2dq512_mask:
1811 case X86::BI__builtin_ia32_cvttps2qq512_mask:
1812 case X86::BI__builtin_ia32_cvttps2udq512_mask:
1813 case X86::BI__builtin_ia32_cvttps2uqq512_mask:
1814 case X86::BI__builtin_ia32_exp2pd_mask:
1815 case X86::BI__builtin_ia32_exp2ps_mask:
1816 case X86::BI__builtin_ia32_getexppd512_mask:
1817 case X86::BI__builtin_ia32_getexpps512_mask:
1818 case X86::BI__builtin_ia32_rcp28pd_mask:
1819 case X86::BI__builtin_ia32_rcp28ps_mask:
1820 case X86::BI__builtin_ia32_rsqrt28pd_mask:
1821 case X86::BI__builtin_ia32_rsqrt28ps_mask:
1822 case X86::BI__builtin_ia32_vcomisd:
1823 case X86::BI__builtin_ia32_vcomiss:
1824 case X86::BI__builtin_ia32_vcvtph2ps512_mask:
1827 case X86::BI__builtin_ia32_cmppd512_mask:
1828 case X86::BI__builtin_ia32_cmpps512_mask:
1829 case X86::BI__builtin_ia32_cmpsd_mask:
1830 case X86::BI__builtin_ia32_cmpss_mask:
1831 case X86::BI__builtin_ia32_cvtss2sd_round_mask:
1832 case X86::BI__builtin_ia32_getexpsd128_round_mask:
1833 case X86::BI__builtin_ia32_getexpss128_round_mask:
1834 case X86::BI__builtin_ia32_maxpd512_mask:
1835 case X86::BI__builtin_ia32_maxps512_mask:
1836 case X86::BI__builtin_ia32_maxsd_round_mask:
1837 case X86::BI__builtin_ia32_maxss_round_mask:
1838 case X86::BI__builtin_ia32_minpd512_mask:
1839 case X86::BI__builtin_ia32_minps512_mask:
1840 case X86::BI__builtin_ia32_minsd_round_mask:
1841 case X86::BI__builtin_ia32_minss_round_mask:
1842 case X86::BI__builtin_ia32_rcp28sd_round_mask:
1843 case X86::BI__builtin_ia32_rcp28ss_round_mask:
1844 case X86::BI__builtin_ia32_reducepd512_mask:
1845 case X86::BI__builtin_ia32_reduceps512_mask:
1846 case X86::BI__builtin_ia32_rndscalepd_mask:
1847 case X86::BI__builtin_ia32_rndscaleps_mask:
1848 case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
1849 case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
1852 case X86::BI__builtin_ia32_fixupimmpd512_mask:
1853 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
1854 case X86::BI__builtin_ia32_fixupimmps512_mask:
1855 case X86::BI__builtin_ia32_fixupimmps512_maskz:
1856 case X86::BI__builtin_ia32_fixupimmsd_mask:
1857 case X86::BI__builtin_ia32_fixupimmsd_maskz:
1858 case X86::BI__builtin_ia32_fixupimmss_mask:
1859 case X86::BI__builtin_ia32_fixupimmss_maskz:
1860 case X86::BI__builtin_ia32_rangepd512_mask:
1861 case X86::BI__builtin_ia32_rangeps512_mask:
1862 case X86::BI__builtin_ia32_rangesd128_round_mask:
1863 case X86::BI__builtin_ia32_rangess128_round_mask:
1864 case X86::BI__builtin_ia32_reducesd_mask:
1865 case X86::BI__builtin_ia32_reducess_mask:
1866 case X86::BI__builtin_ia32_rndscalesd_round_mask:
1867 case X86::BI__builtin_ia32_rndscaless_round_mask:
1870 case X86::BI__builtin_ia32_vcvtsd2si64:
1871 case X86::BI__builtin_ia32_vcvtsd2si32:
1872 case X86::BI__builtin_ia32_vcvtsd2usi32:
1873 case X86::BI__builtin_ia32_vcvtsd2usi64:
1874 case X86::BI__builtin_ia32_vcvtss2si32:
1875 case X86::BI__builtin_ia32_vcvtss2si64:
1876 case X86::BI__builtin_ia32_vcvtss2usi32:
1877 case X86::BI__builtin_ia32_vcvtss2usi64:
1881 case X86::BI__builtin_ia32_cvtsi2sd64:
1882 case X86::BI__builtin_ia32_cvtsi2ss32:
1883 case X86::BI__builtin_ia32_cvtsi2ss64:
1884 case X86::BI__builtin_ia32_cvtusi2sd64:
1885 case X86::BI__builtin_ia32_cvtusi2ss32:
1886 case X86::BI__builtin_ia32_cvtusi2ss64:
1890 case X86::BI__builtin_ia32_cvtdq2ps512_mask:
1891 case X86::BI__builtin_ia32_cvtudq2ps512_mask:
1892 case X86::BI__builtin_ia32_cvtpd2ps512_mask:
1893 case X86::BI__builtin_ia32_cvtpd2qq512_mask:
1894 case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
1895 case X86::BI__builtin_ia32_cvtps2qq512_mask:
1896 case X86::BI__builtin_ia32_cvtps2uqq512_mask:
1897 case X86::BI__builtin_ia32_cvtqq2pd512_mask:
1898 case X86::BI__builtin_ia32_cvtqq2ps512_mask:
1899 case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
1900 case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
1901 case X86::BI__builtin_ia32_sqrtpd512_mask:
1902 case X86::BI__builtin_ia32_sqrtps512_mask:
1906 case X86::BI__builtin_ia32_addpd512_mask:
1907 case X86::BI__builtin_ia32_addps512_mask:
1908 case X86::BI__builtin_ia32_divpd512_mask:
1909 case X86::BI__builtin_ia32_divps512_mask:
1910 case X86::BI__builtin_ia32_mulpd512_mask:
1911 case X86::BI__builtin_ia32_mulps512_mask:
1912 case X86::BI__builtin_ia32_subpd512_mask:
1913 case X86::BI__builtin_ia32_subps512_mask:
1914 case X86::BI__builtin_ia32_addss_round_mask:
1915 case X86::BI__builtin_ia32_addsd_round_mask:
1916 case X86::BI__builtin_ia32_divss_round_mask:
1917 case X86::BI__builtin_ia32_divsd_round_mask:
1918 case X86::BI__builtin_ia32_mulss_round_mask:
1919 case X86::BI__builtin_ia32_mulsd_round_mask:
1920 case X86::BI__builtin_ia32_subss_round_mask:
1921 case X86::BI__builtin_ia32_subsd_round_mask:
1922 case X86::BI__builtin_ia32_scalefpd512_mask:
1923 case X86::BI__builtin_ia32_scalefps512_mask:
1924 case X86::BI__builtin_ia32_scalefsd_round_mask:
1925 case X86::BI__builtin_ia32_scalefss_round_mask:
1926 case X86::BI__builtin_ia32_getmantpd512_mask:
1927 case X86::BI__builtin_ia32_getmantps512_mask:
1928 case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
1929 case X86::BI__builtin_ia32_sqrtsd_round_mask:
1930 case X86::BI__builtin_ia32_sqrtss_round_mask:
1931 case X86::BI__builtin_ia32_vfmaddpd512_mask:
1932 case X86::BI__builtin_ia32_vfmaddpd512_mask3:
1933 case X86::BI__builtin_ia32_vfmaddpd512_maskz:
1934 case X86::BI__builtin_ia32_vfmaddps512_mask:
1935 case X86::BI__builtin_ia32_vfmaddps512_mask3:
1936 case X86::BI__builtin_ia32_vfmaddps512_maskz:
1937 case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
1938 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
1939 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
1940 case X86::BI__builtin_ia32_vfmaddsubps512_mask:
1941 case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
1942 case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
1943 case X86::BI__builtin_ia32_vfmsubpd512_mask3:
1944 case X86::BI__builtin_ia32_vfmsubps512_mask3:
1945 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
1946 case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
1947 case X86::BI__builtin_ia32_vfnmaddpd512_mask:
1948 case X86::BI__builtin_ia32_vfnmaddps512_mask:
1949 case X86::BI__builtin_ia32_vfnmsubpd512_mask:
1950 case X86::BI__builtin_ia32_vfnmsubpd512_mask3:
1951 case X86::BI__builtin_ia32_vfnmsubps512_mask:
1952 case X86::BI__builtin_ia32_vfnmsubps512_mask3:
1953 case X86::BI__builtin_ia32_vfmaddsd3_mask:
1954 case X86::BI__builtin_ia32_vfmaddsd3_maskz:
1955 case X86::BI__builtin_ia32_vfmaddsd3_mask3:
1956 case X86::BI__builtin_ia32_vfmaddss3_mask:
1957 case X86::BI__builtin_ia32_vfmaddss3_maskz:
1958 case X86::BI__builtin_ia32_vfmaddss3_mask3:
1962 case X86::BI__builtin_ia32_getmantsd_round_mask:
1963 case X86::BI__builtin_ia32_getmantss_round_mask:
1969 llvm::APSInt Result;
1971 // We can't check the value of a dependent argument.
1972 Expr *Arg = TheCall->getArg(ArgNum);
1973 if (Arg->isTypeDependent() || Arg->isValueDependent())
1976 // Check constant-ness first.
1977 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
1980 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
1981 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
1982 // combined with ROUND_NO_EXC.
1983 if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
1984 Result == 8/*ROUND_NO_EXC*/ ||
1985 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
1988 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
1989 << Arg->getSourceRange();
1992 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1993 if (BuiltinID == X86::BI__builtin_cpu_supports)
1994 return SemaBuiltinCpuSupports(*this, TheCall);
1996 if (BuiltinID == X86::BI__builtin_ms_va_start)
1997 return SemaBuiltinMSVAStart(TheCall);
1999 // If the intrinsic has rounding or SAE make sure its valid.
2000 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
2003 // For intrinsics which take an immediate value as part of the instruction,
2004 // range check them here.
2005 int i = 0, l = 0, u = 0;
2006 switch (BuiltinID) {
2009 case X86::BI_mm_prefetch:
2010 i = 1; l = 0; u = 3;
2012 case X86::BI__builtin_ia32_sha1rnds4:
2013 case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
2014 case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
2015 case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
2016 case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
2017 i = 2; l = 0; u = 3;
2019 case X86::BI__builtin_ia32_vpermil2pd:
2020 case X86::BI__builtin_ia32_vpermil2pd256:
2021 case X86::BI__builtin_ia32_vpermil2ps:
2022 case X86::BI__builtin_ia32_vpermil2ps256:
2023 i = 3; l = 0; u = 3;
2025 case X86::BI__builtin_ia32_cmpb128_mask:
2026 case X86::BI__builtin_ia32_cmpw128_mask:
2027 case X86::BI__builtin_ia32_cmpd128_mask:
2028 case X86::BI__builtin_ia32_cmpq128_mask:
2029 case X86::BI__builtin_ia32_cmpb256_mask:
2030 case X86::BI__builtin_ia32_cmpw256_mask:
2031 case X86::BI__builtin_ia32_cmpd256_mask:
2032 case X86::BI__builtin_ia32_cmpq256_mask:
2033 case X86::BI__builtin_ia32_cmpb512_mask:
2034 case X86::BI__builtin_ia32_cmpw512_mask:
2035 case X86::BI__builtin_ia32_cmpd512_mask:
2036 case X86::BI__builtin_ia32_cmpq512_mask:
2037 case X86::BI__builtin_ia32_ucmpb128_mask:
2038 case X86::BI__builtin_ia32_ucmpw128_mask:
2039 case X86::BI__builtin_ia32_ucmpd128_mask:
2040 case X86::BI__builtin_ia32_ucmpq128_mask:
2041 case X86::BI__builtin_ia32_ucmpb256_mask:
2042 case X86::BI__builtin_ia32_ucmpw256_mask:
2043 case X86::BI__builtin_ia32_ucmpd256_mask:
2044 case X86::BI__builtin_ia32_ucmpq256_mask:
2045 case X86::BI__builtin_ia32_ucmpb512_mask:
2046 case X86::BI__builtin_ia32_ucmpw512_mask:
2047 case X86::BI__builtin_ia32_ucmpd512_mask:
2048 case X86::BI__builtin_ia32_ucmpq512_mask:
2049 case X86::BI__builtin_ia32_vpcomub:
2050 case X86::BI__builtin_ia32_vpcomuw:
2051 case X86::BI__builtin_ia32_vpcomud:
2052 case X86::BI__builtin_ia32_vpcomuq:
2053 case X86::BI__builtin_ia32_vpcomb:
2054 case X86::BI__builtin_ia32_vpcomw:
2055 case X86::BI__builtin_ia32_vpcomd:
2056 case X86::BI__builtin_ia32_vpcomq:
2057 i = 2; l = 0; u = 7;
2059 case X86::BI__builtin_ia32_roundps:
2060 case X86::BI__builtin_ia32_roundpd:
2061 case X86::BI__builtin_ia32_roundps256:
2062 case X86::BI__builtin_ia32_roundpd256:
2063 i = 1; l = 0; u = 15;
2065 case X86::BI__builtin_ia32_roundss:
2066 case X86::BI__builtin_ia32_roundsd:
2067 case X86::BI__builtin_ia32_rangepd128_mask:
2068 case X86::BI__builtin_ia32_rangepd256_mask:
2069 case X86::BI__builtin_ia32_rangepd512_mask:
2070 case X86::BI__builtin_ia32_rangeps128_mask:
2071 case X86::BI__builtin_ia32_rangeps256_mask:
2072 case X86::BI__builtin_ia32_rangeps512_mask:
2073 case X86::BI__builtin_ia32_getmantsd_round_mask:
2074 case X86::BI__builtin_ia32_getmantss_round_mask:
2075 i = 2; l = 0; u = 15;
2077 case X86::BI__builtin_ia32_cmpps:
2078 case X86::BI__builtin_ia32_cmpss:
2079 case X86::BI__builtin_ia32_cmppd:
2080 case X86::BI__builtin_ia32_cmpsd:
2081 case X86::BI__builtin_ia32_cmpps256:
2082 case X86::BI__builtin_ia32_cmppd256:
2083 case X86::BI__builtin_ia32_cmpps128_mask:
2084 case X86::BI__builtin_ia32_cmppd128_mask:
2085 case X86::BI__builtin_ia32_cmpps256_mask:
2086 case X86::BI__builtin_ia32_cmppd256_mask:
2087 case X86::BI__builtin_ia32_cmpps512_mask:
2088 case X86::BI__builtin_ia32_cmppd512_mask:
2089 case X86::BI__builtin_ia32_cmpsd_mask:
2090 case X86::BI__builtin_ia32_cmpss_mask:
2091 i = 2; l = 0; u = 31;
2093 case X86::BI__builtin_ia32_xabort:
2094 i = 0; l = -128; u = 255;
2096 case X86::BI__builtin_ia32_pshufw:
2097 case X86::BI__builtin_ia32_aeskeygenassist128:
2098 i = 1; l = -128; u = 255;
2100 case X86::BI__builtin_ia32_vcvtps2ph:
2101 case X86::BI__builtin_ia32_vcvtps2ph256:
2102 case X86::BI__builtin_ia32_rndscaleps_128_mask:
2103 case X86::BI__builtin_ia32_rndscalepd_128_mask:
2104 case X86::BI__builtin_ia32_rndscaleps_256_mask:
2105 case X86::BI__builtin_ia32_rndscalepd_256_mask:
2106 case X86::BI__builtin_ia32_rndscaleps_mask:
2107 case X86::BI__builtin_ia32_rndscalepd_mask:
2108 case X86::BI__builtin_ia32_reducepd128_mask:
2109 case X86::BI__builtin_ia32_reducepd256_mask:
2110 case X86::BI__builtin_ia32_reducepd512_mask:
2111 case X86::BI__builtin_ia32_reduceps128_mask:
2112 case X86::BI__builtin_ia32_reduceps256_mask:
2113 case X86::BI__builtin_ia32_reduceps512_mask:
2114 case X86::BI__builtin_ia32_prold512_mask:
2115 case X86::BI__builtin_ia32_prolq512_mask:
2116 case X86::BI__builtin_ia32_prold128_mask:
2117 case X86::BI__builtin_ia32_prold256_mask:
2118 case X86::BI__builtin_ia32_prolq128_mask:
2119 case X86::BI__builtin_ia32_prolq256_mask:
2120 case X86::BI__builtin_ia32_prord128_mask:
2121 case X86::BI__builtin_ia32_prord256_mask:
2122 case X86::BI__builtin_ia32_prorq128_mask:
2123 case X86::BI__builtin_ia32_prorq256_mask:
2124 case X86::BI__builtin_ia32_fpclasspd128_mask:
2125 case X86::BI__builtin_ia32_fpclasspd256_mask:
2126 case X86::BI__builtin_ia32_fpclassps128_mask:
2127 case X86::BI__builtin_ia32_fpclassps256_mask:
2128 case X86::BI__builtin_ia32_fpclassps512_mask:
2129 case X86::BI__builtin_ia32_fpclasspd512_mask:
2130 case X86::BI__builtin_ia32_fpclasssd_mask:
2131 case X86::BI__builtin_ia32_fpclassss_mask:
2132 i = 1; l = 0; u = 255;
2134 case X86::BI__builtin_ia32_palignr:
2135 case X86::BI__builtin_ia32_insertps128:
2136 case X86::BI__builtin_ia32_dpps:
2137 case X86::BI__builtin_ia32_dppd:
2138 case X86::BI__builtin_ia32_dpps256:
2139 case X86::BI__builtin_ia32_mpsadbw128:
2140 case X86::BI__builtin_ia32_mpsadbw256:
2141 case X86::BI__builtin_ia32_pcmpistrm128:
2142 case X86::BI__builtin_ia32_pcmpistri128:
2143 case X86::BI__builtin_ia32_pcmpistria128:
2144 case X86::BI__builtin_ia32_pcmpistric128:
2145 case X86::BI__builtin_ia32_pcmpistrio128:
2146 case X86::BI__builtin_ia32_pcmpistris128:
2147 case X86::BI__builtin_ia32_pcmpistriz128:
2148 case X86::BI__builtin_ia32_pclmulqdq128:
2149 case X86::BI__builtin_ia32_vperm2f128_pd256:
2150 case X86::BI__builtin_ia32_vperm2f128_ps256:
2151 case X86::BI__builtin_ia32_vperm2f128_si256:
2152 case X86::BI__builtin_ia32_permti256:
2153 i = 2; l = -128; u = 255;
2155 case X86::BI__builtin_ia32_palignr128:
2156 case X86::BI__builtin_ia32_palignr256:
2157 case X86::BI__builtin_ia32_palignr512_mask:
2158 case X86::BI__builtin_ia32_vcomisd:
2159 case X86::BI__builtin_ia32_vcomiss:
2160 case X86::BI__builtin_ia32_shuf_f32x4_mask:
2161 case X86::BI__builtin_ia32_shuf_f64x2_mask:
2162 case X86::BI__builtin_ia32_shuf_i32x4_mask:
2163 case X86::BI__builtin_ia32_shuf_i64x2_mask:
2164 case X86::BI__builtin_ia32_dbpsadbw128_mask:
2165 case X86::BI__builtin_ia32_dbpsadbw256_mask:
2166 case X86::BI__builtin_ia32_dbpsadbw512_mask:
2167 i = 2; l = 0; u = 255;
2169 case X86::BI__builtin_ia32_fixupimmpd512_mask:
2170 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2171 case X86::BI__builtin_ia32_fixupimmps512_mask:
2172 case X86::BI__builtin_ia32_fixupimmps512_maskz:
2173 case X86::BI__builtin_ia32_fixupimmsd_mask:
2174 case X86::BI__builtin_ia32_fixupimmsd_maskz:
2175 case X86::BI__builtin_ia32_fixupimmss_mask:
2176 case X86::BI__builtin_ia32_fixupimmss_maskz:
2177 case X86::BI__builtin_ia32_fixupimmpd128_mask:
2178 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2179 case X86::BI__builtin_ia32_fixupimmpd256_mask:
2180 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2181 case X86::BI__builtin_ia32_fixupimmps128_mask:
2182 case X86::BI__builtin_ia32_fixupimmps128_maskz:
2183 case X86::BI__builtin_ia32_fixupimmps256_mask:
2184 case X86::BI__builtin_ia32_fixupimmps256_maskz:
2185 case X86::BI__builtin_ia32_pternlogd512_mask:
2186 case X86::BI__builtin_ia32_pternlogd512_maskz:
2187 case X86::BI__builtin_ia32_pternlogq512_mask:
2188 case X86::BI__builtin_ia32_pternlogq512_maskz:
2189 case X86::BI__builtin_ia32_pternlogd128_mask:
2190 case X86::BI__builtin_ia32_pternlogd128_maskz:
2191 case X86::BI__builtin_ia32_pternlogd256_mask:
2192 case X86::BI__builtin_ia32_pternlogd256_maskz:
2193 case X86::BI__builtin_ia32_pternlogq128_mask:
2194 case X86::BI__builtin_ia32_pternlogq128_maskz:
2195 case X86::BI__builtin_ia32_pternlogq256_mask:
2196 case X86::BI__builtin_ia32_pternlogq256_maskz:
2197 i = 3; l = 0; u = 255;
2199 case X86::BI__builtin_ia32_pcmpestrm128:
2200 case X86::BI__builtin_ia32_pcmpestri128:
2201 case X86::BI__builtin_ia32_pcmpestria128:
2202 case X86::BI__builtin_ia32_pcmpestric128:
2203 case X86::BI__builtin_ia32_pcmpestrio128:
2204 case X86::BI__builtin_ia32_pcmpestris128:
2205 case X86::BI__builtin_ia32_pcmpestriz128:
2206 i = 4; l = -128; u = 255;
2208 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2209 case X86::BI__builtin_ia32_rndscaless_round_mask:
2210 i = 4; l = 0; u = 255;
2213 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2216 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2217 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
2218 /// Returns true when the format fits the function and the FormatStringInfo has
2220 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2221 FormatStringInfo *FSI) {
2222 FSI->HasVAListArg = Format->getFirstArg() == 0;
2223 FSI->FormatIdx = Format->getFormatIdx() - 1;
2224 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
2226 // The way the format attribute works in GCC, the implicit this argument
2227 // of member functions is counted. However, it doesn't appear in our own
2228 // lists, so decrement format_idx in that case.
2230 if(FSI->FormatIdx == 0)
2233 if (FSI->FirstDataArg != 0)
2234 --FSI->FirstDataArg;
2239 /// Checks if a the given expression evaluates to null.
2241 /// \brief Returns true if the value evaluates to null.
2242 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
2243 // If the expression has non-null type, it doesn't evaluate to null.
2244 if (auto nullability
2245 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2246 if (*nullability == NullabilityKind::NonNull)
2250 // As a special case, transparent unions initialized with zero are
2251 // considered null for the purposes of the nonnull attribute.
2252 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
2253 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2254 if (const CompoundLiteralExpr *CLE =
2255 dyn_cast<CompoundLiteralExpr>(Expr))
2256 if (const InitListExpr *ILE =
2257 dyn_cast<InitListExpr>(CLE->getInitializer()))
2258 Expr = ILE->getInit(0);
2262 return (!Expr->isValueDependent() &&
2263 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2267 static void CheckNonNullArgument(Sema &S,
2268 const Expr *ArgExpr,
2269 SourceLocation CallSiteLoc) {
2270 if (CheckNonNullExpr(S, ArgExpr))
2271 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2272 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
2275 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2276 FormatStringInfo FSI;
2277 if ((GetFormatStringType(Format) == FST_NSString) &&
2278 getFormatStringInfo(Format, false, &FSI)) {
2279 Idx = FSI.FormatIdx;
2284 /// \brief Diagnose use of %s directive in an NSString which is being passed
2285 /// as formatting string to formatting method.
2287 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
2288 const NamedDecl *FDecl,
2292 bool Format = false;
2293 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2294 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
2299 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2300 if (S.GetFormatNSStringIdx(I, Idx)) {
2305 if (!Format || NumArgs <= Idx)
2307 const Expr *FormatExpr = Args[Idx];
2308 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2309 FormatExpr = CSCE->getSubExpr();
2310 const StringLiteral *FormatString;
2311 if (const ObjCStringLiteral *OSL =
2312 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2313 FormatString = OSL->getString();
2315 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2318 if (S.FormatStringHasSArg(FormatString)) {
2319 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2321 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2322 << FDecl->getDeclName();
2326 /// Determine whether the given type has a non-null nullability annotation.
2327 static bool isNonNullType(ASTContext &ctx, QualType type) {
2328 if (auto nullability = type->getNullability(ctx))
2329 return *nullability == NullabilityKind::NonNull;
2334 static void CheckNonNullArguments(Sema &S,
2335 const NamedDecl *FDecl,
2336 const FunctionProtoType *Proto,
2337 ArrayRef<const Expr *> Args,
2338 SourceLocation CallSiteLoc) {
2339 assert((FDecl || Proto) && "Need a function declaration or prototype");
2341 // Check the attributes attached to the method/function itself.
2342 llvm::SmallBitVector NonNullArgs;
2344 // Handle the nonnull attribute on the function/method declaration itself.
2345 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2346 if (!NonNull->args_size()) {
2347 // Easy case: all pointer arguments are nonnull.
2348 for (const auto *Arg : Args)
2349 if (S.isValidPointerAttrType(Arg->getType()))
2350 CheckNonNullArgument(S, Arg, CallSiteLoc);
2354 for (unsigned Val : NonNull->args()) {
2355 if (Val >= Args.size())
2357 if (NonNullArgs.empty())
2358 NonNullArgs.resize(Args.size());
2359 NonNullArgs.set(Val);
2364 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2365 // Handle the nonnull attribute on the parameters of the
2367 ArrayRef<ParmVarDecl*> parms;
2368 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2369 parms = FD->parameters();
2371 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2373 unsigned ParamIndex = 0;
2374 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2375 I != E; ++I, ++ParamIndex) {
2376 const ParmVarDecl *PVD = *I;
2377 if (PVD->hasAttr<NonNullAttr>() ||
2378 isNonNullType(S.Context, PVD->getType())) {
2379 if (NonNullArgs.empty())
2380 NonNullArgs.resize(Args.size());
2382 NonNullArgs.set(ParamIndex);
2386 // If we have a non-function, non-method declaration but no
2387 // function prototype, try to dig out the function prototype.
2389 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2390 QualType type = VD->getType().getNonReferenceType();
2391 if (auto pointerType = type->getAs<PointerType>())
2392 type = pointerType->getPointeeType();
2393 else if (auto blockType = type->getAs<BlockPointerType>())
2394 type = blockType->getPointeeType();
2395 // FIXME: data member pointers?
2397 // Dig out the function prototype, if there is one.
2398 Proto = type->getAs<FunctionProtoType>();
2402 // Fill in non-null argument information from the nullability
2403 // information on the parameter types (if we have them).
2406 for (auto paramType : Proto->getParamTypes()) {
2407 if (isNonNullType(S.Context, paramType)) {
2408 if (NonNullArgs.empty())
2409 NonNullArgs.resize(Args.size());
2411 NonNullArgs.set(Index);
2419 // Check for non-null arguments.
2420 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2421 ArgIndex != ArgIndexEnd; ++ArgIndex) {
2422 if (NonNullArgs[ArgIndex])
2423 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
2427 /// Handles the checks for format strings, non-POD arguments to vararg
2428 /// functions, and NULL arguments passed to non-NULL parameters.
2429 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
2430 ArrayRef<const Expr *> Args, bool IsMemberFunction,
2431 SourceLocation Loc, SourceRange Range,
2432 VariadicCallType CallType) {
2433 // FIXME: We should check as much as we can in the template definition.
2434 if (CurContext->isDependentContext())
2437 // Printf and scanf checking.
2438 llvm::SmallBitVector CheckedVarArgs;
2440 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2441 // Only create vector if there are format attributes.
2442 CheckedVarArgs.resize(Args.size());
2444 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
2449 // Refuse POD arguments that weren't caught by the format string
2451 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
2452 if (CallType != VariadicDoesNotApply &&
2453 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
2454 unsigned NumParams = Proto ? Proto->getNumParams()
2455 : FDecl && isa<FunctionDecl>(FDecl)
2456 ? cast<FunctionDecl>(FDecl)->getNumParams()
2457 : FDecl && isa<ObjCMethodDecl>(FDecl)
2458 ? cast<ObjCMethodDecl>(FDecl)->param_size()
2461 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
2462 // Args[ArgIdx] can be null in malformed code.
2463 if (const Expr *Arg = Args[ArgIdx]) {
2464 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
2465 checkVariadicArgument(Arg, CallType);
2470 if (FDecl || Proto) {
2471 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
2473 // Type safety checking.
2475 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
2476 CheckArgumentWithTypeTag(I, Args.data());
2481 /// CheckConstructorCall - Check a constructor call for correctness and safety
2482 /// properties not enforced by the C type system.
2483 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
2484 ArrayRef<const Expr *> Args,
2485 const FunctionProtoType *Proto,
2486 SourceLocation Loc) {
2487 VariadicCallType CallType =
2488 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
2489 checkCall(FDecl, Proto, Args, /*IsMemberFunction=*/true, Loc, SourceRange(),
2493 /// CheckFunctionCall - Check a direct function call for various correctness
2494 /// and safety properties not strictly enforced by the C type system.
2495 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2496 const FunctionProtoType *Proto) {
2497 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2498 isa<CXXMethodDecl>(FDecl);
2499 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2500 IsMemberOperatorCall;
2501 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2502 TheCall->getCallee());
2503 Expr** Args = TheCall->getArgs();
2504 unsigned NumArgs = TheCall->getNumArgs();
2505 if (IsMemberOperatorCall) {
2506 // If this is a call to a member operator, hide the first argument
2508 // FIXME: Our choice of AST representation here is less than ideal.
2512 checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs),
2513 IsMemberFunction, TheCall->getRParenLoc(),
2514 TheCall->getCallee()->getSourceRange(), CallType);
2516 IdentifierInfo *FnInfo = FDecl->getIdentifier();
2517 // None of the checks below are needed for functions that don't have
2518 // simple names (e.g., C++ conversion functions).
2522 CheckAbsoluteValueFunction(TheCall, FDecl);
2523 CheckMaxUnsignedZero(TheCall, FDecl);
2525 if (getLangOpts().ObjC1)
2526 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
2528 unsigned CMId = FDecl->getMemoryFunctionKind();
2532 // Handle memory setting and copying functions.
2533 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
2534 CheckStrlcpycatArguments(TheCall, FnInfo);
2535 else if (CMId == Builtin::BIstrncat)
2536 CheckStrncatArguments(TheCall, FnInfo);
2538 CheckMemaccessArguments(TheCall, CMId, FnInfo);
2543 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
2544 ArrayRef<const Expr *> Args) {
2545 VariadicCallType CallType =
2546 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
2548 checkCall(Method, nullptr, Args,
2549 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
2555 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2556 const FunctionProtoType *Proto) {
2558 if (const auto *V = dyn_cast<VarDecl>(NDecl))
2559 Ty = V->getType().getNonReferenceType();
2560 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
2561 Ty = F->getType().getNonReferenceType();
2565 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2566 !Ty->isFunctionProtoType())
2569 VariadicCallType CallType;
2570 if (!Proto || !Proto->isVariadic()) {
2571 CallType = VariadicDoesNotApply;
2572 } else if (Ty->isBlockPointerType()) {
2573 CallType = VariadicBlock;
2574 } else { // Ty->isFunctionPointerType()
2575 CallType = VariadicFunction;
2578 checkCall(NDecl, Proto,
2579 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2580 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
2581 TheCall->getCallee()->getSourceRange(), CallType);
2586 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2587 /// such as function pointers returned from functions.
2588 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
2589 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
2590 TheCall->getCallee());
2591 checkCall(/*FDecl=*/nullptr, Proto,
2592 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2593 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
2594 TheCall->getCallee()->getSourceRange(), CallType);
2599 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
2600 if (!llvm::isValidAtomicOrderingCABI(Ordering))
2603 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
2605 case AtomicExpr::AO__c11_atomic_init:
2606 llvm_unreachable("There is no ordering argument for an init");
2608 case AtomicExpr::AO__c11_atomic_load:
2609 case AtomicExpr::AO__atomic_load_n:
2610 case AtomicExpr::AO__atomic_load:
2611 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2612 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2614 case AtomicExpr::AO__c11_atomic_store:
2615 case AtomicExpr::AO__atomic_store:
2616 case AtomicExpr::AO__atomic_store_n:
2617 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2618 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2619 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2626 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2627 AtomicExpr::AtomicOp Op) {
2628 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2629 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2631 // All these operations take one of the following forms:
2633 // C __c11_atomic_init(A *, C)
2635 // C __c11_atomic_load(A *, int)
2637 // void __atomic_load(A *, CP, int)
2639 // void __atomic_store(A *, CP, int)
2641 // C __c11_atomic_add(A *, M, int)
2643 // C __atomic_exchange_n(A *, CP, int)
2645 // void __atomic_exchange(A *, C *, CP, int)
2647 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
2649 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
2652 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2653 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
2655 // C is an appropriate type,
2656 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
2657 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
2658 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
2659 // the int parameters are for orderings.
2661 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
2662 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
2663 AtomicExpr::AO__atomic_load,
2664 "need to update code for modified C11 atomics");
2665 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
2666 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
2667 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
2668 Op == AtomicExpr::AO__atomic_store_n ||
2669 Op == AtomicExpr::AO__atomic_exchange_n ||
2670 Op == AtomicExpr::AO__atomic_compare_exchange_n;
2671 bool IsAddSub = false;
2674 case AtomicExpr::AO__c11_atomic_init:
2678 case AtomicExpr::AO__c11_atomic_load:
2679 case AtomicExpr::AO__atomic_load_n:
2683 case AtomicExpr::AO__atomic_load:
2687 case AtomicExpr::AO__c11_atomic_store:
2688 case AtomicExpr::AO__atomic_store:
2689 case AtomicExpr::AO__atomic_store_n:
2693 case AtomicExpr::AO__c11_atomic_fetch_add:
2694 case AtomicExpr::AO__c11_atomic_fetch_sub:
2695 case AtomicExpr::AO__atomic_fetch_add:
2696 case AtomicExpr::AO__atomic_fetch_sub:
2697 case AtomicExpr::AO__atomic_add_fetch:
2698 case AtomicExpr::AO__atomic_sub_fetch:
2701 case AtomicExpr::AO__c11_atomic_fetch_and:
2702 case AtomicExpr::AO__c11_atomic_fetch_or:
2703 case AtomicExpr::AO__c11_atomic_fetch_xor:
2704 case AtomicExpr::AO__atomic_fetch_and:
2705 case AtomicExpr::AO__atomic_fetch_or:
2706 case AtomicExpr::AO__atomic_fetch_xor:
2707 case AtomicExpr::AO__atomic_fetch_nand:
2708 case AtomicExpr::AO__atomic_and_fetch:
2709 case AtomicExpr::AO__atomic_or_fetch:
2710 case AtomicExpr::AO__atomic_xor_fetch:
2711 case AtomicExpr::AO__atomic_nand_fetch:
2715 case AtomicExpr::AO__c11_atomic_exchange:
2716 case AtomicExpr::AO__atomic_exchange_n:
2720 case AtomicExpr::AO__atomic_exchange:
2724 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
2725 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
2729 case AtomicExpr::AO__atomic_compare_exchange:
2730 case AtomicExpr::AO__atomic_compare_exchange_n:
2735 // Check we have the right number of arguments.
2736 if (TheCall->getNumArgs() < NumArgs[Form]) {
2737 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
2738 << 0 << NumArgs[Form] << TheCall->getNumArgs()
2739 << TheCall->getCallee()->getSourceRange();
2741 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
2742 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
2743 diag::err_typecheck_call_too_many_args)
2744 << 0 << NumArgs[Form] << TheCall->getNumArgs()
2745 << TheCall->getCallee()->getSourceRange();
2749 // Inspect the first argument of the atomic operation.
2750 Expr *Ptr = TheCall->getArg(0);
2751 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
2752 if (ConvertedPtr.isInvalid())
2755 Ptr = ConvertedPtr.get();
2756 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
2758 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
2759 << Ptr->getType() << Ptr->getSourceRange();
2763 // For a __c11 builtin, this should be a pointer to an _Atomic type.
2764 QualType AtomTy = pointerType->getPointeeType(); // 'A'
2765 QualType ValType = AtomTy; // 'C'
2767 if (!AtomTy->isAtomicType()) {
2768 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
2769 << Ptr->getType() << Ptr->getSourceRange();
2772 if (AtomTy.isConstQualified()) {
2773 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
2774 << Ptr->getType() << Ptr->getSourceRange();
2777 ValType = AtomTy->getAs<AtomicType>()->getValueType();
2778 } else if (Form != Load && Form != LoadCopy) {
2779 if (ValType.isConstQualified()) {
2780 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
2781 << Ptr->getType() << Ptr->getSourceRange();
2786 // For an arithmetic operation, the implied arithmetic must be well-formed.
2787 if (Form == Arithmetic) {
2788 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
2789 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
2790 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
2791 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2794 if (!IsAddSub && !ValType->isIntegerType()) {
2795 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
2796 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2799 if (IsC11 && ValType->isPointerType() &&
2800 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
2801 diag::err_incomplete_type)) {
2804 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
2805 // For __atomic_*_n operations, the value type must be a scalar integral or
2806 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
2807 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
2808 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2812 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
2813 !AtomTy->isScalarType()) {
2814 // For GNU atomics, require a trivially-copyable type. This is not part of
2815 // the GNU atomics specification, but we enforce it for sanity.
2816 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
2817 << Ptr->getType() << Ptr->getSourceRange();
2821 switch (ValType.getObjCLifetime()) {
2822 case Qualifiers::OCL_None:
2823 case Qualifiers::OCL_ExplicitNone:
2827 case Qualifiers::OCL_Weak:
2828 case Qualifiers::OCL_Strong:
2829 case Qualifiers::OCL_Autoreleasing:
2830 // FIXME: Can this happen? By this point, ValType should be known
2831 // to be trivially copyable.
2832 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
2833 << ValType << Ptr->getSourceRange();
2837 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
2838 // volatile-ness of the pointee-type inject itself into the result or the
2839 // other operands. Similarly atomic_load can take a pointer to a const 'A'.
2840 ValType.removeLocalVolatile();
2841 ValType.removeLocalConst();
2842 QualType ResultType = ValType;
2843 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init)
2844 ResultType = Context.VoidTy;
2845 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
2846 ResultType = Context.BoolTy;
2848 // The type of a parameter passed 'by value'. In the GNU atomics, such
2849 // arguments are actually passed as pointers.
2850 QualType ByValType = ValType; // 'CP'
2852 ByValType = Ptr->getType();
2854 // The first argument --- the pointer --- has a fixed type; we
2855 // deduce the types of the rest of the arguments accordingly. Walk
2856 // the remaining arguments, converting them to the deduced value type.
2857 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
2859 if (i < NumVals[Form] + 1) {
2862 // The second argument is the non-atomic operand. For arithmetic, this
2863 // is always passed by value, and for a compare_exchange it is always
2864 // passed by address. For the rest, GNU uses by-address and C11 uses
2866 assert(Form != Load);
2867 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
2869 else if (Form == Copy || Form == Xchg)
2871 else if (Form == Arithmetic)
2872 Ty = Context.getPointerDiffType();
2874 Expr *ValArg = TheCall->getArg(i);
2875 // Treat this argument as _Nonnull as we want to show a warning if
2876 // NULL is passed into it.
2877 CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
2879 // Keep address space of non-atomic pointer type.
2880 if (const PointerType *PtrTy =
2881 ValArg->getType()->getAs<PointerType>()) {
2882 AS = PtrTy->getPointeeType().getAddressSpace();
2884 Ty = Context.getPointerType(
2885 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
2889 // The third argument to compare_exchange / GNU exchange is a
2890 // (pointer to a) desired value.
2894 // The fourth argument to GNU compare_exchange is a 'weak' flag.
2895 Ty = Context.BoolTy;
2899 // The order(s) are always converted to int.
2903 InitializedEntity Entity =
2904 InitializedEntity::InitializeParameter(Context, Ty, false);
2905 ExprResult Arg = TheCall->getArg(i);
2906 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2907 if (Arg.isInvalid())
2909 TheCall->setArg(i, Arg.get());
2912 // Permute the arguments into a 'consistent' order.
2913 SmallVector<Expr*, 5> SubExprs;
2914 SubExprs.push_back(Ptr);
2917 // Note, AtomicExpr::getVal1() has a special case for this atomic.
2918 SubExprs.push_back(TheCall->getArg(1)); // Val1
2921 SubExprs.push_back(TheCall->getArg(1)); // Order
2927 SubExprs.push_back(TheCall->getArg(2)); // Order
2928 SubExprs.push_back(TheCall->getArg(1)); // Val1
2931 // Note, AtomicExpr::getVal2() has a special case for this atomic.
2932 SubExprs.push_back(TheCall->getArg(3)); // Order
2933 SubExprs.push_back(TheCall->getArg(1)); // Val1
2934 SubExprs.push_back(TheCall->getArg(2)); // Val2
2937 SubExprs.push_back(TheCall->getArg(3)); // Order
2938 SubExprs.push_back(TheCall->getArg(1)); // Val1
2939 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
2940 SubExprs.push_back(TheCall->getArg(2)); // Val2
2943 SubExprs.push_back(TheCall->getArg(4)); // Order
2944 SubExprs.push_back(TheCall->getArg(1)); // Val1
2945 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
2946 SubExprs.push_back(TheCall->getArg(2)); // Val2
2947 SubExprs.push_back(TheCall->getArg(3)); // Weak
2951 if (SubExprs.size() >= 2 && Form != Init) {
2952 llvm::APSInt Result(32);
2953 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
2954 !isValidOrderingForOp(Result.getSExtValue(), Op))
2955 Diag(SubExprs[1]->getLocStart(),
2956 diag::warn_atomic_op_has_invalid_memory_order)
2957 << SubExprs[1]->getSourceRange();
2960 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
2961 SubExprs, ResultType, Op,
2962 TheCall->getRParenLoc());
2964 if ((Op == AtomicExpr::AO__c11_atomic_load ||
2965 (Op == AtomicExpr::AO__c11_atomic_store)) &&
2966 Context.AtomicUsesUnsupportedLibcall(AE))
2967 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
2968 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
2973 /// checkBuiltinArgument - Given a call to a builtin function, perform
2974 /// normal type-checking on the given argument, updating the call in
2975 /// place. This is useful when a builtin function requires custom
2976 /// type-checking for some of its arguments but not necessarily all of
2979 /// Returns true on error.
2980 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
2981 FunctionDecl *Fn = E->getDirectCallee();
2982 assert(Fn && "builtin call without direct callee!");
2984 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
2985 InitializedEntity Entity =
2986 InitializedEntity::InitializeParameter(S.Context, Param);
2988 ExprResult Arg = E->getArg(0);
2989 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
2990 if (Arg.isInvalid())
2993 E->setArg(ArgIndex, Arg.get());
2997 /// SemaBuiltinAtomicOverloaded - We have a call to a function like
2998 /// __sync_fetch_and_add, which is an overloaded function based on the pointer
2999 /// type of its first argument. The main ActOnCallExpr routines have already
3000 /// promoted the types of arguments because all of these calls are prototyped as
3003 /// This function goes through and does final semantic checking for these
3006 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
3007 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3008 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3009 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3011 // Ensure that we have at least one argument to do type inference from.
3012 if (TheCall->getNumArgs() < 1) {
3013 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3014 << 0 << 1 << TheCall->getNumArgs()
3015 << TheCall->getCallee()->getSourceRange();
3019 // Inspect the first argument of the atomic builtin. This should always be
3020 // a pointer type, whose element is an integral scalar or pointer type.
3021 // Because it is a pointer type, we don't have to worry about any implicit
3023 // FIXME: We don't allow floating point scalars as input.
3024 Expr *FirstArg = TheCall->getArg(0);
3025 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3026 if (FirstArgResult.isInvalid())
3028 FirstArg = FirstArgResult.get();
3029 TheCall->setArg(0, FirstArg);
3031 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3033 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3034 << FirstArg->getType() << FirstArg->getSourceRange();
3038 QualType ValType = pointerType->getPointeeType();
3039 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3040 !ValType->isBlockPointerType()) {
3041 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3042 << FirstArg->getType() << FirstArg->getSourceRange();
3046 switch (ValType.getObjCLifetime()) {
3047 case Qualifiers::OCL_None:
3048 case Qualifiers::OCL_ExplicitNone:
3052 case Qualifiers::OCL_Weak:
3053 case Qualifiers::OCL_Strong:
3054 case Qualifiers::OCL_Autoreleasing:
3055 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3056 << ValType << FirstArg->getSourceRange();
3060 // Strip any qualifiers off ValType.
3061 ValType = ValType.getUnqualifiedType();
3063 // The majority of builtins return a value, but a few have special return
3064 // types, so allow them to override appropriately below.
3065 QualType ResultType = ValType;
3067 // We need to figure out which concrete builtin this maps onto. For example,
3068 // __sync_fetch_and_add with a 2 byte object turns into
3069 // __sync_fetch_and_add_2.
3070 #define BUILTIN_ROW(x) \
3071 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3072 Builtin::BI##x##_8, Builtin::BI##x##_16 }
3074 static const unsigned BuiltinIndices[][5] = {
3075 BUILTIN_ROW(__sync_fetch_and_add),
3076 BUILTIN_ROW(__sync_fetch_and_sub),
3077 BUILTIN_ROW(__sync_fetch_and_or),
3078 BUILTIN_ROW(__sync_fetch_and_and),
3079 BUILTIN_ROW(__sync_fetch_and_xor),
3080 BUILTIN_ROW(__sync_fetch_and_nand),
3082 BUILTIN_ROW(__sync_add_and_fetch),
3083 BUILTIN_ROW(__sync_sub_and_fetch),
3084 BUILTIN_ROW(__sync_and_and_fetch),
3085 BUILTIN_ROW(__sync_or_and_fetch),
3086 BUILTIN_ROW(__sync_xor_and_fetch),
3087 BUILTIN_ROW(__sync_nand_and_fetch),
3089 BUILTIN_ROW(__sync_val_compare_and_swap),
3090 BUILTIN_ROW(__sync_bool_compare_and_swap),
3091 BUILTIN_ROW(__sync_lock_test_and_set),
3092 BUILTIN_ROW(__sync_lock_release),
3093 BUILTIN_ROW(__sync_swap)
3097 // Determine the index of the size.
3099 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
3100 case 1: SizeIndex = 0; break;
3101 case 2: SizeIndex = 1; break;
3102 case 4: SizeIndex = 2; break;
3103 case 8: SizeIndex = 3; break;
3104 case 16: SizeIndex = 4; break;
3106 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3107 << FirstArg->getType() << FirstArg->getSourceRange();
3111 // Each of these builtins has one pointer argument, followed by some number of
3112 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3113 // that we ignore. Find out which row of BuiltinIndices to read from as well
3114 // as the number of fixed args.
3115 unsigned BuiltinID = FDecl->getBuiltinID();
3116 unsigned BuiltinIndex, NumFixed = 1;
3117 bool WarnAboutSemanticsChange = false;
3118 switch (BuiltinID) {
3119 default: llvm_unreachable("Unknown overloaded atomic builtin!");
3120 case Builtin::BI__sync_fetch_and_add:
3121 case Builtin::BI__sync_fetch_and_add_1:
3122 case Builtin::BI__sync_fetch_and_add_2:
3123 case Builtin::BI__sync_fetch_and_add_4:
3124 case Builtin::BI__sync_fetch_and_add_8:
3125 case Builtin::BI__sync_fetch_and_add_16:
3129 case Builtin::BI__sync_fetch_and_sub:
3130 case Builtin::BI__sync_fetch_and_sub_1:
3131 case Builtin::BI__sync_fetch_and_sub_2:
3132 case Builtin::BI__sync_fetch_and_sub_4:
3133 case Builtin::BI__sync_fetch_and_sub_8:
3134 case Builtin::BI__sync_fetch_and_sub_16:
3138 case Builtin::BI__sync_fetch_and_or:
3139 case Builtin::BI__sync_fetch_and_or_1:
3140 case Builtin::BI__sync_fetch_and_or_2:
3141 case Builtin::BI__sync_fetch_and_or_4:
3142 case Builtin::BI__sync_fetch_and_or_8:
3143 case Builtin::BI__sync_fetch_and_or_16:
3147 case Builtin::BI__sync_fetch_and_and:
3148 case Builtin::BI__sync_fetch_and_and_1:
3149 case Builtin::BI__sync_fetch_and_and_2:
3150 case Builtin::BI__sync_fetch_and_and_4:
3151 case Builtin::BI__sync_fetch_and_and_8:
3152 case Builtin::BI__sync_fetch_and_and_16:
3156 case Builtin::BI__sync_fetch_and_xor:
3157 case Builtin::BI__sync_fetch_and_xor_1:
3158 case Builtin::BI__sync_fetch_and_xor_2:
3159 case Builtin::BI__sync_fetch_and_xor_4:
3160 case Builtin::BI__sync_fetch_and_xor_8:
3161 case Builtin::BI__sync_fetch_and_xor_16:
3165 case Builtin::BI__sync_fetch_and_nand:
3166 case Builtin::BI__sync_fetch_and_nand_1:
3167 case Builtin::BI__sync_fetch_and_nand_2:
3168 case Builtin::BI__sync_fetch_and_nand_4:
3169 case Builtin::BI__sync_fetch_and_nand_8:
3170 case Builtin::BI__sync_fetch_and_nand_16:
3172 WarnAboutSemanticsChange = true;
3175 case Builtin::BI__sync_add_and_fetch:
3176 case Builtin::BI__sync_add_and_fetch_1:
3177 case Builtin::BI__sync_add_and_fetch_2:
3178 case Builtin::BI__sync_add_and_fetch_4:
3179 case Builtin::BI__sync_add_and_fetch_8:
3180 case Builtin::BI__sync_add_and_fetch_16:
3184 case Builtin::BI__sync_sub_and_fetch:
3185 case Builtin::BI__sync_sub_and_fetch_1:
3186 case Builtin::BI__sync_sub_and_fetch_2:
3187 case Builtin::BI__sync_sub_and_fetch_4:
3188 case Builtin::BI__sync_sub_and_fetch_8:
3189 case Builtin::BI__sync_sub_and_fetch_16:
3193 case Builtin::BI__sync_and_and_fetch:
3194 case Builtin::BI__sync_and_and_fetch_1:
3195 case Builtin::BI__sync_and_and_fetch_2:
3196 case Builtin::BI__sync_and_and_fetch_4:
3197 case Builtin::BI__sync_and_and_fetch_8:
3198 case Builtin::BI__sync_and_and_fetch_16:
3202 case Builtin::BI__sync_or_and_fetch:
3203 case Builtin::BI__sync_or_and_fetch_1:
3204 case Builtin::BI__sync_or_and_fetch_2:
3205 case Builtin::BI__sync_or_and_fetch_4:
3206 case Builtin::BI__sync_or_and_fetch_8:
3207 case Builtin::BI__sync_or_and_fetch_16:
3211 case Builtin::BI__sync_xor_and_fetch:
3212 case Builtin::BI__sync_xor_and_fetch_1:
3213 case Builtin::BI__sync_xor_and_fetch_2:
3214 case Builtin::BI__sync_xor_and_fetch_4:
3215 case Builtin::BI__sync_xor_and_fetch_8:
3216 case Builtin::BI__sync_xor_and_fetch_16:
3220 case Builtin::BI__sync_nand_and_fetch:
3221 case Builtin::BI__sync_nand_and_fetch_1:
3222 case Builtin::BI__sync_nand_and_fetch_2:
3223 case Builtin::BI__sync_nand_and_fetch_4:
3224 case Builtin::BI__sync_nand_and_fetch_8:
3225 case Builtin::BI__sync_nand_and_fetch_16:
3227 WarnAboutSemanticsChange = true;
3230 case Builtin::BI__sync_val_compare_and_swap:
3231 case Builtin::BI__sync_val_compare_and_swap_1:
3232 case Builtin::BI__sync_val_compare_and_swap_2:
3233 case Builtin::BI__sync_val_compare_and_swap_4:
3234 case Builtin::BI__sync_val_compare_and_swap_8:
3235 case Builtin::BI__sync_val_compare_and_swap_16:
3240 case Builtin::BI__sync_bool_compare_and_swap:
3241 case Builtin::BI__sync_bool_compare_and_swap_1:
3242 case Builtin::BI__sync_bool_compare_and_swap_2:
3243 case Builtin::BI__sync_bool_compare_and_swap_4:
3244 case Builtin::BI__sync_bool_compare_and_swap_8:
3245 case Builtin::BI__sync_bool_compare_and_swap_16:
3248 ResultType = Context.BoolTy;
3251 case Builtin::BI__sync_lock_test_and_set:
3252 case Builtin::BI__sync_lock_test_and_set_1:
3253 case Builtin::BI__sync_lock_test_and_set_2:
3254 case Builtin::BI__sync_lock_test_and_set_4:
3255 case Builtin::BI__sync_lock_test_and_set_8:
3256 case Builtin::BI__sync_lock_test_and_set_16:
3260 case Builtin::BI__sync_lock_release:
3261 case Builtin::BI__sync_lock_release_1:
3262 case Builtin::BI__sync_lock_release_2:
3263 case Builtin::BI__sync_lock_release_4:
3264 case Builtin::BI__sync_lock_release_8:
3265 case Builtin::BI__sync_lock_release_16:
3268 ResultType = Context.VoidTy;
3271 case Builtin::BI__sync_swap:
3272 case Builtin::BI__sync_swap_1:
3273 case Builtin::BI__sync_swap_2:
3274 case Builtin::BI__sync_swap_4:
3275 case Builtin::BI__sync_swap_8:
3276 case Builtin::BI__sync_swap_16:
3281 // Now that we know how many fixed arguments we expect, first check that we
3282 // have at least that many.
3283 if (TheCall->getNumArgs() < 1+NumFixed) {
3284 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3285 << 0 << 1+NumFixed << TheCall->getNumArgs()
3286 << TheCall->getCallee()->getSourceRange();
3290 if (WarnAboutSemanticsChange) {
3291 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
3292 << TheCall->getCallee()->getSourceRange();
3295 // Get the decl for the concrete builtin from this, we can tell what the
3296 // concrete integer type we should convert to is.
3297 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
3298 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
3299 FunctionDecl *NewBuiltinDecl;
3300 if (NewBuiltinID == BuiltinID)
3301 NewBuiltinDecl = FDecl;
3303 // Perform builtin lookup to avoid redeclaring it.
3304 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
3305 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
3306 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
3307 assert(Res.getFoundDecl());
3308 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
3309 if (!NewBuiltinDecl)
3313 // The first argument --- the pointer --- has a fixed type; we
3314 // deduce the types of the rest of the arguments accordingly. Walk
3315 // the remaining arguments, converting them to the deduced value type.
3316 for (unsigned i = 0; i != NumFixed; ++i) {
3317 ExprResult Arg = TheCall->getArg(i+1);
3319 // GCC does an implicit conversion to the pointer or integer ValType. This
3320 // can fail in some cases (1i -> int**), check for this error case now.
3321 // Initialize the argument.
3322 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3323 ValType, /*consume*/ false);
3324 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3325 if (Arg.isInvalid())
3328 // Okay, we have something that *can* be converted to the right type. Check
3329 // to see if there is a potentially weird extension going on here. This can
3330 // happen when you do an atomic operation on something like an char* and
3331 // pass in 42. The 42 gets converted to char. This is even more strange
3332 // for things like 45.123 -> char, etc.
3333 // FIXME: Do this check.
3334 TheCall->setArg(i+1, Arg.get());
3337 ASTContext& Context = this->getASTContext();
3339 // Create a new DeclRefExpr to refer to the new decl.
3340 DeclRefExpr* NewDRE = DeclRefExpr::Create(
3342 DRE->getQualifierLoc(),
3345 /*enclosing*/ false,
3347 Context.BuiltinFnTy,
3348 DRE->getValueKind());
3350 // Set the callee in the CallExpr.
3351 // FIXME: This loses syntactic information.
3352 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
3353 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
3354 CK_BuiltinFnToFnPtr);
3355 TheCall->setCallee(PromotedCall.get());
3357 // Change the result type of the call to match the original value type. This
3358 // is arbitrary, but the codegen for these builtins ins design to handle it
3360 TheCall->setType(ResultType);
3362 return TheCallResult;
3365 /// SemaBuiltinNontemporalOverloaded - We have a call to
3366 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3367 /// overloaded function based on the pointer type of its last argument.
3369 /// This function goes through and does final semantic checking for these
3371 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
3372 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3374 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3375 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3376 unsigned BuiltinID = FDecl->getBuiltinID();
3377 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
3378 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
3379 "Unexpected nontemporal load/store builtin!");
3380 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3381 unsigned numArgs = isStore ? 2 : 1;
3383 // Ensure that we have the proper number of arguments.
3384 if (checkArgCount(*this, TheCall, numArgs))
3387 // Inspect the last argument of the nontemporal builtin. This should always
3388 // be a pointer type, from which we imply the type of the memory access.
3389 // Because it is a pointer type, we don't have to worry about any implicit
3391 Expr *PointerArg = TheCall->getArg(numArgs - 1);
3392 ExprResult PointerArgResult =
3393 DefaultFunctionArrayLvalueConversion(PointerArg);
3395 if (PointerArgResult.isInvalid())
3397 PointerArg = PointerArgResult.get();
3398 TheCall->setArg(numArgs - 1, PointerArg);
3400 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3402 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3403 << PointerArg->getType() << PointerArg->getSourceRange();
3407 QualType ValType = pointerType->getPointeeType();
3409 // Strip any qualifiers off ValType.
3410 ValType = ValType.getUnqualifiedType();
3411 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3412 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
3413 !ValType->isVectorType()) {
3414 Diag(DRE->getLocStart(),
3415 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3416 << PointerArg->getType() << PointerArg->getSourceRange();
3421 TheCall->setType(ValType);
3422 return TheCallResult;
3425 ExprResult ValArg = TheCall->getArg(0);
3426 InitializedEntity Entity = InitializedEntity::InitializeParameter(
3427 Context, ValType, /*consume*/ false);
3428 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3429 if (ValArg.isInvalid())
3432 TheCall->setArg(0, ValArg.get());
3433 TheCall->setType(Context.VoidTy);
3434 return TheCallResult;
3437 /// CheckObjCString - Checks that the argument to the builtin
3438 /// CFString constructor is correct
3439 /// Note: It might also make sense to do the UTF-16 conversion here (would
3440 /// simplify the backend).
3441 bool Sema::CheckObjCString(Expr *Arg) {
3442 Arg = Arg->IgnoreParenCasts();
3443 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
3445 if (!Literal || !Literal->isAscii()) {
3446 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
3447 << Arg->getSourceRange();
3451 if (Literal->containsNonAsciiOrNull()) {
3452 StringRef String = Literal->getString();
3453 unsigned NumBytes = String.size();
3454 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
3455 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3456 llvm::UTF16 *ToPtr = &ToBuf[0];
3458 llvm::ConversionResult Result =
3459 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3460 ToPtr + NumBytes, llvm::strictConversion);
3461 // Check for conversion failure.
3462 if (Result != llvm::conversionOK)
3463 Diag(Arg->getLocStart(),
3464 diag::warn_cfstring_truncated) << Arg->getSourceRange();
3469 /// CheckObjCString - Checks that the format string argument to the os_log()
3470 /// and os_trace() functions is correct, and converts it to const char *.
3471 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
3472 Arg = Arg->IgnoreParenCasts();
3473 auto *Literal = dyn_cast<StringLiteral>(Arg);
3475 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
3476 Literal = ObjcLiteral->getString();
3480 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
3482 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
3483 << Arg->getSourceRange());
3486 ExprResult Result(Literal);
3487 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
3488 InitializedEntity Entity =
3489 InitializedEntity::InitializeParameter(Context, ResultTy, false);
3490 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
3494 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
3495 /// for validity. Emit an error and return true on failure; return false
3497 bool Sema::SemaBuiltinVAStartImpl(CallExpr *TheCall) {
3498 Expr *Fn = TheCall->getCallee();
3499 if (TheCall->getNumArgs() > 2) {
3500 Diag(TheCall->getArg(2)->getLocStart(),
3501 diag::err_typecheck_call_too_many_args)
3502 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3503 << Fn->getSourceRange()
3504 << SourceRange(TheCall->getArg(2)->getLocStart(),
3505 (*(TheCall->arg_end()-1))->getLocEnd());
3509 if (TheCall->getNumArgs() < 2) {
3510 return Diag(TheCall->getLocEnd(),
3511 diag::err_typecheck_call_too_few_args_at_least)
3512 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
3515 // Type-check the first argument normally.
3516 if (checkBuiltinArgument(*this, TheCall, 0))
3519 // Determine whether the current function is variadic or not.
3520 BlockScopeInfo *CurBlock = getCurBlock();
3523 isVariadic = CurBlock->TheDecl->isVariadic();
3524 else if (FunctionDecl *FD = getCurFunctionDecl())
3525 isVariadic = FD->isVariadic();
3527 isVariadic = getCurMethodDecl()->isVariadic();
3530 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3534 // Verify that the second argument to the builtin is the last argument of the
3535 // current function or method.
3536 bool SecondArgIsLastNamedArgument = false;
3537 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
3539 // These are valid if SecondArgIsLastNamedArgument is false after the next
3542 SourceLocation ParamLoc;
3543 bool IsCRegister = false;
3545 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
3546 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
3547 // FIXME: This isn't correct for methods (results in bogus warning).
3548 // Get the last formal in the current function.
3549 const ParmVarDecl *LastArg;
3551 LastArg = CurBlock->TheDecl->parameters().back();
3552 else if (FunctionDecl *FD = getCurFunctionDecl())
3553 LastArg = FD->parameters().back();
3555 LastArg = getCurMethodDecl()->parameters().back();
3556 SecondArgIsLastNamedArgument = PV == LastArg;
3558 Type = PV->getType();
3559 ParamLoc = PV->getLocation();
3561 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
3565 if (!SecondArgIsLastNamedArgument)
3566 Diag(TheCall->getArg(1)->getLocStart(),
3567 diag::warn_second_arg_of_va_start_not_last_named_param);
3568 else if (IsCRegister || Type->isReferenceType() ||
3569 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
3570 // Promotable integers are UB, but enumerations need a bit of
3571 // extra checking to see what their promotable type actually is.
3572 if (!Type->isPromotableIntegerType())
3574 if (!Type->isEnumeralType())
3576 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3578 Context.typesAreCompatible(ED->getPromotionType(), Type));
3580 unsigned Reason = 0;
3581 if (Type->isReferenceType()) Reason = 1;
3582 else if (IsCRegister) Reason = 2;
3583 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
3584 Diag(ParamLoc, diag::note_parameter_type) << Type;
3587 TheCall->setType(Context.VoidTy);
3591 /// Check the arguments to '__builtin_va_start' for validity, and that
3592 /// it was called from a function of the native ABI.
3593 /// Emit an error and return true on failure; return false on success.
3594 bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
3595 // On x86-64 Unix, don't allow this in Win64 ABI functions.
3596 // On x64 Windows, don't allow this in System V ABI functions.
3597 // (Yes, that means there's no corresponding way to support variadic
3598 // System V ABI functions on Windows.)
3599 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) {
3600 unsigned OS = Context.getTargetInfo().getTriple().getOS();
3601 clang::CallingConv CC = CC_C;
3602 if (const FunctionDecl *FD = getCurFunctionDecl())
3603 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3604 if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) ||
3605 (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64))
3606 return Diag(TheCall->getCallee()->getLocStart(),
3607 diag::err_va_start_used_in_wrong_abi_function)
3608 << (OS != llvm::Triple::Win32);
3610 return SemaBuiltinVAStartImpl(TheCall);
3613 /// Check the arguments to '__builtin_ms_va_start' for validity, and that
3614 /// it was called from a Win64 ABI function.
3615 /// Emit an error and return true on failure; return false on success.
3616 bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) {
3617 // This only makes sense for x86-64.
3618 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3619 Expr *Callee = TheCall->getCallee();
3620 if (TT.getArch() != llvm::Triple::x86_64)
3621 return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt);
3622 // Don't allow this in System V ABI functions.
3623 clang::CallingConv CC = CC_C;
3624 if (const FunctionDecl *FD = getCurFunctionDecl())
3625 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3626 if (CC == CC_X86_64SysV ||
3627 (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64))
3628 return Diag(Callee->getLocStart(),
3629 diag::err_ms_va_start_used_in_sysv_function);
3630 return SemaBuiltinVAStartImpl(TheCall);
3633 bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
3634 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
3635 // const char *named_addr);
3637 Expr *Func = Call->getCallee();
3639 if (Call->getNumArgs() < 3)
3640 return Diag(Call->getLocEnd(),
3641 diag::err_typecheck_call_too_few_args_at_least)
3642 << 0 /*function call*/ << 3 << Call->getNumArgs();
3644 // Determine whether the current function is variadic or not.
3646 if (BlockScopeInfo *CurBlock = getCurBlock())
3647 IsVariadic = CurBlock->TheDecl->isVariadic();
3648 else if (FunctionDecl *FD = getCurFunctionDecl())
3649 IsVariadic = FD->isVariadic();
3650 else if (ObjCMethodDecl *MD = getCurMethodDecl())
3651 IsVariadic = MD->isVariadic();
3653 llvm_unreachable("unexpected statement type");
3656 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3660 // Type-check the first argument normally.
3661 if (checkBuiltinArgument(*this, Call, 0))
3667 } ArgumentTypes[] = {
3668 { 1, Context.getPointerType(Context.CharTy.withConst()) },
3669 { 2, Context.getSizeType() },
3672 for (const auto &AT : ArgumentTypes) {
3673 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
3674 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
3676 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
3677 << Arg->getType() << AT.Type << 1 /* different class */
3678 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
3679 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
3685 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
3686 /// friends. This is declared to take (...), so we have to check everything.
3687 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
3688 if (TheCall->getNumArgs() < 2)
3689 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
3690 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
3691 if (TheCall->getNumArgs() > 2)
3692 return Diag(TheCall->getArg(2)->getLocStart(),
3693 diag::err_typecheck_call_too_many_args)
3694 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3695 << SourceRange(TheCall->getArg(2)->getLocStart(),
3696 (*(TheCall->arg_end()-1))->getLocEnd());
3698 ExprResult OrigArg0 = TheCall->getArg(0);
3699 ExprResult OrigArg1 = TheCall->getArg(1);
3701 // Do standard promotions between the two arguments, returning their common
3703 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
3704 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
3707 // Make sure any conversions are pushed back into the call; this is
3708 // type safe since unordered compare builtins are declared as "_Bool
3710 TheCall->setArg(0, OrigArg0.get());
3711 TheCall->setArg(1, OrigArg1.get());
3713 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
3716 // If the common type isn't a real floating type, then the arguments were
3717 // invalid for this operation.
3718 if (Res.isNull() || !Res->isRealFloatingType())
3719 return Diag(OrigArg0.get()->getLocStart(),
3720 diag::err_typecheck_call_invalid_ordered_compare)
3721 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
3722 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
3727 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
3728 /// __builtin_isnan and friends. This is declared to take (...), so we have
3729 /// to check everything. We expect the last argument to be a floating point
3731 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
3732 if (TheCall->getNumArgs() < NumArgs)
3733 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
3734 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
3735 if (TheCall->getNumArgs() > NumArgs)
3736 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
3737 diag::err_typecheck_call_too_many_args)
3738 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
3739 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
3740 (*(TheCall->arg_end()-1))->getLocEnd());
3742 Expr *OrigArg = TheCall->getArg(NumArgs-1);
3744 if (OrigArg->isTypeDependent())
3747 // This operation requires a non-_Complex floating-point number.
3748 if (!OrigArg->getType()->isRealFloatingType())
3749 return Diag(OrigArg->getLocStart(),
3750 diag::err_typecheck_call_invalid_unary_fp)
3751 << OrigArg->getType() << OrigArg->getSourceRange();
3753 // If this is an implicit conversion from float -> float or double, remove it.
3754 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
3755 // Only remove standard FloatCasts, leaving other casts inplace
3756 if (Cast->getCastKind() == CK_FloatingCast) {
3757 Expr *CastArg = Cast->getSubExpr();
3758 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
3759 assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
3760 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) &&
3761 "promotion from float to either float or double is the only expected cast here");
3762 Cast->setSubExpr(nullptr);
3763 TheCall->setArg(NumArgs-1, CastArg);
3771 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
3772 // This is declared to take (...), so we have to check everything.
3773 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
3774 if (TheCall->getNumArgs() < 2)
3775 return ExprError(Diag(TheCall->getLocEnd(),
3776 diag::err_typecheck_call_too_few_args_at_least)
3777 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3778 << TheCall->getSourceRange());
3780 // Determine which of the following types of shufflevector we're checking:
3781 // 1) unary, vector mask: (lhs, mask)
3782 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
3783 QualType resType = TheCall->getArg(0)->getType();
3784 unsigned numElements = 0;
3786 if (!TheCall->getArg(0)->isTypeDependent() &&
3787 !TheCall->getArg(1)->isTypeDependent()) {
3788 QualType LHSType = TheCall->getArg(0)->getType();
3789 QualType RHSType = TheCall->getArg(1)->getType();
3791 if (!LHSType->isVectorType() || !RHSType->isVectorType())
3792 return ExprError(Diag(TheCall->getLocStart(),
3793 diag::err_shufflevector_non_vector)
3794 << SourceRange(TheCall->getArg(0)->getLocStart(),
3795 TheCall->getArg(1)->getLocEnd()));
3797 numElements = LHSType->getAs<VectorType>()->getNumElements();
3798 unsigned numResElements = TheCall->getNumArgs() - 2;
3800 // Check to see if we have a call with 2 vector arguments, the unary shuffle
3801 // with mask. If so, verify that RHS is an integer vector type with the
3802 // same number of elts as lhs.
3803 if (TheCall->getNumArgs() == 2) {
3804 if (!RHSType->hasIntegerRepresentation() ||
3805 RHSType->getAs<VectorType>()->getNumElements() != numElements)
3806 return ExprError(Diag(TheCall->getLocStart(),
3807 diag::err_shufflevector_incompatible_vector)
3808 << SourceRange(TheCall->getArg(1)->getLocStart(),
3809 TheCall->getArg(1)->getLocEnd()));
3810 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
3811 return ExprError(Diag(TheCall->getLocStart(),
3812 diag::err_shufflevector_incompatible_vector)
3813 << SourceRange(TheCall->getArg(0)->getLocStart(),
3814 TheCall->getArg(1)->getLocEnd()));
3815 } else if (numElements != numResElements) {
3816 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
3817 resType = Context.getVectorType(eltType, numResElements,
3818 VectorType::GenericVector);
3822 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
3823 if (TheCall->getArg(i)->isTypeDependent() ||
3824 TheCall->getArg(i)->isValueDependent())
3827 llvm::APSInt Result(32);
3828 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
3829 return ExprError(Diag(TheCall->getLocStart(),
3830 diag::err_shufflevector_nonconstant_argument)
3831 << TheCall->getArg(i)->getSourceRange());
3833 // Allow -1 which will be translated to undef in the IR.
3834 if (Result.isSigned() && Result.isAllOnesValue())
3837 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
3838 return ExprError(Diag(TheCall->getLocStart(),
3839 diag::err_shufflevector_argument_too_large)
3840 << TheCall->getArg(i)->getSourceRange());
3843 SmallVector<Expr*, 32> exprs;
3845 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
3846 exprs.push_back(TheCall->getArg(i));
3847 TheCall->setArg(i, nullptr);
3850 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
3851 TheCall->getCallee()->getLocStart(),
3852 TheCall->getRParenLoc());
3855 /// SemaConvertVectorExpr - Handle __builtin_convertvector
3856 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
3857 SourceLocation BuiltinLoc,
3858 SourceLocation RParenLoc) {
3859 ExprValueKind VK = VK_RValue;
3860 ExprObjectKind OK = OK_Ordinary;
3861 QualType DstTy = TInfo->getType();
3862 QualType SrcTy = E->getType();
3864 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
3865 return ExprError(Diag(BuiltinLoc,
3866 diag::err_convertvector_non_vector)
3867 << E->getSourceRange());
3868 if (!DstTy->isVectorType() && !DstTy->isDependentType())
3869 return ExprError(Diag(BuiltinLoc,
3870 diag::err_convertvector_non_vector_type));
3872 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
3873 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
3874 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
3875 if (SrcElts != DstElts)
3876 return ExprError(Diag(BuiltinLoc,
3877 diag::err_convertvector_incompatible_vector)
3878 << E->getSourceRange());
3881 return new (Context)
3882 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
3885 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
3886 // This is declared to take (const void*, ...) and can take two
3887 // optional constant int args.
3888 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
3889 unsigned NumArgs = TheCall->getNumArgs();
3892 return Diag(TheCall->getLocEnd(),
3893 diag::err_typecheck_call_too_many_args_at_most)
3894 << 0 /*function call*/ << 3 << NumArgs
3895 << TheCall->getSourceRange();
3897 // Argument 0 is checked for us and the remaining arguments must be
3898 // constant integers.
3899 for (unsigned i = 1; i != NumArgs; ++i)
3900 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
3906 /// SemaBuiltinAssume - Handle __assume (MS Extension).
3907 // __assume does not evaluate its arguments, and should warn if its argument
3908 // has side effects.
3909 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
3910 Expr *Arg = TheCall->getArg(0);
3911 if (Arg->isInstantiationDependent()) return false;
3913 if (Arg->HasSideEffects(Context))
3914 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
3915 << Arg->getSourceRange()
3916 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
3921 /// Handle __builtin_alloca_with_align. This is declared
3922 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
3924 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
3925 // The alignment must be a constant integer.
3926 Expr *Arg = TheCall->getArg(1);
3928 // We can't check the value of a dependent argument.
3929 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
3930 if (const auto *UE =
3931 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
3932 if (UE->getKind() == UETT_AlignOf)
3933 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
3934 << Arg->getSourceRange();
3936 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
3938 if (!Result.isPowerOf2())
3939 return Diag(TheCall->getLocStart(),
3940 diag::err_alignment_not_power_of_two)
3941 << Arg->getSourceRange();
3943 if (Result < Context.getCharWidth())
3944 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
3945 << (unsigned)Context.getCharWidth()
3946 << Arg->getSourceRange();
3948 if (Result > INT32_MAX)
3949 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
3951 << Arg->getSourceRange();
3957 /// Handle __builtin_assume_aligned. This is declared
3958 /// as (const void*, size_t, ...) and can take one optional constant int arg.
3959 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
3960 unsigned NumArgs = TheCall->getNumArgs();
3963 return Diag(TheCall->getLocEnd(),
3964 diag::err_typecheck_call_too_many_args_at_most)
3965 << 0 /*function call*/ << 3 << NumArgs
3966 << TheCall->getSourceRange();
3968 // The alignment must be a constant integer.
3969 Expr *Arg = TheCall->getArg(1);
3971 // We can't check the value of a dependent argument.
3972 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
3973 llvm::APSInt Result;
3974 if (SemaBuiltinConstantArg(TheCall, 1, Result))
3977 if (!Result.isPowerOf2())
3978 return Diag(TheCall->getLocStart(),
3979 diag::err_alignment_not_power_of_two)
3980 << Arg->getSourceRange();
3984 ExprResult Arg(TheCall->getArg(2));
3985 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3986 Context.getSizeType(), false);
3987 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3988 if (Arg.isInvalid()) return true;
3989 TheCall->setArg(2, Arg.get());
3995 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
3996 unsigned BuiltinID =
3997 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
3998 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
4000 unsigned NumArgs = TheCall->getNumArgs();
4001 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
4002 if (NumArgs < NumRequiredArgs) {
4003 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4004 << 0 /* function call */ << NumRequiredArgs << NumArgs
4005 << TheCall->getSourceRange();
4007 if (NumArgs >= NumRequiredArgs + 0x100) {
4008 return Diag(TheCall->getLocEnd(),
4009 diag::err_typecheck_call_too_many_args_at_most)
4010 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
4011 << TheCall->getSourceRange();
4015 // For formatting call, check buffer arg.
4017 ExprResult Arg(TheCall->getArg(i));
4018 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4019 Context, Context.VoidPtrTy, false);
4020 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4021 if (Arg.isInvalid())
4023 TheCall->setArg(i, Arg.get());
4027 // Check string literal arg.
4028 unsigned FormatIdx = i;
4030 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4031 if (Arg.isInvalid())
4033 TheCall->setArg(i, Arg.get());
4037 // Make sure variadic args are scalar.
4038 unsigned FirstDataArg = i;
4039 while (i < NumArgs) {
4040 ExprResult Arg = DefaultVariadicArgumentPromotion(
4041 TheCall->getArg(i), VariadicFunction, nullptr);
4042 if (Arg.isInvalid())
4044 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4045 if (ArgSize.getQuantity() >= 0x100) {
4046 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4047 << i << (int)ArgSize.getQuantity() << 0xff
4048 << TheCall->getSourceRange();
4050 TheCall->setArg(i, Arg.get());
4054 // Check formatting specifiers. NOTE: We're only doing this for the non-size
4055 // call to avoid duplicate diagnostics.
4057 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4058 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4059 bool Success = CheckFormatArguments(
4060 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4061 VariadicFunction, TheCall->getLocStart(), SourceRange(),
4068 TheCall->setType(Context.getSizeType());
4070 TheCall->setType(Context.VoidPtrTy);
4075 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4076 /// TheCall is a constant expression.
4077 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4078 llvm::APSInt &Result) {
4079 Expr *Arg = TheCall->getArg(ArgNum);
4080 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4081 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4083 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
4085 if (!Arg->isIntegerConstantExpr(Result, Context))
4086 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
4087 << FDecl->getDeclName() << Arg->getSourceRange();
4092 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
4093 /// TheCall is a constant expression in the range [Low, High].
4094 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
4095 int Low, int High) {
4096 llvm::APSInt Result;
4098 // We can't check the value of a dependent argument.
4099 Expr *Arg = TheCall->getArg(ArgNum);
4100 if (Arg->isTypeDependent() || Arg->isValueDependent())
4103 // Check constant-ness first.
4104 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4107 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
4108 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
4109 << Low << High << Arg->getSourceRange();
4114 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
4115 /// TheCall is a constant expression is a multiple of Num..
4116 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
4118 llvm::APSInt Result;
4120 // We can't check the value of a dependent argument.
4121 Expr *Arg = TheCall->getArg(ArgNum);
4122 if (Arg->isTypeDependent() || Arg->isValueDependent())
4125 // Check constant-ness first.
4126 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4129 if (Result.getSExtValue() % Num != 0)
4130 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
4131 << Num << Arg->getSourceRange();
4136 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
4137 /// TheCall is an ARM/AArch64 special register string literal.
4138 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
4139 int ArgNum, unsigned ExpectedFieldNum,
4141 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
4142 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
4143 BuiltinID == ARM::BI__builtin_arm_rsr ||
4144 BuiltinID == ARM::BI__builtin_arm_rsrp ||
4145 BuiltinID == ARM::BI__builtin_arm_wsr ||
4146 BuiltinID == ARM::BI__builtin_arm_wsrp;
4147 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
4148 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
4149 BuiltinID == AArch64::BI__builtin_arm_rsr ||
4150 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
4151 BuiltinID == AArch64::BI__builtin_arm_wsr ||
4152 BuiltinID == AArch64::BI__builtin_arm_wsrp;
4153 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
4155 // We can't check the value of a dependent argument.
4156 Expr *Arg = TheCall->getArg(ArgNum);
4157 if (Arg->isTypeDependent() || Arg->isValueDependent())
4160 // Check if the argument is a string literal.
4161 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4162 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
4163 << Arg->getSourceRange();
4165 // Check the type of special register given.
4166 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4167 SmallVector<StringRef, 6> Fields;
4168 Reg.split(Fields, ":");
4170 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
4171 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4172 << Arg->getSourceRange();
4174 // If the string is the name of a register then we cannot check that it is
4175 // valid here but if the string is of one the forms described in ACLE then we
4176 // can check that the supplied fields are integers and within the valid
4178 if (Fields.size() > 1) {
4179 bool FiveFields = Fields.size() == 5;
4181 bool ValidString = true;
4183 ValidString &= Fields[0].startswith_lower("cp") ||
4184 Fields[0].startswith_lower("p");
4187 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
4189 ValidString &= Fields[2].startswith_lower("c");
4191 Fields[2] = Fields[2].drop_front(1);
4194 ValidString &= Fields[3].startswith_lower("c");
4196 Fields[3] = Fields[3].drop_front(1);
4200 SmallVector<int, 5> Ranges;
4202 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
4204 Ranges.append({15, 7, 15});
4206 for (unsigned i=0; i<Fields.size(); ++i) {
4208 ValidString &= !Fields[i].getAsInteger(10, IntField);
4209 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
4213 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4214 << Arg->getSourceRange();
4216 } else if (IsAArch64Builtin && Fields.size() == 1) {
4217 // If the register name is one of those that appear in the condition below
4218 // and the special register builtin being used is one of the write builtins,
4219 // then we require that the argument provided for writing to the register
4220 // is an integer constant expression. This is because it will be lowered to
4221 // an MSR (immediate) instruction, so we need to know the immediate at
4223 if (TheCall->getNumArgs() != 2)
4226 std::string RegLower = Reg.lower();
4227 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
4228 RegLower != "pan" && RegLower != "uao")
4231 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4237 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
4238 /// This checks that the target supports __builtin_longjmp and
4239 /// that val is a constant 1.
4240 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
4241 if (!Context.getTargetInfo().hasSjLjLowering())
4242 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
4243 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4245 Expr *Arg = TheCall->getArg(1);
4246 llvm::APSInt Result;
4248 // TODO: This is less than ideal. Overload this to take a value.
4249 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4253 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
4254 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
4259 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
4260 /// This checks that the target supports __builtin_setjmp.
4261 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
4262 if (!Context.getTargetInfo().hasSjLjLowering())
4263 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
4264 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4269 class UncoveredArgHandler {
4270 enum { Unknown = -1, AllCovered = -2 };
4271 signed FirstUncoveredArg;
4272 SmallVector<const Expr *, 4> DiagnosticExprs;
4275 UncoveredArgHandler() : FirstUncoveredArg(Unknown) { }
4277 bool hasUncoveredArg() const {
4278 return (FirstUncoveredArg >= 0);
4281 unsigned getUncoveredArg() const {
4282 assert(hasUncoveredArg() && "no uncovered argument");
4283 return FirstUncoveredArg;
4286 void setAllCovered() {
4287 // A string has been found with all arguments covered, so clear out
4289 DiagnosticExprs.clear();
4290 FirstUncoveredArg = AllCovered;
4293 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
4294 assert(NewFirstUncoveredArg >= 0 && "Outside range");
4296 // Don't update if a previous string covers all arguments.
4297 if (FirstUncoveredArg == AllCovered)
4300 // UncoveredArgHandler tracks the highest uncovered argument index
4301 // and with it all the strings that match this index.
4302 if (NewFirstUncoveredArg == FirstUncoveredArg)
4303 DiagnosticExprs.push_back(StrExpr);
4304 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
4305 DiagnosticExprs.clear();
4306 DiagnosticExprs.push_back(StrExpr);
4307 FirstUncoveredArg = NewFirstUncoveredArg;
4311 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
4314 enum StringLiteralCheckType {
4316 SLCT_UncheckedLiteral,
4319 } // end anonymous namespace
4321 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
4322 BinaryOperatorKind BinOpKind,
4323 bool AddendIsRight) {
4324 unsigned BitWidth = Offset.getBitWidth();
4325 unsigned AddendBitWidth = Addend.getBitWidth();
4326 // There might be negative interim results.
4327 if (Addend.isUnsigned()) {
4328 Addend = Addend.zext(++AddendBitWidth);
4329 Addend.setIsSigned(true);
4331 // Adjust the bit width of the APSInts.
4332 if (AddendBitWidth > BitWidth) {
4333 Offset = Offset.sext(AddendBitWidth);
4334 BitWidth = AddendBitWidth;
4335 } else if (BitWidth > AddendBitWidth) {
4336 Addend = Addend.sext(BitWidth);
4340 llvm::APSInt ResOffset = Offset;
4341 if (BinOpKind == BO_Add)
4342 ResOffset = Offset.sadd_ov(Addend, Ov);
4344 assert(AddendIsRight && BinOpKind == BO_Sub &&
4345 "operator must be add or sub with addend on the right");
4346 ResOffset = Offset.ssub_ov(Addend, Ov);
4349 // We add an offset to a pointer here so we should support an offset as big as
4352 assert(BitWidth <= UINT_MAX / 2 && "index (intermediate) result too big");
4353 Offset = Offset.sext(2 * BitWidth);
4354 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
4362 // This is a wrapper class around StringLiteral to support offsetted string
4363 // literals as format strings. It takes the offset into account when returning
4364 // the string and its length or the source locations to display notes correctly.
4365 class FormatStringLiteral {
4366 const StringLiteral *FExpr;
4370 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
4371 : FExpr(fexpr), Offset(Offset) {}
4373 StringRef getString() const {
4374 return FExpr->getString().drop_front(Offset);
4377 unsigned getByteLength() const {
4378 return FExpr->getByteLength() - getCharByteWidth() * Offset;
4380 unsigned getLength() const { return FExpr->getLength() - Offset; }
4381 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
4383 StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
4385 QualType getType() const { return FExpr->getType(); }
4387 bool isAscii() const { return FExpr->isAscii(); }
4388 bool isWide() const { return FExpr->isWide(); }
4389 bool isUTF8() const { return FExpr->isUTF8(); }
4390 bool isUTF16() const { return FExpr->isUTF16(); }
4391 bool isUTF32() const { return FExpr->isUTF32(); }
4392 bool isPascal() const { return FExpr->isPascal(); }
4394 SourceLocation getLocationOfByte(
4395 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
4396 const TargetInfo &Target, unsigned *StartToken = nullptr,
4397 unsigned *StartTokenByteOffset = nullptr) const {
4398 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
4399 StartToken, StartTokenByteOffset);
4402 SourceLocation getLocStart() const LLVM_READONLY {
4403 return FExpr->getLocStart().getLocWithOffset(Offset);
4405 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
4407 } // end anonymous namespace
4409 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
4410 const Expr *OrigFormatExpr,
4411 ArrayRef<const Expr *> Args,
4412 bool HasVAListArg, unsigned format_idx,
4413 unsigned firstDataArg,
4414 Sema::FormatStringType Type,
4415 bool inFunctionCall,
4416 Sema::VariadicCallType CallType,
4417 llvm::SmallBitVector &CheckedVarArgs,
4418 UncoveredArgHandler &UncoveredArg);
4420 // Determine if an expression is a string literal or constant string.
4421 // If this function returns false on the arguments to a function expecting a
4422 // format string, we will usually need to emit a warning.
4423 // True string literals are then checked by CheckFormatString.
4424 static StringLiteralCheckType
4425 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
4426 bool HasVAListArg, unsigned format_idx,
4427 unsigned firstDataArg, Sema::FormatStringType Type,
4428 Sema::VariadicCallType CallType, bool InFunctionCall,
4429 llvm::SmallBitVector &CheckedVarArgs,
4430 UncoveredArgHandler &UncoveredArg,
4431 llvm::APSInt Offset) {
4433 assert(Offset.isSigned() && "invalid offset");
4435 if (E->isTypeDependent() || E->isValueDependent())
4436 return SLCT_NotALiteral;
4438 E = E->IgnoreParenCasts();
4440 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
4441 // Technically -Wformat-nonliteral does not warn about this case.
4442 // The behavior of printf and friends in this case is implementation
4443 // dependent. Ideally if the format string cannot be null then
4444 // it should have a 'nonnull' attribute in the function prototype.
4445 return SLCT_UncheckedLiteral;
4447 switch (E->getStmtClass()) {
4448 case Stmt::BinaryConditionalOperatorClass:
4449 case Stmt::ConditionalOperatorClass: {
4450 // The expression is a literal if both sub-expressions were, and it was
4451 // completely checked only if both sub-expressions were checked.
4452 const AbstractConditionalOperator *C =
4453 cast<AbstractConditionalOperator>(E);
4455 // Determine whether it is necessary to check both sub-expressions, for
4456 // example, because the condition expression is a constant that can be
4457 // evaluated at compile time.
4458 bool CheckLeft = true, CheckRight = true;
4461 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
4468 // We need to maintain the offsets for the right and the left hand side
4469 // separately to check if every possible indexed expression is a valid
4470 // string literal. They might have different offsets for different string
4471 // literals in the end.
4472 StringLiteralCheckType Left;
4474 Left = SLCT_UncheckedLiteral;
4476 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
4477 HasVAListArg, format_idx, firstDataArg,
4478 Type, CallType, InFunctionCall,
4479 CheckedVarArgs, UncoveredArg, Offset);
4480 if (Left == SLCT_NotALiteral || !CheckRight) {
4485 StringLiteralCheckType Right =
4486 checkFormatStringExpr(S, C->getFalseExpr(), Args,
4487 HasVAListArg, format_idx, firstDataArg,
4488 Type, CallType, InFunctionCall, CheckedVarArgs,
4489 UncoveredArg, Offset);
4491 return (CheckLeft && Left < Right) ? Left : Right;
4494 case Stmt::ImplicitCastExprClass: {
4495 E = cast<ImplicitCastExpr>(E)->getSubExpr();
4499 case Stmt::OpaqueValueExprClass:
4500 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
4504 return SLCT_NotALiteral;
4506 case Stmt::PredefinedExprClass:
4507 // While __func__, etc., are technically not string literals, they
4508 // cannot contain format specifiers and thus are not a security
4510 return SLCT_UncheckedLiteral;
4512 case Stmt::DeclRefExprClass: {
4513 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
4515 // As an exception, do not flag errors for variables binding to
4516 // const string literals.
4517 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
4518 bool isConstant = false;
4519 QualType T = DR->getType();
4521 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
4522 isConstant = AT->getElementType().isConstant(S.Context);
4523 } else if (const PointerType *PT = T->getAs<PointerType>()) {
4524 isConstant = T.isConstant(S.Context) &&
4525 PT->getPointeeType().isConstant(S.Context);
4526 } else if (T->isObjCObjectPointerType()) {
4527 // In ObjC, there is usually no "const ObjectPointer" type,
4528 // so don't check if the pointee type is constant.
4529 isConstant = T.isConstant(S.Context);
4533 if (const Expr *Init = VD->getAnyInitializer()) {
4534 // Look through initializers like const char c[] = { "foo" }
4535 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4536 if (InitList->isStringLiteralInit())
4537 Init = InitList->getInit(0)->IgnoreParenImpCasts();
4539 return checkFormatStringExpr(S, Init, Args,
4540 HasVAListArg, format_idx,
4541 firstDataArg, Type, CallType,
4542 /*InFunctionCall*/ false, CheckedVarArgs,
4543 UncoveredArg, Offset);
4547 // For vprintf* functions (i.e., HasVAListArg==true), we add a
4548 // special check to see if the format string is a function parameter
4549 // of the function calling the printf function. If the function
4550 // has an attribute indicating it is a printf-like function, then we
4551 // should suppress warnings concerning non-literals being used in a call
4552 // to a vprintf function. For example:
4555 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
4557 // va_start(ap, fmt);
4558 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
4562 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
4563 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
4564 int PVIndex = PV->getFunctionScopeIndex() + 1;
4565 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
4566 // adjust for implicit parameter
4567 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4568 if (MD->isInstance())
4570 // We also check if the formats are compatible.
4571 // We can't pass a 'scanf' string to a 'printf' function.
4572 if (PVIndex == PVFormat->getFormatIdx() &&
4573 Type == S.GetFormatStringType(PVFormat))
4574 return SLCT_UncheckedLiteral;
4581 return SLCT_NotALiteral;
4584 case Stmt::CallExprClass:
4585 case Stmt::CXXMemberCallExprClass: {
4586 const CallExpr *CE = cast<CallExpr>(E);
4587 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
4588 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
4589 unsigned ArgIndex = FA->getFormatIdx();
4590 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4591 if (MD->isInstance())
4593 const Expr *Arg = CE->getArg(ArgIndex - 1);
4595 return checkFormatStringExpr(S, Arg, Args,
4596 HasVAListArg, format_idx, firstDataArg,
4597 Type, CallType, InFunctionCall,
4598 CheckedVarArgs, UncoveredArg, Offset);
4599 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4600 unsigned BuiltinID = FD->getBuiltinID();
4601 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
4602 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
4603 const Expr *Arg = CE->getArg(0);
4604 return checkFormatStringExpr(S, Arg, Args,
4605 HasVAListArg, format_idx,
4606 firstDataArg, Type, CallType,
4607 InFunctionCall, CheckedVarArgs,
4608 UncoveredArg, Offset);
4613 return SLCT_NotALiteral;
4615 case Stmt::ObjCMessageExprClass: {
4616 const auto *ME = cast<ObjCMessageExpr>(E);
4617 if (const auto *ND = ME->getMethodDecl()) {
4618 if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
4619 unsigned ArgIndex = FA->getFormatIdx();
4620 const Expr *Arg = ME->getArg(ArgIndex - 1);
4621 return checkFormatStringExpr(
4622 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
4623 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
4627 return SLCT_NotALiteral;
4629 case Stmt::ObjCStringLiteralClass:
4630 case Stmt::StringLiteralClass: {
4631 const StringLiteral *StrE = nullptr;
4633 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
4634 StrE = ObjCFExpr->getString();
4636 StrE = cast<StringLiteral>(E);
4639 if (Offset.isNegative() || Offset > StrE->getLength()) {
4640 // TODO: It would be better to have an explicit warning for out of
4642 return SLCT_NotALiteral;
4644 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
4645 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
4646 firstDataArg, Type, InFunctionCall, CallType,
4647 CheckedVarArgs, UncoveredArg);
4648 return SLCT_CheckedLiteral;
4651 return SLCT_NotALiteral;
4653 case Stmt::BinaryOperatorClass: {
4654 llvm::APSInt LResult;
4655 llvm::APSInt RResult;
4657 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
4659 // A string literal + an int offset is still a string literal.
4660 if (BinOp->isAdditiveOp()) {
4661 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
4662 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
4664 if (LIsInt != RIsInt) {
4665 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
4668 if (BinOpKind == BO_Add) {
4669 sumOffsets(Offset, LResult, BinOpKind, RIsInt);
4670 E = BinOp->getRHS();
4674 sumOffsets(Offset, RResult, BinOpKind, RIsInt);
4675 E = BinOp->getLHS();
4681 return SLCT_NotALiteral;
4683 case Stmt::UnaryOperatorClass: {
4684 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
4685 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
4686 if (UnaOp->getOpcode() == clang::UO_AddrOf && ASE) {
4687 llvm::APSInt IndexResult;
4688 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
4689 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
4695 return SLCT_NotALiteral;
4699 return SLCT_NotALiteral;
4703 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
4704 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
4705 .Case("scanf", FST_Scanf)
4706 .Cases("printf", "printf0", FST_Printf)
4707 .Cases("NSString", "CFString", FST_NSString)
4708 .Case("strftime", FST_Strftime)
4709 .Case("strfmon", FST_Strfmon)
4710 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
4711 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
4712 .Case("os_trace", FST_OSLog)
4713 .Case("os_log", FST_OSLog)
4714 .Default(FST_Unknown);
4717 /// CheckFormatArguments - Check calls to printf and scanf (and similar
4718 /// functions) for correct use of format strings.
4719 /// Returns true if a format string has been fully checked.
4720 bool Sema::CheckFormatArguments(const FormatAttr *Format,
4721 ArrayRef<const Expr *> Args,
4723 VariadicCallType CallType,
4724 SourceLocation Loc, SourceRange Range,
4725 llvm::SmallBitVector &CheckedVarArgs) {
4726 FormatStringInfo FSI;
4727 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
4728 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
4729 FSI.FirstDataArg, GetFormatStringType(Format),
4730 CallType, Loc, Range, CheckedVarArgs);
4734 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
4735 bool HasVAListArg, unsigned format_idx,
4736 unsigned firstDataArg, FormatStringType Type,
4737 VariadicCallType CallType,
4738 SourceLocation Loc, SourceRange Range,
4739 llvm::SmallBitVector &CheckedVarArgs) {
4740 // CHECK: printf/scanf-like function is called with no format string.
4741 if (format_idx >= Args.size()) {
4742 Diag(Loc, diag::warn_missing_format_string) << Range;
4746 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
4748 // CHECK: format string is not a string literal.
4750 // Dynamically generated format strings are difficult to
4751 // automatically vet at compile time. Requiring that format strings
4752 // are string literals: (1) permits the checking of format strings by
4753 // the compiler and thereby (2) can practically remove the source of
4754 // many format string exploits.
4756 // Format string can be either ObjC string (e.g. @"%d") or
4757 // C string (e.g. "%d")
4758 // ObjC string uses the same format specifiers as C string, so we can use
4759 // the same format string checking logic for both ObjC and C strings.
4760 UncoveredArgHandler UncoveredArg;
4761 StringLiteralCheckType CT =
4762 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
4763 format_idx, firstDataArg, Type, CallType,
4764 /*IsFunctionCall*/ true, CheckedVarArgs,
4766 /*no string offset*/ llvm::APSInt(64, false) = 0);
4768 // Generate a diagnostic where an uncovered argument is detected.
4769 if (UncoveredArg.hasUncoveredArg()) {
4770 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
4771 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
4772 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
4775 if (CT != SLCT_NotALiteral)
4776 // Literal format string found, check done!
4777 return CT == SLCT_CheckedLiteral;
4779 // Strftime is particular as it always uses a single 'time' argument,
4780 // so it is safe to pass a non-literal string.
4781 if (Type == FST_Strftime)
4784 // Do not emit diag when the string param is a macro expansion and the
4785 // format is either NSString or CFString. This is a hack to prevent
4786 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
4787 // which are usually used in place of NS and CF string literals.
4788 SourceLocation FormatLoc = Args[format_idx]->getLocStart();
4789 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
4792 // If there are no arguments specified, warn with -Wformat-security, otherwise
4793 // warn only with -Wformat-nonliteral.
4794 if (Args.size() == firstDataArg) {
4795 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
4796 << OrigFormatExpr->getSourceRange();
4801 case FST_FreeBSDKPrintf:
4803 Diag(FormatLoc, diag::note_format_security_fixit)
4804 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
4807 Diag(FormatLoc, diag::note_format_security_fixit)
4808 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
4812 Diag(FormatLoc, diag::warn_format_nonliteral)
4813 << OrigFormatExpr->getSourceRange();
4819 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
4822 const FormatStringLiteral *FExpr;
4823 const Expr *OrigFormatExpr;
4824 const Sema::FormatStringType FSType;
4825 const unsigned FirstDataArg;
4826 const unsigned NumDataArgs;
4827 const char *Beg; // Start of format string.
4828 const bool HasVAListArg;
4829 ArrayRef<const Expr *> Args;
4831 llvm::SmallBitVector CoveredArgs;
4832 bool usesPositionalArgs;
4834 bool inFunctionCall;
4835 Sema::VariadicCallType CallType;
4836 llvm::SmallBitVector &CheckedVarArgs;
4837 UncoveredArgHandler &UncoveredArg;
4840 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
4841 const Expr *origFormatExpr,
4842 const Sema::FormatStringType type, unsigned firstDataArg,
4843 unsigned numDataArgs, const char *beg, bool hasVAListArg,
4844 ArrayRef<const Expr *> Args, unsigned formatIdx,
4845 bool inFunctionCall, Sema::VariadicCallType callType,
4846 llvm::SmallBitVector &CheckedVarArgs,
4847 UncoveredArgHandler &UncoveredArg)
4848 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
4849 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
4850 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
4851 usesPositionalArgs(false), atFirstArg(true),
4852 inFunctionCall(inFunctionCall), CallType(callType),
4853 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
4854 CoveredArgs.resize(numDataArgs);
4855 CoveredArgs.reset();
4858 void DoneProcessing();
4860 void HandleIncompleteSpecifier(const char *startSpecifier,
4861 unsigned specifierLen) override;
4863 void HandleInvalidLengthModifier(
4864 const analyze_format_string::FormatSpecifier &FS,
4865 const analyze_format_string::ConversionSpecifier &CS,
4866 const char *startSpecifier, unsigned specifierLen,
4869 void HandleNonStandardLengthModifier(
4870 const analyze_format_string::FormatSpecifier &FS,
4871 const char *startSpecifier, unsigned specifierLen);
4873 void HandleNonStandardConversionSpecifier(
4874 const analyze_format_string::ConversionSpecifier &CS,
4875 const char *startSpecifier, unsigned specifierLen);
4877 void HandlePosition(const char *startPos, unsigned posLen) override;
4879 void HandleInvalidPosition(const char *startSpecifier,
4880 unsigned specifierLen,
4881 analyze_format_string::PositionContext p) override;
4883 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
4885 void HandleNullChar(const char *nullCharacter) override;
4887 template <typename Range>
4889 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
4890 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
4891 bool IsStringLocation, Range StringRange,
4892 ArrayRef<FixItHint> Fixit = None);
4895 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
4896 const char *startSpec,
4897 unsigned specifierLen,
4898 const char *csStart, unsigned csLen);
4900 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
4901 const char *startSpec,
4902 unsigned specifierLen);
4904 SourceRange getFormatStringRange();
4905 CharSourceRange getSpecifierRange(const char *startSpecifier,
4906 unsigned specifierLen);
4907 SourceLocation getLocationOfByte(const char *x);
4909 const Expr *getDataArg(unsigned i) const;
4911 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
4912 const analyze_format_string::ConversionSpecifier &CS,
4913 const char *startSpecifier, unsigned specifierLen,
4916 template <typename Range>
4917 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
4918 bool IsStringLocation, Range StringRange,
4919 ArrayRef<FixItHint> Fixit = None);
4921 } // end anonymous namespace
4923 SourceRange CheckFormatHandler::getFormatStringRange() {
4924 return OrigFormatExpr->getSourceRange();
4927 CharSourceRange CheckFormatHandler::
4928 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
4929 SourceLocation Start = getLocationOfByte(startSpecifier);
4930 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
4932 // Advance the end SourceLocation by one due to half-open ranges.
4933 End = End.getLocWithOffset(1);
4935 return CharSourceRange::getCharRange(Start, End);
4938 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
4939 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
4940 S.getLangOpts(), S.Context.getTargetInfo());
4943 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
4944 unsigned specifierLen){
4945 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
4946 getLocationOfByte(startSpecifier),
4947 /*IsStringLocation*/true,
4948 getSpecifierRange(startSpecifier, specifierLen));
4951 void CheckFormatHandler::HandleInvalidLengthModifier(
4952 const analyze_format_string::FormatSpecifier &FS,
4953 const analyze_format_string::ConversionSpecifier &CS,
4954 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
4955 using namespace analyze_format_string;
4957 const LengthModifier &LM = FS.getLengthModifier();
4958 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4960 // See if we know how to fix this length modifier.
4961 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
4963 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
4964 getLocationOfByte(LM.getStart()),
4965 /*IsStringLocation*/true,
4966 getSpecifierRange(startSpecifier, specifierLen));
4968 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
4969 << FixedLM->toString()
4970 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
4974 if (DiagID == diag::warn_format_nonsensical_length)
4975 Hint = FixItHint::CreateRemoval(LMRange);
4977 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
4978 getLocationOfByte(LM.getStart()),
4979 /*IsStringLocation*/true,
4980 getSpecifierRange(startSpecifier, specifierLen),
4985 void CheckFormatHandler::HandleNonStandardLengthModifier(
4986 const analyze_format_string::FormatSpecifier &FS,
4987 const char *startSpecifier, unsigned specifierLen) {
4988 using namespace analyze_format_string;
4990 const LengthModifier &LM = FS.getLengthModifier();
4991 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4993 // See if we know how to fix this length modifier.
4994 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
4996 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4997 << LM.toString() << 0,
4998 getLocationOfByte(LM.getStart()),
4999 /*IsStringLocation*/true,
5000 getSpecifierRange(startSpecifier, specifierLen));
5002 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5003 << FixedLM->toString()
5004 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5007 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5008 << LM.toString() << 0,
5009 getLocationOfByte(LM.getStart()),
5010 /*IsStringLocation*/true,
5011 getSpecifierRange(startSpecifier, specifierLen));
5015 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5016 const analyze_format_string::ConversionSpecifier &CS,
5017 const char *startSpecifier, unsigned specifierLen) {
5018 using namespace analyze_format_string;
5020 // See if we know how to fix this conversion specifier.
5021 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
5023 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5024 << CS.toString() << /*conversion specifier*/1,
5025 getLocationOfByte(CS.getStart()),
5026 /*IsStringLocation*/true,
5027 getSpecifierRange(startSpecifier, specifierLen));
5029 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5030 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5031 << FixedCS->toString()
5032 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5034 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5035 << CS.toString() << /*conversion specifier*/1,
5036 getLocationOfByte(CS.getStart()),
5037 /*IsStringLocation*/true,
5038 getSpecifierRange(startSpecifier, specifierLen));
5042 void CheckFormatHandler::HandlePosition(const char *startPos,
5044 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5045 getLocationOfByte(startPos),
5046 /*IsStringLocation*/true,
5047 getSpecifierRange(startPos, posLen));
5051 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5052 analyze_format_string::PositionContext p) {
5053 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5055 getLocationOfByte(startPos), /*IsStringLocation*/true,
5056 getSpecifierRange(startPos, posLen));
5059 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
5061 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5062 getLocationOfByte(startPos),
5063 /*IsStringLocation*/true,
5064 getSpecifierRange(startPos, posLen));
5067 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
5068 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
5069 // The presence of a null character is likely an error.
5070 EmitFormatDiagnostic(
5071 S.PDiag(diag::warn_printf_format_string_contains_null_char),
5072 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
5073 getFormatStringRange());
5077 // Note that this may return NULL if there was an error parsing or building
5078 // one of the argument expressions.
5079 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
5080 return Args[FirstDataArg + i];
5083 void CheckFormatHandler::DoneProcessing() {
5084 // Does the number of data arguments exceed the number of
5085 // format conversions in the format string?
5086 if (!HasVAListArg) {
5087 // Find any arguments that weren't covered.
5089 signed notCoveredArg = CoveredArgs.find_first();
5090 if (notCoveredArg >= 0) {
5091 assert((unsigned)notCoveredArg < NumDataArgs);
5092 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
5094 UncoveredArg.setAllCovered();
5099 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
5100 const Expr *ArgExpr) {
5101 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
5107 SourceLocation Loc = ArgExpr->getLocStart();
5109 if (S.getSourceManager().isInSystemMacro(Loc))
5112 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
5113 for (auto E : DiagnosticExprs)
5114 PDiag << E->getSourceRange();
5116 CheckFormatHandler::EmitFormatDiagnostic(
5117 S, IsFunctionCall, DiagnosticExprs[0],
5118 PDiag, Loc, /*IsStringLocation*/false,
5119 DiagnosticExprs[0]->getSourceRange());
5123 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
5125 const char *startSpec,
5126 unsigned specifierLen,
5127 const char *csStart,
5129 bool keepGoing = true;
5130 if (argIndex < NumDataArgs) {
5131 // Consider the argument coverered, even though the specifier doesn't
5133 CoveredArgs.set(argIndex);
5136 // If argIndex exceeds the number of data arguments we
5137 // don't issue a warning because that is just a cascade of warnings (and
5138 // they may have intended '%%' anyway). We don't want to continue processing
5139 // the format string after this point, however, as we will like just get
5140 // gibberish when trying to match arguments.
5144 StringRef Specifier(csStart, csLen);
5146 // If the specifier in non-printable, it could be the first byte of a UTF-8
5147 // sequence. In that case, print the UTF-8 code point. If not, print the byte
5149 std::string CodePointStr;
5150 if (!llvm::sys::locale::isPrint(*csStart)) {
5151 llvm::UTF32 CodePoint;
5152 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
5153 const llvm::UTF8 *E =
5154 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
5155 llvm::ConversionResult Result =
5156 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
5158 if (Result != llvm::conversionOK) {
5159 unsigned char FirstChar = *csStart;
5160 CodePoint = (llvm::UTF32)FirstChar;
5163 llvm::raw_string_ostream OS(CodePointStr);
5164 if (CodePoint < 256)
5165 OS << "\\x" << llvm::format("%02x", CodePoint);
5166 else if (CodePoint <= 0xFFFF)
5167 OS << "\\u" << llvm::format("%04x", CodePoint);
5169 OS << "\\U" << llvm::format("%08x", CodePoint);
5171 Specifier = CodePointStr;
5174 EmitFormatDiagnostic(
5175 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
5176 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
5182 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
5183 const char *startSpec,
5184 unsigned specifierLen) {
5185 EmitFormatDiagnostic(
5186 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
5187 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
5191 CheckFormatHandler::CheckNumArgs(
5192 const analyze_format_string::FormatSpecifier &FS,
5193 const analyze_format_string::ConversionSpecifier &CS,
5194 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
5196 if (argIndex >= NumDataArgs) {
5197 PartialDiagnostic PDiag = FS.usesPositionalArg()
5198 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
5199 << (argIndex+1) << NumDataArgs)
5200 : S.PDiag(diag::warn_printf_insufficient_data_args);
5201 EmitFormatDiagnostic(
5202 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
5203 getSpecifierRange(startSpecifier, specifierLen));
5205 // Since more arguments than conversion tokens are given, by extension
5206 // all arguments are covered, so mark this as so.
5207 UncoveredArg.setAllCovered();
5213 template<typename Range>
5214 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
5216 bool IsStringLocation,
5218 ArrayRef<FixItHint> FixIt) {
5219 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
5220 Loc, IsStringLocation, StringRange, FixIt);
5223 /// \brief If the format string is not within the funcion call, emit a note
5224 /// so that the function call and string are in diagnostic messages.
5226 /// \param InFunctionCall if true, the format string is within the function
5227 /// call and only one diagnostic message will be produced. Otherwise, an
5228 /// extra note will be emitted pointing to location of the format string.
5230 /// \param ArgumentExpr the expression that is passed as the format string
5231 /// argument in the function call. Used for getting locations when two
5232 /// diagnostics are emitted.
5234 /// \param PDiag the callee should already have provided any strings for the
5235 /// diagnostic message. This function only adds locations and fixits
5238 /// \param Loc primary location for diagnostic. If two diagnostics are
5239 /// required, one will be at Loc and a new SourceLocation will be created for
5242 /// \param IsStringLocation if true, Loc points to the format string should be
5243 /// used for the note. Otherwise, Loc points to the argument list and will
5244 /// be used with PDiag.
5246 /// \param StringRange some or all of the string to highlight. This is
5247 /// templated so it can accept either a CharSourceRange or a SourceRange.
5249 /// \param FixIt optional fix it hint for the format string.
5250 template <typename Range>
5251 void CheckFormatHandler::EmitFormatDiagnostic(
5252 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
5253 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
5254 Range StringRange, ArrayRef<FixItHint> FixIt) {
5255 if (InFunctionCall) {
5256 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
5260 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
5261 << ArgumentExpr->getSourceRange();
5263 const Sema::SemaDiagnosticBuilder &Note =
5264 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
5265 diag::note_format_string_defined);
5267 Note << StringRange;
5272 //===--- CHECK: Printf format string checking ------------------------------===//
5275 class CheckPrintfHandler : public CheckFormatHandler {
5277 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
5278 const Expr *origFormatExpr,
5279 const Sema::FormatStringType type, unsigned firstDataArg,
5280 unsigned numDataArgs, bool isObjC, const char *beg,
5281 bool hasVAListArg, ArrayRef<const Expr *> Args,
5282 unsigned formatIdx, bool inFunctionCall,
5283 Sema::VariadicCallType CallType,
5284 llvm::SmallBitVector &CheckedVarArgs,
5285 UncoveredArgHandler &UncoveredArg)
5286 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
5287 numDataArgs, beg, hasVAListArg, Args, formatIdx,
5288 inFunctionCall, CallType, CheckedVarArgs,
5291 bool isObjCContext() const { return FSType == Sema::FST_NSString; }
5293 /// Returns true if '%@' specifiers are allowed in the format string.
5294 bool allowsObjCArg() const {
5295 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
5296 FSType == Sema::FST_OSTrace;
5299 bool HandleInvalidPrintfConversionSpecifier(
5300 const analyze_printf::PrintfSpecifier &FS,
5301 const char *startSpecifier,
5302 unsigned specifierLen) override;
5304 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
5305 const char *startSpecifier,
5306 unsigned specifierLen) override;
5307 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5308 const char *StartSpecifier,
5309 unsigned SpecifierLen,
5312 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
5313 const char *startSpecifier, unsigned specifierLen);
5314 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
5315 const analyze_printf::OptionalAmount &Amt,
5317 const char *startSpecifier, unsigned specifierLen);
5318 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5319 const analyze_printf::OptionalFlag &flag,
5320 const char *startSpecifier, unsigned specifierLen);
5321 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
5322 const analyze_printf::OptionalFlag &ignoredFlag,
5323 const analyze_printf::OptionalFlag &flag,
5324 const char *startSpecifier, unsigned specifierLen);
5325 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
5328 void HandleEmptyObjCModifierFlag(const char *startFlag,
5329 unsigned flagLen) override;
5331 void HandleInvalidObjCModifierFlag(const char *startFlag,
5332 unsigned flagLen) override;
5334 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
5335 const char *flagsEnd,
5336 const char *conversionPosition)
5339 } // end anonymous namespace
5341 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
5342 const analyze_printf::PrintfSpecifier &FS,
5343 const char *startSpecifier,
5344 unsigned specifierLen) {
5345 const analyze_printf::PrintfConversionSpecifier &CS =
5346 FS.getConversionSpecifier();
5348 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5349 getLocationOfByte(CS.getStart()),
5350 startSpecifier, specifierLen,
5351 CS.getStart(), CS.getLength());
5354 bool CheckPrintfHandler::HandleAmount(
5355 const analyze_format_string::OptionalAmount &Amt,
5356 unsigned k, const char *startSpecifier,
5357 unsigned specifierLen) {
5358 if (Amt.hasDataArgument()) {
5359 if (!HasVAListArg) {
5360 unsigned argIndex = Amt.getArgIndex();
5361 if (argIndex >= NumDataArgs) {
5362 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
5364 getLocationOfByte(Amt.getStart()),
5365 /*IsStringLocation*/true,
5366 getSpecifierRange(startSpecifier, specifierLen));
5367 // Don't do any more checking. We will just emit
5372 // Type check the data argument. It should be an 'int'.
5373 // Although not in conformance with C99, we also allow the argument to be
5374 // an 'unsigned int' as that is a reasonably safe case. GCC also
5375 // doesn't emit a warning for that case.
5376 CoveredArgs.set(argIndex);
5377 const Expr *Arg = getDataArg(argIndex);
5381 QualType T = Arg->getType();
5383 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
5384 assert(AT.isValid());
5386 if (!AT.matchesType(S.Context, T)) {
5387 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
5388 << k << AT.getRepresentativeTypeName(S.Context)
5389 << T << Arg->getSourceRange(),
5390 getLocationOfByte(Amt.getStart()),
5391 /*IsStringLocation*/true,
5392 getSpecifierRange(startSpecifier, specifierLen));
5393 // Don't do any more checking. We will just emit
5402 void CheckPrintfHandler::HandleInvalidAmount(
5403 const analyze_printf::PrintfSpecifier &FS,
5404 const analyze_printf::OptionalAmount &Amt,
5406 const char *startSpecifier,
5407 unsigned specifierLen) {
5408 const analyze_printf::PrintfConversionSpecifier &CS =
5409 FS.getConversionSpecifier();
5412 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
5413 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
5414 Amt.getConstantLength()))
5417 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
5418 << type << CS.toString(),
5419 getLocationOfByte(Amt.getStart()),
5420 /*IsStringLocation*/true,
5421 getSpecifierRange(startSpecifier, specifierLen),
5425 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5426 const analyze_printf::OptionalFlag &flag,
5427 const char *startSpecifier,
5428 unsigned specifierLen) {
5429 // Warn about pointless flag with a fixit removal.
5430 const analyze_printf::PrintfConversionSpecifier &CS =
5431 FS.getConversionSpecifier();
5432 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
5433 << flag.toString() << CS.toString(),
5434 getLocationOfByte(flag.getPosition()),
5435 /*IsStringLocation*/true,
5436 getSpecifierRange(startSpecifier, specifierLen),
5437 FixItHint::CreateRemoval(
5438 getSpecifierRange(flag.getPosition(), 1)));
5441 void CheckPrintfHandler::HandleIgnoredFlag(
5442 const analyze_printf::PrintfSpecifier &FS,
5443 const analyze_printf::OptionalFlag &ignoredFlag,
5444 const analyze_printf::OptionalFlag &flag,
5445 const char *startSpecifier,
5446 unsigned specifierLen) {
5447 // Warn about ignored flag with a fixit removal.
5448 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
5449 << ignoredFlag.toString() << flag.toString(),
5450 getLocationOfByte(ignoredFlag.getPosition()),
5451 /*IsStringLocation*/true,
5452 getSpecifierRange(startSpecifier, specifierLen),
5453 FixItHint::CreateRemoval(
5454 getSpecifierRange(ignoredFlag.getPosition(), 1)));
5457 // void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5458 // bool IsStringLocation, Range StringRange,
5459 // ArrayRef<FixItHint> Fixit = None);
5461 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
5463 // Warn about an empty flag.
5464 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
5465 getLocationOfByte(startFlag),
5466 /*IsStringLocation*/true,
5467 getSpecifierRange(startFlag, flagLen));
5470 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
5472 // Warn about an invalid flag.
5473 auto Range = getSpecifierRange(startFlag, flagLen);
5474 StringRef flag(startFlag, flagLen);
5475 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
5476 getLocationOfByte(startFlag),
5477 /*IsStringLocation*/true,
5478 Range, FixItHint::CreateRemoval(Range));
5481 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
5482 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
5483 // Warn about using '[...]' without a '@' conversion.
5484 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
5485 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
5486 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
5487 getLocationOfByte(conversionPosition),
5488 /*IsStringLocation*/true,
5489 Range, FixItHint::CreateRemoval(Range));
5492 // Determines if the specified is a C++ class or struct containing
5493 // a member with the specified name and kind (e.g. a CXXMethodDecl named
5495 template<typename MemberKind>
5496 static llvm::SmallPtrSet<MemberKind*, 1>
5497 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
5498 const RecordType *RT = Ty->getAs<RecordType>();
5499 llvm::SmallPtrSet<MemberKind*, 1> Results;
5503 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
5504 if (!RD || !RD->getDefinition())
5507 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
5508 Sema::LookupMemberName);
5509 R.suppressDiagnostics();
5511 // We just need to include all members of the right kind turned up by the
5512 // filter, at this point.
5513 if (S.LookupQualifiedName(R, RT->getDecl()))
5514 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5515 NamedDecl *decl = (*I)->getUnderlyingDecl();
5516 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
5522 /// Check if we could call '.c_str()' on an object.
5524 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
5525 /// allow the call, or if it would be ambiguous).
5526 bool Sema::hasCStrMethod(const Expr *E) {
5527 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5529 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
5530 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5532 if ((*MI)->getMinRequiredArguments() == 0)
5537 // Check if a (w)string was passed when a (w)char* was needed, and offer a
5538 // better diagnostic if so. AT is assumed to be valid.
5539 // Returns true when a c_str() conversion method is found.
5540 bool CheckPrintfHandler::checkForCStrMembers(
5541 const analyze_printf::ArgType &AT, const Expr *E) {
5542 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5545 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
5547 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5549 const CXXMethodDecl *Method = *MI;
5550 if (Method->getMinRequiredArguments() == 0 &&
5551 AT.matchesType(S.Context, Method->getReturnType())) {
5552 // FIXME: Suggest parens if the expression needs them.
5553 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
5554 S.Diag(E->getLocStart(), diag::note_printf_c_str)
5556 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
5565 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
5567 const char *startSpecifier,
5568 unsigned specifierLen) {
5569 using namespace analyze_format_string;
5570 using namespace analyze_printf;
5571 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
5573 if (FS.consumesDataArgument()) {
5576 usesPositionalArgs = FS.usesPositionalArg();
5578 else if (usesPositionalArgs != FS.usesPositionalArg()) {
5579 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5580 startSpecifier, specifierLen);
5585 // First check if the field width, precision, and conversion specifier
5586 // have matching data arguments.
5587 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
5588 startSpecifier, specifierLen)) {
5592 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
5593 startSpecifier, specifierLen)) {
5597 if (!CS.consumesDataArgument()) {
5598 // FIXME: Technically specifying a precision or field width here
5599 // makes no sense. Worth issuing a warning at some point.
5603 // Consume the argument.
5604 unsigned argIndex = FS.getArgIndex();
5605 if (argIndex < NumDataArgs) {
5606 // The check to see if the argIndex is valid will come later.
5607 // We set the bit here because we may exit early from this
5608 // function if we encounter some other error.
5609 CoveredArgs.set(argIndex);
5612 // FreeBSD kernel extensions.
5613 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
5614 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
5615 // We need at least two arguments.
5616 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
5619 // Claim the second argument.
5620 CoveredArgs.set(argIndex + 1);
5622 // Type check the first argument (int for %b, pointer for %D)
5623 const Expr *Ex = getDataArg(argIndex);
5624 const analyze_printf::ArgType &AT =
5625 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
5626 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
5627 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
5628 EmitFormatDiagnostic(
5629 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5630 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
5631 << false << Ex->getSourceRange(),
5632 Ex->getLocStart(), /*IsStringLocation*/false,
5633 getSpecifierRange(startSpecifier, specifierLen));
5635 // Type check the second argument (char * for both %b and %D)
5636 Ex = getDataArg(argIndex + 1);
5637 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
5638 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
5639 EmitFormatDiagnostic(
5640 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5641 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
5642 << false << Ex->getSourceRange(),
5643 Ex->getLocStart(), /*IsStringLocation*/false,
5644 getSpecifierRange(startSpecifier, specifierLen));
5649 // Check for using an Objective-C specific conversion specifier
5650 // in a non-ObjC literal.
5651 if (!allowsObjCArg() && CS.isObjCArg()) {
5652 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5656 // %P can only be used with os_log.
5657 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
5658 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5662 // %n is not allowed with os_log.
5663 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
5664 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
5665 getLocationOfByte(CS.getStart()),
5666 /*IsStringLocation*/ false,
5667 getSpecifierRange(startSpecifier, specifierLen));
5672 // Only scalars are allowed for os_trace.
5673 if (FSType == Sema::FST_OSTrace &&
5674 (CS.getKind() == ConversionSpecifier::PArg ||
5675 CS.getKind() == ConversionSpecifier::sArg ||
5676 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
5677 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5681 // Check for use of public/private annotation outside of os_log().
5682 if (FSType != Sema::FST_OSLog) {
5683 if (FS.isPublic().isSet()) {
5684 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
5686 getLocationOfByte(FS.isPublic().getPosition()),
5687 /*IsStringLocation*/ false,
5688 getSpecifierRange(startSpecifier, specifierLen));
5690 if (FS.isPrivate().isSet()) {
5691 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
5693 getLocationOfByte(FS.isPrivate().getPosition()),
5694 /*IsStringLocation*/ false,
5695 getSpecifierRange(startSpecifier, specifierLen));
5699 // Check for invalid use of field width
5700 if (!FS.hasValidFieldWidth()) {
5701 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
5702 startSpecifier, specifierLen);
5705 // Check for invalid use of precision
5706 if (!FS.hasValidPrecision()) {
5707 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
5708 startSpecifier, specifierLen);
5711 // Precision is mandatory for %P specifier.
5712 if (CS.getKind() == ConversionSpecifier::PArg &&
5713 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
5714 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
5715 getLocationOfByte(startSpecifier),
5716 /*IsStringLocation*/ false,
5717 getSpecifierRange(startSpecifier, specifierLen));
5720 // Check each flag does not conflict with any other component.
5721 if (!FS.hasValidThousandsGroupingPrefix())
5722 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
5723 if (!FS.hasValidLeadingZeros())
5724 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
5725 if (!FS.hasValidPlusPrefix())
5726 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
5727 if (!FS.hasValidSpacePrefix())
5728 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
5729 if (!FS.hasValidAlternativeForm())
5730 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
5731 if (!FS.hasValidLeftJustified())
5732 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
5734 // Check that flags are not ignored by another flag
5735 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
5736 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
5737 startSpecifier, specifierLen);
5738 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
5739 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
5740 startSpecifier, specifierLen);
5742 // Check the length modifier is valid with the given conversion specifier.
5743 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
5744 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5745 diag::warn_format_nonsensical_length);
5746 else if (!FS.hasStandardLengthModifier())
5747 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
5748 else if (!FS.hasStandardLengthConversionCombination())
5749 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5750 diag::warn_format_non_standard_conversion_spec);
5752 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
5753 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
5755 // The remaining checks depend on the data arguments.
5759 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
5762 const Expr *Arg = getDataArg(argIndex);
5766 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
5769 static bool requiresParensToAddCast(const Expr *E) {
5770 // FIXME: We should have a general way to reason about operator
5771 // precedence and whether parens are actually needed here.
5772 // Take care of a few common cases where they aren't.
5773 const Expr *Inside = E->IgnoreImpCasts();
5774 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
5775 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
5777 switch (Inside->getStmtClass()) {
5778 case Stmt::ArraySubscriptExprClass:
5779 case Stmt::CallExprClass:
5780 case Stmt::CharacterLiteralClass:
5781 case Stmt::CXXBoolLiteralExprClass:
5782 case Stmt::DeclRefExprClass:
5783 case Stmt::FloatingLiteralClass:
5784 case Stmt::IntegerLiteralClass:
5785 case Stmt::MemberExprClass:
5786 case Stmt::ObjCArrayLiteralClass:
5787 case Stmt::ObjCBoolLiteralExprClass:
5788 case Stmt::ObjCBoxedExprClass:
5789 case Stmt::ObjCDictionaryLiteralClass:
5790 case Stmt::ObjCEncodeExprClass:
5791 case Stmt::ObjCIvarRefExprClass:
5792 case Stmt::ObjCMessageExprClass:
5793 case Stmt::ObjCPropertyRefExprClass:
5794 case Stmt::ObjCStringLiteralClass:
5795 case Stmt::ObjCSubscriptRefExprClass:
5796 case Stmt::ParenExprClass:
5797 case Stmt::StringLiteralClass:
5798 case Stmt::UnaryOperatorClass:
5805 static std::pair<QualType, StringRef>
5806 shouldNotPrintDirectly(const ASTContext &Context,
5807 QualType IntendedTy,
5809 // Use a 'while' to peel off layers of typedefs.
5810 QualType TyTy = IntendedTy;
5811 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
5812 StringRef Name = UserTy->getDecl()->getName();
5813 QualType CastTy = llvm::StringSwitch<QualType>(Name)
5814 .Case("NSInteger", Context.LongTy)
5815 .Case("NSUInteger", Context.UnsignedLongTy)
5816 .Case("SInt32", Context.IntTy)
5817 .Case("UInt32", Context.UnsignedIntTy)
5818 .Default(QualType());
5820 if (!CastTy.isNull())
5821 return std::make_pair(CastTy, Name);
5823 TyTy = UserTy->desugar();
5826 // Strip parens if necessary.
5827 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
5828 return shouldNotPrintDirectly(Context,
5829 PE->getSubExpr()->getType(),
5832 // If this is a conditional expression, then its result type is constructed
5833 // via usual arithmetic conversions and thus there might be no necessary
5834 // typedef sugar there. Recurse to operands to check for NSInteger &
5835 // Co. usage condition.
5836 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5837 QualType TrueTy, FalseTy;
5838 StringRef TrueName, FalseName;
5840 std::tie(TrueTy, TrueName) =
5841 shouldNotPrintDirectly(Context,
5842 CO->getTrueExpr()->getType(),
5844 std::tie(FalseTy, FalseName) =
5845 shouldNotPrintDirectly(Context,
5846 CO->getFalseExpr()->getType(),
5847 CO->getFalseExpr());
5849 if (TrueTy == FalseTy)
5850 return std::make_pair(TrueTy, TrueName);
5851 else if (TrueTy.isNull())
5852 return std::make_pair(FalseTy, FalseName);
5853 else if (FalseTy.isNull())
5854 return std::make_pair(TrueTy, TrueName);
5857 return std::make_pair(QualType(), StringRef());
5861 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5862 const char *StartSpecifier,
5863 unsigned SpecifierLen,
5865 using namespace analyze_format_string;
5866 using namespace analyze_printf;
5867 // Now type check the data expression that matches the
5868 // format specifier.
5869 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
5873 QualType ExprTy = E->getType();
5874 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
5875 ExprTy = TET->getUnderlyingExpr()->getType();
5878 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
5880 if (match == analyze_printf::ArgType::Match) {
5884 // Look through argument promotions for our error message's reported type.
5885 // This includes the integral and floating promotions, but excludes array
5886 // and function pointer decay; seeing that an argument intended to be a
5887 // string has type 'char [6]' is probably more confusing than 'char *'.
5888 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5889 if (ICE->getCastKind() == CK_IntegralCast ||
5890 ICE->getCastKind() == CK_FloatingCast) {
5891 E = ICE->getSubExpr();
5892 ExprTy = E->getType();
5894 // Check if we didn't match because of an implicit cast from a 'char'
5895 // or 'short' to an 'int'. This is done because printf is a varargs
5897 if (ICE->getType() == S.Context.IntTy ||
5898 ICE->getType() == S.Context.UnsignedIntTy) {
5899 // All further checking is done on the subexpression.
5900 if (AT.matchesType(S.Context, ExprTy))
5904 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
5905 // Special case for 'a', which has type 'int' in C.
5906 // Note, however, that we do /not/ want to treat multibyte constants like
5907 // 'MooV' as characters! This form is deprecated but still exists.
5908 if (ExprTy == S.Context.IntTy)
5909 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
5910 ExprTy = S.Context.CharTy;
5913 // Look through enums to their underlying type.
5914 bool IsEnum = false;
5915 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
5916 ExprTy = EnumTy->getDecl()->getIntegerType();
5920 // %C in an Objective-C context prints a unichar, not a wchar_t.
5921 // If the argument is an integer of some kind, believe the %C and suggest
5922 // a cast instead of changing the conversion specifier.
5923 QualType IntendedTy = ExprTy;
5924 if (isObjCContext() &&
5925 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
5926 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
5927 !ExprTy->isCharType()) {
5928 // 'unichar' is defined as a typedef of unsigned short, but we should
5929 // prefer using the typedef if it is visible.
5930 IntendedTy = S.Context.UnsignedShortTy;
5932 // While we are here, check if the value is an IntegerLiteral that happens
5933 // to be within the valid range.
5934 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
5935 const llvm::APInt &V = IL->getValue();
5936 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
5940 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
5941 Sema::LookupOrdinaryName);
5942 if (S.LookupName(Result, S.getCurScope())) {
5943 NamedDecl *ND = Result.getFoundDecl();
5944 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
5945 if (TD->getUnderlyingType() == IntendedTy)
5946 IntendedTy = S.Context.getTypedefType(TD);
5951 // Special-case some of Darwin's platform-independence types by suggesting
5952 // casts to primitive types that are known to be large enough.
5953 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
5954 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
5956 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
5957 if (!CastTy.isNull()) {
5958 IntendedTy = CastTy;
5959 ShouldNotPrintDirectly = true;
5963 // We may be able to offer a FixItHint if it is a supported type.
5964 PrintfSpecifier fixedFS = FS;
5966 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
5969 // Get the fix string from the fixed format specifier
5970 SmallString<16> buf;
5971 llvm::raw_svector_ostream os(buf);
5972 fixedFS.toString(os);
5974 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
5976 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
5977 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5978 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
5979 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5981 // In this case, the specifier is wrong and should be changed to match
5983 EmitFormatDiagnostic(S.PDiag(diag)
5984 << AT.getRepresentativeTypeName(S.Context)
5985 << IntendedTy << IsEnum << E->getSourceRange(),
5987 /*IsStringLocation*/ false, SpecRange,
5988 FixItHint::CreateReplacement(SpecRange, os.str()));
5990 // The canonical type for formatting this value is different from the
5991 // actual type of the expression. (This occurs, for example, with Darwin's
5992 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
5993 // should be printed as 'long' for 64-bit compatibility.)
5994 // Rather than emitting a normal format/argument mismatch, we want to
5995 // add a cast to the recommended type (and correct the format string
5997 SmallString<16> CastBuf;
5998 llvm::raw_svector_ostream CastFix(CastBuf);
6000 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
6003 SmallVector<FixItHint,4> Hints;
6004 if (!AT.matchesType(S.Context, IntendedTy))
6005 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
6007 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
6008 // If there's already a cast present, just replace it.
6009 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
6010 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
6012 } else if (!requiresParensToAddCast(E)) {
6013 // If the expression has high enough precedence,
6014 // just write the C-style cast.
6015 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6018 // Otherwise, add parens around the expression as well as the cast.
6020 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6023 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
6024 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6027 if (ShouldNotPrintDirectly) {
6028 // The expression has a type that should not be printed directly.
6029 // We extract the name from the typedef because we don't want to show
6030 // the underlying type in the diagnostic.
6032 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6033 Name = TypedefTy->getDecl()->getName();
6036 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
6037 << Name << IntendedTy << IsEnum
6038 << E->getSourceRange(),
6039 E->getLocStart(), /*IsStringLocation=*/false,
6042 // In this case, the expression could be printed using a different
6043 // specifier, but we've decided that the specifier is probably correct
6044 // and we should cast instead. Just use the normal warning message.
6045 EmitFormatDiagnostic(
6046 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6047 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
6048 << E->getSourceRange(),
6049 E->getLocStart(), /*IsStringLocation*/false,
6054 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
6056 // Since the warning for passing non-POD types to variadic functions
6057 // was deferred until now, we emit a warning for non-POD
6059 switch (S.isValidVarArgType(ExprTy)) {
6060 case Sema::VAK_Valid:
6061 case Sema::VAK_ValidInCXX11: {
6062 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6063 if (match == analyze_printf::ArgType::NoMatchPedantic) {
6064 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6067 EmitFormatDiagnostic(
6068 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
6069 << IsEnum << CSR << E->getSourceRange(),
6070 E->getLocStart(), /*IsStringLocation*/ false, CSR);
6073 case Sema::VAK_Undefined:
6074 case Sema::VAK_MSVCUndefined:
6075 EmitFormatDiagnostic(
6076 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
6077 << S.getLangOpts().CPlusPlus11
6080 << AT.getRepresentativeTypeName(S.Context)
6082 << E->getSourceRange(),
6083 E->getLocStart(), /*IsStringLocation*/false, CSR);
6084 checkForCStrMembers(AT, E);
6087 case Sema::VAK_Invalid:
6088 if (ExprTy->isObjCObjectType())
6089 EmitFormatDiagnostic(
6090 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
6091 << S.getLangOpts().CPlusPlus11
6094 << AT.getRepresentativeTypeName(S.Context)
6096 << E->getSourceRange(),
6097 E->getLocStart(), /*IsStringLocation*/false, CSR);
6099 // FIXME: If this is an initializer list, suggest removing the braces
6100 // or inserting a cast to the target type.
6101 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
6102 << isa<InitListExpr>(E) << ExprTy << CallType
6103 << AT.getRepresentativeTypeName(S.Context)
6104 << E->getSourceRange();
6108 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
6109 "format string specifier index out of range");
6110 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
6116 //===--- CHECK: Scanf format string checking ------------------------------===//
6119 class CheckScanfHandler : public CheckFormatHandler {
6121 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
6122 const Expr *origFormatExpr, Sema::FormatStringType type,
6123 unsigned firstDataArg, unsigned numDataArgs,
6124 const char *beg, bool hasVAListArg,
6125 ArrayRef<const Expr *> Args, unsigned formatIdx,
6126 bool inFunctionCall, Sema::VariadicCallType CallType,
6127 llvm::SmallBitVector &CheckedVarArgs,
6128 UncoveredArgHandler &UncoveredArg)
6129 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6130 numDataArgs, beg, hasVAListArg, Args, formatIdx,
6131 inFunctionCall, CallType, CheckedVarArgs,
6134 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
6135 const char *startSpecifier,
6136 unsigned specifierLen) override;
6138 bool HandleInvalidScanfConversionSpecifier(
6139 const analyze_scanf::ScanfSpecifier &FS,
6140 const char *startSpecifier,
6141 unsigned specifierLen) override;
6143 void HandleIncompleteScanList(const char *start, const char *end) override;
6145 } // end anonymous namespace
6147 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
6149 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
6150 getLocationOfByte(end), /*IsStringLocation*/true,
6151 getSpecifierRange(start, end - start));
6154 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
6155 const analyze_scanf::ScanfSpecifier &FS,
6156 const char *startSpecifier,
6157 unsigned specifierLen) {
6159 const analyze_scanf::ScanfConversionSpecifier &CS =
6160 FS.getConversionSpecifier();
6162 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6163 getLocationOfByte(CS.getStart()),
6164 startSpecifier, specifierLen,
6165 CS.getStart(), CS.getLength());
6168 bool CheckScanfHandler::HandleScanfSpecifier(
6169 const analyze_scanf::ScanfSpecifier &FS,
6170 const char *startSpecifier,
6171 unsigned specifierLen) {
6172 using namespace analyze_scanf;
6173 using namespace analyze_format_string;
6175 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
6177 // Handle case where '%' and '*' don't consume an argument. These shouldn't
6178 // be used to decide if we are using positional arguments consistently.
6179 if (FS.consumesDataArgument()) {
6182 usesPositionalArgs = FS.usesPositionalArg();
6184 else if (usesPositionalArgs != FS.usesPositionalArg()) {
6185 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6186 startSpecifier, specifierLen);
6191 // Check if the field with is non-zero.
6192 const OptionalAmount &Amt = FS.getFieldWidth();
6193 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
6194 if (Amt.getConstantAmount() == 0) {
6195 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
6196 Amt.getConstantLength());
6197 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
6198 getLocationOfByte(Amt.getStart()),
6199 /*IsStringLocation*/true, R,
6200 FixItHint::CreateRemoval(R));
6204 if (!FS.consumesDataArgument()) {
6205 // FIXME: Technically specifying a precision or field width here
6206 // makes no sense. Worth issuing a warning at some point.
6210 // Consume the argument.
6211 unsigned argIndex = FS.getArgIndex();
6212 if (argIndex < NumDataArgs) {
6213 // The check to see if the argIndex is valid will come later.
6214 // We set the bit here because we may exit early from this
6215 // function if we encounter some other error.
6216 CoveredArgs.set(argIndex);
6219 // Check the length modifier is valid with the given conversion specifier.
6220 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
6221 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6222 diag::warn_format_nonsensical_length);
6223 else if (!FS.hasStandardLengthModifier())
6224 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
6225 else if (!FS.hasStandardLengthConversionCombination())
6226 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6227 diag::warn_format_non_standard_conversion_spec);
6229 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6230 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6232 // The remaining checks depend on the data arguments.
6236 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
6239 // Check that the argument type matches the format specifier.
6240 const Expr *Ex = getDataArg(argIndex);
6244 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
6246 if (!AT.isValid()) {
6250 analyze_format_string::ArgType::MatchKind match =
6251 AT.matchesType(S.Context, Ex->getType());
6252 if (match == analyze_format_string::ArgType::Match) {
6256 ScanfSpecifier fixedFS = FS;
6257 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
6258 S.getLangOpts(), S.Context);
6260 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6261 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6262 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6266 // Get the fix string from the fixed format specifier.
6267 SmallString<128> buf;
6268 llvm::raw_svector_ostream os(buf);
6269 fixedFS.toString(os);
6271 EmitFormatDiagnostic(
6272 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
6273 << Ex->getType() << false << Ex->getSourceRange(),
6275 /*IsStringLocation*/ false,
6276 getSpecifierRange(startSpecifier, specifierLen),
6277 FixItHint::CreateReplacement(
6278 getSpecifierRange(startSpecifier, specifierLen), os.str()));
6280 EmitFormatDiagnostic(S.PDiag(diag)
6281 << AT.getRepresentativeTypeName(S.Context)
6282 << Ex->getType() << false << Ex->getSourceRange(),
6284 /*IsStringLocation*/ false,
6285 getSpecifierRange(startSpecifier, specifierLen));
6291 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
6292 const Expr *OrigFormatExpr,
6293 ArrayRef<const Expr *> Args,
6294 bool HasVAListArg, unsigned format_idx,
6295 unsigned firstDataArg,
6296 Sema::FormatStringType Type,
6297 bool inFunctionCall,
6298 Sema::VariadicCallType CallType,
6299 llvm::SmallBitVector &CheckedVarArgs,
6300 UncoveredArgHandler &UncoveredArg) {
6301 // CHECK: is the format string a wide literal?
6302 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
6303 CheckFormatHandler::EmitFormatDiagnostic(
6304 S, inFunctionCall, Args[format_idx],
6305 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
6306 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
6310 // Str - The format string. NOTE: this is NOT null-terminated!
6311 StringRef StrRef = FExpr->getString();
6312 const char *Str = StrRef.data();
6313 // Account for cases where the string literal is truncated in a declaration.
6314 const ConstantArrayType *T =
6315 S.Context.getAsConstantArrayType(FExpr->getType());
6316 assert(T && "String literal not of constant array type!");
6317 size_t TypeSize = T->getSize().getZExtValue();
6318 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6319 const unsigned numDataArgs = Args.size() - firstDataArg;
6321 // Emit a warning if the string literal is truncated and does not contain an
6322 // embedded null character.
6323 if (TypeSize <= StrRef.size() &&
6324 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
6325 CheckFormatHandler::EmitFormatDiagnostic(
6326 S, inFunctionCall, Args[format_idx],
6327 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
6328 FExpr->getLocStart(),
6329 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
6333 // CHECK: empty format string?
6334 if (StrLen == 0 && numDataArgs > 0) {
6335 CheckFormatHandler::EmitFormatDiagnostic(
6336 S, inFunctionCall, Args[format_idx],
6337 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
6338 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
6342 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
6343 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
6344 Type == Sema::FST_OSTrace) {
6345 CheckPrintfHandler H(
6346 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
6347 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
6348 HasVAListArg, Args, format_idx, inFunctionCall, CallType,
6349 CheckedVarArgs, UncoveredArg);
6351 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
6353 S.Context.getTargetInfo(),
6354 Type == Sema::FST_FreeBSDKPrintf))
6356 } else if (Type == Sema::FST_Scanf) {
6357 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
6358 numDataArgs, Str, HasVAListArg, Args, format_idx,
6359 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
6361 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
6363 S.Context.getTargetInfo()))
6365 } // TODO: handle other formats
6368 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
6369 // Str - The format string. NOTE: this is NOT null-terminated!
6370 StringRef StrRef = FExpr->getString();
6371 const char *Str = StrRef.data();
6372 // Account for cases where the string literal is truncated in a declaration.
6373 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
6374 assert(T && "String literal not of constant array type!");
6375 size_t TypeSize = T->getSize().getZExtValue();
6376 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6377 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
6379 Context.getTargetInfo());
6382 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
6384 // Returns the related absolute value function that is larger, of 0 if one
6386 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
6387 switch (AbsFunction) {
6391 case Builtin::BI__builtin_abs:
6392 return Builtin::BI__builtin_labs;
6393 case Builtin::BI__builtin_labs:
6394 return Builtin::BI__builtin_llabs;
6395 case Builtin::BI__builtin_llabs:
6398 case Builtin::BI__builtin_fabsf:
6399 return Builtin::BI__builtin_fabs;
6400 case Builtin::BI__builtin_fabs:
6401 return Builtin::BI__builtin_fabsl;
6402 case Builtin::BI__builtin_fabsl:
6405 case Builtin::BI__builtin_cabsf:
6406 return Builtin::BI__builtin_cabs;
6407 case Builtin::BI__builtin_cabs:
6408 return Builtin::BI__builtin_cabsl;
6409 case Builtin::BI__builtin_cabsl:
6412 case Builtin::BIabs:
6413 return Builtin::BIlabs;
6414 case Builtin::BIlabs:
6415 return Builtin::BIllabs;
6416 case Builtin::BIllabs:
6419 case Builtin::BIfabsf:
6420 return Builtin::BIfabs;
6421 case Builtin::BIfabs:
6422 return Builtin::BIfabsl;
6423 case Builtin::BIfabsl:
6426 case Builtin::BIcabsf:
6427 return Builtin::BIcabs;
6428 case Builtin::BIcabs:
6429 return Builtin::BIcabsl;
6430 case Builtin::BIcabsl:
6435 // Returns the argument type of the absolute value function.
6436 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
6441 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
6442 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
6443 if (Error != ASTContext::GE_None)
6446 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
6450 if (FT->getNumParams() != 1)
6453 return FT->getParamType(0);
6456 // Returns the best absolute value function, or zero, based on type and
6457 // current absolute value function.
6458 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
6459 unsigned AbsFunctionKind) {
6460 unsigned BestKind = 0;
6461 uint64_t ArgSize = Context.getTypeSize(ArgType);
6462 for (unsigned Kind = AbsFunctionKind; Kind != 0;
6463 Kind = getLargerAbsoluteValueFunction(Kind)) {
6464 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
6465 if (Context.getTypeSize(ParamType) >= ArgSize) {
6468 else if (Context.hasSameType(ParamType, ArgType)) {
6477 enum AbsoluteValueKind {
6483 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
6484 if (T->isIntegralOrEnumerationType())
6486 if (T->isRealFloatingType())
6487 return AVK_Floating;
6488 if (T->isAnyComplexType())
6491 llvm_unreachable("Type not integer, floating, or complex");
6494 // Changes the absolute value function to a different type. Preserves whether
6495 // the function is a builtin.
6496 static unsigned changeAbsFunction(unsigned AbsKind,
6497 AbsoluteValueKind ValueKind) {
6498 switch (ValueKind) {
6503 case Builtin::BI__builtin_fabsf:
6504 case Builtin::BI__builtin_fabs:
6505 case Builtin::BI__builtin_fabsl:
6506 case Builtin::BI__builtin_cabsf:
6507 case Builtin::BI__builtin_cabs:
6508 case Builtin::BI__builtin_cabsl:
6509 return Builtin::BI__builtin_abs;
6510 case Builtin::BIfabsf:
6511 case Builtin::BIfabs:
6512 case Builtin::BIfabsl:
6513 case Builtin::BIcabsf:
6514 case Builtin::BIcabs:
6515 case Builtin::BIcabsl:
6516 return Builtin::BIabs;
6522 case Builtin::BI__builtin_abs:
6523 case Builtin::BI__builtin_labs:
6524 case Builtin::BI__builtin_llabs:
6525 case Builtin::BI__builtin_cabsf:
6526 case Builtin::BI__builtin_cabs:
6527 case Builtin::BI__builtin_cabsl:
6528 return Builtin::BI__builtin_fabsf;
6529 case Builtin::BIabs:
6530 case Builtin::BIlabs:
6531 case Builtin::BIllabs:
6532 case Builtin::BIcabsf:
6533 case Builtin::BIcabs:
6534 case Builtin::BIcabsl:
6535 return Builtin::BIfabsf;
6541 case Builtin::BI__builtin_abs:
6542 case Builtin::BI__builtin_labs:
6543 case Builtin::BI__builtin_llabs:
6544 case Builtin::BI__builtin_fabsf:
6545 case Builtin::BI__builtin_fabs:
6546 case Builtin::BI__builtin_fabsl:
6547 return Builtin::BI__builtin_cabsf;
6548 case Builtin::BIabs:
6549 case Builtin::BIlabs:
6550 case Builtin::BIllabs:
6551 case Builtin::BIfabsf:
6552 case Builtin::BIfabs:
6553 case Builtin::BIfabsl:
6554 return Builtin::BIcabsf;
6557 llvm_unreachable("Unable to convert function");
6560 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
6561 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
6565 switch (FDecl->getBuiltinID()) {
6568 case Builtin::BI__builtin_abs:
6569 case Builtin::BI__builtin_fabs:
6570 case Builtin::BI__builtin_fabsf:
6571 case Builtin::BI__builtin_fabsl:
6572 case Builtin::BI__builtin_labs:
6573 case Builtin::BI__builtin_llabs:
6574 case Builtin::BI__builtin_cabs:
6575 case Builtin::BI__builtin_cabsf:
6576 case Builtin::BI__builtin_cabsl:
6577 case Builtin::BIabs:
6578 case Builtin::BIlabs:
6579 case Builtin::BIllabs:
6580 case Builtin::BIfabs:
6581 case Builtin::BIfabsf:
6582 case Builtin::BIfabsl:
6583 case Builtin::BIcabs:
6584 case Builtin::BIcabsf:
6585 case Builtin::BIcabsl:
6586 return FDecl->getBuiltinID();
6588 llvm_unreachable("Unknown Builtin type");
6591 // If the replacement is valid, emit a note with replacement function.
6592 // Additionally, suggest including the proper header if not already included.
6593 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
6594 unsigned AbsKind, QualType ArgType) {
6595 bool EmitHeaderHint = true;
6596 const char *HeaderName = nullptr;
6597 const char *FunctionName = nullptr;
6598 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
6599 FunctionName = "std::abs";
6600 if (ArgType->isIntegralOrEnumerationType()) {
6601 HeaderName = "cstdlib";
6602 } else if (ArgType->isRealFloatingType()) {
6603 HeaderName = "cmath";
6605 llvm_unreachable("Invalid Type");
6608 // Lookup all std::abs
6609 if (NamespaceDecl *Std = S.getStdNamespace()) {
6610 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
6611 R.suppressDiagnostics();
6612 S.LookupQualifiedName(R, Std);
6614 for (const auto *I : R) {
6615 const FunctionDecl *FDecl = nullptr;
6616 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
6617 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
6619 FDecl = dyn_cast<FunctionDecl>(I);
6624 // Found std::abs(), check that they are the right ones.
6625 if (FDecl->getNumParams() != 1)
6628 // Check that the parameter type can handle the argument.
6629 QualType ParamType = FDecl->getParamDecl(0)->getType();
6630 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
6631 S.Context.getTypeSize(ArgType) <=
6632 S.Context.getTypeSize(ParamType)) {
6633 // Found a function, don't need the header hint.
6634 EmitHeaderHint = false;
6640 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
6641 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
6644 DeclarationName DN(&S.Context.Idents.get(FunctionName));
6645 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
6646 R.suppressDiagnostics();
6647 S.LookupName(R, S.getCurScope());
6649 if (R.isSingleResult()) {
6650 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
6651 if (FD && FD->getBuiltinID() == AbsKind) {
6652 EmitHeaderHint = false;
6656 } else if (!R.empty()) {
6662 S.Diag(Loc, diag::note_replace_abs_function)
6663 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
6668 if (!EmitHeaderHint)
6671 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
6675 template <std::size_t StrLen>
6676 static bool IsStdFunction(const FunctionDecl *FDecl,
6677 const char (&Str)[StrLen]) {
6680 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
6682 if (!FDecl->isInStdNamespace())
6688 // Warn when using the wrong abs() function.
6689 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
6690 const FunctionDecl *FDecl) {
6691 if (Call->getNumArgs() != 1)
6694 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
6695 bool IsStdAbs = IsStdFunction(FDecl, "abs");
6696 if (AbsKind == 0 && !IsStdAbs)
6699 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
6700 QualType ParamType = Call->getArg(0)->getType();
6702 // Unsigned types cannot be negative. Suggest removing the absolute value
6704 if (ArgType->isUnsignedIntegerType()) {
6705 const char *FunctionName =
6706 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
6707 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
6708 Diag(Call->getExprLoc(), diag::note_remove_abs)
6710 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
6714 // Taking the absolute value of a pointer is very suspicious, they probably
6715 // wanted to index into an array, dereference a pointer, call a function, etc.
6716 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
6717 unsigned DiagType = 0;
6718 if (ArgType->isFunctionType())
6720 else if (ArgType->isArrayType())
6723 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
6727 // std::abs has overloads which prevent most of the absolute value problems
6732 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
6733 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
6735 // The argument and parameter are the same kind. Check if they are the right
6737 if (ArgValueKind == ParamValueKind) {
6738 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
6741 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
6742 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
6743 << FDecl << ArgType << ParamType;
6745 if (NewAbsKind == 0)
6748 emitReplacement(*this, Call->getExprLoc(),
6749 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
6753 // ArgValueKind != ParamValueKind
6754 // The wrong type of absolute value function was used. Attempt to find the
6756 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
6757 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
6758 if (NewAbsKind == 0)
6761 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
6762 << FDecl << ParamValueKind << ArgValueKind;
6764 emitReplacement(*this, Call->getExprLoc(),
6765 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
6768 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
6769 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
6770 const FunctionDecl *FDecl) {
6771 if (!Call || !FDecl) return;
6773 // Ignore template specializations and macros.
6774 if (!ActiveTemplateInstantiations.empty()) return;
6775 if (Call->getExprLoc().isMacroID()) return;
6777 // Only care about the one template argument, two function parameter std::max
6778 if (Call->getNumArgs() != 2) return;
6779 if (!IsStdFunction(FDecl, "max")) return;
6780 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
6781 if (!ArgList) return;
6782 if (ArgList->size() != 1) return;
6784 // Check that template type argument is unsigned integer.
6785 const auto& TA = ArgList->get(0);
6786 if (TA.getKind() != TemplateArgument::Type) return;
6787 QualType ArgType = TA.getAsType();
6788 if (!ArgType->isUnsignedIntegerType()) return;
6790 // See if either argument is a literal zero.
6791 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
6792 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
6793 if (!MTE) return false;
6794 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
6795 if (!Num) return false;
6796 if (Num->getValue() != 0) return false;
6800 const Expr *FirstArg = Call->getArg(0);
6801 const Expr *SecondArg = Call->getArg(1);
6802 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
6803 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
6805 // Only warn when exactly one argument is zero.
6806 if (IsFirstArgZero == IsSecondArgZero) return;
6808 SourceRange FirstRange = FirstArg->getSourceRange();
6809 SourceRange SecondRange = SecondArg->getSourceRange();
6811 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
6813 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
6814 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
6816 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
6817 SourceRange RemovalRange;
6818 if (IsFirstArgZero) {
6819 RemovalRange = SourceRange(FirstRange.getBegin(),
6820 SecondRange.getBegin().getLocWithOffset(-1));
6822 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
6823 SecondRange.getEnd());
6826 Diag(Call->getExprLoc(), diag::note_remove_max_call)
6827 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
6828 << FixItHint::CreateRemoval(RemovalRange);
6831 //===--- CHECK: Standard memory functions ---------------------------------===//
6833 /// \brief Takes the expression passed to the size_t parameter of functions
6834 /// such as memcmp, strncat, etc and warns if it's a comparison.
6836 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
6837 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
6838 IdentifierInfo *FnName,
6839 SourceLocation FnLoc,
6840 SourceLocation RParenLoc) {
6841 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
6845 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
6846 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
6849 SourceRange SizeRange = Size->getSourceRange();
6850 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
6851 << SizeRange << FnName;
6852 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
6853 << FnName << FixItHint::CreateInsertion(
6854 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
6855 << FixItHint::CreateRemoval(RParenLoc);
6856 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
6857 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
6858 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
6864 /// \brief Determine whether the given type is or contains a dynamic class type
6865 /// (e.g., whether it has a vtable).
6866 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
6867 bool &IsContained) {
6868 // Look through array types while ignoring qualifiers.
6869 const Type *Ty = T->getBaseElementTypeUnsafe();
6870 IsContained = false;
6872 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
6873 RD = RD ? RD->getDefinition() : nullptr;
6874 if (!RD || RD->isInvalidDecl())
6877 if (RD->isDynamicClass())
6880 // Check all the fields. If any bases were dynamic, the class is dynamic.
6881 // It's impossible for a class to transitively contain itself by value, so
6882 // infinite recursion is impossible.
6883 for (auto *FD : RD->fields()) {
6885 if (const CXXRecordDecl *ContainedRD =
6886 getContainedDynamicClass(FD->getType(), SubContained)) {
6895 /// \brief If E is a sizeof expression, returns its argument expression,
6896 /// otherwise returns NULL.
6897 static const Expr *getSizeOfExprArg(const Expr *E) {
6898 if (const UnaryExprOrTypeTraitExpr *SizeOf =
6899 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
6900 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
6901 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
6906 /// \brief If E is a sizeof expression, returns its argument type.
6907 static QualType getSizeOfArgType(const Expr *E) {
6908 if (const UnaryExprOrTypeTraitExpr *SizeOf =
6909 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
6910 if (SizeOf->getKind() == clang::UETT_SizeOf)
6911 return SizeOf->getTypeOfArgument();
6916 /// \brief Check for dangerous or invalid arguments to memset().
6918 /// This issues warnings on known problematic, dangerous or unspecified
6919 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
6922 /// \param Call The call expression to diagnose.
6923 void Sema::CheckMemaccessArguments(const CallExpr *Call,
6925 IdentifierInfo *FnName) {
6928 // It is possible to have a non-standard definition of memset. Validate
6929 // we have enough arguments, and if not, abort further checking.
6930 unsigned ExpectedNumArgs =
6931 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
6932 if (Call->getNumArgs() < ExpectedNumArgs)
6935 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
6936 BId == Builtin::BIstrndup ? 1 : 2);
6938 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
6939 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
6941 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
6942 Call->getLocStart(), Call->getRParenLoc()))
6945 // We have special checking when the length is a sizeof expression.
6946 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
6947 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
6948 llvm::FoldingSetNodeID SizeOfArgID;
6950 // Although widely used, 'bzero' is not a standard function. Be more strict
6951 // with the argument types before allowing diagnostics and only allow the
6952 // form bzero(ptr, sizeof(...)).
6953 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
6954 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
6957 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
6958 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
6959 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
6961 QualType DestTy = Dest->getType();
6963 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
6964 PointeeTy = DestPtrTy->getPointeeType();
6966 // Never warn about void type pointers. This can be used to suppress
6968 if (PointeeTy->isVoidType())
6971 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
6972 // actually comparing the expressions for equality. Because computing the
6973 // expression IDs can be expensive, we only do this if the diagnostic is
6976 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
6977 SizeOfArg->getExprLoc())) {
6978 // We only compute IDs for expressions if the warning is enabled, and
6979 // cache the sizeof arg's ID.
6980 if (SizeOfArgID == llvm::FoldingSetNodeID())
6981 SizeOfArg->Profile(SizeOfArgID, Context, true);
6982 llvm::FoldingSetNodeID DestID;
6983 Dest->Profile(DestID, Context, true);
6984 if (DestID == SizeOfArgID) {
6985 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
6986 // over sizeof(src) as well.
6987 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
6988 StringRef ReadableName = FnName->getName();
6990 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
6991 if (UnaryOp->getOpcode() == UO_AddrOf)
6992 ActionIdx = 1; // If its an address-of operator, just remove it.
6993 if (!PointeeTy->isIncompleteType() &&
6994 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
6995 ActionIdx = 2; // If the pointee's size is sizeof(char),
6996 // suggest an explicit length.
6998 // If the function is defined as a builtin macro, do not show macro
7000 SourceLocation SL = SizeOfArg->getExprLoc();
7001 SourceRange DSR = Dest->getSourceRange();
7002 SourceRange SSR = SizeOfArg->getSourceRange();
7003 SourceManager &SM = getSourceManager();
7005 if (SM.isMacroArgExpansion(SL)) {
7006 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
7007 SL = SM.getSpellingLoc(SL);
7008 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
7009 SM.getSpellingLoc(DSR.getEnd()));
7010 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
7011 SM.getSpellingLoc(SSR.getEnd()));
7014 DiagRuntimeBehavior(SL, SizeOfArg,
7015 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
7021 DiagRuntimeBehavior(SL, SizeOfArg,
7022 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
7030 // Also check for cases where the sizeof argument is the exact same
7031 // type as the memory argument, and where it points to a user-defined
7033 if (SizeOfArgTy != QualType()) {
7034 if (PointeeTy->isRecordType() &&
7035 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
7036 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
7037 PDiag(diag::warn_sizeof_pointer_type_memaccess)
7038 << FnName << SizeOfArgTy << ArgIdx
7039 << PointeeTy << Dest->getSourceRange()
7040 << LenExpr->getSourceRange());
7044 } else if (DestTy->isArrayType()) {
7048 if (PointeeTy == QualType())
7051 // Always complain about dynamic classes.
7053 if (const CXXRecordDecl *ContainedRD =
7054 getContainedDynamicClass(PointeeTy, IsContained)) {
7056 unsigned OperationType = 0;
7057 // "overwritten" if we're warning about the destination for any call
7058 // but memcmp; otherwise a verb appropriate to the call.
7059 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
7060 if (BId == Builtin::BImemcpy)
7062 else if(BId == Builtin::BImemmove)
7064 else if (BId == Builtin::BImemcmp)
7068 DiagRuntimeBehavior(
7069 Dest->getExprLoc(), Dest,
7070 PDiag(diag::warn_dyn_class_memaccess)
7071 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
7072 << FnName << IsContained << ContainedRD << OperationType
7073 << Call->getCallee()->getSourceRange());
7074 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
7075 BId != Builtin::BImemset)
7076 DiagRuntimeBehavior(
7077 Dest->getExprLoc(), Dest,
7078 PDiag(diag::warn_arc_object_memaccess)
7079 << ArgIdx << FnName << PointeeTy
7080 << Call->getCallee()->getSourceRange());
7084 DiagRuntimeBehavior(
7085 Dest->getExprLoc(), Dest,
7086 PDiag(diag::note_bad_memaccess_silence)
7087 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
7092 // A little helper routine: ignore addition and subtraction of integer literals.
7093 // This intentionally does not ignore all integer constant expressions because
7094 // we don't want to remove sizeof().
7095 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
7096 Ex = Ex->IgnoreParenCasts();
7099 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
7100 if (!BO || !BO->isAdditiveOp())
7103 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
7104 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
7106 if (isa<IntegerLiteral>(RHS))
7108 else if (isa<IntegerLiteral>(LHS))
7117 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
7118 ASTContext &Context) {
7119 // Only handle constant-sized or VLAs, but not flexible members.
7120 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
7121 // Only issue the FIXIT for arrays of size > 1.
7122 if (CAT->getSize().getSExtValue() <= 1)
7124 } else if (!Ty->isVariableArrayType()) {
7130 // Warn if the user has made the 'size' argument to strlcpy or strlcat
7131 // be the size of the source, instead of the destination.
7132 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
7133 IdentifierInfo *FnName) {
7135 // Don't crash if the user has the wrong number of arguments
7136 unsigned NumArgs = Call->getNumArgs();
7137 if ((NumArgs != 3) && (NumArgs != 4))
7140 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
7141 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
7142 const Expr *CompareWithSrc = nullptr;
7144 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
7145 Call->getLocStart(), Call->getRParenLoc()))
7148 // Look for 'strlcpy(dst, x, sizeof(x))'
7149 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
7150 CompareWithSrc = Ex;
7152 // Look for 'strlcpy(dst, x, strlen(x))'
7153 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
7154 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
7155 SizeCall->getNumArgs() == 1)
7156 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
7160 if (!CompareWithSrc)
7163 // Determine if the argument to sizeof/strlen is equal to the source
7164 // argument. In principle there's all kinds of things you could do
7165 // here, for instance creating an == expression and evaluating it with
7166 // EvaluateAsBooleanCondition, but this uses a more direct technique:
7167 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
7171 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
7172 if (!CompareWithSrcDRE ||
7173 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
7176 const Expr *OriginalSizeArg = Call->getArg(2);
7177 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
7178 << OriginalSizeArg->getSourceRange() << FnName;
7180 // Output a FIXIT hint if the destination is an array (rather than a
7181 // pointer to an array). This could be enhanced to handle some
7182 // pointers if we know the actual size, like if DstArg is 'array+2'
7183 // we could say 'sizeof(array)-2'.
7184 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
7185 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
7188 SmallString<128> sizeString;
7189 llvm::raw_svector_ostream OS(sizeString);
7191 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7194 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
7195 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
7199 /// Check if two expressions refer to the same declaration.
7200 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
7201 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
7202 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
7203 return D1->getDecl() == D2->getDecl();
7207 static const Expr *getStrlenExprArg(const Expr *E) {
7208 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7209 const FunctionDecl *FD = CE->getDirectCallee();
7210 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
7212 return CE->getArg(0)->IgnoreParenCasts();
7217 // Warn on anti-patterns as the 'size' argument to strncat.
7218 // The correct size argument should look like following:
7219 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
7220 void Sema::CheckStrncatArguments(const CallExpr *CE,
7221 IdentifierInfo *FnName) {
7222 // Don't crash if the user has the wrong number of arguments.
7223 if (CE->getNumArgs() < 3)
7225 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
7226 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
7227 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
7229 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
7230 CE->getRParenLoc()))
7233 // Identify common expressions, which are wrongly used as the size argument
7234 // to strncat and may lead to buffer overflows.
7235 unsigned PatternType = 0;
7236 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
7238 if (referToTheSameDecl(SizeOfArg, DstArg))
7241 else if (referToTheSameDecl(SizeOfArg, SrcArg))
7243 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
7244 if (BE->getOpcode() == BO_Sub) {
7245 const Expr *L = BE->getLHS()->IgnoreParenCasts();
7246 const Expr *R = BE->getRHS()->IgnoreParenCasts();
7247 // - sizeof(dst) - strlen(dst)
7248 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
7249 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
7251 // - sizeof(src) - (anything)
7252 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
7257 if (PatternType == 0)
7260 // Generate the diagnostic.
7261 SourceLocation SL = LenArg->getLocStart();
7262 SourceRange SR = LenArg->getSourceRange();
7263 SourceManager &SM = getSourceManager();
7265 // If the function is defined as a builtin macro, do not show macro expansion.
7266 if (SM.isMacroArgExpansion(SL)) {
7267 SL = SM.getSpellingLoc(SL);
7268 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
7269 SM.getSpellingLoc(SR.getEnd()));
7272 // Check if the destination is an array (rather than a pointer to an array).
7273 QualType DstTy = DstArg->getType();
7274 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
7276 if (!isKnownSizeArray) {
7277 if (PatternType == 1)
7278 Diag(SL, diag::warn_strncat_wrong_size) << SR;
7280 Diag(SL, diag::warn_strncat_src_size) << SR;
7284 if (PatternType == 1)
7285 Diag(SL, diag::warn_strncat_large_size) << SR;
7287 Diag(SL, diag::warn_strncat_src_size) << SR;
7289 SmallString<128> sizeString;
7290 llvm::raw_svector_ostream OS(sizeString);
7292 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7295 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7298 Diag(SL, diag::note_strncat_wrong_size)
7299 << FixItHint::CreateReplacement(SR, OS.str());
7302 //===--- CHECK: Return Address of Stack Variable --------------------------===//
7304 static const Expr *EvalVal(const Expr *E,
7305 SmallVectorImpl<const DeclRefExpr *> &refVars,
7306 const Decl *ParentDecl);
7307 static const Expr *EvalAddr(const Expr *E,
7308 SmallVectorImpl<const DeclRefExpr *> &refVars,
7309 const Decl *ParentDecl);
7311 /// CheckReturnStackAddr - Check if a return statement returns the address
7312 /// of a stack variable.
7314 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
7315 SourceLocation ReturnLoc) {
7317 const Expr *stackE = nullptr;
7318 SmallVector<const DeclRefExpr *, 8> refVars;
7320 // Perform checking for returned stack addresses, local blocks,
7321 // label addresses or references to temporaries.
7322 if (lhsType->isPointerType() ||
7323 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
7324 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
7325 } else if (lhsType->isReferenceType()) {
7326 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
7330 return; // Nothing suspicious was found.
7332 // Parameters are initalized in the calling scope, so taking the address
7333 // of a parameter reference doesn't need a warning.
7334 for (auto *DRE : refVars)
7335 if (isa<ParmVarDecl>(DRE->getDecl()))
7338 SourceLocation diagLoc;
7339 SourceRange diagRange;
7340 if (refVars.empty()) {
7341 diagLoc = stackE->getLocStart();
7342 diagRange = stackE->getSourceRange();
7344 // We followed through a reference variable. 'stackE' contains the
7345 // problematic expression but we will warn at the return statement pointing
7346 // at the reference variable. We will later display the "trail" of
7347 // reference variables using notes.
7348 diagLoc = refVars[0]->getLocStart();
7349 diagRange = refVars[0]->getSourceRange();
7352 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
7353 // address of local var
7354 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
7355 << DR->getDecl()->getDeclName() << diagRange;
7356 } else if (isa<BlockExpr>(stackE)) { // local block.
7357 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
7358 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
7359 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
7360 } else { // local temporary.
7361 // If there is an LValue->RValue conversion, then the value of the
7362 // reference type is used, not the reference.
7363 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
7364 if (ICE->getCastKind() == CK_LValueToRValue) {
7368 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
7369 << lhsType->isReferenceType() << diagRange;
7372 // Display the "trail" of reference variables that we followed until we
7373 // found the problematic expression using notes.
7374 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
7375 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
7376 // If this var binds to another reference var, show the range of the next
7377 // var, otherwise the var binds to the problematic expression, in which case
7378 // show the range of the expression.
7379 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
7380 : stackE->getSourceRange();
7381 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
7382 << VD->getDeclName() << range;
7386 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
7387 /// check if the expression in a return statement evaluates to an address
7388 /// to a location on the stack, a local block, an address of a label, or a
7389 /// reference to local temporary. The recursion is used to traverse the
7390 /// AST of the return expression, with recursion backtracking when we
7391 /// encounter a subexpression that (1) clearly does not lead to one of the
7392 /// above problematic expressions (2) is something we cannot determine leads to
7393 /// a problematic expression based on such local checking.
7395 /// Both EvalAddr and EvalVal follow through reference variables to evaluate
7396 /// the expression that they point to. Such variables are added to the
7397 /// 'refVars' vector so that we know what the reference variable "trail" was.
7399 /// EvalAddr processes expressions that are pointers that are used as
7400 /// references (and not L-values). EvalVal handles all other values.
7401 /// At the base case of the recursion is a check for the above problematic
7404 /// This implementation handles:
7406 /// * pointer-to-pointer casts
7407 /// * implicit conversions from array references to pointers
7408 /// * taking the address of fields
7409 /// * arbitrary interplay between "&" and "*" operators
7410 /// * pointer arithmetic from an address of a stack variable
7411 /// * taking the address of an array element where the array is on the stack
7412 static const Expr *EvalAddr(const Expr *E,
7413 SmallVectorImpl<const DeclRefExpr *> &refVars,
7414 const Decl *ParentDecl) {
7415 if (E->isTypeDependent())
7418 // We should only be called for evaluating pointer expressions.
7419 assert((E->getType()->isAnyPointerType() ||
7420 E->getType()->isBlockPointerType() ||
7421 E->getType()->isObjCQualifiedIdType()) &&
7422 "EvalAddr only works on pointers");
7424 E = E->IgnoreParens();
7426 // Our "symbolic interpreter" is just a dispatch off the currently
7427 // viewed AST node. We then recursively traverse the AST by calling
7428 // EvalAddr and EvalVal appropriately.
7429 switch (E->getStmtClass()) {
7430 case Stmt::DeclRefExprClass: {
7431 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7433 // If we leave the immediate function, the lifetime isn't about to end.
7434 if (DR->refersToEnclosingVariableOrCapture())
7437 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
7438 // If this is a reference variable, follow through to the expression that
7440 if (V->hasLocalStorage() &&
7441 V->getType()->isReferenceType() && V->hasInit()) {
7442 // Add the reference variable to the "trail".
7443 refVars.push_back(DR);
7444 return EvalAddr(V->getInit(), refVars, ParentDecl);
7450 case Stmt::UnaryOperatorClass: {
7451 // The only unary operator that make sense to handle here
7452 // is AddrOf. All others don't make sense as pointers.
7453 const UnaryOperator *U = cast<UnaryOperator>(E);
7455 if (U->getOpcode() == UO_AddrOf)
7456 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
7460 case Stmt::BinaryOperatorClass: {
7461 // Handle pointer arithmetic. All other binary operators are not valid
7463 const BinaryOperator *B = cast<BinaryOperator>(E);
7464 BinaryOperatorKind op = B->getOpcode();
7466 if (op != BO_Add && op != BO_Sub)
7469 const Expr *Base = B->getLHS();
7471 // Determine which argument is the real pointer base. It could be
7472 // the RHS argument instead of the LHS.
7473 if (!Base->getType()->isPointerType())
7476 assert(Base->getType()->isPointerType());
7477 return EvalAddr(Base, refVars, ParentDecl);
7480 // For conditional operators we need to see if either the LHS or RHS are
7481 // valid DeclRefExpr*s. If one of them is valid, we return it.
7482 case Stmt::ConditionalOperatorClass: {
7483 const ConditionalOperator *C = cast<ConditionalOperator>(E);
7485 // Handle the GNU extension for missing LHS.
7486 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
7487 if (const Expr *LHSExpr = C->getLHS()) {
7488 // In C++, we can have a throw-expression, which has 'void' type.
7489 if (!LHSExpr->getType()->isVoidType())
7490 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
7494 // In C++, we can have a throw-expression, which has 'void' type.
7495 if (C->getRHS()->getType()->isVoidType())
7498 return EvalAddr(C->getRHS(), refVars, ParentDecl);
7501 case Stmt::BlockExprClass:
7502 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
7503 return E; // local block.
7506 case Stmt::AddrLabelExprClass:
7507 return E; // address of label.
7509 case Stmt::ExprWithCleanupsClass:
7510 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7513 // For casts, we need to handle conversions from arrays to
7514 // pointer values, and pointer-to-pointer conversions.
7515 case Stmt::ImplicitCastExprClass:
7516 case Stmt::CStyleCastExprClass:
7517 case Stmt::CXXFunctionalCastExprClass:
7518 case Stmt::ObjCBridgedCastExprClass:
7519 case Stmt::CXXStaticCastExprClass:
7520 case Stmt::CXXDynamicCastExprClass:
7521 case Stmt::CXXConstCastExprClass:
7522 case Stmt::CXXReinterpretCastExprClass: {
7523 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
7524 switch (cast<CastExpr>(E)->getCastKind()) {
7525 case CK_LValueToRValue:
7527 case CK_BaseToDerived:
7528 case CK_DerivedToBase:
7529 case CK_UncheckedDerivedToBase:
7531 case CK_CPointerToObjCPointerCast:
7532 case CK_BlockPointerToObjCPointerCast:
7533 case CK_AnyPointerToBlockPointerCast:
7534 return EvalAddr(SubExpr, refVars, ParentDecl);
7536 case CK_ArrayToPointerDecay:
7537 return EvalVal(SubExpr, refVars, ParentDecl);
7540 if (SubExpr->getType()->isAnyPointerType() ||
7541 SubExpr->getType()->isBlockPointerType() ||
7542 SubExpr->getType()->isObjCQualifiedIdType())
7543 return EvalAddr(SubExpr, refVars, ParentDecl);
7552 case Stmt::MaterializeTemporaryExprClass:
7553 if (const Expr *Result =
7554 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7555 refVars, ParentDecl))
7559 // Everything else: we simply don't reason about them.
7565 /// EvalVal - This function is complements EvalAddr in the mutual recursion.
7566 /// See the comments for EvalAddr for more details.
7567 static const Expr *EvalVal(const Expr *E,
7568 SmallVectorImpl<const DeclRefExpr *> &refVars,
7569 const Decl *ParentDecl) {
7571 // We should only be called for evaluating non-pointer expressions, or
7572 // expressions with a pointer type that are not used as references but
7574 // are l-values (e.g., DeclRefExpr with a pointer type).
7576 // Our "symbolic interpreter" is just a dispatch off the currently
7577 // viewed AST node. We then recursively traverse the AST by calling
7578 // EvalAddr and EvalVal appropriately.
7580 E = E->IgnoreParens();
7581 switch (E->getStmtClass()) {
7582 case Stmt::ImplicitCastExprClass: {
7583 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
7584 if (IE->getValueKind() == VK_LValue) {
7585 E = IE->getSubExpr();
7591 case Stmt::ExprWithCleanupsClass:
7592 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7595 case Stmt::DeclRefExprClass: {
7596 // When we hit a DeclRefExpr we are looking at code that refers to a
7597 // variable's name. If it's not a reference variable we check if it has
7598 // local storage within the function, and if so, return the expression.
7599 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7601 // If we leave the immediate function, the lifetime isn't about to end.
7602 if (DR->refersToEnclosingVariableOrCapture())
7605 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
7606 // Check if it refers to itself, e.g. "int& i = i;".
7607 if (V == ParentDecl)
7610 if (V->hasLocalStorage()) {
7611 if (!V->getType()->isReferenceType())
7614 // Reference variable, follow through to the expression that
7617 // Add the reference variable to the "trail".
7618 refVars.push_back(DR);
7619 return EvalVal(V->getInit(), refVars, V);
7627 case Stmt::UnaryOperatorClass: {
7628 // The only unary operator that make sense to handle here
7629 // is Deref. All others don't resolve to a "name." This includes
7630 // handling all sorts of rvalues passed to a unary operator.
7631 const UnaryOperator *U = cast<UnaryOperator>(E);
7633 if (U->getOpcode() == UO_Deref)
7634 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
7639 case Stmt::ArraySubscriptExprClass: {
7640 // Array subscripts are potential references to data on the stack. We
7641 // retrieve the DeclRefExpr* for the array variable if it indeed
7642 // has local storage.
7643 const auto *ASE = cast<ArraySubscriptExpr>(E);
7644 if (ASE->isTypeDependent())
7646 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
7649 case Stmt::OMPArraySectionExprClass: {
7650 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
7654 case Stmt::ConditionalOperatorClass: {
7655 // For conditional operators we need to see if either the LHS or RHS are
7656 // non-NULL Expr's. If one is non-NULL, we return it.
7657 const ConditionalOperator *C = cast<ConditionalOperator>(E);
7659 // Handle the GNU extension for missing LHS.
7660 if (const Expr *LHSExpr = C->getLHS()) {
7661 // In C++, we can have a throw-expression, which has 'void' type.
7662 if (!LHSExpr->getType()->isVoidType())
7663 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
7667 // In C++, we can have a throw-expression, which has 'void' type.
7668 if (C->getRHS()->getType()->isVoidType())
7671 return EvalVal(C->getRHS(), refVars, ParentDecl);
7674 // Accesses to members are potential references to data on the stack.
7675 case Stmt::MemberExprClass: {
7676 const MemberExpr *M = cast<MemberExpr>(E);
7678 // Check for indirect access. We only want direct field accesses.
7682 // Check whether the member type is itself a reference, in which case
7683 // we're not going to refer to the member, but to what the member refers
7685 if (M->getMemberDecl()->getType()->isReferenceType())
7688 return EvalVal(M->getBase(), refVars, ParentDecl);
7691 case Stmt::MaterializeTemporaryExprClass:
7692 if (const Expr *Result =
7693 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7694 refVars, ParentDecl))
7699 // Check that we don't return or take the address of a reference to a
7700 // temporary. This is only useful in C++.
7701 if (!E->isTypeDependent() && E->isRValue())
7704 // Everything else: we simply don't reason about them.
7711 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
7712 SourceLocation ReturnLoc,
7714 const AttrVec *Attrs,
7715 const FunctionDecl *FD) {
7716 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
7718 // Check if the return value is null but should not be.
7719 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
7720 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
7721 CheckNonNullExpr(*this, RetValExp))
7722 Diag(ReturnLoc, diag::warn_null_ret)
7723 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
7725 // C++11 [basic.stc.dynamic.allocation]p4:
7726 // If an allocation function declared with a non-throwing
7727 // exception-specification fails to allocate storage, it shall return
7728 // a null pointer. Any other allocation function that fails to allocate
7729 // storage shall indicate failure only by throwing an exception [...]
7731 OverloadedOperatorKind Op = FD->getOverloadedOperator();
7732 if (Op == OO_New || Op == OO_Array_New) {
7733 const FunctionProtoType *Proto
7734 = FD->getType()->castAs<FunctionProtoType>();
7735 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
7736 CheckNonNullExpr(*this, RetValExp))
7737 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
7738 << FD << getLangOpts().CPlusPlus11;
7743 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
7745 /// Check for comparisons of floating point operands using != and ==.
7746 /// Issue a warning if these are no self-comparisons, as they are not likely
7747 /// to do what the programmer intended.
7748 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
7749 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
7750 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
7752 // Special case: check for x == x (which is OK).
7753 // Do not emit warnings for such cases.
7754 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
7755 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
7756 if (DRL->getDecl() == DRR->getDecl())
7759 // Special case: check for comparisons against literals that can be exactly
7760 // represented by APFloat. In such cases, do not emit a warning. This
7761 // is a heuristic: often comparison against such literals are used to
7762 // detect if a value in a variable has not changed. This clearly can
7763 // lead to false negatives.
7764 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
7768 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
7772 // Check for comparisons with builtin types.
7773 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
7774 if (CL->getBuiltinCallee())
7777 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
7778 if (CR->getBuiltinCallee())
7781 // Emit the diagnostic.
7782 Diag(Loc, diag::warn_floatingpoint_eq)
7783 << LHS->getSourceRange() << RHS->getSourceRange();
7786 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
7787 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
7791 /// Structure recording the 'active' range of an integer-valued
7794 /// The number of bits active in the int.
7797 /// True if the int is known not to have negative values.
7800 IntRange(unsigned Width, bool NonNegative)
7801 : Width(Width), NonNegative(NonNegative)
7804 /// Returns the range of the bool type.
7805 static IntRange forBoolType() {
7806 return IntRange(1, true);
7809 /// Returns the range of an opaque value of the given integral type.
7810 static IntRange forValueOfType(ASTContext &C, QualType T) {
7811 return forValueOfCanonicalType(C,
7812 T->getCanonicalTypeInternal().getTypePtr());
7815 /// Returns the range of an opaque value of a canonical integral type.
7816 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
7817 assert(T->isCanonicalUnqualified());
7819 if (const VectorType *VT = dyn_cast<VectorType>(T))
7820 T = VT->getElementType().getTypePtr();
7821 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
7822 T = CT->getElementType().getTypePtr();
7823 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7824 T = AT->getValueType().getTypePtr();
7826 // For enum types, use the known bit width of the enumerators.
7827 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
7828 EnumDecl *Enum = ET->getDecl();
7829 if (!Enum->isCompleteDefinition())
7830 return IntRange(C.getIntWidth(QualType(T, 0)), false);
7832 unsigned NumPositive = Enum->getNumPositiveBits();
7833 unsigned NumNegative = Enum->getNumNegativeBits();
7835 if (NumNegative == 0)
7836 return IntRange(NumPositive, true/*NonNegative*/);
7838 return IntRange(std::max(NumPositive + 1, NumNegative),
7839 false/*NonNegative*/);
7842 const BuiltinType *BT = cast<BuiltinType>(T);
7843 assert(BT->isInteger());
7845 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7848 /// Returns the "target" range of a canonical integral type, i.e.
7849 /// the range of values expressible in the type.
7851 /// This matches forValueOfCanonicalType except that enums have the
7852 /// full range of their type, not the range of their enumerators.
7853 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
7854 assert(T->isCanonicalUnqualified());
7856 if (const VectorType *VT = dyn_cast<VectorType>(T))
7857 T = VT->getElementType().getTypePtr();
7858 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
7859 T = CT->getElementType().getTypePtr();
7860 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7861 T = AT->getValueType().getTypePtr();
7862 if (const EnumType *ET = dyn_cast<EnumType>(T))
7863 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
7865 const BuiltinType *BT = cast<BuiltinType>(T);
7866 assert(BT->isInteger());
7868 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7871 /// Returns the supremum of two ranges: i.e. their conservative merge.
7872 static IntRange join(IntRange L, IntRange R) {
7873 return IntRange(std::max(L.Width, R.Width),
7874 L.NonNegative && R.NonNegative);
7877 /// Returns the infinum of two ranges: i.e. their aggressive merge.
7878 static IntRange meet(IntRange L, IntRange R) {
7879 return IntRange(std::min(L.Width, R.Width),
7880 L.NonNegative || R.NonNegative);
7884 IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
7885 if (value.isSigned() && value.isNegative())
7886 return IntRange(value.getMinSignedBits(), false);
7888 if (value.getBitWidth() > MaxWidth)
7889 value = value.trunc(MaxWidth);
7891 // isNonNegative() just checks the sign bit without considering
7893 return IntRange(value.getActiveBits(), true);
7896 IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
7897 unsigned MaxWidth) {
7899 return GetValueRange(C, result.getInt(), MaxWidth);
7901 if (result.isVector()) {
7902 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
7903 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
7904 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
7905 R = IntRange::join(R, El);
7910 if (result.isComplexInt()) {
7911 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
7912 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
7913 return IntRange::join(R, I);
7916 // This can happen with lossless casts to intptr_t of "based" lvalues.
7917 // Assume it might use arbitrary bits.
7918 // FIXME: The only reason we need to pass the type in here is to get
7919 // the sign right on this one case. It would be nice if APValue
7921 assert(result.isLValue() || result.isAddrLabelDiff());
7922 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
7925 QualType GetExprType(const Expr *E) {
7926 QualType Ty = E->getType();
7927 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
7928 Ty = AtomicRHS->getValueType();
7932 /// Pseudo-evaluate the given integer expression, estimating the
7933 /// range of values it might take.
7935 /// \param MaxWidth - the width to which the value will be truncated
7936 IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
7937 E = E->IgnoreParens();
7939 // Try a full evaluation first.
7940 Expr::EvalResult result;
7941 if (E->EvaluateAsRValue(result, C))
7942 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
7944 // I think we only want to look through implicit casts here; if the
7945 // user has an explicit widening cast, we should treat the value as
7946 // being of the new, wider type.
7947 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
7948 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
7949 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
7951 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
7953 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
7954 CE->getCastKind() == CK_BooleanToSignedIntegral;
7956 // Assume that non-integer casts can span the full range of the type.
7958 return OutputTypeRange;
7961 = GetExprRange(C, CE->getSubExpr(),
7962 std::min(MaxWidth, OutputTypeRange.Width));
7964 // Bail out if the subexpr's range is as wide as the cast type.
7965 if (SubRange.Width >= OutputTypeRange.Width)
7966 return OutputTypeRange;
7968 // Otherwise, we take the smaller width, and we're non-negative if
7969 // either the output type or the subexpr is.
7970 return IntRange(SubRange.Width,
7971 SubRange.NonNegative || OutputTypeRange.NonNegative);
7974 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
7975 // If we can fold the condition, just take that operand.
7977 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
7978 return GetExprRange(C, CondResult ? CO->getTrueExpr()
7979 : CO->getFalseExpr(),
7982 // Otherwise, conservatively merge.
7983 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
7984 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
7985 return IntRange::join(L, R);
7988 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
7989 switch (BO->getOpcode()) {
7991 // Boolean-valued operations are single-bit and positive.
8000 return IntRange::forBoolType();
8002 // The type of the assignments is the type of the LHS, so the RHS
8003 // is not necessarily the same type.
8012 return IntRange::forValueOfType(C, GetExprType(E));
8014 // Simple assignments just pass through the RHS, which will have
8015 // been coerced to the LHS type.
8018 return GetExprRange(C, BO->getRHS(), MaxWidth);
8020 // Operations with opaque sources are black-listed.
8023 return IntRange::forValueOfType(C, GetExprType(E));
8025 // Bitwise-and uses the *infinum* of the two source ranges.
8028 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
8029 GetExprRange(C, BO->getRHS(), MaxWidth));
8031 // Left shift gets black-listed based on a judgement call.
8033 // ...except that we want to treat '1 << (blah)' as logically
8034 // positive. It's an important idiom.
8035 if (IntegerLiteral *I
8036 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
8037 if (I->getValue() == 1) {
8038 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
8039 return IntRange(R.Width, /*NonNegative*/ true);
8045 return IntRange::forValueOfType(C, GetExprType(E));
8047 // Right shift by a constant can narrow its left argument.
8049 case BO_ShrAssign: {
8050 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8052 // If the shift amount is a positive constant, drop the width by
8055 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
8056 shift.isNonNegative()) {
8057 unsigned zext = shift.getZExtValue();
8058 if (zext >= L.Width)
8059 L.Width = (L.NonNegative ? 0 : 1);
8067 // Comma acts as its right operand.
8069 return GetExprRange(C, BO->getRHS(), MaxWidth);
8071 // Black-list pointer subtractions.
8073 if (BO->getLHS()->getType()->isPointerType())
8074 return IntRange::forValueOfType(C, GetExprType(E));
8077 // The width of a division result is mostly determined by the size
8080 // Don't 'pre-truncate' the operands.
8081 unsigned opWidth = C.getIntWidth(GetExprType(E));
8082 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8084 // If the divisor is constant, use that.
8085 llvm::APSInt divisor;
8086 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
8087 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
8088 if (log2 >= L.Width)
8089 L.Width = (L.NonNegative ? 0 : 1);
8091 L.Width = std::min(L.Width - log2, MaxWidth);
8095 // Otherwise, just use the LHS's width.
8096 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8097 return IntRange(L.Width, L.NonNegative && R.NonNegative);
8100 // The result of a remainder can't be larger than the result of
8103 // Don't 'pre-truncate' the operands.
8104 unsigned opWidth = C.getIntWidth(GetExprType(E));
8105 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8106 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8108 IntRange meet = IntRange::meet(L, R);
8109 meet.Width = std::min(meet.Width, MaxWidth);
8113 // The default behavior is okay for these.
8121 // The default case is to treat the operation as if it were closed
8122 // on the narrowest type that encompasses both operands.
8123 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8124 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
8125 return IntRange::join(L, R);
8128 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
8129 switch (UO->getOpcode()) {
8130 // Boolean-valued operations are white-listed.
8132 return IntRange::forBoolType();
8134 // Operations with opaque sources are black-listed.
8136 case UO_AddrOf: // should be impossible
8137 return IntRange::forValueOfType(C, GetExprType(E));
8140 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
8144 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
8145 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
8147 if (const auto *BitField = E->getSourceBitField())
8148 return IntRange(BitField->getBitWidthValue(C),
8149 BitField->getType()->isUnsignedIntegerOrEnumerationType());
8151 return IntRange::forValueOfType(C, GetExprType(E));
8154 IntRange GetExprRange(ASTContext &C, const Expr *E) {
8155 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
8158 /// Checks whether the given value, which currently has the given
8159 /// source semantics, has the same value when coerced through the
8160 /// target semantics.
8161 bool IsSameFloatAfterCast(const llvm::APFloat &value,
8162 const llvm::fltSemantics &Src,
8163 const llvm::fltSemantics &Tgt) {
8164 llvm::APFloat truncated = value;
8167 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
8168 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
8170 return truncated.bitwiseIsEqual(value);
8173 /// Checks whether the given value, which currently has the given
8174 /// source semantics, has the same value when coerced through the
8175 /// target semantics.
8177 /// The value might be a vector of floats (or a complex number).
8178 bool IsSameFloatAfterCast(const APValue &value,
8179 const llvm::fltSemantics &Src,
8180 const llvm::fltSemantics &Tgt) {
8181 if (value.isFloat())
8182 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
8184 if (value.isVector()) {
8185 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
8186 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
8191 assert(value.isComplexFloat());
8192 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
8193 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
8196 void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
8198 bool IsZero(Sema &S, Expr *E) {
8199 // Suppress cases where we are comparing against an enum constant.
8200 if (const DeclRefExpr *DR =
8201 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
8202 if (isa<EnumConstantDecl>(DR->getDecl()))
8205 // Suppress cases where the '0' value is expanded from a macro.
8206 if (E->getLocStart().isMacroID())
8210 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
8213 bool HasEnumType(Expr *E) {
8214 // Strip off implicit integral promotions.
8215 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8216 if (ICE->getCastKind() != CK_IntegralCast &&
8217 ICE->getCastKind() != CK_NoOp)
8219 E = ICE->getSubExpr();
8222 return E->getType()->isEnumeralType();
8225 void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
8226 // Disable warning in template instantiations.
8227 if (!S.ActiveTemplateInstantiations.empty())
8230 BinaryOperatorKind op = E->getOpcode();
8231 if (E->isValueDependent())
8234 if (op == BO_LT && IsZero(S, E->getRHS())) {
8235 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
8236 << "< 0" << "false" << HasEnumType(E->getLHS())
8237 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8238 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
8239 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
8240 << ">= 0" << "true" << HasEnumType(E->getLHS())
8241 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8242 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
8243 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
8244 << "0 >" << "false" << HasEnumType(E->getRHS())
8245 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8246 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
8247 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
8248 << "0 <=" << "true" << HasEnumType(E->getRHS())
8249 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8253 void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant,
8254 Expr *Other, const llvm::APSInt &Value,
8256 // Disable warning in template instantiations.
8257 if (!S.ActiveTemplateInstantiations.empty())
8260 // TODO: Investigate using GetExprRange() to get tighter bounds
8261 // on the bit ranges.
8262 QualType OtherT = Other->getType();
8263 if (const auto *AT = OtherT->getAs<AtomicType>())
8264 OtherT = AT->getValueType();
8265 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
8266 unsigned OtherWidth = OtherRange.Width;
8268 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
8270 // 0 values are handled later by CheckTrivialUnsignedComparison().
8271 if ((Value == 0) && (!OtherIsBooleanType))
8274 BinaryOperatorKind op = E->getOpcode();
8277 // Used for diagnostic printout.
8279 LiteralConstant = 0,
8282 } LiteralOrBoolConstant = LiteralConstant;
8284 if (!OtherIsBooleanType) {
8285 QualType ConstantT = Constant->getType();
8286 QualType CommonT = E->getLHS()->getType();
8288 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
8290 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
8291 "comparison with non-integer type");
8293 bool ConstantSigned = ConstantT->isSignedIntegerType();
8294 bool CommonSigned = CommonT->isSignedIntegerType();
8296 bool EqualityOnly = false;
8299 // The common type is signed, therefore no signed to unsigned conversion.
8300 if (!OtherRange.NonNegative) {
8301 // Check that the constant is representable in type OtherT.
8302 if (ConstantSigned) {
8303 if (OtherWidth >= Value.getMinSignedBits())
8305 } else { // !ConstantSigned
8306 if (OtherWidth >= Value.getActiveBits() + 1)
8309 } else { // !OtherSigned
8310 // Check that the constant is representable in type OtherT.
8311 // Negative values are out of range.
8312 if (ConstantSigned) {
8313 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
8315 } else { // !ConstantSigned
8316 if (OtherWidth >= Value.getActiveBits())
8320 } else { // !CommonSigned
8321 if (OtherRange.NonNegative) {
8322 if (OtherWidth >= Value.getActiveBits())
8324 } else { // OtherSigned
8325 assert(!ConstantSigned &&
8326 "Two signed types converted to unsigned types.");
8327 // Check to see if the constant is representable in OtherT.
8328 if (OtherWidth > Value.getActiveBits())
8330 // Check to see if the constant is equivalent to a negative value
8332 if (S.Context.getIntWidth(ConstantT) ==
8333 S.Context.getIntWidth(CommonT) &&
8334 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
8336 // The constant value rests between values that OtherT can represent
8337 // after conversion. Relational comparison still works, but equality
8338 // comparisons will be tautological.
8339 EqualityOnly = true;
8343 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
8345 if (op == BO_EQ || op == BO_NE) {
8346 IsTrue = op == BO_NE;
8347 } else if (EqualityOnly) {
8349 } else if (RhsConstant) {
8350 if (op == BO_GT || op == BO_GE)
8351 IsTrue = !PositiveConstant;
8352 else // op == BO_LT || op == BO_LE
8353 IsTrue = PositiveConstant;
8355 if (op == BO_LT || op == BO_LE)
8356 IsTrue = !PositiveConstant;
8357 else // op == BO_GT || op == BO_GE
8358 IsTrue = PositiveConstant;
8361 // Other isKnownToHaveBooleanValue
8362 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
8363 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
8364 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
8366 static const struct LinkedConditions {
8367 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
8368 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
8369 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
8370 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
8371 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
8372 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
8375 // Constant on LHS. | Constant on RHS. |
8376 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
8377 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
8378 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
8379 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
8380 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
8381 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
8382 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
8385 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
8387 enum ConstantValue ConstVal = Zero;
8388 if (Value.isUnsigned() || Value.isNonNegative()) {
8390 LiteralOrBoolConstant =
8391 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
8393 } else if (Value == 1) {
8394 LiteralOrBoolConstant =
8395 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
8398 LiteralOrBoolConstant = LiteralConstant;
8405 CompareBoolWithConstantResult CmpRes;
8409 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
8412 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
8415 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
8418 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
8421 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
8424 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
8431 if (CmpRes == AFals) {
8433 } else if (CmpRes == ATrue) {
8440 // If this is a comparison to an enum constant, include that
8441 // constant in the diagnostic.
8442 const EnumConstantDecl *ED = nullptr;
8443 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
8444 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
8446 SmallString<64> PrettySourceValue;
8447 llvm::raw_svector_ostream OS(PrettySourceValue);
8449 OS << '\'' << *ED << "' (" << Value << ")";
8453 S.DiagRuntimeBehavior(
8454 E->getOperatorLoc(), E,
8455 S.PDiag(diag::warn_out_of_range_compare)
8456 << OS.str() << LiteralOrBoolConstant
8457 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
8458 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
8461 /// Analyze the operands of the given comparison. Implements the
8462 /// fallback case from AnalyzeComparison.
8463 void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
8464 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8465 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
8468 /// \brief Implements -Wsign-compare.
8470 /// \param E the binary operator to check for warnings
8471 void AnalyzeComparison(Sema &S, BinaryOperator *E) {
8472 // The type the comparison is being performed in.
8473 QualType T = E->getLHS()->getType();
8475 // Only analyze comparison operators where both sides have been converted to
8477 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
8478 return AnalyzeImpConvsInComparison(S, E);
8480 // Don't analyze value-dependent comparisons directly.
8481 if (E->isValueDependent())
8482 return AnalyzeImpConvsInComparison(S, E);
8484 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
8485 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
8487 bool IsComparisonConstant = false;
8489 // Check whether an integer constant comparison results in a value
8490 // of 'true' or 'false'.
8491 if (T->isIntegralType(S.Context)) {
8492 llvm::APSInt RHSValue;
8493 bool IsRHSIntegralLiteral =
8494 RHS->isIntegerConstantExpr(RHSValue, S.Context);
8495 llvm::APSInt LHSValue;
8496 bool IsLHSIntegralLiteral =
8497 LHS->isIntegerConstantExpr(LHSValue, S.Context);
8498 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
8499 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
8500 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
8501 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
8503 IsComparisonConstant =
8504 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
8505 } else if (!T->hasUnsignedIntegerRepresentation())
8506 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
8508 // We don't do anything special if this isn't an unsigned integral
8509 // comparison: we're only interested in integral comparisons, and
8510 // signed comparisons only happen in cases we don't care to warn about.
8512 // We also don't care about value-dependent expressions or expressions
8513 // whose result is a constant.
8514 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
8515 return AnalyzeImpConvsInComparison(S, E);
8517 // Check to see if one of the (unmodified) operands is of different
8519 Expr *signedOperand, *unsignedOperand;
8520 if (LHS->getType()->hasSignedIntegerRepresentation()) {
8521 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
8522 "unsigned comparison between two signed integer expressions?");
8523 signedOperand = LHS;
8524 unsignedOperand = RHS;
8525 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
8526 signedOperand = RHS;
8527 unsignedOperand = LHS;
8529 CheckTrivialUnsignedComparison(S, E);
8530 return AnalyzeImpConvsInComparison(S, E);
8533 // Otherwise, calculate the effective range of the signed operand.
8534 IntRange signedRange = GetExprRange(S.Context, signedOperand);
8536 // Go ahead and analyze implicit conversions in the operands. Note
8537 // that we skip the implicit conversions on both sides.
8538 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
8539 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
8541 // If the signed range is non-negative, -Wsign-compare won't fire,
8542 // but we should still check for comparisons which are always true
8544 if (signedRange.NonNegative)
8545 return CheckTrivialUnsignedComparison(S, E);
8547 // For (in)equality comparisons, if the unsigned operand is a
8548 // constant which cannot collide with a overflowed signed operand,
8549 // then reinterpreting the signed operand as unsigned will not
8550 // change the result of the comparison.
8551 if (E->isEqualityOp()) {
8552 unsigned comparisonWidth = S.Context.getIntWidth(T);
8553 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
8555 // We should never be unable to prove that the unsigned operand is
8557 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
8559 if (unsignedRange.Width < comparisonWidth)
8563 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
8564 S.PDiag(diag::warn_mixed_sign_comparison)
8565 << LHS->getType() << RHS->getType()
8566 << LHS->getSourceRange() << RHS->getSourceRange());
8569 /// Analyzes an attempt to assign the given value to a bitfield.
8571 /// Returns true if there was something fishy about the attempt.
8572 bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
8573 SourceLocation InitLoc) {
8574 assert(Bitfield->isBitField());
8575 if (Bitfield->isInvalidDecl())
8578 // White-list bool bitfields.
8579 QualType BitfieldType = Bitfield->getType();
8580 if (BitfieldType->isBooleanType())
8583 if (BitfieldType->isEnumeralType()) {
8584 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
8585 // If the underlying enum type was not explicitly specified as an unsigned
8586 // type and the enum contain only positive values, MSVC++ will cause an
8587 // inconsistency by storing this as a signed type.
8588 if (S.getLangOpts().CPlusPlus11 &&
8589 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
8590 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
8591 BitfieldEnumDecl->getNumNegativeBits() == 0) {
8592 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
8593 << BitfieldEnumDecl->getNameAsString();
8597 if (Bitfield->getType()->isBooleanType())
8600 // Ignore value- or type-dependent expressions.
8601 if (Bitfield->getBitWidth()->isValueDependent() ||
8602 Bitfield->getBitWidth()->isTypeDependent() ||
8603 Init->isValueDependent() ||
8604 Init->isTypeDependent())
8607 Expr *OriginalInit = Init->IgnoreParenImpCasts();
8610 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
8613 unsigned OriginalWidth = Value.getBitWidth();
8614 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
8616 if (!Value.isSigned() || Value.isNegative())
8617 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
8618 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
8619 OriginalWidth = Value.getMinSignedBits();
8621 if (OriginalWidth <= FieldWidth)
8624 // Compute the value which the bitfield will contain.
8625 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
8626 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
8628 // Check whether the stored value is equal to the original value.
8629 TruncatedValue = TruncatedValue.extend(OriginalWidth);
8630 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
8633 // Special-case bitfields of width 1: booleans are naturally 0/1, and
8634 // therefore don't strictly fit into a signed bitfield of width 1.
8635 if (FieldWidth == 1 && Value == 1)
8638 std::string PrettyValue = Value.toString(10);
8639 std::string PrettyTrunc = TruncatedValue.toString(10);
8641 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
8642 << PrettyValue << PrettyTrunc << OriginalInit->getType()
8643 << Init->getSourceRange();
8648 /// Analyze the given simple or compound assignment for warning-worthy
8650 void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
8651 // Just recurse on the LHS.
8652 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8654 // We want to recurse on the RHS as normal unless we're assigning to
8656 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
8657 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
8658 E->getOperatorLoc())) {
8659 // Recurse, ignoring any implicit conversions on the RHS.
8660 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
8661 E->getOperatorLoc());
8665 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
8668 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
8669 void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
8670 SourceLocation CContext, unsigned diag,
8671 bool pruneControlFlow = false) {
8672 if (pruneControlFlow) {
8673 S.DiagRuntimeBehavior(E->getExprLoc(), E,
8675 << SourceType << T << E->getSourceRange()
8676 << SourceRange(CContext));
8679 S.Diag(E->getExprLoc(), diag)
8680 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
8683 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
8684 void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
8685 unsigned diag, bool pruneControlFlow = false) {
8686 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
8690 /// Diagnose an implicit cast from a floating point value to an integer value.
8691 void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
8693 SourceLocation CContext) {
8694 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
8695 const bool PruneWarnings = !S.ActiveTemplateInstantiations.empty();
8697 Expr *InnerE = E->IgnoreParenImpCasts();
8698 // We also want to warn on, e.g., "int i = -1.234"
8699 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
8700 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
8701 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
8703 const bool IsLiteral =
8704 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
8706 llvm::APFloat Value(0.0);
8708 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
8710 return DiagnoseImpCast(S, E, T, CContext,
8711 diag::warn_impcast_float_integer, PruneWarnings);
8714 bool isExact = false;
8716 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
8717 T->hasUnsignedIntegerRepresentation());
8718 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
8719 &isExact) == llvm::APFloat::opOK &&
8721 if (IsLiteral) return;
8722 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
8726 unsigned DiagID = 0;
8728 // Warn on floating point literal to integer.
8729 DiagID = diag::warn_impcast_literal_float_to_integer;
8730 } else if (IntegerValue == 0) {
8731 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
8732 return DiagnoseImpCast(S, E, T, CContext,
8733 diag::warn_impcast_float_integer, PruneWarnings);
8735 // Warn on non-zero to zero conversion.
8736 DiagID = diag::warn_impcast_float_to_integer_zero;
8738 if (IntegerValue.isUnsigned()) {
8739 if (!IntegerValue.isMaxValue()) {
8740 return DiagnoseImpCast(S, E, T, CContext,
8741 diag::warn_impcast_float_integer, PruneWarnings);
8743 } else { // IntegerValue.isSigned()
8744 if (!IntegerValue.isMaxSignedValue() &&
8745 !IntegerValue.isMinSignedValue()) {
8746 return DiagnoseImpCast(S, E, T, CContext,
8747 diag::warn_impcast_float_integer, PruneWarnings);
8750 // Warn on evaluatable floating point expression to integer conversion.
8751 DiagID = diag::warn_impcast_float_to_integer;
8754 // FIXME: Force the precision of the source value down so we don't print
8755 // digits which are usually useless (we don't really care here if we
8756 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
8757 // would automatically print the shortest representation, but it's a bit
8758 // tricky to implement.
8759 SmallString<16> PrettySourceValue;
8760 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
8761 precision = (precision * 59 + 195) / 196;
8762 Value.toString(PrettySourceValue, precision);
8764 SmallString<16> PrettyTargetValue;
8766 PrettyTargetValue = Value.isZero() ? "false" : "true";
8768 IntegerValue.toString(PrettyTargetValue);
8770 if (PruneWarnings) {
8771 S.DiagRuntimeBehavior(E->getExprLoc(), E,
8773 << E->getType() << T.getUnqualifiedType()
8774 << PrettySourceValue << PrettyTargetValue
8775 << E->getSourceRange() << SourceRange(CContext));
8777 S.Diag(E->getExprLoc(), DiagID)
8778 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
8779 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
8783 std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
8784 if (!Range.Width) return "0";
8786 llvm::APSInt ValueInRange = Value;
8787 ValueInRange.setIsSigned(!Range.NonNegative);
8788 ValueInRange = ValueInRange.trunc(Range.Width);
8789 return ValueInRange.toString(10);
8792 bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
8793 if (!isa<ImplicitCastExpr>(Ex))
8796 Expr *InnerE = Ex->IgnoreParenImpCasts();
8797 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
8798 const Type *Source =
8799 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
8800 if (Target->isDependentType())
8803 const BuiltinType *FloatCandidateBT =
8804 dyn_cast<BuiltinType>(ToBool ? Source : Target);
8805 const Type *BoolCandidateType = ToBool ? Target : Source;
8807 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
8808 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
8811 void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
8812 SourceLocation CC) {
8813 unsigned NumArgs = TheCall->getNumArgs();
8814 for (unsigned i = 0; i < NumArgs; ++i) {
8815 Expr *CurrA = TheCall->getArg(i);
8816 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
8819 bool IsSwapped = ((i > 0) &&
8820 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
8821 IsSwapped |= ((i < (NumArgs - 1)) &&
8822 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
8824 // Warn on this floating-point to bool conversion.
8825 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
8826 CurrA->getType(), CC,
8827 diag::warn_impcast_floating_point_to_bool);
8832 void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
8833 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
8837 // Don't warn on functions which have return type nullptr_t.
8838 if (isa<CallExpr>(E))
8841 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
8842 const Expr::NullPointerConstantKind NullKind =
8843 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
8844 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
8847 // Return if target type is a safe conversion.
8848 if (T->isAnyPointerType() || T->isBlockPointerType() ||
8849 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
8852 SourceLocation Loc = E->getSourceRange().getBegin();
8854 // Venture through the macro stacks to get to the source of macro arguments.
8855 // The new location is a better location than the complete location that was
8857 while (S.SourceMgr.isMacroArgExpansion(Loc))
8858 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
8860 while (S.SourceMgr.isMacroArgExpansion(CC))
8861 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
8863 // __null is usually wrapped in a macro. Go up a macro if that is the case.
8864 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
8865 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
8866 Loc, S.SourceMgr, S.getLangOpts());
8867 if (MacroName == "NULL")
8868 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
8871 // Only warn if the null and context location are in the same macro expansion.
8872 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
8875 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
8876 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
8877 << FixItHint::CreateReplacement(Loc,
8878 S.getFixItZeroLiteralForType(T, Loc));
8881 void checkObjCArrayLiteral(Sema &S, QualType TargetType,
8882 ObjCArrayLiteral *ArrayLiteral);
8883 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
8884 ObjCDictionaryLiteral *DictionaryLiteral);
8886 /// Check a single element within a collection literal against the
8887 /// target element type.
8888 void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
8889 Expr *Element, unsigned ElementKind) {
8890 // Skip a bitcast to 'id' or qualified 'id'.
8891 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
8892 if (ICE->getCastKind() == CK_BitCast &&
8893 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
8894 Element = ICE->getSubExpr();
8897 QualType ElementType = Element->getType();
8898 ExprResult ElementResult(Element);
8899 if (ElementType->getAs<ObjCObjectPointerType>() &&
8900 S.CheckSingleAssignmentConstraints(TargetElementType,
8903 != Sema::Compatible) {
8904 S.Diag(Element->getLocStart(),
8905 diag::warn_objc_collection_literal_element)
8906 << ElementType << ElementKind << TargetElementType
8907 << Element->getSourceRange();
8910 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
8911 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
8912 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
8913 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
8916 /// Check an Objective-C array literal being converted to the given
8918 void checkObjCArrayLiteral(Sema &S, QualType TargetType,
8919 ObjCArrayLiteral *ArrayLiteral) {
8923 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
8927 if (TargetObjCPtr->isUnspecialized() ||
8928 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
8929 != S.NSArrayDecl->getCanonicalDecl())
8932 auto TypeArgs = TargetObjCPtr->getTypeArgs();
8933 if (TypeArgs.size() != 1)
8936 QualType TargetElementType = TypeArgs[0];
8937 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
8938 checkObjCCollectionLiteralElement(S, TargetElementType,
8939 ArrayLiteral->getElement(I),
8944 /// Check an Objective-C dictionary literal being converted to the given
8946 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
8947 ObjCDictionaryLiteral *DictionaryLiteral) {
8948 if (!S.NSDictionaryDecl)
8951 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
8955 if (TargetObjCPtr->isUnspecialized() ||
8956 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
8957 != S.NSDictionaryDecl->getCanonicalDecl())
8960 auto TypeArgs = TargetObjCPtr->getTypeArgs();
8961 if (TypeArgs.size() != 2)
8964 QualType TargetKeyType = TypeArgs[0];
8965 QualType TargetObjectType = TypeArgs[1];
8966 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
8967 auto Element = DictionaryLiteral->getKeyValueElement(I);
8968 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
8969 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
8973 // Helper function to filter out cases for constant width constant conversion.
8974 // Don't warn on char array initialization or for non-decimal values.
8975 bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
8976 SourceLocation CC) {
8977 // If initializing from a constant, and the constant starts with '0',
8978 // then it is a binary, octal, or hexadecimal. Allow these constants
8979 // to fill all the bits, even if there is a sign change.
8980 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
8981 const char FirstLiteralCharacter =
8982 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
8983 if (FirstLiteralCharacter == '0')
8987 // If the CC location points to a '{', and the type is char, then assume
8988 // assume it is an array initialization.
8989 if (CC.isValid() && T->isCharType()) {
8990 const char FirstContextCharacter =
8991 S.getSourceManager().getCharacterData(CC)[0];
8992 if (FirstContextCharacter == '{')
8999 void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
9000 SourceLocation CC, bool *ICContext = nullptr) {
9001 if (E->isTypeDependent() || E->isValueDependent()) return;
9003 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
9004 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
9005 if (Source == Target) return;
9006 if (Target->isDependentType()) return;
9008 // If the conversion context location is invalid don't complain. We also
9009 // don't want to emit a warning if the issue occurs from the expansion of
9010 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
9011 // delay this check as long as possible. Once we detect we are in that
9012 // scenario, we just return.
9016 // Diagnose implicit casts to bool.
9017 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
9018 if (isa<StringLiteral>(E))
9019 // Warn on string literal to bool. Checks for string literals in logical
9020 // and expressions, for instance, assert(0 && "error here"), are
9021 // prevented by a check in AnalyzeImplicitConversions().
9022 return DiagnoseImpCast(S, E, T, CC,
9023 diag::warn_impcast_string_literal_to_bool);
9024 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
9025 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
9026 // This covers the literal expressions that evaluate to Objective-C
9028 return DiagnoseImpCast(S, E, T, CC,
9029 diag::warn_impcast_objective_c_literal_to_bool);
9031 if (Source->isPointerType() || Source->canDecayToPointerType()) {
9032 // Warn on pointer to bool conversion that is always true.
9033 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
9038 // Check implicit casts from Objective-C collection literals to specialized
9039 // collection types, e.g., NSArray<NSString *> *.
9040 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
9041 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
9042 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
9043 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
9045 // Strip vector types.
9046 if (isa<VectorType>(Source)) {
9047 if (!isa<VectorType>(Target)) {
9048 if (S.SourceMgr.isInSystemMacro(CC))
9050 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
9053 // If the vector cast is cast between two vectors of the same size, it is
9054 // a bitcast, not a conversion.
9055 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
9058 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
9059 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
9061 if (auto VecTy = dyn_cast<VectorType>(Target))
9062 Target = VecTy->getElementType().getTypePtr();
9064 // Strip complex types.
9065 if (isa<ComplexType>(Source)) {
9066 if (!isa<ComplexType>(Target)) {
9067 if (S.SourceMgr.isInSystemMacro(CC))
9070 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
9073 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
9074 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
9077 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
9078 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
9080 // If the source is floating point...
9081 if (SourceBT && SourceBT->isFloatingPoint()) {
9082 // ...and the target is floating point...
9083 if (TargetBT && TargetBT->isFloatingPoint()) {
9084 // ...then warn if we're dropping FP rank.
9086 // Builtin FP kinds are ordered by increasing FP rank.
9087 if (SourceBT->getKind() > TargetBT->getKind()) {
9088 // Don't warn about float constants that are precisely
9089 // representable in the target type.
9090 Expr::EvalResult result;
9091 if (E->EvaluateAsRValue(result, S.Context)) {
9092 // Value might be a float, a float vector, or a float complex.
9093 if (IsSameFloatAfterCast(result.Val,
9094 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
9095 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
9099 if (S.SourceMgr.isInSystemMacro(CC))
9102 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
9104 // ... or possibly if we're increasing rank, too
9105 else if (TargetBT->getKind() > SourceBT->getKind()) {
9106 if (S.SourceMgr.isInSystemMacro(CC))
9109 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
9114 // If the target is integral, always warn.
9115 if (TargetBT && TargetBT->isInteger()) {
9116 if (S.SourceMgr.isInSystemMacro(CC))
9119 DiagnoseFloatingImpCast(S, E, T, CC);
9122 // Detect the case where a call result is converted from floating-point to
9123 // to bool, and the final argument to the call is converted from bool, to
9124 // discover this typo:
9126 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
9128 // FIXME: This is an incredibly special case; is there some more general
9129 // way to detect this class of misplaced-parentheses bug?
9130 if (Target->isBooleanType() && isa<CallExpr>(E)) {
9131 // Check last argument of function call to see if it is an
9132 // implicit cast from a type matching the type the result
9133 // is being cast to.
9134 CallExpr *CEx = cast<CallExpr>(E);
9135 if (unsigned NumArgs = CEx->getNumArgs()) {
9136 Expr *LastA = CEx->getArg(NumArgs - 1);
9137 Expr *InnerE = LastA->IgnoreParenImpCasts();
9138 if (isa<ImplicitCastExpr>(LastA) &&
9139 InnerE->getType()->isBooleanType()) {
9140 // Warn on this floating-point to bool conversion
9141 DiagnoseImpCast(S, E, T, CC,
9142 diag::warn_impcast_floating_point_to_bool);
9149 DiagnoseNullConversion(S, E, T, CC);
9151 S.DiscardMisalignedMemberAddress(Target, E);
9153 if (!Source->isIntegerType() || !Target->isIntegerType())
9156 // TODO: remove this early return once the false positives for constant->bool
9157 // in templates, macros, etc, are reduced or removed.
9158 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
9161 IntRange SourceRange = GetExprRange(S.Context, E);
9162 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
9164 if (SourceRange.Width > TargetRange.Width) {
9165 // If the source is a constant, use a default-on diagnostic.
9166 // TODO: this should happen for bitfield stores, too.
9167 llvm::APSInt Value(32);
9168 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
9169 if (S.SourceMgr.isInSystemMacro(CC))
9172 std::string PrettySourceValue = Value.toString(10);
9173 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
9175 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9176 S.PDiag(diag::warn_impcast_integer_precision_constant)
9177 << PrettySourceValue << PrettyTargetValue
9178 << E->getType() << T << E->getSourceRange()
9179 << clang::SourceRange(CC));
9183 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
9184 if (S.SourceMgr.isInSystemMacro(CC))
9187 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
9188 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
9189 /* pruneControlFlow */ true);
9190 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
9193 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
9194 SourceRange.NonNegative && Source->isSignedIntegerType()) {
9195 // Warn when doing a signed to signed conversion, warn if the positive
9196 // source value is exactly the width of the target type, which will
9197 // cause a negative value to be stored.
9200 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
9201 !S.SourceMgr.isInSystemMacro(CC)) {
9202 if (isSameWidthConstantConversion(S, E, T, CC)) {
9203 std::string PrettySourceValue = Value.toString(10);
9204 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
9206 S.DiagRuntimeBehavior(
9208 S.PDiag(diag::warn_impcast_integer_precision_constant)
9209 << PrettySourceValue << PrettyTargetValue << E->getType() << T
9210 << E->getSourceRange() << clang::SourceRange(CC));
9215 // Fall through for non-constants to give a sign conversion warning.
9218 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
9219 (!TargetRange.NonNegative && SourceRange.NonNegative &&
9220 SourceRange.Width == TargetRange.Width)) {
9221 if (S.SourceMgr.isInSystemMacro(CC))
9224 unsigned DiagID = diag::warn_impcast_integer_sign;
9226 // Traditionally, gcc has warned about this under -Wsign-compare.
9227 // We also want to warn about it in -Wconversion.
9228 // So if -Wconversion is off, use a completely identical diagnostic
9229 // in the sign-compare group.
9230 // The conditional-checking code will
9232 DiagID = diag::warn_impcast_integer_sign_conditional;
9236 return DiagnoseImpCast(S, E, T, CC, DiagID);
9239 // Diagnose conversions between different enumeration types.
9240 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
9241 // type, to give us better diagnostics.
9242 QualType SourceType = E->getType();
9243 if (!S.getLangOpts().CPlusPlus) {
9244 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9245 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
9246 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
9247 SourceType = S.Context.getTypeDeclType(Enum);
9248 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
9252 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
9253 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
9254 if (SourceEnum->getDecl()->hasNameForLinkage() &&
9255 TargetEnum->getDecl()->hasNameForLinkage() &&
9256 SourceEnum != TargetEnum) {
9257 if (S.SourceMgr.isInSystemMacro(CC))
9260 return DiagnoseImpCast(S, E, SourceType, T, CC,
9261 diag::warn_impcast_different_enum_types);
9265 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9266 SourceLocation CC, QualType T);
9268 void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
9269 SourceLocation CC, bool &ICContext) {
9270 E = E->IgnoreParenImpCasts();
9272 if (isa<ConditionalOperator>(E))
9273 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
9275 AnalyzeImplicitConversions(S, E, CC);
9276 if (E->getType() != T)
9277 return CheckImplicitConversion(S, E, T, CC, &ICContext);
9280 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9281 SourceLocation CC, QualType T) {
9282 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
9284 bool Suspicious = false;
9285 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
9286 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
9288 // If -Wconversion would have warned about either of the candidates
9289 // for a signedness conversion to the context type...
9290 if (!Suspicious) return;
9292 // ...but it's currently ignored...
9293 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
9296 // ...then check whether it would have warned about either of the
9297 // candidates for a signedness conversion to the condition type.
9298 if (E->getType() == T) return;
9301 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
9302 E->getType(), CC, &Suspicious);
9304 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
9305 E->getType(), CC, &Suspicious);
9308 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9309 /// Input argument E is a logical expression.
9310 void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
9311 if (S.getLangOpts().Bool)
9313 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
9316 /// AnalyzeImplicitConversions - Find and report any interesting
9317 /// implicit conversions in the given expression. There are a couple
9318 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
9319 void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
9320 QualType T = OrigE->getType();
9321 Expr *E = OrigE->IgnoreParenImpCasts();
9323 if (E->isTypeDependent() || E->isValueDependent())
9326 // For conditional operators, we analyze the arguments as if they
9327 // were being fed directly into the output.
9328 if (isa<ConditionalOperator>(E)) {
9329 ConditionalOperator *CO = cast<ConditionalOperator>(E);
9330 CheckConditionalOperator(S, CO, CC, T);
9334 // Check implicit argument conversions for function calls.
9335 if (CallExpr *Call = dyn_cast<CallExpr>(E))
9336 CheckImplicitArgumentConversions(S, Call, CC);
9338 // Go ahead and check any implicit conversions we might have skipped.
9339 // The non-canonical typecheck is just an optimization;
9340 // CheckImplicitConversion will filter out dead implicit conversions.
9341 if (E->getType() != T)
9342 CheckImplicitConversion(S, E, T, CC);
9344 // Now continue drilling into this expression.
9346 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
9347 // The bound subexpressions in a PseudoObjectExpr are not reachable
9348 // as transitive children.
9349 // FIXME: Use a more uniform representation for this.
9350 for (auto *SE : POE->semantics())
9351 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
9352 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
9355 // Skip past explicit casts.
9356 if (isa<ExplicitCastExpr>(E)) {
9357 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
9358 return AnalyzeImplicitConversions(S, E, CC);
9361 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9362 // Do a somewhat different check with comparison operators.
9363 if (BO->isComparisonOp())
9364 return AnalyzeComparison(S, BO);
9366 // And with simple assignments.
9367 if (BO->getOpcode() == BO_Assign)
9368 return AnalyzeAssignment(S, BO);
9371 // These break the otherwise-useful invariant below. Fortunately,
9372 // we don't really need to recurse into them, because any internal
9373 // expressions should have been analyzed already when they were
9374 // built into statements.
9375 if (isa<StmtExpr>(E)) return;
9377 // Don't descend into unevaluated contexts.
9378 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
9380 // Now just recurse over the expression's children.
9381 CC = E->getExprLoc();
9382 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
9383 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
9384 for (Stmt *SubStmt : E->children()) {
9385 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
9389 if (IsLogicalAndOperator &&
9390 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
9391 // Ignore checking string literals that are in logical and operators.
9392 // This is a common pattern for asserts.
9394 AnalyzeImplicitConversions(S, ChildExpr, CC);
9397 if (BO && BO->isLogicalOp()) {
9398 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
9399 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
9400 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
9402 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
9403 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
9404 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
9407 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
9408 if (U->getOpcode() == UO_LNot)
9409 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
9412 } // end anonymous namespace
9414 /// Diagnose integer type and any valid implicit convertion to it.
9415 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
9416 // Taking into account implicit conversions,
9417 // allow any integer.
9418 if (!E->getType()->isIntegerType()) {
9419 S.Diag(E->getLocStart(),
9420 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
9423 // Potentially emit standard warnings for implicit conversions if enabled
9424 // using -Wconversion.
9425 CheckImplicitConversion(S, E, IntT, E->getLocStart());
9429 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
9430 // Returns true when emitting a warning about taking the address of a reference.
9431 static bool CheckForReference(Sema &SemaRef, const Expr *E,
9432 const PartialDiagnostic &PD) {
9433 E = E->IgnoreParenImpCasts();
9435 const FunctionDecl *FD = nullptr;
9437 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9438 if (!DRE->getDecl()->getType()->isReferenceType())
9440 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9441 if (!M->getMemberDecl()->getType()->isReferenceType())
9443 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
9444 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
9446 FD = Call->getDirectCallee();
9451 SemaRef.Diag(E->getExprLoc(), PD);
9453 // If possible, point to location of function.
9455 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
9461 // Returns true if the SourceLocation is expanded from any macro body.
9462 // Returns false if the SourceLocation is invalid, is from not in a macro
9463 // expansion, or is from expanded from a top-level macro argument.
9464 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
9465 if (Loc.isInvalid())
9468 while (Loc.isMacroID()) {
9469 if (SM.isMacroBodyExpansion(Loc))
9471 Loc = SM.getImmediateMacroCallerLoc(Loc);
9477 /// \brief Diagnose pointers that are always non-null.
9478 /// \param E the expression containing the pointer
9479 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
9480 /// compared to a null pointer
9481 /// \param IsEqual True when the comparison is equal to a null pointer
9482 /// \param Range Extra SourceRange to highlight in the diagnostic
9483 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
9484 Expr::NullPointerConstantKind NullKind,
9485 bool IsEqual, SourceRange Range) {
9489 // Don't warn inside macros.
9490 if (E->getExprLoc().isMacroID()) {
9491 const SourceManager &SM = getSourceManager();
9492 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
9493 IsInAnyMacroBody(SM, Range.getBegin()))
9496 E = E->IgnoreImpCasts();
9498 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
9500 if (isa<CXXThisExpr>(E)) {
9501 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
9502 : diag::warn_this_bool_conversion;
9503 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
9507 bool IsAddressOf = false;
9509 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9510 if (UO->getOpcode() != UO_AddrOf)
9513 E = UO->getSubExpr();
9517 unsigned DiagID = IsCompare
9518 ? diag::warn_address_of_reference_null_compare
9519 : diag::warn_address_of_reference_bool_conversion;
9520 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
9522 if (CheckForReference(*this, E, PD)) {
9527 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
9528 bool IsParam = isa<NonNullAttr>(NonnullAttr);
9530 llvm::raw_string_ostream S(Str);
9531 E->printPretty(S, nullptr, getPrintingPolicy());
9532 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
9533 : diag::warn_cast_nonnull_to_bool;
9534 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
9535 << E->getSourceRange() << Range << IsEqual;
9536 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
9539 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
9540 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
9541 if (auto *Callee = Call->getDirectCallee()) {
9542 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
9543 ComplainAboutNonnullParamOrCall(A);
9549 // Expect to find a single Decl. Skip anything more complicated.
9550 ValueDecl *D = nullptr;
9551 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
9553 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9554 D = M->getMemberDecl();
9557 // Weak Decls can be null.
9558 if (!D || D->isWeak())
9561 // Check for parameter decl with nonnull attribute
9562 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
9563 if (getCurFunction() &&
9564 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
9565 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
9566 ComplainAboutNonnullParamOrCall(A);
9570 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
9571 auto ParamIter = llvm::find(FD->parameters(), PV);
9572 assert(ParamIter != FD->param_end());
9573 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
9575 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
9576 if (!NonNull->args_size()) {
9577 ComplainAboutNonnullParamOrCall(NonNull);
9581 for (unsigned ArgNo : NonNull->args()) {
9582 if (ArgNo == ParamNo) {
9583 ComplainAboutNonnullParamOrCall(NonNull);
9592 QualType T = D->getType();
9593 const bool IsArray = T->isArrayType();
9594 const bool IsFunction = T->isFunctionType();
9596 // Address of function is used to silence the function warning.
9597 if (IsAddressOf && IsFunction) {
9602 if (!IsAddressOf && !IsFunction && !IsArray)
9605 // Pretty print the expression for the diagnostic.
9607 llvm::raw_string_ostream S(Str);
9608 E->printPretty(S, nullptr, getPrintingPolicy());
9610 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
9611 : diag::warn_impcast_pointer_to_bool;
9618 DiagType = AddressOf;
9619 else if (IsFunction)
9620 DiagType = FunctionPointer;
9622 DiagType = ArrayPointer;
9624 llvm_unreachable("Could not determine diagnostic.");
9625 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
9626 << Range << IsEqual;
9631 // Suggest '&' to silence the function warning.
9632 Diag(E->getExprLoc(), diag::note_function_warning_silence)
9633 << FixItHint::CreateInsertion(E->getLocStart(), "&");
9635 // Check to see if '()' fixit should be emitted.
9636 QualType ReturnType;
9637 UnresolvedSet<4> NonTemplateOverloads;
9638 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
9639 if (ReturnType.isNull())
9643 // There are two cases here. If there is null constant, the only suggest
9644 // for a pointer return type. If the null is 0, then suggest if the return
9645 // type is a pointer or an integer type.
9646 if (!ReturnType->isPointerType()) {
9647 if (NullKind == Expr::NPCK_ZeroExpression ||
9648 NullKind == Expr::NPCK_ZeroLiteral) {
9649 if (!ReturnType->isIntegerType())
9655 } else { // !IsCompare
9656 // For function to bool, only suggest if the function pointer has bool
9658 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
9661 Diag(E->getExprLoc(), diag::note_function_to_function_call)
9662 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
9665 /// Diagnoses "dangerous" implicit conversions within the given
9666 /// expression (which is a full expression). Implements -Wconversion
9667 /// and -Wsign-compare.
9669 /// \param CC the "context" location of the implicit conversion, i.e.
9670 /// the most location of the syntactic entity requiring the implicit
9672 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
9673 // Don't diagnose in unevaluated contexts.
9674 if (isUnevaluatedContext())
9677 // Don't diagnose for value- or type-dependent expressions.
9678 if (E->isTypeDependent() || E->isValueDependent())
9681 // Check for array bounds violations in cases where the check isn't triggered
9682 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
9683 // ArraySubscriptExpr is on the RHS of a variable initialization.
9684 CheckArrayAccess(E);
9686 // This is not the right CC for (e.g.) a variable initialization.
9687 AnalyzeImplicitConversions(*this, E, CC);
9690 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9691 /// Input argument E is a logical expression.
9692 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
9693 ::CheckBoolLikeConversion(*this, E, CC);
9696 /// Diagnose when expression is an integer constant expression and its evaluation
9697 /// results in integer overflow
9698 void Sema::CheckForIntOverflow (Expr *E) {
9699 // Use a work list to deal with nested struct initializers.
9700 SmallVector<Expr *, 2> Exprs(1, E);
9703 Expr *E = Exprs.pop_back_val();
9705 if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
9706 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
9710 if (auto InitList = dyn_cast<InitListExpr>(E))
9711 Exprs.append(InitList->inits().begin(), InitList->inits().end());
9712 } while (!Exprs.empty());
9716 /// \brief Visitor for expressions which looks for unsequenced operations on the
9718 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
9719 typedef EvaluatedExprVisitor<SequenceChecker> Base;
9721 /// \brief A tree of sequenced regions within an expression. Two regions are
9722 /// unsequenced if one is an ancestor or a descendent of the other. When we
9723 /// finish processing an expression with sequencing, such as a comma
9724 /// expression, we fold its tree nodes into its parent, since they are
9725 /// unsequenced with respect to nodes we will visit later.
9726 class SequenceTree {
9728 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
9729 unsigned Parent : 31;
9730 unsigned Merged : 1;
9732 SmallVector<Value, 8> Values;
9735 /// \brief A region within an expression which may be sequenced with respect
9736 /// to some other region.
9738 explicit Seq(unsigned N) : Index(N) {}
9740 friend class SequenceTree;
9745 SequenceTree() { Values.push_back(Value(0)); }
9746 Seq root() const { return Seq(0); }
9748 /// \brief Create a new sequence of operations, which is an unsequenced
9749 /// subset of \p Parent. This sequence of operations is sequenced with
9750 /// respect to other children of \p Parent.
9751 Seq allocate(Seq Parent) {
9752 Values.push_back(Value(Parent.Index));
9753 return Seq(Values.size() - 1);
9756 /// \brief Merge a sequence of operations into its parent.
9758 Values[S.Index].Merged = true;
9761 /// \brief Determine whether two operations are unsequenced. This operation
9762 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
9763 /// should have been merged into its parent as appropriate.
9764 bool isUnsequenced(Seq Cur, Seq Old) {
9765 unsigned C = representative(Cur.Index);
9766 unsigned Target = representative(Old.Index);
9767 while (C >= Target) {
9770 C = Values[C].Parent;
9776 /// \brief Pick a representative for a sequence.
9777 unsigned representative(unsigned K) {
9778 if (Values[K].Merged)
9779 // Perform path compression as we go.
9780 return Values[K].Parent = representative(Values[K].Parent);
9785 /// An object for which we can track unsequenced uses.
9786 typedef NamedDecl *Object;
9788 /// Different flavors of object usage which we track. We only track the
9789 /// least-sequenced usage of each kind.
9791 /// A read of an object. Multiple unsequenced reads are OK.
9793 /// A modification of an object which is sequenced before the value
9794 /// computation of the expression, such as ++n in C++.
9796 /// A modification of an object which is not sequenced before the value
9797 /// computation of the expression, such as n++.
9800 UK_Count = UK_ModAsSideEffect + 1
9804 Usage() : Use(nullptr), Seq() {}
9806 SequenceTree::Seq Seq;
9810 UsageInfo() : Diagnosed(false) {}
9811 Usage Uses[UK_Count];
9812 /// Have we issued a diagnostic for this variable already?
9815 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
9818 /// Sequenced regions within the expression.
9820 /// Declaration modifications and references which we have seen.
9821 UsageInfoMap UsageMap;
9822 /// The region we are currently within.
9823 SequenceTree::Seq Region;
9824 /// Filled in with declarations which were modified as a side-effect
9825 /// (that is, post-increment operations).
9826 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
9827 /// Expressions to check later. We defer checking these to reduce
9829 SmallVectorImpl<Expr *> &WorkList;
9831 /// RAII object wrapping the visitation of a sequenced subexpression of an
9832 /// expression. At the end of this process, the side-effects of the evaluation
9833 /// become sequenced with respect to the value computation of the result, so
9834 /// we downgrade any UK_ModAsSideEffect within the evaluation to
9836 struct SequencedSubexpression {
9837 SequencedSubexpression(SequenceChecker &Self)
9838 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
9839 Self.ModAsSideEffect = &ModAsSideEffect;
9841 ~SequencedSubexpression() {
9842 for (auto &M : llvm::reverse(ModAsSideEffect)) {
9843 UsageInfo &U = Self.UsageMap[M.first];
9844 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
9845 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
9846 SideEffectUsage = M.second;
9848 Self.ModAsSideEffect = OldModAsSideEffect;
9851 SequenceChecker &Self;
9852 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
9853 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
9856 /// RAII object wrapping the visitation of a subexpression which we might
9857 /// choose to evaluate as a constant. If any subexpression is evaluated and
9858 /// found to be non-constant, this allows us to suppress the evaluation of
9859 /// the outer expression.
9860 class EvaluationTracker {
9862 EvaluationTracker(SequenceChecker &Self)
9863 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
9864 Self.EvalTracker = this;
9866 ~EvaluationTracker() {
9867 Self.EvalTracker = Prev;
9869 Prev->EvalOK &= EvalOK;
9872 bool evaluate(const Expr *E, bool &Result) {
9873 if (!EvalOK || E->isValueDependent())
9875 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
9880 SequenceChecker &Self;
9881 EvaluationTracker *Prev;
9885 /// \brief Find the object which is produced by the specified expression,
9887 Object getObject(Expr *E, bool Mod) const {
9888 E = E->IgnoreParenCasts();
9889 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9890 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
9891 return getObject(UO->getSubExpr(), Mod);
9892 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9893 if (BO->getOpcode() == BO_Comma)
9894 return getObject(BO->getRHS(), Mod);
9895 if (Mod && BO->isAssignmentOp())
9896 return getObject(BO->getLHS(), Mod);
9897 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
9898 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
9899 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
9900 return ME->getMemberDecl();
9901 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9902 // FIXME: If this is a reference, map through to its value.
9903 return DRE->getDecl();
9907 /// \brief Note that an object was modified or used by an expression.
9908 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
9909 Usage &U = UI.Uses[UK];
9910 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
9911 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
9912 ModAsSideEffect->push_back(std::make_pair(O, U));
9917 /// \brief Check whether a modification or use conflicts with a prior usage.
9918 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
9923 const Usage &U = UI.Uses[OtherKind];
9924 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
9928 Expr *ModOrUse = Ref;
9929 if (OtherKind == UK_Use)
9930 std::swap(Mod, ModOrUse);
9932 SemaRef.Diag(Mod->getExprLoc(),
9933 IsModMod ? diag::warn_unsequenced_mod_mod
9934 : diag::warn_unsequenced_mod_use)
9935 << O << SourceRange(ModOrUse->getExprLoc());
9936 UI.Diagnosed = true;
9939 void notePreUse(Object O, Expr *Use) {
9940 UsageInfo &U = UsageMap[O];
9941 // Uses conflict with other modifications.
9942 checkUsage(O, U, Use, UK_ModAsValue, false);
9944 void notePostUse(Object O, Expr *Use) {
9945 UsageInfo &U = UsageMap[O];
9946 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
9947 addUsage(U, O, Use, UK_Use);
9950 void notePreMod(Object O, Expr *Mod) {
9951 UsageInfo &U = UsageMap[O];
9952 // Modifications conflict with other modifications and with uses.
9953 checkUsage(O, U, Mod, UK_ModAsValue, true);
9954 checkUsage(O, U, Mod, UK_Use, false);
9956 void notePostMod(Object O, Expr *Use, UsageKind UK) {
9957 UsageInfo &U = UsageMap[O];
9958 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
9959 addUsage(U, O, Use, UK);
9963 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
9964 : Base(S.Context), SemaRef(S), Region(Tree.root()),
9965 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
9969 void VisitStmt(Stmt *S) {
9970 // Skip all statements which aren't expressions for now.
9973 void VisitExpr(Expr *E) {
9974 // By default, just recurse to evaluated subexpressions.
9978 void VisitCastExpr(CastExpr *E) {
9979 Object O = Object();
9980 if (E->getCastKind() == CK_LValueToRValue)
9981 O = getObject(E->getSubExpr(), false);
9990 void VisitBinComma(BinaryOperator *BO) {
9991 // C++11 [expr.comma]p1:
9992 // Every value computation and side effect associated with the left
9993 // expression is sequenced before every value computation and side
9994 // effect associated with the right expression.
9995 SequenceTree::Seq LHS = Tree.allocate(Region);
9996 SequenceTree::Seq RHS = Tree.allocate(Region);
9997 SequenceTree::Seq OldRegion = Region;
10000 SequencedSubexpression SeqLHS(*this);
10002 Visit(BO->getLHS());
10006 Visit(BO->getRHS());
10008 Region = OldRegion;
10010 // Forget that LHS and RHS are sequenced. They are both unsequenced
10011 // with respect to other stuff.
10016 void VisitBinAssign(BinaryOperator *BO) {
10017 // The modification is sequenced after the value computation of the LHS
10018 // and RHS, so check it before inspecting the operands and update the
10020 Object O = getObject(BO->getLHS(), true);
10022 return VisitExpr(BO);
10026 // C++11 [expr.ass]p7:
10027 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
10030 // Therefore, for a compound assignment operator, O is considered used
10031 // everywhere except within the evaluation of E1 itself.
10032 if (isa<CompoundAssignOperator>(BO))
10035 Visit(BO->getLHS());
10037 if (isa<CompoundAssignOperator>(BO))
10038 notePostUse(O, BO);
10040 Visit(BO->getRHS());
10042 // C++11 [expr.ass]p1:
10043 // the assignment is sequenced [...] before the value computation of the
10044 // assignment expression.
10045 // C11 6.5.16/3 has no such rule.
10046 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10047 : UK_ModAsSideEffect);
10050 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
10051 VisitBinAssign(CAO);
10054 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10055 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10056 void VisitUnaryPreIncDec(UnaryOperator *UO) {
10057 Object O = getObject(UO->getSubExpr(), true);
10059 return VisitExpr(UO);
10062 Visit(UO->getSubExpr());
10063 // C++11 [expr.pre.incr]p1:
10064 // the expression ++x is equivalent to x+=1
10065 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10066 : UK_ModAsSideEffect);
10069 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10070 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10071 void VisitUnaryPostIncDec(UnaryOperator *UO) {
10072 Object O = getObject(UO->getSubExpr(), true);
10074 return VisitExpr(UO);
10077 Visit(UO->getSubExpr());
10078 notePostMod(O, UO, UK_ModAsSideEffect);
10081 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
10082 void VisitBinLOr(BinaryOperator *BO) {
10083 // The side-effects of the LHS of an '&&' are sequenced before the
10084 // value computation of the RHS, and hence before the value computation
10085 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
10086 // as if they were unconditionally sequenced.
10087 EvaluationTracker Eval(*this);
10089 SequencedSubexpression Sequenced(*this);
10090 Visit(BO->getLHS());
10094 if (Eval.evaluate(BO->getLHS(), Result)) {
10096 Visit(BO->getRHS());
10098 // Check for unsequenced operations in the RHS, treating it as an
10099 // entirely separate evaluation.
10101 // FIXME: If there are operations in the RHS which are unsequenced
10102 // with respect to operations outside the RHS, and those operations
10103 // are unconditionally evaluated, diagnose them.
10104 WorkList.push_back(BO->getRHS());
10107 void VisitBinLAnd(BinaryOperator *BO) {
10108 EvaluationTracker Eval(*this);
10110 SequencedSubexpression Sequenced(*this);
10111 Visit(BO->getLHS());
10115 if (Eval.evaluate(BO->getLHS(), Result)) {
10117 Visit(BO->getRHS());
10119 WorkList.push_back(BO->getRHS());
10123 // Only visit the condition, unless we can be sure which subexpression will
10125 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
10126 EvaluationTracker Eval(*this);
10128 SequencedSubexpression Sequenced(*this);
10129 Visit(CO->getCond());
10133 if (Eval.evaluate(CO->getCond(), Result))
10134 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
10136 WorkList.push_back(CO->getTrueExpr());
10137 WorkList.push_back(CO->getFalseExpr());
10141 void VisitCallExpr(CallExpr *CE) {
10142 // C++11 [intro.execution]p15:
10143 // When calling a function [...], every value computation and side effect
10144 // associated with any argument expression, or with the postfix expression
10145 // designating the called function, is sequenced before execution of every
10146 // expression or statement in the body of the function [and thus before
10147 // the value computation of its result].
10148 SequencedSubexpression Sequenced(*this);
10149 Base::VisitCallExpr(CE);
10151 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
10154 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
10155 // This is a call, so all subexpressions are sequenced before the result.
10156 SequencedSubexpression Sequenced(*this);
10158 if (!CCE->isListInitialization())
10159 return VisitExpr(CCE);
10161 // In C++11, list initializations are sequenced.
10162 SmallVector<SequenceTree::Seq, 32> Elts;
10163 SequenceTree::Seq Parent = Region;
10164 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
10165 E = CCE->arg_end();
10167 Region = Tree.allocate(Parent);
10168 Elts.push_back(Region);
10172 // Forget that the initializers are sequenced.
10174 for (unsigned I = 0; I < Elts.size(); ++I)
10175 Tree.merge(Elts[I]);
10178 void VisitInitListExpr(InitListExpr *ILE) {
10179 if (!SemaRef.getLangOpts().CPlusPlus11)
10180 return VisitExpr(ILE);
10182 // In C++11, list initializations are sequenced.
10183 SmallVector<SequenceTree::Seq, 32> Elts;
10184 SequenceTree::Seq Parent = Region;
10185 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
10186 Expr *E = ILE->getInit(I);
10188 Region = Tree.allocate(Parent);
10189 Elts.push_back(Region);
10193 // Forget that the initializers are sequenced.
10195 for (unsigned I = 0; I < Elts.size(); ++I)
10196 Tree.merge(Elts[I]);
10199 } // end anonymous namespace
10201 void Sema::CheckUnsequencedOperations(Expr *E) {
10202 SmallVector<Expr *, 8> WorkList;
10203 WorkList.push_back(E);
10204 while (!WorkList.empty()) {
10205 Expr *Item = WorkList.pop_back_val();
10206 SequenceChecker(*this, Item, WorkList);
10210 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
10211 bool IsConstexpr) {
10212 CheckImplicitConversions(E, CheckLoc);
10213 if (!E->isInstantiationDependent())
10214 CheckUnsequencedOperations(E);
10215 if (!IsConstexpr && !E->isValueDependent())
10216 CheckForIntOverflow(E);
10217 DiagnoseMisalignedMembers();
10220 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
10221 FieldDecl *BitField,
10223 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
10226 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
10227 SourceLocation Loc) {
10228 if (!PType->isVariablyModifiedType())
10230 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
10231 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
10234 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
10235 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
10238 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
10239 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
10243 const ArrayType *AT = S.Context.getAsArrayType(PType);
10247 if (AT->getSizeModifier() != ArrayType::Star) {
10248 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
10252 S.Diag(Loc, diag::err_array_star_in_function_definition);
10255 /// CheckParmsForFunctionDef - Check that the parameters of the given
10256 /// function are appropriate for the definition of a function. This
10257 /// takes care of any checks that cannot be performed on the
10258 /// declaration itself, e.g., that the types of each of the function
10259 /// parameters are complete.
10260 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
10261 bool CheckParameterNames) {
10262 bool HasInvalidParm = false;
10263 for (ParmVarDecl *Param : Parameters) {
10264 // C99 6.7.5.3p4: the parameters in a parameter type list in a
10265 // function declarator that is part of a function definition of
10266 // that function shall not have incomplete type.
10268 // This is also C++ [dcl.fct]p6.
10269 if (!Param->isInvalidDecl() &&
10270 RequireCompleteType(Param->getLocation(), Param->getType(),
10271 diag::err_typecheck_decl_incomplete_type)) {
10272 Param->setInvalidDecl();
10273 HasInvalidParm = true;
10276 // C99 6.9.1p5: If the declarator includes a parameter type list, the
10277 // declaration of each parameter shall include an identifier.
10278 if (CheckParameterNames &&
10279 Param->getIdentifier() == nullptr &&
10280 !Param->isImplicit() &&
10281 !getLangOpts().CPlusPlus)
10282 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
10285 // If the function declarator is not part of a definition of that
10286 // function, parameters may have incomplete type and may use the [*]
10287 // notation in their sequences of declarator specifiers to specify
10288 // variable length array types.
10289 QualType PType = Param->getOriginalType();
10290 // FIXME: This diagnostic should point the '[*]' if source-location
10291 // information is added for it.
10292 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
10294 // MSVC destroys objects passed by value in the callee. Therefore a
10295 // function definition which takes such a parameter must be able to call the
10296 // object's destructor. However, we don't perform any direct access check
10298 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
10300 .areArgsDestroyedLeftToRightInCallee()) {
10301 if (!Param->isInvalidDecl()) {
10302 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
10303 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
10304 if (!ClassDecl->isInvalidDecl() &&
10305 !ClassDecl->hasIrrelevantDestructor() &&
10306 !ClassDecl->isDependentContext()) {
10307 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10308 MarkFunctionReferenced(Param->getLocation(), Destructor);
10309 DiagnoseUseOfDecl(Destructor, Param->getLocation());
10315 // Parameters with the pass_object_size attribute only need to be marked
10316 // constant at function definitions. Because we lack information about
10317 // whether we're on a declaration or definition when we're instantiating the
10318 // attribute, we need to check for constness here.
10319 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
10320 if (!Param->getType().isConstQualified())
10321 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
10322 << Attr->getSpelling() << 1;
10325 return HasInvalidParm;
10328 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr
10330 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
10331 ASTContext &Context) {
10332 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
10333 return Context.getDeclAlign(DRE->getDecl());
10335 if (const auto *ME = dyn_cast<MemberExpr>(E))
10336 return Context.getDeclAlign(ME->getMemberDecl());
10341 /// CheckCastAlign - Implements -Wcast-align, which warns when a
10342 /// pointer cast increases the alignment requirements.
10343 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
10344 // This is actually a lot of work to potentially be doing on every
10345 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
10346 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
10349 // Ignore dependent types.
10350 if (T->isDependentType() || Op->getType()->isDependentType())
10353 // Require that the destination be a pointer type.
10354 const PointerType *DestPtr = T->getAs<PointerType>();
10355 if (!DestPtr) return;
10357 // If the destination has alignment 1, we're done.
10358 QualType DestPointee = DestPtr->getPointeeType();
10359 if (DestPointee->isIncompleteType()) return;
10360 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
10361 if (DestAlign.isOne()) return;
10363 // Require that the source be a pointer type.
10364 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
10365 if (!SrcPtr) return;
10366 QualType SrcPointee = SrcPtr->getPointeeType();
10368 // Whitelist casts from cv void*. We already implicitly
10369 // whitelisted casts to cv void*, since they have alignment 1.
10370 // Also whitelist casts involving incomplete types, which implicitly
10371 // includes 'void'.
10372 if (SrcPointee->isIncompleteType()) return;
10374 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
10376 if (auto *CE = dyn_cast<CastExpr>(Op)) {
10377 if (CE->getCastKind() == CK_ArrayToPointerDecay)
10378 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
10379 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
10380 if (UO->getOpcode() == UO_AddrOf)
10381 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
10384 if (SrcAlign >= DestAlign) return;
10386 Diag(TRange.getBegin(), diag::warn_cast_align)
10387 << Op->getType() << T
10388 << static_cast<unsigned>(SrcAlign.getQuantity())
10389 << static_cast<unsigned>(DestAlign.getQuantity())
10390 << TRange << Op->getSourceRange();
10393 /// \brief Check whether this array fits the idiom of a size-one tail padded
10394 /// array member of a struct.
10396 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
10397 /// commonly used to emulate flexible arrays in C89 code.
10398 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
10399 const NamedDecl *ND) {
10400 if (Size != 1 || !ND) return false;
10402 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
10403 if (!FD) return false;
10405 // Don't consider sizes resulting from macro expansions or template argument
10406 // substitution to form C89 tail-padded arrays.
10408 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
10410 TypeLoc TL = TInfo->getTypeLoc();
10411 // Look through typedefs.
10412 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
10413 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
10414 TInfo = TDL->getTypeSourceInfo();
10417 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
10418 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
10419 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
10425 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
10426 if (!RD) return false;
10427 if (RD->isUnion()) return false;
10428 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10429 if (!CRD->isStandardLayout()) return false;
10432 // See if this is the last field decl in the record.
10433 const Decl *D = FD;
10434 while ((D = D->getNextDeclInContext()))
10435 if (isa<FieldDecl>(D))
10440 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
10441 const ArraySubscriptExpr *ASE,
10442 bool AllowOnePastEnd, bool IndexNegated) {
10443 IndexExpr = IndexExpr->IgnoreParenImpCasts();
10444 if (IndexExpr->isValueDependent())
10447 const Type *EffectiveType =
10448 BaseExpr->getType()->getPointeeOrArrayElementType();
10449 BaseExpr = BaseExpr->IgnoreParenCasts();
10450 const ConstantArrayType *ArrayTy =
10451 Context.getAsConstantArrayType(BaseExpr->getType());
10455 llvm::APSInt index;
10456 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
10461 const NamedDecl *ND = nullptr;
10462 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10463 ND = dyn_cast<NamedDecl>(DRE->getDecl());
10464 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
10465 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
10467 if (index.isUnsigned() || !index.isNegative()) {
10468 llvm::APInt size = ArrayTy->getSize();
10469 if (!size.isStrictlyPositive())
10472 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
10473 if (BaseType != EffectiveType) {
10474 // Make sure we're comparing apples to apples when comparing index to size
10475 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
10476 uint64_t array_typesize = Context.getTypeSize(BaseType);
10477 // Handle ptrarith_typesize being zero, such as when casting to void*
10478 if (!ptrarith_typesize) ptrarith_typesize = 1;
10479 if (ptrarith_typesize != array_typesize) {
10480 // There's a cast to a different size type involved
10481 uint64_t ratio = array_typesize / ptrarith_typesize;
10482 // TODO: Be smarter about handling cases where array_typesize is not a
10483 // multiple of ptrarith_typesize
10484 if (ptrarith_typesize * ratio == array_typesize)
10485 size *= llvm::APInt(size.getBitWidth(), ratio);
10489 if (size.getBitWidth() > index.getBitWidth())
10490 index = index.zext(size.getBitWidth());
10491 else if (size.getBitWidth() < index.getBitWidth())
10492 size = size.zext(index.getBitWidth());
10494 // For array subscripting the index must be less than size, but for pointer
10495 // arithmetic also allow the index (offset) to be equal to size since
10496 // computing the next address after the end of the array is legal and
10497 // commonly done e.g. in C++ iterators and range-based for loops.
10498 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
10501 // Also don't warn for arrays of size 1 which are members of some
10502 // structure. These are often used to approximate flexible arrays in C89
10504 if (IsTailPaddedMemberArray(*this, size, ND))
10507 // Suppress the warning if the subscript expression (as identified by the
10508 // ']' location) and the index expression are both from macro expansions
10509 // within a system header.
10511 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
10512 ASE->getRBracketLoc());
10513 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
10514 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
10515 IndexExpr->getLocStart());
10516 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
10521 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
10523 DiagID = diag::warn_array_index_exceeds_bounds;
10525 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10526 PDiag(DiagID) << index.toString(10, true)
10527 << size.toString(10, true)
10528 << (unsigned)size.getLimitedValue(~0U)
10529 << IndexExpr->getSourceRange());
10531 unsigned DiagID = diag::warn_array_index_precedes_bounds;
10533 DiagID = diag::warn_ptr_arith_precedes_bounds;
10534 if (index.isNegative()) index = -index;
10537 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10538 PDiag(DiagID) << index.toString(10, true)
10539 << IndexExpr->getSourceRange());
10543 // Try harder to find a NamedDecl to point at in the note.
10544 while (const ArraySubscriptExpr *ASE =
10545 dyn_cast<ArraySubscriptExpr>(BaseExpr))
10546 BaseExpr = ASE->getBase()->IgnoreParenCasts();
10547 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10548 ND = dyn_cast<NamedDecl>(DRE->getDecl());
10549 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
10550 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
10554 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
10555 PDiag(diag::note_array_index_out_of_bounds)
10556 << ND->getDeclName());
10559 void Sema::CheckArrayAccess(const Expr *expr) {
10560 int AllowOnePastEnd = 0;
10562 expr = expr->IgnoreParenImpCasts();
10563 switch (expr->getStmtClass()) {
10564 case Stmt::ArraySubscriptExprClass: {
10565 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
10566 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
10567 AllowOnePastEnd > 0);
10570 case Stmt::OMPArraySectionExprClass: {
10571 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
10572 if (ASE->getLowerBound())
10573 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
10574 /*ASE=*/nullptr, AllowOnePastEnd > 0);
10577 case Stmt::UnaryOperatorClass: {
10578 // Only unwrap the * and & unary operators
10579 const UnaryOperator *UO = cast<UnaryOperator>(expr);
10580 expr = UO->getSubExpr();
10581 switch (UO->getOpcode()) {
10593 case Stmt::ConditionalOperatorClass: {
10594 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
10595 if (const Expr *lhs = cond->getLHS())
10596 CheckArrayAccess(lhs);
10597 if (const Expr *rhs = cond->getRHS())
10598 CheckArrayAccess(rhs);
10607 //===--- CHECK: Objective-C retain cycles ----------------------------------//
10610 struct RetainCycleOwner {
10611 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
10614 SourceLocation Loc;
10617 void setLocsFrom(Expr *e) {
10618 Loc = e->getExprLoc();
10619 Range = e->getSourceRange();
10622 } // end anonymous namespace
10624 /// Consider whether capturing the given variable can possibly lead to
10625 /// a retain cycle.
10626 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
10627 // In ARC, it's captured strongly iff the variable has __strong
10628 // lifetime. In MRR, it's captured strongly if the variable is
10629 // __block and has an appropriate type.
10630 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10633 owner.Variable = var;
10635 owner.setLocsFrom(ref);
10639 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
10641 e = e->IgnoreParens();
10642 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
10643 switch (cast->getCastKind()) {
10645 case CK_LValueBitCast:
10646 case CK_LValueToRValue:
10647 case CK_ARCReclaimReturnedObject:
10648 e = cast->getSubExpr();
10656 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
10657 ObjCIvarDecl *ivar = ref->getDecl();
10658 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10661 // Try to find a retain cycle in the base.
10662 if (!findRetainCycleOwner(S, ref->getBase(), owner))
10665 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
10666 owner.Indirect = true;
10670 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
10671 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
10672 if (!var) return false;
10673 return considerVariable(var, ref, owner);
10676 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
10677 if (member->isArrow()) return false;
10679 // Don't count this as an indirect ownership.
10680 e = member->getBase();
10684 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
10685 // Only pay attention to pseudo-objects on property references.
10686 ObjCPropertyRefExpr *pre
10687 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
10689 if (!pre) return false;
10690 if (pre->isImplicitProperty()) return false;
10691 ObjCPropertyDecl *property = pre->getExplicitProperty();
10692 if (!property->isRetaining() &&
10693 !(property->getPropertyIvarDecl() &&
10694 property->getPropertyIvarDecl()->getType()
10695 .getObjCLifetime() == Qualifiers::OCL_Strong))
10698 owner.Indirect = true;
10699 if (pre->isSuperReceiver()) {
10700 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
10701 if (!owner.Variable)
10703 owner.Loc = pre->getLocation();
10704 owner.Range = pre->getSourceRange();
10707 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
10708 ->getSourceExpr());
10719 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
10720 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
10721 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
10722 Context(Context), Variable(variable), Capturer(nullptr),
10723 VarWillBeReased(false) {}
10724 ASTContext &Context;
10727 bool VarWillBeReased;
10729 void VisitDeclRefExpr(DeclRefExpr *ref) {
10730 if (ref->getDecl() == Variable && !Capturer)
10734 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
10735 if (Capturer) return;
10736 Visit(ref->getBase());
10737 if (Capturer && ref->isFreeIvar())
10741 void VisitBlockExpr(BlockExpr *block) {
10742 // Look inside nested blocks
10743 if (block->getBlockDecl()->capturesVariable(Variable))
10744 Visit(block->getBlockDecl()->getBody());
10747 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
10748 if (Capturer) return;
10749 if (OVE->getSourceExpr())
10750 Visit(OVE->getSourceExpr());
10752 void VisitBinaryOperator(BinaryOperator *BinOp) {
10753 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
10755 Expr *LHS = BinOp->getLHS();
10756 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
10757 if (DRE->getDecl() != Variable)
10759 if (Expr *RHS = BinOp->getRHS()) {
10760 RHS = RHS->IgnoreParenCasts();
10761 llvm::APSInt Value;
10763 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
10768 } // end anonymous namespace
10770 /// Check whether the given argument is a block which captures a
10772 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
10773 assert(owner.Variable && owner.Loc.isValid());
10775 e = e->IgnoreParenCasts();
10777 // Look through [^{...} copy] and Block_copy(^{...}).
10778 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
10779 Selector Cmd = ME->getSelector();
10780 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
10781 e = ME->getInstanceReceiver();
10784 e = e->IgnoreParenCasts();
10786 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
10787 if (CE->getNumArgs() == 1) {
10788 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
10790 const IdentifierInfo *FnI = Fn->getIdentifier();
10791 if (FnI && FnI->isStr("_Block_copy")) {
10792 e = CE->getArg(0)->IgnoreParenCasts();
10798 BlockExpr *block = dyn_cast<BlockExpr>(e);
10799 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
10802 FindCaptureVisitor visitor(S.Context, owner.Variable);
10803 visitor.Visit(block->getBlockDecl()->getBody());
10804 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
10807 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
10808 RetainCycleOwner &owner) {
10810 assert(owner.Variable && owner.Loc.isValid());
10812 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
10813 << owner.Variable << capturer->getSourceRange();
10814 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
10815 << owner.Indirect << owner.Range;
10818 /// Check for a keyword selector that starts with the word 'add' or
10820 static bool isSetterLikeSelector(Selector sel) {
10821 if (sel.isUnarySelector()) return false;
10823 StringRef str = sel.getNameForSlot(0);
10824 while (!str.empty() && str.front() == '_') str = str.substr(1);
10825 if (str.startswith("set"))
10826 str = str.substr(3);
10827 else if (str.startswith("add")) {
10828 // Specially whitelist 'addOperationWithBlock:'.
10829 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
10831 str = str.substr(3);
10836 if (str.empty()) return true;
10837 return !isLowercase(str.front());
10840 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
10841 ObjCMessageExpr *Message) {
10842 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
10843 Message->getReceiverInterface(),
10844 NSAPI::ClassId_NSMutableArray);
10845 if (!IsMutableArray) {
10849 Selector Sel = Message->getSelector();
10851 Optional<NSAPI::NSArrayMethodKind> MKOpt =
10852 S.NSAPIObj->getNSArrayMethodKind(Sel);
10857 NSAPI::NSArrayMethodKind MK = *MKOpt;
10860 case NSAPI::NSMutableArr_addObject:
10861 case NSAPI::NSMutableArr_insertObjectAtIndex:
10862 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
10864 case NSAPI::NSMutableArr_replaceObjectAtIndex:
10875 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
10876 ObjCMessageExpr *Message) {
10877 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
10878 Message->getReceiverInterface(),
10879 NSAPI::ClassId_NSMutableDictionary);
10880 if (!IsMutableDictionary) {
10884 Selector Sel = Message->getSelector();
10886 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
10887 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
10892 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
10895 case NSAPI::NSMutableDict_setObjectForKey:
10896 case NSAPI::NSMutableDict_setValueForKey:
10897 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
10907 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
10908 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
10909 Message->getReceiverInterface(),
10910 NSAPI::ClassId_NSMutableSet);
10912 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
10913 Message->getReceiverInterface(),
10914 NSAPI::ClassId_NSMutableOrderedSet);
10915 if (!IsMutableSet && !IsMutableOrderedSet) {
10919 Selector Sel = Message->getSelector();
10921 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
10926 NSAPI::NSSetMethodKind MK = *MKOpt;
10929 case NSAPI::NSMutableSet_addObject:
10930 case NSAPI::NSOrderedSet_setObjectAtIndex:
10931 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
10932 case NSAPI::NSOrderedSet_insertObjectAtIndex:
10934 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
10941 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
10942 if (!Message->isInstanceMessage()) {
10946 Optional<int> ArgOpt;
10948 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
10949 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
10950 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
10954 int ArgIndex = *ArgOpt;
10956 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
10957 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
10958 Arg = OE->getSourceExpr()->IgnoreImpCasts();
10961 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
10962 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
10963 if (ArgRE->isObjCSelfExpr()) {
10964 Diag(Message->getSourceRange().getBegin(),
10965 diag::warn_objc_circular_container)
10966 << ArgRE->getDecl()->getName() << StringRef("super");
10970 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
10972 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
10973 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
10976 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
10977 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
10978 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
10979 ValueDecl *Decl = ReceiverRE->getDecl();
10980 Diag(Message->getSourceRange().getBegin(),
10981 diag::warn_objc_circular_container)
10982 << Decl->getName() << Decl->getName();
10983 if (!ArgRE->isObjCSelfExpr()) {
10984 Diag(Decl->getLocation(),
10985 diag::note_objc_circular_container_declared_here)
10986 << Decl->getName();
10990 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
10991 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
10992 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
10993 ObjCIvarDecl *Decl = IvarRE->getDecl();
10994 Diag(Message->getSourceRange().getBegin(),
10995 diag::warn_objc_circular_container)
10996 << Decl->getName() << Decl->getName();
10997 Diag(Decl->getLocation(),
10998 diag::note_objc_circular_container_declared_here)
10999 << Decl->getName();
11006 /// Check a message send to see if it's likely to cause a retain cycle.
11007 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
11008 // Only check instance methods whose selector looks like a setter.
11009 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
11012 // Try to find a variable that the receiver is strongly owned by.
11013 RetainCycleOwner owner;
11014 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
11015 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
11018 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
11019 owner.Variable = getCurMethodDecl()->getSelfDecl();
11020 owner.Loc = msg->getSuperLoc();
11021 owner.Range = msg->getSuperLoc();
11024 // Check whether the receiver is captured by any of the arguments.
11025 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
11026 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
11027 return diagnoseRetainCycle(*this, capturer, owner);
11030 /// Check a property assign to see if it's likely to cause a retain cycle.
11031 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
11032 RetainCycleOwner owner;
11033 if (!findRetainCycleOwner(*this, receiver, owner))
11036 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
11037 diagnoseRetainCycle(*this, capturer, owner);
11040 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
11041 RetainCycleOwner Owner;
11042 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
11045 // Because we don't have an expression for the variable, we have to set the
11046 // location explicitly here.
11047 Owner.Loc = Var->getLocation();
11048 Owner.Range = Var->getSourceRange();
11050 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
11051 diagnoseRetainCycle(*this, Capturer, Owner);
11054 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
11055 Expr *RHS, bool isProperty) {
11056 // Check if RHS is an Objective-C object literal, which also can get
11057 // immediately zapped in a weak reference. Note that we explicitly
11058 // allow ObjCStringLiterals, since those are designed to never really die.
11059 RHS = RHS->IgnoreParenImpCasts();
11061 // This enum needs to match with the 'select' in
11062 // warn_objc_arc_literal_assign (off-by-1).
11063 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
11064 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
11067 S.Diag(Loc, diag::warn_arc_literal_assign)
11069 << (isProperty ? 0 : 1)
11070 << RHS->getSourceRange();
11075 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
11076 Qualifiers::ObjCLifetime LT,
11077 Expr *RHS, bool isProperty) {
11078 // Strip off any implicit cast added to get to the one ARC-specific.
11079 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11080 if (cast->getCastKind() == CK_ARCConsumeObject) {
11081 S.Diag(Loc, diag::warn_arc_retained_assign)
11082 << (LT == Qualifiers::OCL_ExplicitNone)
11083 << (isProperty ? 0 : 1)
11084 << RHS->getSourceRange();
11087 RHS = cast->getSubExpr();
11090 if (LT == Qualifiers::OCL_Weak &&
11091 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
11097 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
11098 QualType LHS, Expr *RHS) {
11099 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
11101 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
11104 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
11110 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
11111 Expr *LHS, Expr *RHS) {
11113 // PropertyRef on LHS type need be directly obtained from
11114 // its declaration as it has a PseudoType.
11115 ObjCPropertyRefExpr *PRE
11116 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
11117 if (PRE && !PRE->isImplicitProperty()) {
11118 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11120 LHSType = PD->getType();
11123 if (LHSType.isNull())
11124 LHSType = LHS->getType();
11126 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
11128 if (LT == Qualifiers::OCL_Weak) {
11129 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
11130 getCurFunction()->markSafeWeakUse(LHS);
11133 if (checkUnsafeAssigns(Loc, LHSType, RHS))
11136 // FIXME. Check for other life times.
11137 if (LT != Qualifiers::OCL_None)
11141 if (PRE->isImplicitProperty())
11143 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11147 unsigned Attributes = PD->getPropertyAttributes();
11148 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
11149 // when 'assign' attribute was not explicitly specified
11150 // by user, ignore it and rely on property type itself
11151 // for lifetime info.
11152 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
11153 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
11154 LHSType->isObjCRetainableType())
11157 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11158 if (cast->getCastKind() == CK_ARCConsumeObject) {
11159 Diag(Loc, diag::warn_arc_retained_property_assign)
11160 << RHS->getSourceRange();
11163 RHS = cast->getSubExpr();
11166 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
11167 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
11173 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
11176 bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
11177 SourceLocation StmtLoc,
11178 const NullStmt *Body) {
11179 // Do not warn if the body is a macro that expands to nothing, e.g:
11185 if (Body->hasLeadingEmptyMacro())
11188 // Get line numbers of statement and body.
11189 bool StmtLineInvalid;
11190 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
11192 if (StmtLineInvalid)
11195 bool BodyLineInvalid;
11196 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
11198 if (BodyLineInvalid)
11201 // Warn if null statement and body are on the same line.
11202 if (StmtLine != BodyLine)
11207 } // end anonymous namespace
11209 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
11212 // Since this is a syntactic check, don't emit diagnostic for template
11213 // instantiations, this just adds noise.
11214 if (CurrentInstantiationScope)
11217 // The body should be a null statement.
11218 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11222 // Do the usual checks.
11223 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11226 Diag(NBody->getSemiLoc(), DiagID);
11227 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11230 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
11231 const Stmt *PossibleBody) {
11232 assert(!CurrentInstantiationScope); // Ensured by caller
11234 SourceLocation StmtLoc;
11237 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
11238 StmtLoc = FS->getRParenLoc();
11239 Body = FS->getBody();
11240 DiagID = diag::warn_empty_for_body;
11241 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
11242 StmtLoc = WS->getCond()->getSourceRange().getEnd();
11243 Body = WS->getBody();
11244 DiagID = diag::warn_empty_while_body;
11246 return; // Neither `for' nor `while'.
11248 // The body should be a null statement.
11249 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11253 // Skip expensive checks if diagnostic is disabled.
11254 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
11257 // Do the usual checks.
11258 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11261 // `for(...);' and `while(...);' are popular idioms, so in order to keep
11262 // noise level low, emit diagnostics only if for/while is followed by a
11263 // CompoundStmt, e.g.:
11264 // for (int i = 0; i < n; i++);
11268 // or if for/while is followed by a statement with more indentation
11269 // than for/while itself:
11270 // for (int i = 0; i < n; i++);
11272 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
11273 if (!ProbableTypo) {
11274 bool BodyColInvalid;
11275 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
11276 PossibleBody->getLocStart(),
11278 if (BodyColInvalid)
11281 bool StmtColInvalid;
11282 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
11285 if (StmtColInvalid)
11288 if (BodyCol > StmtCol)
11289 ProbableTypo = true;
11292 if (ProbableTypo) {
11293 Diag(NBody->getSemiLoc(), DiagID);
11294 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11298 //===--- CHECK: Warn on self move with std::move. -------------------------===//
11300 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
11301 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
11302 SourceLocation OpLoc) {
11303 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
11306 if (!ActiveTemplateInstantiations.empty())
11309 // Strip parens and casts away.
11310 LHSExpr = LHSExpr->IgnoreParenImpCasts();
11311 RHSExpr = RHSExpr->IgnoreParenImpCasts();
11313 // Check for a call expression
11314 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
11315 if (!CE || CE->getNumArgs() != 1)
11318 // Check for a call to std::move
11319 const FunctionDecl *FD = CE->getDirectCallee();
11320 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
11321 !FD->getIdentifier()->isStr("move"))
11324 // Get argument from std::move
11325 RHSExpr = CE->getArg(0);
11327 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11328 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11330 // Two DeclRefExpr's, check that the decls are the same.
11331 if (LHSDeclRef && RHSDeclRef) {
11332 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11334 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11335 RHSDeclRef->getDecl()->getCanonicalDecl())
11338 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11339 << LHSExpr->getSourceRange()
11340 << RHSExpr->getSourceRange();
11344 // Member variables require a different approach to check for self moves.
11345 // MemberExpr's are the same if every nested MemberExpr refers to the same
11346 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
11347 // the base Expr's are CXXThisExpr's.
11348 const Expr *LHSBase = LHSExpr;
11349 const Expr *RHSBase = RHSExpr;
11350 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
11351 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
11352 if (!LHSME || !RHSME)
11355 while (LHSME && RHSME) {
11356 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
11357 RHSME->getMemberDecl()->getCanonicalDecl())
11360 LHSBase = LHSME->getBase();
11361 RHSBase = RHSME->getBase();
11362 LHSME = dyn_cast<MemberExpr>(LHSBase);
11363 RHSME = dyn_cast<MemberExpr>(RHSBase);
11366 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
11367 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
11368 if (LHSDeclRef && RHSDeclRef) {
11369 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11371 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11372 RHSDeclRef->getDecl()->getCanonicalDecl())
11375 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11376 << LHSExpr->getSourceRange()
11377 << RHSExpr->getSourceRange();
11381 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
11382 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11383 << LHSExpr->getSourceRange()
11384 << RHSExpr->getSourceRange();
11387 //===--- Layout compatibility ----------------------------------------------//
11391 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
11393 /// \brief Check if two enumeration types are layout-compatible.
11394 bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
11395 // C++11 [dcl.enum] p8:
11396 // Two enumeration types are layout-compatible if they have the same
11397 // underlying type.
11398 return ED1->isComplete() && ED2->isComplete() &&
11399 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
11402 /// \brief Check if two fields are layout-compatible.
11403 bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
11404 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
11407 if (Field1->isBitField() != Field2->isBitField())
11410 if (Field1->isBitField()) {
11411 // Make sure that the bit-fields are the same length.
11412 unsigned Bits1 = Field1->getBitWidthValue(C);
11413 unsigned Bits2 = Field2->getBitWidthValue(C);
11415 if (Bits1 != Bits2)
11422 /// \brief Check if two standard-layout structs are layout-compatible.
11423 /// (C++11 [class.mem] p17)
11424 bool isLayoutCompatibleStruct(ASTContext &C,
11427 // If both records are C++ classes, check that base classes match.
11428 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
11429 // If one of records is a CXXRecordDecl we are in C++ mode,
11430 // thus the other one is a CXXRecordDecl, too.
11431 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
11432 // Check number of base classes.
11433 if (D1CXX->getNumBases() != D2CXX->getNumBases())
11436 // Check the base classes.
11437 for (CXXRecordDecl::base_class_const_iterator
11438 Base1 = D1CXX->bases_begin(),
11439 BaseEnd1 = D1CXX->bases_end(),
11440 Base2 = D2CXX->bases_begin();
11442 ++Base1, ++Base2) {
11443 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
11446 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
11447 // If only RD2 is a C++ class, it should have zero base classes.
11448 if (D2CXX->getNumBases() > 0)
11452 // Check the fields.
11453 RecordDecl::field_iterator Field2 = RD2->field_begin(),
11454 Field2End = RD2->field_end(),
11455 Field1 = RD1->field_begin(),
11456 Field1End = RD1->field_end();
11457 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
11458 if (!isLayoutCompatible(C, *Field1, *Field2))
11461 if (Field1 != Field1End || Field2 != Field2End)
11467 /// \brief Check if two standard-layout unions are layout-compatible.
11468 /// (C++11 [class.mem] p18)
11469 bool isLayoutCompatibleUnion(ASTContext &C,
11472 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
11473 for (auto *Field2 : RD2->fields())
11474 UnmatchedFields.insert(Field2);
11476 for (auto *Field1 : RD1->fields()) {
11477 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
11478 I = UnmatchedFields.begin(),
11479 E = UnmatchedFields.end();
11481 for ( ; I != E; ++I) {
11482 if (isLayoutCompatible(C, Field1, *I)) {
11483 bool Result = UnmatchedFields.erase(*I);
11493 return UnmatchedFields.empty();
11496 bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
11497 if (RD1->isUnion() != RD2->isUnion())
11500 if (RD1->isUnion())
11501 return isLayoutCompatibleUnion(C, RD1, RD2);
11503 return isLayoutCompatibleStruct(C, RD1, RD2);
11506 /// \brief Check if two types are layout-compatible in C++11 sense.
11507 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
11508 if (T1.isNull() || T2.isNull())
11511 // C++11 [basic.types] p11:
11512 // If two types T1 and T2 are the same type, then T1 and T2 are
11513 // layout-compatible types.
11514 if (C.hasSameType(T1, T2))
11517 T1 = T1.getCanonicalType().getUnqualifiedType();
11518 T2 = T2.getCanonicalType().getUnqualifiedType();
11520 const Type::TypeClass TC1 = T1->getTypeClass();
11521 const Type::TypeClass TC2 = T2->getTypeClass();
11526 if (TC1 == Type::Enum) {
11527 return isLayoutCompatible(C,
11528 cast<EnumType>(T1)->getDecl(),
11529 cast<EnumType>(T2)->getDecl());
11530 } else if (TC1 == Type::Record) {
11531 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
11534 return isLayoutCompatible(C,
11535 cast<RecordType>(T1)->getDecl(),
11536 cast<RecordType>(T2)->getDecl());
11541 } // end anonymous namespace
11543 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
11546 /// \brief Given a type tag expression find the type tag itself.
11548 /// \param TypeExpr Type tag expression, as it appears in user's code.
11550 /// \param VD Declaration of an identifier that appears in a type tag.
11552 /// \param MagicValue Type tag magic value.
11553 bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
11554 const ValueDecl **VD, uint64_t *MagicValue) {
11559 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
11561 switch (TypeExpr->getStmtClass()) {
11562 case Stmt::UnaryOperatorClass: {
11563 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
11564 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
11565 TypeExpr = UO->getSubExpr();
11571 case Stmt::DeclRefExprClass: {
11572 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
11573 *VD = DRE->getDecl();
11577 case Stmt::IntegerLiteralClass: {
11578 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
11579 llvm::APInt MagicValueAPInt = IL->getValue();
11580 if (MagicValueAPInt.getActiveBits() <= 64) {
11581 *MagicValue = MagicValueAPInt.getZExtValue();
11587 case Stmt::BinaryConditionalOperatorClass:
11588 case Stmt::ConditionalOperatorClass: {
11589 const AbstractConditionalOperator *ACO =
11590 cast<AbstractConditionalOperator>(TypeExpr);
11592 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
11594 TypeExpr = ACO->getTrueExpr();
11596 TypeExpr = ACO->getFalseExpr();
11602 case Stmt::BinaryOperatorClass: {
11603 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
11604 if (BO->getOpcode() == BO_Comma) {
11605 TypeExpr = BO->getRHS();
11617 /// \brief Retrieve the C type corresponding to type tag TypeExpr.
11619 /// \param TypeExpr Expression that specifies a type tag.
11621 /// \param MagicValues Registered magic values.
11623 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
11626 /// \param TypeInfo Information about the corresponding C type.
11628 /// \returns true if the corresponding C type was found.
11629 bool GetMatchingCType(
11630 const IdentifierInfo *ArgumentKind,
11631 const Expr *TypeExpr, const ASTContext &Ctx,
11632 const llvm::DenseMap<Sema::TypeTagMagicValue,
11633 Sema::TypeTagData> *MagicValues,
11634 bool &FoundWrongKind,
11635 Sema::TypeTagData &TypeInfo) {
11636 FoundWrongKind = false;
11638 // Variable declaration that has type_tag_for_datatype attribute.
11639 const ValueDecl *VD = nullptr;
11641 uint64_t MagicValue;
11643 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
11647 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
11648 if (I->getArgumentKind() != ArgumentKind) {
11649 FoundWrongKind = true;
11652 TypeInfo.Type = I->getMatchingCType();
11653 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
11654 TypeInfo.MustBeNull = I->getMustBeNull();
11663 llvm::DenseMap<Sema::TypeTagMagicValue,
11664 Sema::TypeTagData>::const_iterator I =
11665 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
11666 if (I == MagicValues->end())
11669 TypeInfo = I->second;
11672 } // end anonymous namespace
11674 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
11675 uint64_t MagicValue, QualType Type,
11676 bool LayoutCompatible,
11678 if (!TypeTagForDatatypeMagicValues)
11679 TypeTagForDatatypeMagicValues.reset(
11680 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
11682 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
11683 (*TypeTagForDatatypeMagicValues)[Magic] =
11684 TypeTagData(Type, LayoutCompatible, MustBeNull);
11688 bool IsSameCharType(QualType T1, QualType T2) {
11689 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
11693 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
11697 BuiltinType::Kind T1Kind = BT1->getKind();
11698 BuiltinType::Kind T2Kind = BT2->getKind();
11700 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
11701 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
11702 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
11703 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
11705 } // end anonymous namespace
11707 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
11708 const Expr * const *ExprArgs) {
11709 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
11710 bool IsPointerAttr = Attr->getIsPointer();
11712 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
11713 bool FoundWrongKind;
11714 TypeTagData TypeInfo;
11715 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
11716 TypeTagForDatatypeMagicValues.get(),
11717 FoundWrongKind, TypeInfo)) {
11718 if (FoundWrongKind)
11719 Diag(TypeTagExpr->getExprLoc(),
11720 diag::warn_type_tag_for_datatype_wrong_kind)
11721 << TypeTagExpr->getSourceRange();
11725 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
11726 if (IsPointerAttr) {
11727 // Skip implicit cast of pointer to `void *' (as a function argument).
11728 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
11729 if (ICE->getType()->isVoidPointerType() &&
11730 ICE->getCastKind() == CK_BitCast)
11731 ArgumentExpr = ICE->getSubExpr();
11733 QualType ArgumentType = ArgumentExpr->getType();
11735 // Passing a `void*' pointer shouldn't trigger a warning.
11736 if (IsPointerAttr && ArgumentType->isVoidPointerType())
11739 if (TypeInfo.MustBeNull) {
11740 // Type tag with matching void type requires a null pointer.
11741 if (!ArgumentExpr->isNullPointerConstant(Context,
11742 Expr::NPC_ValueDependentIsNotNull)) {
11743 Diag(ArgumentExpr->getExprLoc(),
11744 diag::warn_type_safety_null_pointer_required)
11745 << ArgumentKind->getName()
11746 << ArgumentExpr->getSourceRange()
11747 << TypeTagExpr->getSourceRange();
11752 QualType RequiredType = TypeInfo.Type;
11754 RequiredType = Context.getPointerType(RequiredType);
11756 bool mismatch = false;
11757 if (!TypeInfo.LayoutCompatible) {
11758 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
11760 // C++11 [basic.fundamental] p1:
11761 // Plain char, signed char, and unsigned char are three distinct types.
11763 // But we treat plain `char' as equivalent to `signed char' or `unsigned
11764 // char' depending on the current char signedness mode.
11766 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
11767 RequiredType->getPointeeType())) ||
11768 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
11772 mismatch = !isLayoutCompatible(Context,
11773 ArgumentType->getPointeeType(),
11774 RequiredType->getPointeeType());
11776 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
11779 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
11780 << ArgumentType << ArgumentKind
11781 << TypeInfo.LayoutCompatible << RequiredType
11782 << ArgumentExpr->getSourceRange()
11783 << TypeTagExpr->getSourceRange();
11786 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
11787 CharUnits Alignment) {
11788 MisalignedMembers.emplace_back(E, RD, MD, Alignment);
11791 void Sema::DiagnoseMisalignedMembers() {
11792 for (MisalignedMember &m : MisalignedMembers) {
11793 const NamedDecl *ND = m.RD;
11794 if (ND->getName().empty()) {
11795 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
11798 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
11799 << m.MD << ND << m.E->getSourceRange();
11801 MisalignedMembers.clear();
11804 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
11805 E = E->IgnoreParens();
11806 if (!T->isPointerType() && !T->isIntegerType())
11808 if (isa<UnaryOperator>(E) &&
11809 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
11810 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
11811 if (isa<MemberExpr>(Op)) {
11812 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
11813 MisalignedMember(Op));
11814 if (MA != MisalignedMembers.end() &&
11815 (T->isIntegerType() ||
11816 (T->isPointerType() &&
11817 Context.getTypeAlignInChars(T->getPointeeType()) <= MA->Alignment)))
11818 MisalignedMembers.erase(MA);
11823 void Sema::RefersToMemberWithReducedAlignment(
11825 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
11827 const auto *ME = dyn_cast<MemberExpr>(E);
11831 // For a chain of MemberExpr like "a.b.c.d" this list
11832 // will keep FieldDecl's like [d, c, b].
11833 SmallVector<FieldDecl *, 4> ReverseMemberChain;
11834 const MemberExpr *TopME = nullptr;
11835 bool AnyIsPacked = false;
11837 QualType BaseType = ME->getBase()->getType();
11839 BaseType = BaseType->getPointeeType();
11840 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
11842 ValueDecl *MD = ME->getMemberDecl();
11843 auto *FD = dyn_cast<FieldDecl>(MD);
11844 // We do not care about non-data members.
11845 if (!FD || FD->isInvalidDecl())
11849 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
11850 ReverseMemberChain.push_back(FD);
11853 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
11855 assert(TopME && "We did not compute a topmost MemberExpr!");
11857 // Not the scope of this diagnostic.
11861 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
11862 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
11863 // TODO: The innermost base of the member expression may be too complicated.
11864 // For now, just disregard these cases. This is left for future
11866 if (!DRE && !isa<CXXThisExpr>(TopBase))
11869 // Alignment expected by the whole expression.
11870 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
11872 // No need to do anything else with this case.
11873 if (ExpectedAlignment.isOne())
11876 // Synthesize offset of the whole access.
11878 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
11880 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
11883 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
11884 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
11885 ReverseMemberChain.back()->getParent()->getTypeForDecl());
11887 // The base expression of the innermost MemberExpr may give
11888 // stronger guarantees than the class containing the member.
11889 if (DRE && !TopME->isArrow()) {
11890 const ValueDecl *VD = DRE->getDecl();
11891 if (!VD->getType()->isReferenceType())
11892 CompleteObjectAlignment =
11893 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
11896 // Check if the synthesized offset fulfills the alignment.
11897 if (Offset % ExpectedAlignment != 0 ||
11898 // It may fulfill the offset it but the effective alignment may still be
11899 // lower than the expected expression alignment.
11900 CompleteObjectAlignment < ExpectedAlignment) {
11901 // If this happens, we want to determine a sensible culprit of this.
11902 // Intuitively, watching the chain of member expressions from right to
11903 // left, we start with the required alignment (as required by the field
11904 // type) but some packed attribute in that chain has reduced the alignment.
11905 // It may happen that another packed structure increases it again. But if
11906 // we are here such increase has not been enough. So pointing the first
11907 // FieldDecl that either is packed or else its RecordDecl is,
11908 // seems reasonable.
11909 FieldDecl *FD = nullptr;
11910 CharUnits Alignment;
11911 for (FieldDecl *FDI : ReverseMemberChain) {
11912 if (FDI->hasAttr<PackedAttr>() ||
11913 FDI->getParent()->hasAttr<PackedAttr>()) {
11915 Alignment = std::min(
11916 Context.getTypeAlignInChars(FD->getType()),
11917 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
11921 assert(FD && "We did not find a packed FieldDecl!");
11922 Action(E, FD->getParent(), FD, Alignment);
11926 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
11927 using namespace std::placeholders;
11928 RefersToMemberWithReducedAlignment(
11929 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,