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 ||
1246 Arch == llvm::Triple::aarch64_be;
1248 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1250 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
1252 EltTy = EltTy.withConst();
1253 QualType LHSTy = Context.getPointerType(EltTy);
1254 AssignConvertType ConvTy;
1255 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1256 if (RHS.isInvalid())
1258 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1259 RHS.get(), AA_Assigning))
1263 // For NEON intrinsics which take an immediate value as part of the
1264 // instruction, range check them here.
1265 unsigned i = 0, l = 0, u = 0;
1266 switch (BuiltinID) {
1269 #define GET_NEON_IMMEDIATE_CHECK
1270 #include "clang/Basic/arm_neon.inc"
1271 #undef GET_NEON_IMMEDIATE_CHECK
1274 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1277 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1278 unsigned MaxWidth) {
1279 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
1280 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1281 BuiltinID == ARM::BI__builtin_arm_strex ||
1282 BuiltinID == ARM::BI__builtin_arm_stlex ||
1283 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1284 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1285 BuiltinID == AArch64::BI__builtin_arm_strex ||
1286 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
1287 "unexpected ARM builtin");
1288 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
1289 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1290 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1291 BuiltinID == AArch64::BI__builtin_arm_ldaex;
1293 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1295 // Ensure that we have the proper number of arguments.
1296 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1299 // Inspect the pointer argument of the atomic builtin. This should always be
1300 // a pointer type, whose element is an integral scalar or pointer type.
1301 // Because it is a pointer type, we don't have to worry about any implicit
1303 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1304 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1305 if (PointerArgRes.isInvalid())
1307 PointerArg = PointerArgRes.get();
1309 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1311 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1312 << PointerArg->getType() << PointerArg->getSourceRange();
1316 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1317 // task is to insert the appropriate casts into the AST. First work out just
1318 // what the appropriate type is.
1319 QualType ValType = pointerType->getPointeeType();
1320 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1322 AddrType.addConst();
1324 // Issue a warning if the cast is dodgy.
1325 CastKind CastNeeded = CK_NoOp;
1326 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1327 CastNeeded = CK_BitCast;
1328 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1329 << PointerArg->getType()
1330 << Context.getPointerType(AddrType)
1331 << AA_Passing << PointerArg->getSourceRange();
1334 // Finally, do the cast and replace the argument with the corrected version.
1335 AddrType = Context.getPointerType(AddrType);
1336 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1337 if (PointerArgRes.isInvalid())
1339 PointerArg = PointerArgRes.get();
1341 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1343 // In general, we allow ints, floats and pointers to be loaded and stored.
1344 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1345 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1346 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1347 << PointerArg->getType() << PointerArg->getSourceRange();
1351 // But ARM doesn't have instructions to deal with 128-bit versions.
1352 if (Context.getTypeSize(ValType) > MaxWidth) {
1353 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
1354 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1355 << PointerArg->getType() << PointerArg->getSourceRange();
1359 switch (ValType.getObjCLifetime()) {
1360 case Qualifiers::OCL_None:
1361 case Qualifiers::OCL_ExplicitNone:
1365 case Qualifiers::OCL_Weak:
1366 case Qualifiers::OCL_Strong:
1367 case Qualifiers::OCL_Autoreleasing:
1368 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1369 << ValType << PointerArg->getSourceRange();
1374 TheCall->setType(ValType);
1378 // Initialize the argument to be stored.
1379 ExprResult ValArg = TheCall->getArg(0);
1380 InitializedEntity Entity = InitializedEntity::InitializeParameter(
1381 Context, ValType, /*consume*/ false);
1382 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1383 if (ValArg.isInvalid())
1385 TheCall->setArg(0, ValArg.get());
1387 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1388 // but the custom checker bypasses all default analysis.
1389 TheCall->setType(Context.IntTy);
1393 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1394 llvm::APSInt Result;
1396 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
1397 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1398 BuiltinID == ARM::BI__builtin_arm_strex ||
1399 BuiltinID == ARM::BI__builtin_arm_stlex) {
1400 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
1403 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1404 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1405 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1408 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1409 BuiltinID == ARM::BI__builtin_arm_wsr64)
1410 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1412 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1413 BuiltinID == ARM::BI__builtin_arm_rsrp ||
1414 BuiltinID == ARM::BI__builtin_arm_wsr ||
1415 BuiltinID == ARM::BI__builtin_arm_wsrp)
1416 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1418 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1421 // For intrinsics which take an immediate value as part of the instruction,
1422 // range check them here.
1423 unsigned i = 0, l = 0, u = 0;
1424 switch (BuiltinID) {
1425 default: return false;
1426 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
1427 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
1428 case ARM::BI__builtin_arm_vcvtr_f:
1429 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
1430 case ARM::BI__builtin_arm_dmb:
1431 case ARM::BI__builtin_arm_dsb:
1432 case ARM::BI__builtin_arm_isb:
1433 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
1436 // FIXME: VFP Intrinsics should error if VFP not present.
1437 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1440 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
1441 CallExpr *TheCall) {
1442 llvm::APSInt Result;
1444 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1445 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1446 BuiltinID == AArch64::BI__builtin_arm_strex ||
1447 BuiltinID == AArch64::BI__builtin_arm_stlex) {
1448 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1451 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1452 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1453 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1454 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1455 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1458 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1459 BuiltinID == AArch64::BI__builtin_arm_wsr64)
1460 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1462 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1463 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1464 BuiltinID == AArch64::BI__builtin_arm_wsr ||
1465 BuiltinID == AArch64::BI__builtin_arm_wsrp)
1466 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1468 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1471 // For intrinsics which take an immediate value as part of the instruction,
1472 // range check them here.
1473 unsigned i = 0, l = 0, u = 0;
1474 switch (BuiltinID) {
1475 default: return false;
1476 case AArch64::BI__builtin_arm_dmb:
1477 case AArch64::BI__builtin_arm_dsb:
1478 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1481 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1484 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
1485 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
1486 // ordering for DSP is unspecified. MSA is ordered by the data format used
1487 // by the underlying instruction i.e., df/m, df/n and then by size.
1489 // FIXME: The size tests here should instead be tablegen'd along with the
1490 // definitions from include/clang/Basic/BuiltinsMips.def.
1491 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
1493 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1494 unsigned i = 0, l = 0, u = 0, m = 0;
1495 switch (BuiltinID) {
1496 default: return false;
1497 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1498 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
1499 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1500 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1501 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1502 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1503 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
1504 // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
1506 // These intrinsics take an unsigned 3 bit immediate.
1507 case Mips::BI__builtin_msa_bclri_b:
1508 case Mips::BI__builtin_msa_bnegi_b:
1509 case Mips::BI__builtin_msa_bseti_b:
1510 case Mips::BI__builtin_msa_sat_s_b:
1511 case Mips::BI__builtin_msa_sat_u_b:
1512 case Mips::BI__builtin_msa_slli_b:
1513 case Mips::BI__builtin_msa_srai_b:
1514 case Mips::BI__builtin_msa_srari_b:
1515 case Mips::BI__builtin_msa_srli_b:
1516 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
1517 case Mips::BI__builtin_msa_binsli_b:
1518 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
1519 // These intrinsics take an unsigned 4 bit immediate.
1520 case Mips::BI__builtin_msa_bclri_h:
1521 case Mips::BI__builtin_msa_bnegi_h:
1522 case Mips::BI__builtin_msa_bseti_h:
1523 case Mips::BI__builtin_msa_sat_s_h:
1524 case Mips::BI__builtin_msa_sat_u_h:
1525 case Mips::BI__builtin_msa_slli_h:
1526 case Mips::BI__builtin_msa_srai_h:
1527 case Mips::BI__builtin_msa_srari_h:
1528 case Mips::BI__builtin_msa_srli_h:
1529 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
1530 case Mips::BI__builtin_msa_binsli_h:
1531 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
1532 // These intrinsics take an unsigned 5 bit immedate.
1533 // The first block of intrinsics actually have an unsigned 5 bit field,
1534 // not a df/n field.
1535 case Mips::BI__builtin_msa_clei_u_b:
1536 case Mips::BI__builtin_msa_clei_u_h:
1537 case Mips::BI__builtin_msa_clei_u_w:
1538 case Mips::BI__builtin_msa_clei_u_d:
1539 case Mips::BI__builtin_msa_clti_u_b:
1540 case Mips::BI__builtin_msa_clti_u_h:
1541 case Mips::BI__builtin_msa_clti_u_w:
1542 case Mips::BI__builtin_msa_clti_u_d:
1543 case Mips::BI__builtin_msa_maxi_u_b:
1544 case Mips::BI__builtin_msa_maxi_u_h:
1545 case Mips::BI__builtin_msa_maxi_u_w:
1546 case Mips::BI__builtin_msa_maxi_u_d:
1547 case Mips::BI__builtin_msa_mini_u_b:
1548 case Mips::BI__builtin_msa_mini_u_h:
1549 case Mips::BI__builtin_msa_mini_u_w:
1550 case Mips::BI__builtin_msa_mini_u_d:
1551 case Mips::BI__builtin_msa_addvi_b:
1552 case Mips::BI__builtin_msa_addvi_h:
1553 case Mips::BI__builtin_msa_addvi_w:
1554 case Mips::BI__builtin_msa_addvi_d:
1555 case Mips::BI__builtin_msa_bclri_w:
1556 case Mips::BI__builtin_msa_bnegi_w:
1557 case Mips::BI__builtin_msa_bseti_w:
1558 case Mips::BI__builtin_msa_sat_s_w:
1559 case Mips::BI__builtin_msa_sat_u_w:
1560 case Mips::BI__builtin_msa_slli_w:
1561 case Mips::BI__builtin_msa_srai_w:
1562 case Mips::BI__builtin_msa_srari_w:
1563 case Mips::BI__builtin_msa_srli_w:
1564 case Mips::BI__builtin_msa_srlri_w:
1565 case Mips::BI__builtin_msa_subvi_b:
1566 case Mips::BI__builtin_msa_subvi_h:
1567 case Mips::BI__builtin_msa_subvi_w:
1568 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
1569 case Mips::BI__builtin_msa_binsli_w:
1570 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
1571 // These intrinsics take an unsigned 6 bit immediate.
1572 case Mips::BI__builtin_msa_bclri_d:
1573 case Mips::BI__builtin_msa_bnegi_d:
1574 case Mips::BI__builtin_msa_bseti_d:
1575 case Mips::BI__builtin_msa_sat_s_d:
1576 case Mips::BI__builtin_msa_sat_u_d:
1577 case Mips::BI__builtin_msa_slli_d:
1578 case Mips::BI__builtin_msa_srai_d:
1579 case Mips::BI__builtin_msa_srari_d:
1580 case Mips::BI__builtin_msa_srli_d:
1581 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
1582 case Mips::BI__builtin_msa_binsli_d:
1583 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
1584 // These intrinsics take a signed 5 bit immediate.
1585 case Mips::BI__builtin_msa_ceqi_b:
1586 case Mips::BI__builtin_msa_ceqi_h:
1587 case Mips::BI__builtin_msa_ceqi_w:
1588 case Mips::BI__builtin_msa_ceqi_d:
1589 case Mips::BI__builtin_msa_clti_s_b:
1590 case Mips::BI__builtin_msa_clti_s_h:
1591 case Mips::BI__builtin_msa_clti_s_w:
1592 case Mips::BI__builtin_msa_clti_s_d:
1593 case Mips::BI__builtin_msa_clei_s_b:
1594 case Mips::BI__builtin_msa_clei_s_h:
1595 case Mips::BI__builtin_msa_clei_s_w:
1596 case Mips::BI__builtin_msa_clei_s_d:
1597 case Mips::BI__builtin_msa_maxi_s_b:
1598 case Mips::BI__builtin_msa_maxi_s_h:
1599 case Mips::BI__builtin_msa_maxi_s_w:
1600 case Mips::BI__builtin_msa_maxi_s_d:
1601 case Mips::BI__builtin_msa_mini_s_b:
1602 case Mips::BI__builtin_msa_mini_s_h:
1603 case Mips::BI__builtin_msa_mini_s_w:
1604 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
1605 // These intrinsics take an unsigned 8 bit immediate.
1606 case Mips::BI__builtin_msa_andi_b:
1607 case Mips::BI__builtin_msa_nori_b:
1608 case Mips::BI__builtin_msa_ori_b:
1609 case Mips::BI__builtin_msa_shf_b:
1610 case Mips::BI__builtin_msa_shf_h:
1611 case Mips::BI__builtin_msa_shf_w:
1612 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
1613 case Mips::BI__builtin_msa_bseli_b:
1614 case Mips::BI__builtin_msa_bmnzi_b:
1615 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
1617 // These intrinsics take an unsigned 4 bit immediate.
1618 case Mips::BI__builtin_msa_copy_s_b:
1619 case Mips::BI__builtin_msa_copy_u_b:
1620 case Mips::BI__builtin_msa_insve_b:
1621 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
1622 case Mips::BI__builtin_msa_sld_b:
1623 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
1624 // These intrinsics take an unsigned 3 bit immediate.
1625 case Mips::BI__builtin_msa_copy_s_h:
1626 case Mips::BI__builtin_msa_copy_u_h:
1627 case Mips::BI__builtin_msa_insve_h:
1628 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
1629 case Mips::BI__builtin_msa_sld_h:
1630 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
1631 // These intrinsics take an unsigned 2 bit immediate.
1632 case Mips::BI__builtin_msa_copy_s_w:
1633 case Mips::BI__builtin_msa_copy_u_w:
1634 case Mips::BI__builtin_msa_insve_w:
1635 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
1636 case Mips::BI__builtin_msa_sld_w:
1637 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
1638 // These intrinsics take an unsigned 1 bit immediate.
1639 case Mips::BI__builtin_msa_copy_s_d:
1640 case Mips::BI__builtin_msa_copy_u_d:
1641 case Mips::BI__builtin_msa_insve_d:
1642 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
1643 case Mips::BI__builtin_msa_sld_d:
1644 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
1645 // Memory offsets and immediate loads.
1646 // These intrinsics take a signed 10 bit immediate.
1647 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 127; break;
1648 case Mips::BI__builtin_msa_ldi_h:
1649 case Mips::BI__builtin_msa_ldi_w:
1650 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
1651 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
1652 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
1653 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
1654 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
1655 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
1656 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
1657 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
1658 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
1662 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1664 return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
1665 SemaBuiltinConstantArgMultiple(TheCall, i, m);
1668 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1669 unsigned i = 0, l = 0, u = 0;
1670 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1671 BuiltinID == PPC::BI__builtin_divdeu ||
1672 BuiltinID == PPC::BI__builtin_bpermd;
1673 bool IsTarget64Bit = Context.getTargetInfo()
1674 .getTypeWidth(Context
1676 .getIntPtrType()) == 64;
1677 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1678 BuiltinID == PPC::BI__builtin_divweu ||
1679 BuiltinID == PPC::BI__builtin_divde ||
1680 BuiltinID == PPC::BI__builtin_divdeu;
1682 if (Is64BitBltin && !IsTarget64Bit)
1683 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1684 << TheCall->getSourceRange();
1686 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1687 (BuiltinID == PPC::BI__builtin_bpermd &&
1688 !Context.getTargetInfo().hasFeature("bpermd")))
1689 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1690 << TheCall->getSourceRange();
1692 switch (BuiltinID) {
1693 default: return false;
1694 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1695 case PPC::BI__builtin_altivec_crypto_vshasigmad:
1696 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1697 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1698 case PPC::BI__builtin_tbegin:
1699 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1700 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1701 case PPC::BI__builtin_tabortwc:
1702 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1703 case PPC::BI__builtin_tabortwci:
1704 case PPC::BI__builtin_tabortdci:
1705 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1706 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
1708 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1711 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1712 CallExpr *TheCall) {
1713 if (BuiltinID == SystemZ::BI__builtin_tabort) {
1714 Expr *Arg = TheCall->getArg(0);
1715 llvm::APSInt AbortCode(32);
1716 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1717 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1718 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1719 << Arg->getSourceRange();
1722 // For intrinsics which take an immediate value as part of the instruction,
1723 // range check them here.
1724 unsigned i = 0, l = 0, u = 0;
1725 switch (BuiltinID) {
1726 default: return false;
1727 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1728 case SystemZ::BI__builtin_s390_verimb:
1729 case SystemZ::BI__builtin_s390_verimh:
1730 case SystemZ::BI__builtin_s390_verimf:
1731 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1732 case SystemZ::BI__builtin_s390_vfaeb:
1733 case SystemZ::BI__builtin_s390_vfaeh:
1734 case SystemZ::BI__builtin_s390_vfaef:
1735 case SystemZ::BI__builtin_s390_vfaebs:
1736 case SystemZ::BI__builtin_s390_vfaehs:
1737 case SystemZ::BI__builtin_s390_vfaefs:
1738 case SystemZ::BI__builtin_s390_vfaezb:
1739 case SystemZ::BI__builtin_s390_vfaezh:
1740 case SystemZ::BI__builtin_s390_vfaezf:
1741 case SystemZ::BI__builtin_s390_vfaezbs:
1742 case SystemZ::BI__builtin_s390_vfaezhs:
1743 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1744 case SystemZ::BI__builtin_s390_vfidb:
1745 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1746 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1747 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1748 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1749 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1750 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1751 case SystemZ::BI__builtin_s390_vstrcb:
1752 case SystemZ::BI__builtin_s390_vstrch:
1753 case SystemZ::BI__builtin_s390_vstrcf:
1754 case SystemZ::BI__builtin_s390_vstrczb:
1755 case SystemZ::BI__builtin_s390_vstrczh:
1756 case SystemZ::BI__builtin_s390_vstrczf:
1757 case SystemZ::BI__builtin_s390_vstrcbs:
1758 case SystemZ::BI__builtin_s390_vstrchs:
1759 case SystemZ::BI__builtin_s390_vstrcfs:
1760 case SystemZ::BI__builtin_s390_vstrczbs:
1761 case SystemZ::BI__builtin_s390_vstrczhs:
1762 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1764 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1767 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1768 /// This checks that the target supports __builtin_cpu_supports and
1769 /// that the string argument is constant and valid.
1770 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1771 Expr *Arg = TheCall->getArg(0);
1773 // Check if the argument is a string literal.
1774 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1775 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1776 << Arg->getSourceRange();
1778 // Check the contents of the string.
1780 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1781 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1782 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1783 << Arg->getSourceRange();
1787 // Check if the rounding mode is legal.
1788 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
1789 // Indicates if this instruction has rounding control or just SAE.
1792 unsigned ArgNum = 0;
1793 switch (BuiltinID) {
1796 case X86::BI__builtin_ia32_vcvttsd2si32:
1797 case X86::BI__builtin_ia32_vcvttsd2si64:
1798 case X86::BI__builtin_ia32_vcvttsd2usi32:
1799 case X86::BI__builtin_ia32_vcvttsd2usi64:
1800 case X86::BI__builtin_ia32_vcvttss2si32:
1801 case X86::BI__builtin_ia32_vcvttss2si64:
1802 case X86::BI__builtin_ia32_vcvttss2usi32:
1803 case X86::BI__builtin_ia32_vcvttss2usi64:
1806 case X86::BI__builtin_ia32_cvtps2pd512_mask:
1807 case X86::BI__builtin_ia32_cvttpd2dq512_mask:
1808 case X86::BI__builtin_ia32_cvttpd2qq512_mask:
1809 case X86::BI__builtin_ia32_cvttpd2udq512_mask:
1810 case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
1811 case X86::BI__builtin_ia32_cvttps2dq512_mask:
1812 case X86::BI__builtin_ia32_cvttps2qq512_mask:
1813 case X86::BI__builtin_ia32_cvttps2udq512_mask:
1814 case X86::BI__builtin_ia32_cvttps2uqq512_mask:
1815 case X86::BI__builtin_ia32_exp2pd_mask:
1816 case X86::BI__builtin_ia32_exp2ps_mask:
1817 case X86::BI__builtin_ia32_getexppd512_mask:
1818 case X86::BI__builtin_ia32_getexpps512_mask:
1819 case X86::BI__builtin_ia32_rcp28pd_mask:
1820 case X86::BI__builtin_ia32_rcp28ps_mask:
1821 case X86::BI__builtin_ia32_rsqrt28pd_mask:
1822 case X86::BI__builtin_ia32_rsqrt28ps_mask:
1823 case X86::BI__builtin_ia32_vcomisd:
1824 case X86::BI__builtin_ia32_vcomiss:
1825 case X86::BI__builtin_ia32_vcvtph2ps512_mask:
1828 case X86::BI__builtin_ia32_cmppd512_mask:
1829 case X86::BI__builtin_ia32_cmpps512_mask:
1830 case X86::BI__builtin_ia32_cmpsd_mask:
1831 case X86::BI__builtin_ia32_cmpss_mask:
1832 case X86::BI__builtin_ia32_cvtss2sd_round_mask:
1833 case X86::BI__builtin_ia32_getexpsd128_round_mask:
1834 case X86::BI__builtin_ia32_getexpss128_round_mask:
1835 case X86::BI__builtin_ia32_maxpd512_mask:
1836 case X86::BI__builtin_ia32_maxps512_mask:
1837 case X86::BI__builtin_ia32_maxsd_round_mask:
1838 case X86::BI__builtin_ia32_maxss_round_mask:
1839 case X86::BI__builtin_ia32_minpd512_mask:
1840 case X86::BI__builtin_ia32_minps512_mask:
1841 case X86::BI__builtin_ia32_minsd_round_mask:
1842 case X86::BI__builtin_ia32_minss_round_mask:
1843 case X86::BI__builtin_ia32_rcp28sd_round_mask:
1844 case X86::BI__builtin_ia32_rcp28ss_round_mask:
1845 case X86::BI__builtin_ia32_reducepd512_mask:
1846 case X86::BI__builtin_ia32_reduceps512_mask:
1847 case X86::BI__builtin_ia32_rndscalepd_mask:
1848 case X86::BI__builtin_ia32_rndscaleps_mask:
1849 case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
1850 case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
1853 case X86::BI__builtin_ia32_fixupimmpd512_mask:
1854 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
1855 case X86::BI__builtin_ia32_fixupimmps512_mask:
1856 case X86::BI__builtin_ia32_fixupimmps512_maskz:
1857 case X86::BI__builtin_ia32_fixupimmsd_mask:
1858 case X86::BI__builtin_ia32_fixupimmsd_maskz:
1859 case X86::BI__builtin_ia32_fixupimmss_mask:
1860 case X86::BI__builtin_ia32_fixupimmss_maskz:
1861 case X86::BI__builtin_ia32_rangepd512_mask:
1862 case X86::BI__builtin_ia32_rangeps512_mask:
1863 case X86::BI__builtin_ia32_rangesd128_round_mask:
1864 case X86::BI__builtin_ia32_rangess128_round_mask:
1865 case X86::BI__builtin_ia32_reducesd_mask:
1866 case X86::BI__builtin_ia32_reducess_mask:
1867 case X86::BI__builtin_ia32_rndscalesd_round_mask:
1868 case X86::BI__builtin_ia32_rndscaless_round_mask:
1871 case X86::BI__builtin_ia32_vcvtsd2si64:
1872 case X86::BI__builtin_ia32_vcvtsd2si32:
1873 case X86::BI__builtin_ia32_vcvtsd2usi32:
1874 case X86::BI__builtin_ia32_vcvtsd2usi64:
1875 case X86::BI__builtin_ia32_vcvtss2si32:
1876 case X86::BI__builtin_ia32_vcvtss2si64:
1877 case X86::BI__builtin_ia32_vcvtss2usi32:
1878 case X86::BI__builtin_ia32_vcvtss2usi64:
1882 case X86::BI__builtin_ia32_cvtsi2sd64:
1883 case X86::BI__builtin_ia32_cvtsi2ss32:
1884 case X86::BI__builtin_ia32_cvtsi2ss64:
1885 case X86::BI__builtin_ia32_cvtusi2sd64:
1886 case X86::BI__builtin_ia32_cvtusi2ss32:
1887 case X86::BI__builtin_ia32_cvtusi2ss64:
1891 case X86::BI__builtin_ia32_cvtdq2ps512_mask:
1892 case X86::BI__builtin_ia32_cvtudq2ps512_mask:
1893 case X86::BI__builtin_ia32_cvtpd2ps512_mask:
1894 case X86::BI__builtin_ia32_cvtpd2qq512_mask:
1895 case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
1896 case X86::BI__builtin_ia32_cvtps2qq512_mask:
1897 case X86::BI__builtin_ia32_cvtps2uqq512_mask:
1898 case X86::BI__builtin_ia32_cvtqq2pd512_mask:
1899 case X86::BI__builtin_ia32_cvtqq2ps512_mask:
1900 case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
1901 case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
1902 case X86::BI__builtin_ia32_sqrtpd512_mask:
1903 case X86::BI__builtin_ia32_sqrtps512_mask:
1907 case X86::BI__builtin_ia32_addpd512_mask:
1908 case X86::BI__builtin_ia32_addps512_mask:
1909 case X86::BI__builtin_ia32_divpd512_mask:
1910 case X86::BI__builtin_ia32_divps512_mask:
1911 case X86::BI__builtin_ia32_mulpd512_mask:
1912 case X86::BI__builtin_ia32_mulps512_mask:
1913 case X86::BI__builtin_ia32_subpd512_mask:
1914 case X86::BI__builtin_ia32_subps512_mask:
1915 case X86::BI__builtin_ia32_addss_round_mask:
1916 case X86::BI__builtin_ia32_addsd_round_mask:
1917 case X86::BI__builtin_ia32_divss_round_mask:
1918 case X86::BI__builtin_ia32_divsd_round_mask:
1919 case X86::BI__builtin_ia32_mulss_round_mask:
1920 case X86::BI__builtin_ia32_mulsd_round_mask:
1921 case X86::BI__builtin_ia32_subss_round_mask:
1922 case X86::BI__builtin_ia32_subsd_round_mask:
1923 case X86::BI__builtin_ia32_scalefpd512_mask:
1924 case X86::BI__builtin_ia32_scalefps512_mask:
1925 case X86::BI__builtin_ia32_scalefsd_round_mask:
1926 case X86::BI__builtin_ia32_scalefss_round_mask:
1927 case X86::BI__builtin_ia32_getmantpd512_mask:
1928 case X86::BI__builtin_ia32_getmantps512_mask:
1929 case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
1930 case X86::BI__builtin_ia32_sqrtsd_round_mask:
1931 case X86::BI__builtin_ia32_sqrtss_round_mask:
1932 case X86::BI__builtin_ia32_vfmaddpd512_mask:
1933 case X86::BI__builtin_ia32_vfmaddpd512_mask3:
1934 case X86::BI__builtin_ia32_vfmaddpd512_maskz:
1935 case X86::BI__builtin_ia32_vfmaddps512_mask:
1936 case X86::BI__builtin_ia32_vfmaddps512_mask3:
1937 case X86::BI__builtin_ia32_vfmaddps512_maskz:
1938 case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
1939 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
1940 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
1941 case X86::BI__builtin_ia32_vfmaddsubps512_mask:
1942 case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
1943 case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
1944 case X86::BI__builtin_ia32_vfmsubpd512_mask3:
1945 case X86::BI__builtin_ia32_vfmsubps512_mask3:
1946 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
1947 case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
1948 case X86::BI__builtin_ia32_vfnmaddpd512_mask:
1949 case X86::BI__builtin_ia32_vfnmaddps512_mask:
1950 case X86::BI__builtin_ia32_vfnmsubpd512_mask:
1951 case X86::BI__builtin_ia32_vfnmsubpd512_mask3:
1952 case X86::BI__builtin_ia32_vfnmsubps512_mask:
1953 case X86::BI__builtin_ia32_vfnmsubps512_mask3:
1954 case X86::BI__builtin_ia32_vfmaddsd3_mask:
1955 case X86::BI__builtin_ia32_vfmaddsd3_maskz:
1956 case X86::BI__builtin_ia32_vfmaddsd3_mask3:
1957 case X86::BI__builtin_ia32_vfmaddss3_mask:
1958 case X86::BI__builtin_ia32_vfmaddss3_maskz:
1959 case X86::BI__builtin_ia32_vfmaddss3_mask3:
1963 case X86::BI__builtin_ia32_getmantsd_round_mask:
1964 case X86::BI__builtin_ia32_getmantss_round_mask:
1970 llvm::APSInt Result;
1972 // We can't check the value of a dependent argument.
1973 Expr *Arg = TheCall->getArg(ArgNum);
1974 if (Arg->isTypeDependent() || Arg->isValueDependent())
1977 // Check constant-ness first.
1978 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
1981 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
1982 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
1983 // combined with ROUND_NO_EXC.
1984 if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
1985 Result == 8/*ROUND_NO_EXC*/ ||
1986 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
1989 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
1990 << Arg->getSourceRange();
1993 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1994 if (BuiltinID == X86::BI__builtin_cpu_supports)
1995 return SemaBuiltinCpuSupports(*this, TheCall);
1997 if (BuiltinID == X86::BI__builtin_ms_va_start)
1998 return SemaBuiltinMSVAStart(TheCall);
2000 // If the intrinsic has rounding or SAE make sure its valid.
2001 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
2004 // For intrinsics which take an immediate value as part of the instruction,
2005 // range check them here.
2006 int i = 0, l = 0, u = 0;
2007 switch (BuiltinID) {
2010 case X86::BI_mm_prefetch:
2011 i = 1; l = 0; u = 3;
2013 case X86::BI__builtin_ia32_sha1rnds4:
2014 case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
2015 case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
2016 case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
2017 case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
2018 i = 2; l = 0; u = 3;
2020 case X86::BI__builtin_ia32_vpermil2pd:
2021 case X86::BI__builtin_ia32_vpermil2pd256:
2022 case X86::BI__builtin_ia32_vpermil2ps:
2023 case X86::BI__builtin_ia32_vpermil2ps256:
2024 i = 3; l = 0; u = 3;
2026 case X86::BI__builtin_ia32_cmpb128_mask:
2027 case X86::BI__builtin_ia32_cmpw128_mask:
2028 case X86::BI__builtin_ia32_cmpd128_mask:
2029 case X86::BI__builtin_ia32_cmpq128_mask:
2030 case X86::BI__builtin_ia32_cmpb256_mask:
2031 case X86::BI__builtin_ia32_cmpw256_mask:
2032 case X86::BI__builtin_ia32_cmpd256_mask:
2033 case X86::BI__builtin_ia32_cmpq256_mask:
2034 case X86::BI__builtin_ia32_cmpb512_mask:
2035 case X86::BI__builtin_ia32_cmpw512_mask:
2036 case X86::BI__builtin_ia32_cmpd512_mask:
2037 case X86::BI__builtin_ia32_cmpq512_mask:
2038 case X86::BI__builtin_ia32_ucmpb128_mask:
2039 case X86::BI__builtin_ia32_ucmpw128_mask:
2040 case X86::BI__builtin_ia32_ucmpd128_mask:
2041 case X86::BI__builtin_ia32_ucmpq128_mask:
2042 case X86::BI__builtin_ia32_ucmpb256_mask:
2043 case X86::BI__builtin_ia32_ucmpw256_mask:
2044 case X86::BI__builtin_ia32_ucmpd256_mask:
2045 case X86::BI__builtin_ia32_ucmpq256_mask:
2046 case X86::BI__builtin_ia32_ucmpb512_mask:
2047 case X86::BI__builtin_ia32_ucmpw512_mask:
2048 case X86::BI__builtin_ia32_ucmpd512_mask:
2049 case X86::BI__builtin_ia32_ucmpq512_mask:
2050 case X86::BI__builtin_ia32_vpcomub:
2051 case X86::BI__builtin_ia32_vpcomuw:
2052 case X86::BI__builtin_ia32_vpcomud:
2053 case X86::BI__builtin_ia32_vpcomuq:
2054 case X86::BI__builtin_ia32_vpcomb:
2055 case X86::BI__builtin_ia32_vpcomw:
2056 case X86::BI__builtin_ia32_vpcomd:
2057 case X86::BI__builtin_ia32_vpcomq:
2058 i = 2; l = 0; u = 7;
2060 case X86::BI__builtin_ia32_roundps:
2061 case X86::BI__builtin_ia32_roundpd:
2062 case X86::BI__builtin_ia32_roundps256:
2063 case X86::BI__builtin_ia32_roundpd256:
2064 i = 1; l = 0; u = 15;
2066 case X86::BI__builtin_ia32_roundss:
2067 case X86::BI__builtin_ia32_roundsd:
2068 case X86::BI__builtin_ia32_rangepd128_mask:
2069 case X86::BI__builtin_ia32_rangepd256_mask:
2070 case X86::BI__builtin_ia32_rangepd512_mask:
2071 case X86::BI__builtin_ia32_rangeps128_mask:
2072 case X86::BI__builtin_ia32_rangeps256_mask:
2073 case X86::BI__builtin_ia32_rangeps512_mask:
2074 case X86::BI__builtin_ia32_getmantsd_round_mask:
2075 case X86::BI__builtin_ia32_getmantss_round_mask:
2076 i = 2; l = 0; u = 15;
2078 case X86::BI__builtin_ia32_cmpps:
2079 case X86::BI__builtin_ia32_cmpss:
2080 case X86::BI__builtin_ia32_cmppd:
2081 case X86::BI__builtin_ia32_cmpsd:
2082 case X86::BI__builtin_ia32_cmpps256:
2083 case X86::BI__builtin_ia32_cmppd256:
2084 case X86::BI__builtin_ia32_cmpps128_mask:
2085 case X86::BI__builtin_ia32_cmppd128_mask:
2086 case X86::BI__builtin_ia32_cmpps256_mask:
2087 case X86::BI__builtin_ia32_cmppd256_mask:
2088 case X86::BI__builtin_ia32_cmpps512_mask:
2089 case X86::BI__builtin_ia32_cmppd512_mask:
2090 case X86::BI__builtin_ia32_cmpsd_mask:
2091 case X86::BI__builtin_ia32_cmpss_mask:
2092 i = 2; l = 0; u = 31;
2094 case X86::BI__builtin_ia32_xabort:
2095 i = 0; l = -128; u = 255;
2097 case X86::BI__builtin_ia32_pshufw:
2098 case X86::BI__builtin_ia32_aeskeygenassist128:
2099 i = 1; l = -128; u = 255;
2101 case X86::BI__builtin_ia32_vcvtps2ph:
2102 case X86::BI__builtin_ia32_vcvtps2ph256:
2103 case X86::BI__builtin_ia32_rndscaleps_128_mask:
2104 case X86::BI__builtin_ia32_rndscalepd_128_mask:
2105 case X86::BI__builtin_ia32_rndscaleps_256_mask:
2106 case X86::BI__builtin_ia32_rndscalepd_256_mask:
2107 case X86::BI__builtin_ia32_rndscaleps_mask:
2108 case X86::BI__builtin_ia32_rndscalepd_mask:
2109 case X86::BI__builtin_ia32_reducepd128_mask:
2110 case X86::BI__builtin_ia32_reducepd256_mask:
2111 case X86::BI__builtin_ia32_reducepd512_mask:
2112 case X86::BI__builtin_ia32_reduceps128_mask:
2113 case X86::BI__builtin_ia32_reduceps256_mask:
2114 case X86::BI__builtin_ia32_reduceps512_mask:
2115 case X86::BI__builtin_ia32_prold512_mask:
2116 case X86::BI__builtin_ia32_prolq512_mask:
2117 case X86::BI__builtin_ia32_prold128_mask:
2118 case X86::BI__builtin_ia32_prold256_mask:
2119 case X86::BI__builtin_ia32_prolq128_mask:
2120 case X86::BI__builtin_ia32_prolq256_mask:
2121 case X86::BI__builtin_ia32_prord128_mask:
2122 case X86::BI__builtin_ia32_prord256_mask:
2123 case X86::BI__builtin_ia32_prorq128_mask:
2124 case X86::BI__builtin_ia32_prorq256_mask:
2125 case X86::BI__builtin_ia32_fpclasspd128_mask:
2126 case X86::BI__builtin_ia32_fpclasspd256_mask:
2127 case X86::BI__builtin_ia32_fpclassps128_mask:
2128 case X86::BI__builtin_ia32_fpclassps256_mask:
2129 case X86::BI__builtin_ia32_fpclassps512_mask:
2130 case X86::BI__builtin_ia32_fpclasspd512_mask:
2131 case X86::BI__builtin_ia32_fpclasssd_mask:
2132 case X86::BI__builtin_ia32_fpclassss_mask:
2133 i = 1; l = 0; u = 255;
2135 case X86::BI__builtin_ia32_palignr:
2136 case X86::BI__builtin_ia32_insertps128:
2137 case X86::BI__builtin_ia32_dpps:
2138 case X86::BI__builtin_ia32_dppd:
2139 case X86::BI__builtin_ia32_dpps256:
2140 case X86::BI__builtin_ia32_mpsadbw128:
2141 case X86::BI__builtin_ia32_mpsadbw256:
2142 case X86::BI__builtin_ia32_pcmpistrm128:
2143 case X86::BI__builtin_ia32_pcmpistri128:
2144 case X86::BI__builtin_ia32_pcmpistria128:
2145 case X86::BI__builtin_ia32_pcmpistric128:
2146 case X86::BI__builtin_ia32_pcmpistrio128:
2147 case X86::BI__builtin_ia32_pcmpistris128:
2148 case X86::BI__builtin_ia32_pcmpistriz128:
2149 case X86::BI__builtin_ia32_pclmulqdq128:
2150 case X86::BI__builtin_ia32_vperm2f128_pd256:
2151 case X86::BI__builtin_ia32_vperm2f128_ps256:
2152 case X86::BI__builtin_ia32_vperm2f128_si256:
2153 case X86::BI__builtin_ia32_permti256:
2154 i = 2; l = -128; u = 255;
2156 case X86::BI__builtin_ia32_palignr128:
2157 case X86::BI__builtin_ia32_palignr256:
2158 case X86::BI__builtin_ia32_palignr512_mask:
2159 case X86::BI__builtin_ia32_vcomisd:
2160 case X86::BI__builtin_ia32_vcomiss:
2161 case X86::BI__builtin_ia32_shuf_f32x4_mask:
2162 case X86::BI__builtin_ia32_shuf_f64x2_mask:
2163 case X86::BI__builtin_ia32_shuf_i32x4_mask:
2164 case X86::BI__builtin_ia32_shuf_i64x2_mask:
2165 case X86::BI__builtin_ia32_dbpsadbw128_mask:
2166 case X86::BI__builtin_ia32_dbpsadbw256_mask:
2167 case X86::BI__builtin_ia32_dbpsadbw512_mask:
2168 i = 2; l = 0; u = 255;
2170 case X86::BI__builtin_ia32_fixupimmpd512_mask:
2171 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2172 case X86::BI__builtin_ia32_fixupimmps512_mask:
2173 case X86::BI__builtin_ia32_fixupimmps512_maskz:
2174 case X86::BI__builtin_ia32_fixupimmsd_mask:
2175 case X86::BI__builtin_ia32_fixupimmsd_maskz:
2176 case X86::BI__builtin_ia32_fixupimmss_mask:
2177 case X86::BI__builtin_ia32_fixupimmss_maskz:
2178 case X86::BI__builtin_ia32_fixupimmpd128_mask:
2179 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2180 case X86::BI__builtin_ia32_fixupimmpd256_mask:
2181 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2182 case X86::BI__builtin_ia32_fixupimmps128_mask:
2183 case X86::BI__builtin_ia32_fixupimmps128_maskz:
2184 case X86::BI__builtin_ia32_fixupimmps256_mask:
2185 case X86::BI__builtin_ia32_fixupimmps256_maskz:
2186 case X86::BI__builtin_ia32_pternlogd512_mask:
2187 case X86::BI__builtin_ia32_pternlogd512_maskz:
2188 case X86::BI__builtin_ia32_pternlogq512_mask:
2189 case X86::BI__builtin_ia32_pternlogq512_maskz:
2190 case X86::BI__builtin_ia32_pternlogd128_mask:
2191 case X86::BI__builtin_ia32_pternlogd128_maskz:
2192 case X86::BI__builtin_ia32_pternlogd256_mask:
2193 case X86::BI__builtin_ia32_pternlogd256_maskz:
2194 case X86::BI__builtin_ia32_pternlogq128_mask:
2195 case X86::BI__builtin_ia32_pternlogq128_maskz:
2196 case X86::BI__builtin_ia32_pternlogq256_mask:
2197 case X86::BI__builtin_ia32_pternlogq256_maskz:
2198 i = 3; l = 0; u = 255;
2200 case X86::BI__builtin_ia32_pcmpestrm128:
2201 case X86::BI__builtin_ia32_pcmpestri128:
2202 case X86::BI__builtin_ia32_pcmpestria128:
2203 case X86::BI__builtin_ia32_pcmpestric128:
2204 case X86::BI__builtin_ia32_pcmpestrio128:
2205 case X86::BI__builtin_ia32_pcmpestris128:
2206 case X86::BI__builtin_ia32_pcmpestriz128:
2207 i = 4; l = -128; u = 255;
2209 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2210 case X86::BI__builtin_ia32_rndscaless_round_mask:
2211 i = 4; l = 0; u = 255;
2214 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2217 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2218 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
2219 /// Returns true when the format fits the function and the FormatStringInfo has
2221 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2222 FormatStringInfo *FSI) {
2223 FSI->HasVAListArg = Format->getFirstArg() == 0;
2224 FSI->FormatIdx = Format->getFormatIdx() - 1;
2225 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
2227 // The way the format attribute works in GCC, the implicit this argument
2228 // of member functions is counted. However, it doesn't appear in our own
2229 // lists, so decrement format_idx in that case.
2231 if(FSI->FormatIdx == 0)
2234 if (FSI->FirstDataArg != 0)
2235 --FSI->FirstDataArg;
2240 /// Checks if a the given expression evaluates to null.
2242 /// \brief Returns true if the value evaluates to null.
2243 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
2244 // If the expression has non-null type, it doesn't evaluate to null.
2245 if (auto nullability
2246 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2247 if (*nullability == NullabilityKind::NonNull)
2251 // As a special case, transparent unions initialized with zero are
2252 // considered null for the purposes of the nonnull attribute.
2253 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
2254 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2255 if (const CompoundLiteralExpr *CLE =
2256 dyn_cast<CompoundLiteralExpr>(Expr))
2257 if (const InitListExpr *ILE =
2258 dyn_cast<InitListExpr>(CLE->getInitializer()))
2259 Expr = ILE->getInit(0);
2263 return (!Expr->isValueDependent() &&
2264 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2268 static void CheckNonNullArgument(Sema &S,
2269 const Expr *ArgExpr,
2270 SourceLocation CallSiteLoc) {
2271 if (CheckNonNullExpr(S, ArgExpr))
2272 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2273 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
2276 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2277 FormatStringInfo FSI;
2278 if ((GetFormatStringType(Format) == FST_NSString) &&
2279 getFormatStringInfo(Format, false, &FSI)) {
2280 Idx = FSI.FormatIdx;
2285 /// \brief Diagnose use of %s directive in an NSString which is being passed
2286 /// as formatting string to formatting method.
2288 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
2289 const NamedDecl *FDecl,
2293 bool Format = false;
2294 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2295 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
2300 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2301 if (S.GetFormatNSStringIdx(I, Idx)) {
2306 if (!Format || NumArgs <= Idx)
2308 const Expr *FormatExpr = Args[Idx];
2309 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2310 FormatExpr = CSCE->getSubExpr();
2311 const StringLiteral *FormatString;
2312 if (const ObjCStringLiteral *OSL =
2313 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2314 FormatString = OSL->getString();
2316 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2319 if (S.FormatStringHasSArg(FormatString)) {
2320 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2322 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2323 << FDecl->getDeclName();
2327 /// Determine whether the given type has a non-null nullability annotation.
2328 static bool isNonNullType(ASTContext &ctx, QualType type) {
2329 if (auto nullability = type->getNullability(ctx))
2330 return *nullability == NullabilityKind::NonNull;
2335 static void CheckNonNullArguments(Sema &S,
2336 const NamedDecl *FDecl,
2337 const FunctionProtoType *Proto,
2338 ArrayRef<const Expr *> Args,
2339 SourceLocation CallSiteLoc) {
2340 assert((FDecl || Proto) && "Need a function declaration or prototype");
2342 // Check the attributes attached to the method/function itself.
2343 llvm::SmallBitVector NonNullArgs;
2345 // Handle the nonnull attribute on the function/method declaration itself.
2346 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2347 if (!NonNull->args_size()) {
2348 // Easy case: all pointer arguments are nonnull.
2349 for (const auto *Arg : Args)
2350 if (S.isValidPointerAttrType(Arg->getType()))
2351 CheckNonNullArgument(S, Arg, CallSiteLoc);
2355 for (unsigned Val : NonNull->args()) {
2356 if (Val >= Args.size())
2358 if (NonNullArgs.empty())
2359 NonNullArgs.resize(Args.size());
2360 NonNullArgs.set(Val);
2365 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2366 // Handle the nonnull attribute on the parameters of the
2368 ArrayRef<ParmVarDecl*> parms;
2369 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2370 parms = FD->parameters();
2372 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2374 unsigned ParamIndex = 0;
2375 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2376 I != E; ++I, ++ParamIndex) {
2377 const ParmVarDecl *PVD = *I;
2378 if (PVD->hasAttr<NonNullAttr>() ||
2379 isNonNullType(S.Context, PVD->getType())) {
2380 if (NonNullArgs.empty())
2381 NonNullArgs.resize(Args.size());
2383 NonNullArgs.set(ParamIndex);
2387 // If we have a non-function, non-method declaration but no
2388 // function prototype, try to dig out the function prototype.
2390 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2391 QualType type = VD->getType().getNonReferenceType();
2392 if (auto pointerType = type->getAs<PointerType>())
2393 type = pointerType->getPointeeType();
2394 else if (auto blockType = type->getAs<BlockPointerType>())
2395 type = blockType->getPointeeType();
2396 // FIXME: data member pointers?
2398 // Dig out the function prototype, if there is one.
2399 Proto = type->getAs<FunctionProtoType>();
2403 // Fill in non-null argument information from the nullability
2404 // information on the parameter types (if we have them).
2407 for (auto paramType : Proto->getParamTypes()) {
2408 if (isNonNullType(S.Context, paramType)) {
2409 if (NonNullArgs.empty())
2410 NonNullArgs.resize(Args.size());
2412 NonNullArgs.set(Index);
2420 // Check for non-null arguments.
2421 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2422 ArgIndex != ArgIndexEnd; ++ArgIndex) {
2423 if (NonNullArgs[ArgIndex])
2424 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
2428 /// Handles the checks for format strings, non-POD arguments to vararg
2429 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
2431 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
2432 const Expr *ThisArg, ArrayRef<const Expr *> Args,
2433 bool IsMemberFunction, SourceLocation Loc,
2434 SourceRange Range, VariadicCallType CallType) {
2435 // FIXME: We should check as much as we can in the template definition.
2436 if (CurContext->isDependentContext())
2439 // Printf and scanf checking.
2440 llvm::SmallBitVector CheckedVarArgs;
2442 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2443 // Only create vector if there are format attributes.
2444 CheckedVarArgs.resize(Args.size());
2446 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
2451 // Refuse POD arguments that weren't caught by the format string
2453 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
2454 if (CallType != VariadicDoesNotApply &&
2455 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
2456 unsigned NumParams = Proto ? Proto->getNumParams()
2457 : FDecl && isa<FunctionDecl>(FDecl)
2458 ? cast<FunctionDecl>(FDecl)->getNumParams()
2459 : FDecl && isa<ObjCMethodDecl>(FDecl)
2460 ? cast<ObjCMethodDecl>(FDecl)->param_size()
2463 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
2464 // Args[ArgIdx] can be null in malformed code.
2465 if (const Expr *Arg = Args[ArgIdx]) {
2466 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
2467 checkVariadicArgument(Arg, CallType);
2472 if (FDecl || Proto) {
2473 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
2475 // Type safety checking.
2477 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
2478 CheckArgumentWithTypeTag(I, Args.data());
2483 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
2486 /// CheckConstructorCall - Check a constructor call for correctness and safety
2487 /// properties not enforced by the C type system.
2488 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
2489 ArrayRef<const Expr *> Args,
2490 const FunctionProtoType *Proto,
2491 SourceLocation Loc) {
2492 VariadicCallType CallType =
2493 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
2494 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
2495 Loc, SourceRange(), CallType);
2498 /// CheckFunctionCall - Check a direct function call for various correctness
2499 /// and safety properties not strictly enforced by the C type system.
2500 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2501 const FunctionProtoType *Proto) {
2502 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2503 isa<CXXMethodDecl>(FDecl);
2504 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2505 IsMemberOperatorCall;
2506 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2507 TheCall->getCallee());
2508 Expr** Args = TheCall->getArgs();
2509 unsigned NumArgs = TheCall->getNumArgs();
2511 Expr *ImplicitThis = nullptr;
2512 if (IsMemberOperatorCall) {
2513 // If this is a call to a member operator, hide the first argument
2515 // FIXME: Our choice of AST representation here is less than ideal.
2516 ImplicitThis = Args[0];
2519 } else if (IsMemberFunction)
2521 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
2523 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
2524 IsMemberFunction, TheCall->getRParenLoc(),
2525 TheCall->getCallee()->getSourceRange(), CallType);
2527 IdentifierInfo *FnInfo = FDecl->getIdentifier();
2528 // None of the checks below are needed for functions that don't have
2529 // simple names (e.g., C++ conversion functions).
2533 CheckAbsoluteValueFunction(TheCall, FDecl);
2534 CheckMaxUnsignedZero(TheCall, FDecl);
2536 if (getLangOpts().ObjC1)
2537 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
2539 unsigned CMId = FDecl->getMemoryFunctionKind();
2543 // Handle memory setting and copying functions.
2544 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
2545 CheckStrlcpycatArguments(TheCall, FnInfo);
2546 else if (CMId == Builtin::BIstrncat)
2547 CheckStrncatArguments(TheCall, FnInfo);
2549 CheckMemaccessArguments(TheCall, CMId, FnInfo);
2554 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
2555 ArrayRef<const Expr *> Args) {
2556 VariadicCallType CallType =
2557 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
2559 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
2560 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
2566 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2567 const FunctionProtoType *Proto) {
2569 if (const auto *V = dyn_cast<VarDecl>(NDecl))
2570 Ty = V->getType().getNonReferenceType();
2571 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
2572 Ty = F->getType().getNonReferenceType();
2576 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2577 !Ty->isFunctionProtoType())
2580 VariadicCallType CallType;
2581 if (!Proto || !Proto->isVariadic()) {
2582 CallType = VariadicDoesNotApply;
2583 } else if (Ty->isBlockPointerType()) {
2584 CallType = VariadicBlock;
2585 } else { // Ty->isFunctionPointerType()
2586 CallType = VariadicFunction;
2589 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
2590 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2591 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
2592 TheCall->getCallee()->getSourceRange(), CallType);
2597 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2598 /// such as function pointers returned from functions.
2599 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
2600 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
2601 TheCall->getCallee());
2602 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
2603 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2604 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
2605 TheCall->getCallee()->getSourceRange(), CallType);
2610 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
2611 if (!llvm::isValidAtomicOrderingCABI(Ordering))
2614 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
2616 case AtomicExpr::AO__c11_atomic_init:
2617 llvm_unreachable("There is no ordering argument for an init");
2619 case AtomicExpr::AO__c11_atomic_load:
2620 case AtomicExpr::AO__atomic_load_n:
2621 case AtomicExpr::AO__atomic_load:
2622 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2623 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2625 case AtomicExpr::AO__c11_atomic_store:
2626 case AtomicExpr::AO__atomic_store:
2627 case AtomicExpr::AO__atomic_store_n:
2628 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2629 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2630 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2637 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2638 AtomicExpr::AtomicOp Op) {
2639 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2640 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2642 // All these operations take one of the following forms:
2644 // C __c11_atomic_init(A *, C)
2646 // C __c11_atomic_load(A *, int)
2648 // void __atomic_load(A *, CP, int)
2650 // void __atomic_store(A *, CP, int)
2652 // C __c11_atomic_add(A *, M, int)
2654 // C __atomic_exchange_n(A *, CP, int)
2656 // void __atomic_exchange(A *, C *, CP, int)
2658 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
2660 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
2663 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2664 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
2666 // C is an appropriate type,
2667 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
2668 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
2669 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
2670 // the int parameters are for orderings.
2672 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
2673 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
2674 AtomicExpr::AO__atomic_load,
2675 "need to update code for modified C11 atomics");
2676 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
2677 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
2678 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
2679 Op == AtomicExpr::AO__atomic_store_n ||
2680 Op == AtomicExpr::AO__atomic_exchange_n ||
2681 Op == AtomicExpr::AO__atomic_compare_exchange_n;
2682 bool IsAddSub = false;
2685 case AtomicExpr::AO__c11_atomic_init:
2689 case AtomicExpr::AO__c11_atomic_load:
2690 case AtomicExpr::AO__atomic_load_n:
2694 case AtomicExpr::AO__atomic_load:
2698 case AtomicExpr::AO__c11_atomic_store:
2699 case AtomicExpr::AO__atomic_store:
2700 case AtomicExpr::AO__atomic_store_n:
2704 case AtomicExpr::AO__c11_atomic_fetch_add:
2705 case AtomicExpr::AO__c11_atomic_fetch_sub:
2706 case AtomicExpr::AO__atomic_fetch_add:
2707 case AtomicExpr::AO__atomic_fetch_sub:
2708 case AtomicExpr::AO__atomic_add_fetch:
2709 case AtomicExpr::AO__atomic_sub_fetch:
2712 case AtomicExpr::AO__c11_atomic_fetch_and:
2713 case AtomicExpr::AO__c11_atomic_fetch_or:
2714 case AtomicExpr::AO__c11_atomic_fetch_xor:
2715 case AtomicExpr::AO__atomic_fetch_and:
2716 case AtomicExpr::AO__atomic_fetch_or:
2717 case AtomicExpr::AO__atomic_fetch_xor:
2718 case AtomicExpr::AO__atomic_fetch_nand:
2719 case AtomicExpr::AO__atomic_and_fetch:
2720 case AtomicExpr::AO__atomic_or_fetch:
2721 case AtomicExpr::AO__atomic_xor_fetch:
2722 case AtomicExpr::AO__atomic_nand_fetch:
2726 case AtomicExpr::AO__c11_atomic_exchange:
2727 case AtomicExpr::AO__atomic_exchange_n:
2731 case AtomicExpr::AO__atomic_exchange:
2735 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
2736 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
2740 case AtomicExpr::AO__atomic_compare_exchange:
2741 case AtomicExpr::AO__atomic_compare_exchange_n:
2746 // Check we have the right number of arguments.
2747 if (TheCall->getNumArgs() < NumArgs[Form]) {
2748 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
2749 << 0 << NumArgs[Form] << TheCall->getNumArgs()
2750 << TheCall->getCallee()->getSourceRange();
2752 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
2753 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
2754 diag::err_typecheck_call_too_many_args)
2755 << 0 << NumArgs[Form] << TheCall->getNumArgs()
2756 << TheCall->getCallee()->getSourceRange();
2760 // Inspect the first argument of the atomic operation.
2761 Expr *Ptr = TheCall->getArg(0);
2762 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
2763 if (ConvertedPtr.isInvalid())
2766 Ptr = ConvertedPtr.get();
2767 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
2769 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
2770 << Ptr->getType() << Ptr->getSourceRange();
2774 // For a __c11 builtin, this should be a pointer to an _Atomic type.
2775 QualType AtomTy = pointerType->getPointeeType(); // 'A'
2776 QualType ValType = AtomTy; // 'C'
2778 if (!AtomTy->isAtomicType()) {
2779 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
2780 << Ptr->getType() << Ptr->getSourceRange();
2783 if (AtomTy.isConstQualified()) {
2784 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
2785 << Ptr->getType() << Ptr->getSourceRange();
2788 ValType = AtomTy->getAs<AtomicType>()->getValueType();
2789 } else if (Form != Load && Form != LoadCopy) {
2790 if (ValType.isConstQualified()) {
2791 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
2792 << Ptr->getType() << Ptr->getSourceRange();
2797 // For an arithmetic operation, the implied arithmetic must be well-formed.
2798 if (Form == Arithmetic) {
2799 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
2800 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
2801 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
2802 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2805 if (!IsAddSub && !ValType->isIntegerType()) {
2806 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
2807 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2810 if (IsC11 && ValType->isPointerType() &&
2811 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
2812 diag::err_incomplete_type)) {
2815 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
2816 // For __atomic_*_n operations, the value type must be a scalar integral or
2817 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
2818 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
2819 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2823 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
2824 !AtomTy->isScalarType()) {
2825 // For GNU atomics, require a trivially-copyable type. This is not part of
2826 // the GNU atomics specification, but we enforce it for sanity.
2827 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
2828 << Ptr->getType() << Ptr->getSourceRange();
2832 switch (ValType.getObjCLifetime()) {
2833 case Qualifiers::OCL_None:
2834 case Qualifiers::OCL_ExplicitNone:
2838 case Qualifiers::OCL_Weak:
2839 case Qualifiers::OCL_Strong:
2840 case Qualifiers::OCL_Autoreleasing:
2841 // FIXME: Can this happen? By this point, ValType should be known
2842 // to be trivially copyable.
2843 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
2844 << ValType << Ptr->getSourceRange();
2848 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
2849 // volatile-ness of the pointee-type inject itself into the result or the
2850 // other operands. Similarly atomic_load can take a pointer to a const 'A'.
2851 ValType.removeLocalVolatile();
2852 ValType.removeLocalConst();
2853 QualType ResultType = ValType;
2854 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init)
2855 ResultType = Context.VoidTy;
2856 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
2857 ResultType = Context.BoolTy;
2859 // The type of a parameter passed 'by value'. In the GNU atomics, such
2860 // arguments are actually passed as pointers.
2861 QualType ByValType = ValType; // 'CP'
2863 ByValType = Ptr->getType();
2865 // The first argument --- the pointer --- has a fixed type; we
2866 // deduce the types of the rest of the arguments accordingly. Walk
2867 // the remaining arguments, converting them to the deduced value type.
2868 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
2870 if (i < NumVals[Form] + 1) {
2873 // The second argument is the non-atomic operand. For arithmetic, this
2874 // is always passed by value, and for a compare_exchange it is always
2875 // passed by address. For the rest, GNU uses by-address and C11 uses
2877 assert(Form != Load);
2878 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
2880 else if (Form == Copy || Form == Xchg)
2882 else if (Form == Arithmetic)
2883 Ty = Context.getPointerDiffType();
2885 Expr *ValArg = TheCall->getArg(i);
2886 // Treat this argument as _Nonnull as we want to show a warning if
2887 // NULL is passed into it.
2888 CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
2890 // Keep address space of non-atomic pointer type.
2891 if (const PointerType *PtrTy =
2892 ValArg->getType()->getAs<PointerType>()) {
2893 AS = PtrTy->getPointeeType().getAddressSpace();
2895 Ty = Context.getPointerType(
2896 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
2900 // The third argument to compare_exchange / GNU exchange is a
2901 // (pointer to a) desired value.
2905 // The fourth argument to GNU compare_exchange is a 'weak' flag.
2906 Ty = Context.BoolTy;
2910 // The order(s) are always converted to int.
2914 InitializedEntity Entity =
2915 InitializedEntity::InitializeParameter(Context, Ty, false);
2916 ExprResult Arg = TheCall->getArg(i);
2917 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2918 if (Arg.isInvalid())
2920 TheCall->setArg(i, Arg.get());
2923 // Permute the arguments into a 'consistent' order.
2924 SmallVector<Expr*, 5> SubExprs;
2925 SubExprs.push_back(Ptr);
2928 // Note, AtomicExpr::getVal1() has a special case for this atomic.
2929 SubExprs.push_back(TheCall->getArg(1)); // Val1
2932 SubExprs.push_back(TheCall->getArg(1)); // Order
2938 SubExprs.push_back(TheCall->getArg(2)); // Order
2939 SubExprs.push_back(TheCall->getArg(1)); // Val1
2942 // Note, AtomicExpr::getVal2() has a special case for this atomic.
2943 SubExprs.push_back(TheCall->getArg(3)); // Order
2944 SubExprs.push_back(TheCall->getArg(1)); // Val1
2945 SubExprs.push_back(TheCall->getArg(2)); // Val2
2948 SubExprs.push_back(TheCall->getArg(3)); // Order
2949 SubExprs.push_back(TheCall->getArg(1)); // Val1
2950 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
2951 SubExprs.push_back(TheCall->getArg(2)); // Val2
2954 SubExprs.push_back(TheCall->getArg(4)); // Order
2955 SubExprs.push_back(TheCall->getArg(1)); // Val1
2956 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
2957 SubExprs.push_back(TheCall->getArg(2)); // Val2
2958 SubExprs.push_back(TheCall->getArg(3)); // Weak
2962 if (SubExprs.size() >= 2 && Form != Init) {
2963 llvm::APSInt Result(32);
2964 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
2965 !isValidOrderingForOp(Result.getSExtValue(), Op))
2966 Diag(SubExprs[1]->getLocStart(),
2967 diag::warn_atomic_op_has_invalid_memory_order)
2968 << SubExprs[1]->getSourceRange();
2971 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
2972 SubExprs, ResultType, Op,
2973 TheCall->getRParenLoc());
2975 if ((Op == AtomicExpr::AO__c11_atomic_load ||
2976 (Op == AtomicExpr::AO__c11_atomic_store)) &&
2977 Context.AtomicUsesUnsupportedLibcall(AE))
2978 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
2979 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
2984 /// checkBuiltinArgument - Given a call to a builtin function, perform
2985 /// normal type-checking on the given argument, updating the call in
2986 /// place. This is useful when a builtin function requires custom
2987 /// type-checking for some of its arguments but not necessarily all of
2990 /// Returns true on error.
2991 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
2992 FunctionDecl *Fn = E->getDirectCallee();
2993 assert(Fn && "builtin call without direct callee!");
2995 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
2996 InitializedEntity Entity =
2997 InitializedEntity::InitializeParameter(S.Context, Param);
2999 ExprResult Arg = E->getArg(0);
3000 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
3001 if (Arg.isInvalid())
3004 E->setArg(ArgIndex, Arg.get());
3008 /// SemaBuiltinAtomicOverloaded - We have a call to a function like
3009 /// __sync_fetch_and_add, which is an overloaded function based on the pointer
3010 /// type of its first argument. The main ActOnCallExpr routines have already
3011 /// promoted the types of arguments because all of these calls are prototyped as
3014 /// This function goes through and does final semantic checking for these
3017 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
3018 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3019 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3020 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3022 // Ensure that we have at least one argument to do type inference from.
3023 if (TheCall->getNumArgs() < 1) {
3024 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3025 << 0 << 1 << TheCall->getNumArgs()
3026 << TheCall->getCallee()->getSourceRange();
3030 // Inspect the first argument of the atomic builtin. This should always be
3031 // a pointer type, whose element is an integral scalar or pointer type.
3032 // Because it is a pointer type, we don't have to worry about any implicit
3034 // FIXME: We don't allow floating point scalars as input.
3035 Expr *FirstArg = TheCall->getArg(0);
3036 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3037 if (FirstArgResult.isInvalid())
3039 FirstArg = FirstArgResult.get();
3040 TheCall->setArg(0, FirstArg);
3042 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3044 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3045 << FirstArg->getType() << FirstArg->getSourceRange();
3049 QualType ValType = pointerType->getPointeeType();
3050 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3051 !ValType->isBlockPointerType()) {
3052 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3053 << FirstArg->getType() << FirstArg->getSourceRange();
3057 switch (ValType.getObjCLifetime()) {
3058 case Qualifiers::OCL_None:
3059 case Qualifiers::OCL_ExplicitNone:
3063 case Qualifiers::OCL_Weak:
3064 case Qualifiers::OCL_Strong:
3065 case Qualifiers::OCL_Autoreleasing:
3066 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3067 << ValType << FirstArg->getSourceRange();
3071 // Strip any qualifiers off ValType.
3072 ValType = ValType.getUnqualifiedType();
3074 // The majority of builtins return a value, but a few have special return
3075 // types, so allow them to override appropriately below.
3076 QualType ResultType = ValType;
3078 // We need to figure out which concrete builtin this maps onto. For example,
3079 // __sync_fetch_and_add with a 2 byte object turns into
3080 // __sync_fetch_and_add_2.
3081 #define BUILTIN_ROW(x) \
3082 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3083 Builtin::BI##x##_8, Builtin::BI##x##_16 }
3085 static const unsigned BuiltinIndices[][5] = {
3086 BUILTIN_ROW(__sync_fetch_and_add),
3087 BUILTIN_ROW(__sync_fetch_and_sub),
3088 BUILTIN_ROW(__sync_fetch_and_or),
3089 BUILTIN_ROW(__sync_fetch_and_and),
3090 BUILTIN_ROW(__sync_fetch_and_xor),
3091 BUILTIN_ROW(__sync_fetch_and_nand),
3093 BUILTIN_ROW(__sync_add_and_fetch),
3094 BUILTIN_ROW(__sync_sub_and_fetch),
3095 BUILTIN_ROW(__sync_and_and_fetch),
3096 BUILTIN_ROW(__sync_or_and_fetch),
3097 BUILTIN_ROW(__sync_xor_and_fetch),
3098 BUILTIN_ROW(__sync_nand_and_fetch),
3100 BUILTIN_ROW(__sync_val_compare_and_swap),
3101 BUILTIN_ROW(__sync_bool_compare_and_swap),
3102 BUILTIN_ROW(__sync_lock_test_and_set),
3103 BUILTIN_ROW(__sync_lock_release),
3104 BUILTIN_ROW(__sync_swap)
3108 // Determine the index of the size.
3110 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
3111 case 1: SizeIndex = 0; break;
3112 case 2: SizeIndex = 1; break;
3113 case 4: SizeIndex = 2; break;
3114 case 8: SizeIndex = 3; break;
3115 case 16: SizeIndex = 4; break;
3117 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3118 << FirstArg->getType() << FirstArg->getSourceRange();
3122 // Each of these builtins has one pointer argument, followed by some number of
3123 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3124 // that we ignore. Find out which row of BuiltinIndices to read from as well
3125 // as the number of fixed args.
3126 unsigned BuiltinID = FDecl->getBuiltinID();
3127 unsigned BuiltinIndex, NumFixed = 1;
3128 bool WarnAboutSemanticsChange = false;
3129 switch (BuiltinID) {
3130 default: llvm_unreachable("Unknown overloaded atomic builtin!");
3131 case Builtin::BI__sync_fetch_and_add:
3132 case Builtin::BI__sync_fetch_and_add_1:
3133 case Builtin::BI__sync_fetch_and_add_2:
3134 case Builtin::BI__sync_fetch_and_add_4:
3135 case Builtin::BI__sync_fetch_and_add_8:
3136 case Builtin::BI__sync_fetch_and_add_16:
3140 case Builtin::BI__sync_fetch_and_sub:
3141 case Builtin::BI__sync_fetch_and_sub_1:
3142 case Builtin::BI__sync_fetch_and_sub_2:
3143 case Builtin::BI__sync_fetch_and_sub_4:
3144 case Builtin::BI__sync_fetch_and_sub_8:
3145 case Builtin::BI__sync_fetch_and_sub_16:
3149 case Builtin::BI__sync_fetch_and_or:
3150 case Builtin::BI__sync_fetch_and_or_1:
3151 case Builtin::BI__sync_fetch_and_or_2:
3152 case Builtin::BI__sync_fetch_and_or_4:
3153 case Builtin::BI__sync_fetch_and_or_8:
3154 case Builtin::BI__sync_fetch_and_or_16:
3158 case Builtin::BI__sync_fetch_and_and:
3159 case Builtin::BI__sync_fetch_and_and_1:
3160 case Builtin::BI__sync_fetch_and_and_2:
3161 case Builtin::BI__sync_fetch_and_and_4:
3162 case Builtin::BI__sync_fetch_and_and_8:
3163 case Builtin::BI__sync_fetch_and_and_16:
3167 case Builtin::BI__sync_fetch_and_xor:
3168 case Builtin::BI__sync_fetch_and_xor_1:
3169 case Builtin::BI__sync_fetch_and_xor_2:
3170 case Builtin::BI__sync_fetch_and_xor_4:
3171 case Builtin::BI__sync_fetch_and_xor_8:
3172 case Builtin::BI__sync_fetch_and_xor_16:
3176 case Builtin::BI__sync_fetch_and_nand:
3177 case Builtin::BI__sync_fetch_and_nand_1:
3178 case Builtin::BI__sync_fetch_and_nand_2:
3179 case Builtin::BI__sync_fetch_and_nand_4:
3180 case Builtin::BI__sync_fetch_and_nand_8:
3181 case Builtin::BI__sync_fetch_and_nand_16:
3183 WarnAboutSemanticsChange = true;
3186 case Builtin::BI__sync_add_and_fetch:
3187 case Builtin::BI__sync_add_and_fetch_1:
3188 case Builtin::BI__sync_add_and_fetch_2:
3189 case Builtin::BI__sync_add_and_fetch_4:
3190 case Builtin::BI__sync_add_and_fetch_8:
3191 case Builtin::BI__sync_add_and_fetch_16:
3195 case Builtin::BI__sync_sub_and_fetch:
3196 case Builtin::BI__sync_sub_and_fetch_1:
3197 case Builtin::BI__sync_sub_and_fetch_2:
3198 case Builtin::BI__sync_sub_and_fetch_4:
3199 case Builtin::BI__sync_sub_and_fetch_8:
3200 case Builtin::BI__sync_sub_and_fetch_16:
3204 case Builtin::BI__sync_and_and_fetch:
3205 case Builtin::BI__sync_and_and_fetch_1:
3206 case Builtin::BI__sync_and_and_fetch_2:
3207 case Builtin::BI__sync_and_and_fetch_4:
3208 case Builtin::BI__sync_and_and_fetch_8:
3209 case Builtin::BI__sync_and_and_fetch_16:
3213 case Builtin::BI__sync_or_and_fetch:
3214 case Builtin::BI__sync_or_and_fetch_1:
3215 case Builtin::BI__sync_or_and_fetch_2:
3216 case Builtin::BI__sync_or_and_fetch_4:
3217 case Builtin::BI__sync_or_and_fetch_8:
3218 case Builtin::BI__sync_or_and_fetch_16:
3222 case Builtin::BI__sync_xor_and_fetch:
3223 case Builtin::BI__sync_xor_and_fetch_1:
3224 case Builtin::BI__sync_xor_and_fetch_2:
3225 case Builtin::BI__sync_xor_and_fetch_4:
3226 case Builtin::BI__sync_xor_and_fetch_8:
3227 case Builtin::BI__sync_xor_and_fetch_16:
3231 case Builtin::BI__sync_nand_and_fetch:
3232 case Builtin::BI__sync_nand_and_fetch_1:
3233 case Builtin::BI__sync_nand_and_fetch_2:
3234 case Builtin::BI__sync_nand_and_fetch_4:
3235 case Builtin::BI__sync_nand_and_fetch_8:
3236 case Builtin::BI__sync_nand_and_fetch_16:
3238 WarnAboutSemanticsChange = true;
3241 case Builtin::BI__sync_val_compare_and_swap:
3242 case Builtin::BI__sync_val_compare_and_swap_1:
3243 case Builtin::BI__sync_val_compare_and_swap_2:
3244 case Builtin::BI__sync_val_compare_and_swap_4:
3245 case Builtin::BI__sync_val_compare_and_swap_8:
3246 case Builtin::BI__sync_val_compare_and_swap_16:
3251 case Builtin::BI__sync_bool_compare_and_swap:
3252 case Builtin::BI__sync_bool_compare_and_swap_1:
3253 case Builtin::BI__sync_bool_compare_and_swap_2:
3254 case Builtin::BI__sync_bool_compare_and_swap_4:
3255 case Builtin::BI__sync_bool_compare_and_swap_8:
3256 case Builtin::BI__sync_bool_compare_and_swap_16:
3259 ResultType = Context.BoolTy;
3262 case Builtin::BI__sync_lock_test_and_set:
3263 case Builtin::BI__sync_lock_test_and_set_1:
3264 case Builtin::BI__sync_lock_test_and_set_2:
3265 case Builtin::BI__sync_lock_test_and_set_4:
3266 case Builtin::BI__sync_lock_test_and_set_8:
3267 case Builtin::BI__sync_lock_test_and_set_16:
3271 case Builtin::BI__sync_lock_release:
3272 case Builtin::BI__sync_lock_release_1:
3273 case Builtin::BI__sync_lock_release_2:
3274 case Builtin::BI__sync_lock_release_4:
3275 case Builtin::BI__sync_lock_release_8:
3276 case Builtin::BI__sync_lock_release_16:
3279 ResultType = Context.VoidTy;
3282 case Builtin::BI__sync_swap:
3283 case Builtin::BI__sync_swap_1:
3284 case Builtin::BI__sync_swap_2:
3285 case Builtin::BI__sync_swap_4:
3286 case Builtin::BI__sync_swap_8:
3287 case Builtin::BI__sync_swap_16:
3292 // Now that we know how many fixed arguments we expect, first check that we
3293 // have at least that many.
3294 if (TheCall->getNumArgs() < 1+NumFixed) {
3295 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3296 << 0 << 1+NumFixed << TheCall->getNumArgs()
3297 << TheCall->getCallee()->getSourceRange();
3301 if (WarnAboutSemanticsChange) {
3302 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
3303 << TheCall->getCallee()->getSourceRange();
3306 // Get the decl for the concrete builtin from this, we can tell what the
3307 // concrete integer type we should convert to is.
3308 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
3309 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
3310 FunctionDecl *NewBuiltinDecl;
3311 if (NewBuiltinID == BuiltinID)
3312 NewBuiltinDecl = FDecl;
3314 // Perform builtin lookup to avoid redeclaring it.
3315 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
3316 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
3317 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
3318 assert(Res.getFoundDecl());
3319 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
3320 if (!NewBuiltinDecl)
3324 // The first argument --- the pointer --- has a fixed type; we
3325 // deduce the types of the rest of the arguments accordingly. Walk
3326 // the remaining arguments, converting them to the deduced value type.
3327 for (unsigned i = 0; i != NumFixed; ++i) {
3328 ExprResult Arg = TheCall->getArg(i+1);
3330 // GCC does an implicit conversion to the pointer or integer ValType. This
3331 // can fail in some cases (1i -> int**), check for this error case now.
3332 // Initialize the argument.
3333 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3334 ValType, /*consume*/ false);
3335 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3336 if (Arg.isInvalid())
3339 // Okay, we have something that *can* be converted to the right type. Check
3340 // to see if there is a potentially weird extension going on here. This can
3341 // happen when you do an atomic operation on something like an char* and
3342 // pass in 42. The 42 gets converted to char. This is even more strange
3343 // for things like 45.123 -> char, etc.
3344 // FIXME: Do this check.
3345 TheCall->setArg(i+1, Arg.get());
3348 ASTContext& Context = this->getASTContext();
3350 // Create a new DeclRefExpr to refer to the new decl.
3351 DeclRefExpr* NewDRE = DeclRefExpr::Create(
3353 DRE->getQualifierLoc(),
3356 /*enclosing*/ false,
3358 Context.BuiltinFnTy,
3359 DRE->getValueKind());
3361 // Set the callee in the CallExpr.
3362 // FIXME: This loses syntactic information.
3363 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
3364 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
3365 CK_BuiltinFnToFnPtr);
3366 TheCall->setCallee(PromotedCall.get());
3368 // Change the result type of the call to match the original value type. This
3369 // is arbitrary, but the codegen for these builtins ins design to handle it
3371 TheCall->setType(ResultType);
3373 return TheCallResult;
3376 /// SemaBuiltinNontemporalOverloaded - We have a call to
3377 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3378 /// overloaded function based on the pointer type of its last argument.
3380 /// This function goes through and does final semantic checking for these
3382 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
3383 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3385 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3386 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3387 unsigned BuiltinID = FDecl->getBuiltinID();
3388 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
3389 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
3390 "Unexpected nontemporal load/store builtin!");
3391 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3392 unsigned numArgs = isStore ? 2 : 1;
3394 // Ensure that we have the proper number of arguments.
3395 if (checkArgCount(*this, TheCall, numArgs))
3398 // Inspect the last argument of the nontemporal builtin. This should always
3399 // be a pointer type, from which we imply the type of the memory access.
3400 // Because it is a pointer type, we don't have to worry about any implicit
3402 Expr *PointerArg = TheCall->getArg(numArgs - 1);
3403 ExprResult PointerArgResult =
3404 DefaultFunctionArrayLvalueConversion(PointerArg);
3406 if (PointerArgResult.isInvalid())
3408 PointerArg = PointerArgResult.get();
3409 TheCall->setArg(numArgs - 1, PointerArg);
3411 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3413 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3414 << PointerArg->getType() << PointerArg->getSourceRange();
3418 QualType ValType = pointerType->getPointeeType();
3420 // Strip any qualifiers off ValType.
3421 ValType = ValType.getUnqualifiedType();
3422 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3423 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
3424 !ValType->isVectorType()) {
3425 Diag(DRE->getLocStart(),
3426 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3427 << PointerArg->getType() << PointerArg->getSourceRange();
3432 TheCall->setType(ValType);
3433 return TheCallResult;
3436 ExprResult ValArg = TheCall->getArg(0);
3437 InitializedEntity Entity = InitializedEntity::InitializeParameter(
3438 Context, ValType, /*consume*/ false);
3439 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3440 if (ValArg.isInvalid())
3443 TheCall->setArg(0, ValArg.get());
3444 TheCall->setType(Context.VoidTy);
3445 return TheCallResult;
3448 /// CheckObjCString - Checks that the argument to the builtin
3449 /// CFString constructor is correct
3450 /// Note: It might also make sense to do the UTF-16 conversion here (would
3451 /// simplify the backend).
3452 bool Sema::CheckObjCString(Expr *Arg) {
3453 Arg = Arg->IgnoreParenCasts();
3454 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
3456 if (!Literal || !Literal->isAscii()) {
3457 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
3458 << Arg->getSourceRange();
3462 if (Literal->containsNonAsciiOrNull()) {
3463 StringRef String = Literal->getString();
3464 unsigned NumBytes = String.size();
3465 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
3466 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3467 llvm::UTF16 *ToPtr = &ToBuf[0];
3469 llvm::ConversionResult Result =
3470 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3471 ToPtr + NumBytes, llvm::strictConversion);
3472 // Check for conversion failure.
3473 if (Result != llvm::conversionOK)
3474 Diag(Arg->getLocStart(),
3475 diag::warn_cfstring_truncated) << Arg->getSourceRange();
3480 /// CheckObjCString - Checks that the format string argument to the os_log()
3481 /// and os_trace() functions is correct, and converts it to const char *.
3482 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
3483 Arg = Arg->IgnoreParenCasts();
3484 auto *Literal = dyn_cast<StringLiteral>(Arg);
3486 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
3487 Literal = ObjcLiteral->getString();
3491 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
3493 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
3494 << Arg->getSourceRange());
3497 ExprResult Result(Literal);
3498 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
3499 InitializedEntity Entity =
3500 InitializedEntity::InitializeParameter(Context, ResultTy, false);
3501 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
3505 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
3506 /// for validity. Emit an error and return true on failure; return false
3508 bool Sema::SemaBuiltinVAStartImpl(CallExpr *TheCall) {
3509 Expr *Fn = TheCall->getCallee();
3510 if (TheCall->getNumArgs() > 2) {
3511 Diag(TheCall->getArg(2)->getLocStart(),
3512 diag::err_typecheck_call_too_many_args)
3513 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3514 << Fn->getSourceRange()
3515 << SourceRange(TheCall->getArg(2)->getLocStart(),
3516 (*(TheCall->arg_end()-1))->getLocEnd());
3520 if (TheCall->getNumArgs() < 2) {
3521 return Diag(TheCall->getLocEnd(),
3522 diag::err_typecheck_call_too_few_args_at_least)
3523 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
3526 // Type-check the first argument normally.
3527 if (checkBuiltinArgument(*this, TheCall, 0))
3530 // Determine whether the current function is variadic or not.
3531 BlockScopeInfo *CurBlock = getCurBlock();
3534 isVariadic = CurBlock->TheDecl->isVariadic();
3535 else if (FunctionDecl *FD = getCurFunctionDecl())
3536 isVariadic = FD->isVariadic();
3538 isVariadic = getCurMethodDecl()->isVariadic();
3541 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3545 // Verify that the second argument to the builtin is the last argument of the
3546 // current function or method.
3547 bool SecondArgIsLastNamedArgument = false;
3548 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
3550 // These are valid if SecondArgIsLastNamedArgument is false after the next
3553 SourceLocation ParamLoc;
3554 bool IsCRegister = false;
3556 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
3557 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
3558 // FIXME: This isn't correct for methods (results in bogus warning).
3559 // Get the last formal in the current function.
3560 const ParmVarDecl *LastArg;
3562 LastArg = CurBlock->TheDecl->parameters().back();
3563 else if (FunctionDecl *FD = getCurFunctionDecl())
3564 LastArg = FD->parameters().back();
3566 LastArg = getCurMethodDecl()->parameters().back();
3567 SecondArgIsLastNamedArgument = PV == LastArg;
3569 Type = PV->getType();
3570 ParamLoc = PV->getLocation();
3572 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
3576 if (!SecondArgIsLastNamedArgument)
3577 Diag(TheCall->getArg(1)->getLocStart(),
3578 diag::warn_second_arg_of_va_start_not_last_named_param);
3579 else if (IsCRegister || Type->isReferenceType() ||
3580 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
3581 // Promotable integers are UB, but enumerations need a bit of
3582 // extra checking to see what their promotable type actually is.
3583 if (!Type->isPromotableIntegerType())
3585 if (!Type->isEnumeralType())
3587 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3589 Context.typesAreCompatible(ED->getPromotionType(), Type));
3591 unsigned Reason = 0;
3592 if (Type->isReferenceType()) Reason = 1;
3593 else if (IsCRegister) Reason = 2;
3594 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
3595 Diag(ParamLoc, diag::note_parameter_type) << Type;
3598 TheCall->setType(Context.VoidTy);
3602 /// Check the arguments to '__builtin_va_start' for validity, and that
3603 /// it was called from a function of the native ABI.
3604 /// Emit an error and return true on failure; return false on success.
3605 bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
3606 // On x86-64 Unix, don't allow this in Win64 ABI functions.
3607 // On x64 Windows, don't allow this in System V ABI functions.
3608 // (Yes, that means there's no corresponding way to support variadic
3609 // System V ABI functions on Windows.)
3610 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) {
3611 unsigned OS = Context.getTargetInfo().getTriple().getOS();
3612 clang::CallingConv CC = CC_C;
3613 if (const FunctionDecl *FD = getCurFunctionDecl())
3614 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3615 if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) ||
3616 (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64))
3617 return Diag(TheCall->getCallee()->getLocStart(),
3618 diag::err_va_start_used_in_wrong_abi_function)
3619 << (OS != llvm::Triple::Win32);
3621 return SemaBuiltinVAStartImpl(TheCall);
3624 /// Check the arguments to '__builtin_ms_va_start' for validity, and that
3625 /// it was called from a Win64 ABI function.
3626 /// Emit an error and return true on failure; return false on success.
3627 bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) {
3628 // This only makes sense for x86-64.
3629 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3630 Expr *Callee = TheCall->getCallee();
3631 if (TT.getArch() != llvm::Triple::x86_64)
3632 return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt);
3633 // Don't allow this in System V ABI functions.
3634 clang::CallingConv CC = CC_C;
3635 if (const FunctionDecl *FD = getCurFunctionDecl())
3636 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3637 if (CC == CC_X86_64SysV ||
3638 (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64))
3639 return Diag(Callee->getLocStart(),
3640 diag::err_ms_va_start_used_in_sysv_function);
3641 return SemaBuiltinVAStartImpl(TheCall);
3644 bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
3645 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
3646 // const char *named_addr);
3648 Expr *Func = Call->getCallee();
3650 if (Call->getNumArgs() < 3)
3651 return Diag(Call->getLocEnd(),
3652 diag::err_typecheck_call_too_few_args_at_least)
3653 << 0 /*function call*/ << 3 << Call->getNumArgs();
3655 // Determine whether the current function is variadic or not.
3657 if (BlockScopeInfo *CurBlock = getCurBlock())
3658 IsVariadic = CurBlock->TheDecl->isVariadic();
3659 else if (FunctionDecl *FD = getCurFunctionDecl())
3660 IsVariadic = FD->isVariadic();
3661 else if (ObjCMethodDecl *MD = getCurMethodDecl())
3662 IsVariadic = MD->isVariadic();
3664 llvm_unreachable("unexpected statement type");
3667 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3671 // Type-check the first argument normally.
3672 if (checkBuiltinArgument(*this, Call, 0))
3678 } ArgumentTypes[] = {
3679 { 1, Context.getPointerType(Context.CharTy.withConst()) },
3680 { 2, Context.getSizeType() },
3683 for (const auto &AT : ArgumentTypes) {
3684 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
3685 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
3687 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
3688 << Arg->getType() << AT.Type << 1 /* different class */
3689 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
3690 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
3696 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
3697 /// friends. This is declared to take (...), so we have to check everything.
3698 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
3699 if (TheCall->getNumArgs() < 2)
3700 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
3701 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
3702 if (TheCall->getNumArgs() > 2)
3703 return Diag(TheCall->getArg(2)->getLocStart(),
3704 diag::err_typecheck_call_too_many_args)
3705 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3706 << SourceRange(TheCall->getArg(2)->getLocStart(),
3707 (*(TheCall->arg_end()-1))->getLocEnd());
3709 ExprResult OrigArg0 = TheCall->getArg(0);
3710 ExprResult OrigArg1 = TheCall->getArg(1);
3712 // Do standard promotions between the two arguments, returning their common
3714 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
3715 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
3718 // Make sure any conversions are pushed back into the call; this is
3719 // type safe since unordered compare builtins are declared as "_Bool
3721 TheCall->setArg(0, OrigArg0.get());
3722 TheCall->setArg(1, OrigArg1.get());
3724 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
3727 // If the common type isn't a real floating type, then the arguments were
3728 // invalid for this operation.
3729 if (Res.isNull() || !Res->isRealFloatingType())
3730 return Diag(OrigArg0.get()->getLocStart(),
3731 diag::err_typecheck_call_invalid_ordered_compare)
3732 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
3733 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
3738 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
3739 /// __builtin_isnan and friends. This is declared to take (...), so we have
3740 /// to check everything. We expect the last argument to be a floating point
3742 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
3743 if (TheCall->getNumArgs() < NumArgs)
3744 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
3745 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
3746 if (TheCall->getNumArgs() > NumArgs)
3747 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
3748 diag::err_typecheck_call_too_many_args)
3749 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
3750 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
3751 (*(TheCall->arg_end()-1))->getLocEnd());
3753 Expr *OrigArg = TheCall->getArg(NumArgs-1);
3755 if (OrigArg->isTypeDependent())
3758 // This operation requires a non-_Complex floating-point number.
3759 if (!OrigArg->getType()->isRealFloatingType())
3760 return Diag(OrigArg->getLocStart(),
3761 diag::err_typecheck_call_invalid_unary_fp)
3762 << OrigArg->getType() << OrigArg->getSourceRange();
3764 // If this is an implicit conversion from float -> float or double, remove it.
3765 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
3766 // Only remove standard FloatCasts, leaving other casts inplace
3767 if (Cast->getCastKind() == CK_FloatingCast) {
3768 Expr *CastArg = Cast->getSubExpr();
3769 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
3770 assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
3771 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) &&
3772 "promotion from float to either float or double is the only expected cast here");
3773 Cast->setSubExpr(nullptr);
3774 TheCall->setArg(NumArgs-1, CastArg);
3782 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
3783 // This is declared to take (...), so we have to check everything.
3784 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
3785 if (TheCall->getNumArgs() < 2)
3786 return ExprError(Diag(TheCall->getLocEnd(),
3787 diag::err_typecheck_call_too_few_args_at_least)
3788 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3789 << TheCall->getSourceRange());
3791 // Determine which of the following types of shufflevector we're checking:
3792 // 1) unary, vector mask: (lhs, mask)
3793 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
3794 QualType resType = TheCall->getArg(0)->getType();
3795 unsigned numElements = 0;
3797 if (!TheCall->getArg(0)->isTypeDependent() &&
3798 !TheCall->getArg(1)->isTypeDependent()) {
3799 QualType LHSType = TheCall->getArg(0)->getType();
3800 QualType RHSType = TheCall->getArg(1)->getType();
3802 if (!LHSType->isVectorType() || !RHSType->isVectorType())
3803 return ExprError(Diag(TheCall->getLocStart(),
3804 diag::err_shufflevector_non_vector)
3805 << SourceRange(TheCall->getArg(0)->getLocStart(),
3806 TheCall->getArg(1)->getLocEnd()));
3808 numElements = LHSType->getAs<VectorType>()->getNumElements();
3809 unsigned numResElements = TheCall->getNumArgs() - 2;
3811 // Check to see if we have a call with 2 vector arguments, the unary shuffle
3812 // with mask. If so, verify that RHS is an integer vector type with the
3813 // same number of elts as lhs.
3814 if (TheCall->getNumArgs() == 2) {
3815 if (!RHSType->hasIntegerRepresentation() ||
3816 RHSType->getAs<VectorType>()->getNumElements() != numElements)
3817 return ExprError(Diag(TheCall->getLocStart(),
3818 diag::err_shufflevector_incompatible_vector)
3819 << SourceRange(TheCall->getArg(1)->getLocStart(),
3820 TheCall->getArg(1)->getLocEnd()));
3821 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
3822 return ExprError(Diag(TheCall->getLocStart(),
3823 diag::err_shufflevector_incompatible_vector)
3824 << SourceRange(TheCall->getArg(0)->getLocStart(),
3825 TheCall->getArg(1)->getLocEnd()));
3826 } else if (numElements != numResElements) {
3827 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
3828 resType = Context.getVectorType(eltType, numResElements,
3829 VectorType::GenericVector);
3833 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
3834 if (TheCall->getArg(i)->isTypeDependent() ||
3835 TheCall->getArg(i)->isValueDependent())
3838 llvm::APSInt Result(32);
3839 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
3840 return ExprError(Diag(TheCall->getLocStart(),
3841 diag::err_shufflevector_nonconstant_argument)
3842 << TheCall->getArg(i)->getSourceRange());
3844 // Allow -1 which will be translated to undef in the IR.
3845 if (Result.isSigned() && Result.isAllOnesValue())
3848 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
3849 return ExprError(Diag(TheCall->getLocStart(),
3850 diag::err_shufflevector_argument_too_large)
3851 << TheCall->getArg(i)->getSourceRange());
3854 SmallVector<Expr*, 32> exprs;
3856 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
3857 exprs.push_back(TheCall->getArg(i));
3858 TheCall->setArg(i, nullptr);
3861 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
3862 TheCall->getCallee()->getLocStart(),
3863 TheCall->getRParenLoc());
3866 /// SemaConvertVectorExpr - Handle __builtin_convertvector
3867 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
3868 SourceLocation BuiltinLoc,
3869 SourceLocation RParenLoc) {
3870 ExprValueKind VK = VK_RValue;
3871 ExprObjectKind OK = OK_Ordinary;
3872 QualType DstTy = TInfo->getType();
3873 QualType SrcTy = E->getType();
3875 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
3876 return ExprError(Diag(BuiltinLoc,
3877 diag::err_convertvector_non_vector)
3878 << E->getSourceRange());
3879 if (!DstTy->isVectorType() && !DstTy->isDependentType())
3880 return ExprError(Diag(BuiltinLoc,
3881 diag::err_convertvector_non_vector_type));
3883 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
3884 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
3885 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
3886 if (SrcElts != DstElts)
3887 return ExprError(Diag(BuiltinLoc,
3888 diag::err_convertvector_incompatible_vector)
3889 << E->getSourceRange());
3892 return new (Context)
3893 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
3896 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
3897 // This is declared to take (const void*, ...) and can take two
3898 // optional constant int args.
3899 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
3900 unsigned NumArgs = TheCall->getNumArgs();
3903 return Diag(TheCall->getLocEnd(),
3904 diag::err_typecheck_call_too_many_args_at_most)
3905 << 0 /*function call*/ << 3 << NumArgs
3906 << TheCall->getSourceRange();
3908 // Argument 0 is checked for us and the remaining arguments must be
3909 // constant integers.
3910 for (unsigned i = 1; i != NumArgs; ++i)
3911 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
3917 /// SemaBuiltinAssume - Handle __assume (MS Extension).
3918 // __assume does not evaluate its arguments, and should warn if its argument
3919 // has side effects.
3920 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
3921 Expr *Arg = TheCall->getArg(0);
3922 if (Arg->isInstantiationDependent()) return false;
3924 if (Arg->HasSideEffects(Context))
3925 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
3926 << Arg->getSourceRange()
3927 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
3932 /// Handle __builtin_alloca_with_align. This is declared
3933 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
3935 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
3936 // The alignment must be a constant integer.
3937 Expr *Arg = TheCall->getArg(1);
3939 // We can't check the value of a dependent argument.
3940 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
3941 if (const auto *UE =
3942 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
3943 if (UE->getKind() == UETT_AlignOf)
3944 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
3945 << Arg->getSourceRange();
3947 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
3949 if (!Result.isPowerOf2())
3950 return Diag(TheCall->getLocStart(),
3951 diag::err_alignment_not_power_of_two)
3952 << Arg->getSourceRange();
3954 if (Result < Context.getCharWidth())
3955 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
3956 << (unsigned)Context.getCharWidth()
3957 << Arg->getSourceRange();
3959 if (Result > INT32_MAX)
3960 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
3962 << Arg->getSourceRange();
3968 /// Handle __builtin_assume_aligned. This is declared
3969 /// as (const void*, size_t, ...) and can take one optional constant int arg.
3970 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
3971 unsigned NumArgs = TheCall->getNumArgs();
3974 return Diag(TheCall->getLocEnd(),
3975 diag::err_typecheck_call_too_many_args_at_most)
3976 << 0 /*function call*/ << 3 << NumArgs
3977 << TheCall->getSourceRange();
3979 // The alignment must be a constant integer.
3980 Expr *Arg = TheCall->getArg(1);
3982 // We can't check the value of a dependent argument.
3983 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
3984 llvm::APSInt Result;
3985 if (SemaBuiltinConstantArg(TheCall, 1, Result))
3988 if (!Result.isPowerOf2())
3989 return Diag(TheCall->getLocStart(),
3990 diag::err_alignment_not_power_of_two)
3991 << Arg->getSourceRange();
3995 ExprResult Arg(TheCall->getArg(2));
3996 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3997 Context.getSizeType(), false);
3998 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3999 if (Arg.isInvalid()) return true;
4000 TheCall->setArg(2, Arg.get());
4006 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
4007 unsigned BuiltinID =
4008 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
4009 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
4011 unsigned NumArgs = TheCall->getNumArgs();
4012 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
4013 if (NumArgs < NumRequiredArgs) {
4014 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4015 << 0 /* function call */ << NumRequiredArgs << NumArgs
4016 << TheCall->getSourceRange();
4018 if (NumArgs >= NumRequiredArgs + 0x100) {
4019 return Diag(TheCall->getLocEnd(),
4020 diag::err_typecheck_call_too_many_args_at_most)
4021 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
4022 << TheCall->getSourceRange();
4026 // For formatting call, check buffer arg.
4028 ExprResult Arg(TheCall->getArg(i));
4029 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4030 Context, Context.VoidPtrTy, false);
4031 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4032 if (Arg.isInvalid())
4034 TheCall->setArg(i, Arg.get());
4038 // Check string literal arg.
4039 unsigned FormatIdx = i;
4041 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4042 if (Arg.isInvalid())
4044 TheCall->setArg(i, Arg.get());
4048 // Make sure variadic args are scalar.
4049 unsigned FirstDataArg = i;
4050 while (i < NumArgs) {
4051 ExprResult Arg = DefaultVariadicArgumentPromotion(
4052 TheCall->getArg(i), VariadicFunction, nullptr);
4053 if (Arg.isInvalid())
4055 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4056 if (ArgSize.getQuantity() >= 0x100) {
4057 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4058 << i << (int)ArgSize.getQuantity() << 0xff
4059 << TheCall->getSourceRange();
4061 TheCall->setArg(i, Arg.get());
4065 // Check formatting specifiers. NOTE: We're only doing this for the non-size
4066 // call to avoid duplicate diagnostics.
4068 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4069 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4070 bool Success = CheckFormatArguments(
4071 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4072 VariadicFunction, TheCall->getLocStart(), SourceRange(),
4079 TheCall->setType(Context.getSizeType());
4081 TheCall->setType(Context.VoidPtrTy);
4086 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4087 /// TheCall is a constant expression.
4088 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4089 llvm::APSInt &Result) {
4090 Expr *Arg = TheCall->getArg(ArgNum);
4091 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4092 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4094 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
4096 if (!Arg->isIntegerConstantExpr(Result, Context))
4097 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
4098 << FDecl->getDeclName() << Arg->getSourceRange();
4103 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
4104 /// TheCall is a constant expression in the range [Low, High].
4105 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
4106 int Low, int High) {
4107 llvm::APSInt Result;
4109 // We can't check the value of a dependent argument.
4110 Expr *Arg = TheCall->getArg(ArgNum);
4111 if (Arg->isTypeDependent() || Arg->isValueDependent())
4114 // Check constant-ness first.
4115 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4118 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
4119 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
4120 << Low << High << Arg->getSourceRange();
4125 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
4126 /// TheCall is a constant expression is a multiple of Num..
4127 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
4129 llvm::APSInt Result;
4131 // We can't check the value of a dependent argument.
4132 Expr *Arg = TheCall->getArg(ArgNum);
4133 if (Arg->isTypeDependent() || Arg->isValueDependent())
4136 // Check constant-ness first.
4137 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4140 if (Result.getSExtValue() % Num != 0)
4141 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
4142 << Num << Arg->getSourceRange();
4147 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
4148 /// TheCall is an ARM/AArch64 special register string literal.
4149 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
4150 int ArgNum, unsigned ExpectedFieldNum,
4152 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
4153 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
4154 BuiltinID == ARM::BI__builtin_arm_rsr ||
4155 BuiltinID == ARM::BI__builtin_arm_rsrp ||
4156 BuiltinID == ARM::BI__builtin_arm_wsr ||
4157 BuiltinID == ARM::BI__builtin_arm_wsrp;
4158 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
4159 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
4160 BuiltinID == AArch64::BI__builtin_arm_rsr ||
4161 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
4162 BuiltinID == AArch64::BI__builtin_arm_wsr ||
4163 BuiltinID == AArch64::BI__builtin_arm_wsrp;
4164 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
4166 // We can't check the value of a dependent argument.
4167 Expr *Arg = TheCall->getArg(ArgNum);
4168 if (Arg->isTypeDependent() || Arg->isValueDependent())
4171 // Check if the argument is a string literal.
4172 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4173 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
4174 << Arg->getSourceRange();
4176 // Check the type of special register given.
4177 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4178 SmallVector<StringRef, 6> Fields;
4179 Reg.split(Fields, ":");
4181 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
4182 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4183 << Arg->getSourceRange();
4185 // If the string is the name of a register then we cannot check that it is
4186 // valid here but if the string is of one the forms described in ACLE then we
4187 // can check that the supplied fields are integers and within the valid
4189 if (Fields.size() > 1) {
4190 bool FiveFields = Fields.size() == 5;
4192 bool ValidString = true;
4194 ValidString &= Fields[0].startswith_lower("cp") ||
4195 Fields[0].startswith_lower("p");
4198 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
4200 ValidString &= Fields[2].startswith_lower("c");
4202 Fields[2] = Fields[2].drop_front(1);
4205 ValidString &= Fields[3].startswith_lower("c");
4207 Fields[3] = Fields[3].drop_front(1);
4211 SmallVector<int, 5> Ranges;
4213 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
4215 Ranges.append({15, 7, 15});
4217 for (unsigned i=0; i<Fields.size(); ++i) {
4219 ValidString &= !Fields[i].getAsInteger(10, IntField);
4220 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
4224 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4225 << Arg->getSourceRange();
4227 } else if (IsAArch64Builtin && Fields.size() == 1) {
4228 // If the register name is one of those that appear in the condition below
4229 // and the special register builtin being used is one of the write builtins,
4230 // then we require that the argument provided for writing to the register
4231 // is an integer constant expression. This is because it will be lowered to
4232 // an MSR (immediate) instruction, so we need to know the immediate at
4234 if (TheCall->getNumArgs() != 2)
4237 std::string RegLower = Reg.lower();
4238 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
4239 RegLower != "pan" && RegLower != "uao")
4242 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4248 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
4249 /// This checks that the target supports __builtin_longjmp and
4250 /// that val is a constant 1.
4251 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
4252 if (!Context.getTargetInfo().hasSjLjLowering())
4253 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
4254 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4256 Expr *Arg = TheCall->getArg(1);
4257 llvm::APSInt Result;
4259 // TODO: This is less than ideal. Overload this to take a value.
4260 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4264 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
4265 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
4270 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
4271 /// This checks that the target supports __builtin_setjmp.
4272 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
4273 if (!Context.getTargetInfo().hasSjLjLowering())
4274 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
4275 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4280 class UncoveredArgHandler {
4281 enum { Unknown = -1, AllCovered = -2 };
4282 signed FirstUncoveredArg;
4283 SmallVector<const Expr *, 4> DiagnosticExprs;
4286 UncoveredArgHandler() : FirstUncoveredArg(Unknown) { }
4288 bool hasUncoveredArg() const {
4289 return (FirstUncoveredArg >= 0);
4292 unsigned getUncoveredArg() const {
4293 assert(hasUncoveredArg() && "no uncovered argument");
4294 return FirstUncoveredArg;
4297 void setAllCovered() {
4298 // A string has been found with all arguments covered, so clear out
4300 DiagnosticExprs.clear();
4301 FirstUncoveredArg = AllCovered;
4304 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
4305 assert(NewFirstUncoveredArg >= 0 && "Outside range");
4307 // Don't update if a previous string covers all arguments.
4308 if (FirstUncoveredArg == AllCovered)
4311 // UncoveredArgHandler tracks the highest uncovered argument index
4312 // and with it all the strings that match this index.
4313 if (NewFirstUncoveredArg == FirstUncoveredArg)
4314 DiagnosticExprs.push_back(StrExpr);
4315 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
4316 DiagnosticExprs.clear();
4317 DiagnosticExprs.push_back(StrExpr);
4318 FirstUncoveredArg = NewFirstUncoveredArg;
4322 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
4325 enum StringLiteralCheckType {
4327 SLCT_UncheckedLiteral,
4330 } // end anonymous namespace
4332 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
4333 BinaryOperatorKind BinOpKind,
4334 bool AddendIsRight) {
4335 unsigned BitWidth = Offset.getBitWidth();
4336 unsigned AddendBitWidth = Addend.getBitWidth();
4337 // There might be negative interim results.
4338 if (Addend.isUnsigned()) {
4339 Addend = Addend.zext(++AddendBitWidth);
4340 Addend.setIsSigned(true);
4342 // Adjust the bit width of the APSInts.
4343 if (AddendBitWidth > BitWidth) {
4344 Offset = Offset.sext(AddendBitWidth);
4345 BitWidth = AddendBitWidth;
4346 } else if (BitWidth > AddendBitWidth) {
4347 Addend = Addend.sext(BitWidth);
4351 llvm::APSInt ResOffset = Offset;
4352 if (BinOpKind == BO_Add)
4353 ResOffset = Offset.sadd_ov(Addend, Ov);
4355 assert(AddendIsRight && BinOpKind == BO_Sub &&
4356 "operator must be add or sub with addend on the right");
4357 ResOffset = Offset.ssub_ov(Addend, Ov);
4360 // We add an offset to a pointer here so we should support an offset as big as
4363 assert(BitWidth <= UINT_MAX / 2 && "index (intermediate) result too big");
4364 Offset = Offset.sext(2 * BitWidth);
4365 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
4373 // This is a wrapper class around StringLiteral to support offsetted string
4374 // literals as format strings. It takes the offset into account when returning
4375 // the string and its length or the source locations to display notes correctly.
4376 class FormatStringLiteral {
4377 const StringLiteral *FExpr;
4381 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
4382 : FExpr(fexpr), Offset(Offset) {}
4384 StringRef getString() const {
4385 return FExpr->getString().drop_front(Offset);
4388 unsigned getByteLength() const {
4389 return FExpr->getByteLength() - getCharByteWidth() * Offset;
4391 unsigned getLength() const { return FExpr->getLength() - Offset; }
4392 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
4394 StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
4396 QualType getType() const { return FExpr->getType(); }
4398 bool isAscii() const { return FExpr->isAscii(); }
4399 bool isWide() const { return FExpr->isWide(); }
4400 bool isUTF8() const { return FExpr->isUTF8(); }
4401 bool isUTF16() const { return FExpr->isUTF16(); }
4402 bool isUTF32() const { return FExpr->isUTF32(); }
4403 bool isPascal() const { return FExpr->isPascal(); }
4405 SourceLocation getLocationOfByte(
4406 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
4407 const TargetInfo &Target, unsigned *StartToken = nullptr,
4408 unsigned *StartTokenByteOffset = nullptr) const {
4409 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
4410 StartToken, StartTokenByteOffset);
4413 SourceLocation getLocStart() const LLVM_READONLY {
4414 return FExpr->getLocStart().getLocWithOffset(Offset);
4416 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
4418 } // end anonymous namespace
4420 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
4421 const Expr *OrigFormatExpr,
4422 ArrayRef<const Expr *> Args,
4423 bool HasVAListArg, unsigned format_idx,
4424 unsigned firstDataArg,
4425 Sema::FormatStringType Type,
4426 bool inFunctionCall,
4427 Sema::VariadicCallType CallType,
4428 llvm::SmallBitVector &CheckedVarArgs,
4429 UncoveredArgHandler &UncoveredArg);
4431 // Determine if an expression is a string literal or constant string.
4432 // If this function returns false on the arguments to a function expecting a
4433 // format string, we will usually need to emit a warning.
4434 // True string literals are then checked by CheckFormatString.
4435 static StringLiteralCheckType
4436 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
4437 bool HasVAListArg, unsigned format_idx,
4438 unsigned firstDataArg, Sema::FormatStringType Type,
4439 Sema::VariadicCallType CallType, bool InFunctionCall,
4440 llvm::SmallBitVector &CheckedVarArgs,
4441 UncoveredArgHandler &UncoveredArg,
4442 llvm::APSInt Offset) {
4444 assert(Offset.isSigned() && "invalid offset");
4446 if (E->isTypeDependent() || E->isValueDependent())
4447 return SLCT_NotALiteral;
4449 E = E->IgnoreParenCasts();
4451 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
4452 // Technically -Wformat-nonliteral does not warn about this case.
4453 // The behavior of printf and friends in this case is implementation
4454 // dependent. Ideally if the format string cannot be null then
4455 // it should have a 'nonnull' attribute in the function prototype.
4456 return SLCT_UncheckedLiteral;
4458 switch (E->getStmtClass()) {
4459 case Stmt::BinaryConditionalOperatorClass:
4460 case Stmt::ConditionalOperatorClass: {
4461 // The expression is a literal if both sub-expressions were, and it was
4462 // completely checked only if both sub-expressions were checked.
4463 const AbstractConditionalOperator *C =
4464 cast<AbstractConditionalOperator>(E);
4466 // Determine whether it is necessary to check both sub-expressions, for
4467 // example, because the condition expression is a constant that can be
4468 // evaluated at compile time.
4469 bool CheckLeft = true, CheckRight = true;
4472 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
4479 // We need to maintain the offsets for the right and the left hand side
4480 // separately to check if every possible indexed expression is a valid
4481 // string literal. They might have different offsets for different string
4482 // literals in the end.
4483 StringLiteralCheckType Left;
4485 Left = SLCT_UncheckedLiteral;
4487 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
4488 HasVAListArg, format_idx, firstDataArg,
4489 Type, CallType, InFunctionCall,
4490 CheckedVarArgs, UncoveredArg, Offset);
4491 if (Left == SLCT_NotALiteral || !CheckRight) {
4496 StringLiteralCheckType Right =
4497 checkFormatStringExpr(S, C->getFalseExpr(), Args,
4498 HasVAListArg, format_idx, firstDataArg,
4499 Type, CallType, InFunctionCall, CheckedVarArgs,
4500 UncoveredArg, Offset);
4502 return (CheckLeft && Left < Right) ? Left : Right;
4505 case Stmt::ImplicitCastExprClass: {
4506 E = cast<ImplicitCastExpr>(E)->getSubExpr();
4510 case Stmt::OpaqueValueExprClass:
4511 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
4515 return SLCT_NotALiteral;
4517 case Stmt::PredefinedExprClass:
4518 // While __func__, etc., are technically not string literals, they
4519 // cannot contain format specifiers and thus are not a security
4521 return SLCT_UncheckedLiteral;
4523 case Stmt::DeclRefExprClass: {
4524 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
4526 // As an exception, do not flag errors for variables binding to
4527 // const string literals.
4528 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
4529 bool isConstant = false;
4530 QualType T = DR->getType();
4532 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
4533 isConstant = AT->getElementType().isConstant(S.Context);
4534 } else if (const PointerType *PT = T->getAs<PointerType>()) {
4535 isConstant = T.isConstant(S.Context) &&
4536 PT->getPointeeType().isConstant(S.Context);
4537 } else if (T->isObjCObjectPointerType()) {
4538 // In ObjC, there is usually no "const ObjectPointer" type,
4539 // so don't check if the pointee type is constant.
4540 isConstant = T.isConstant(S.Context);
4544 if (const Expr *Init = VD->getAnyInitializer()) {
4545 // Look through initializers like const char c[] = { "foo" }
4546 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4547 if (InitList->isStringLiteralInit())
4548 Init = InitList->getInit(0)->IgnoreParenImpCasts();
4550 return checkFormatStringExpr(S, Init, Args,
4551 HasVAListArg, format_idx,
4552 firstDataArg, Type, CallType,
4553 /*InFunctionCall*/ false, CheckedVarArgs,
4554 UncoveredArg, Offset);
4558 // For vprintf* functions (i.e., HasVAListArg==true), we add a
4559 // special check to see if the format string is a function parameter
4560 // of the function calling the printf function. If the function
4561 // has an attribute indicating it is a printf-like function, then we
4562 // should suppress warnings concerning non-literals being used in a call
4563 // to a vprintf function. For example:
4566 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
4568 // va_start(ap, fmt);
4569 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
4573 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
4574 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
4575 int PVIndex = PV->getFunctionScopeIndex() + 1;
4576 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
4577 // adjust for implicit parameter
4578 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4579 if (MD->isInstance())
4581 // We also check if the formats are compatible.
4582 // We can't pass a 'scanf' string to a 'printf' function.
4583 if (PVIndex == PVFormat->getFormatIdx() &&
4584 Type == S.GetFormatStringType(PVFormat))
4585 return SLCT_UncheckedLiteral;
4592 return SLCT_NotALiteral;
4595 case Stmt::CallExprClass:
4596 case Stmt::CXXMemberCallExprClass: {
4597 const CallExpr *CE = cast<CallExpr>(E);
4598 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
4599 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
4600 unsigned ArgIndex = FA->getFormatIdx();
4601 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4602 if (MD->isInstance())
4604 const Expr *Arg = CE->getArg(ArgIndex - 1);
4606 return checkFormatStringExpr(S, Arg, Args,
4607 HasVAListArg, format_idx, firstDataArg,
4608 Type, CallType, InFunctionCall,
4609 CheckedVarArgs, UncoveredArg, Offset);
4610 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4611 unsigned BuiltinID = FD->getBuiltinID();
4612 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
4613 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
4614 const Expr *Arg = CE->getArg(0);
4615 return checkFormatStringExpr(S, Arg, Args,
4616 HasVAListArg, format_idx,
4617 firstDataArg, Type, CallType,
4618 InFunctionCall, CheckedVarArgs,
4619 UncoveredArg, Offset);
4624 return SLCT_NotALiteral;
4626 case Stmt::ObjCMessageExprClass: {
4627 const auto *ME = cast<ObjCMessageExpr>(E);
4628 if (const auto *ND = ME->getMethodDecl()) {
4629 if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
4630 unsigned ArgIndex = FA->getFormatIdx();
4631 const Expr *Arg = ME->getArg(ArgIndex - 1);
4632 return checkFormatStringExpr(
4633 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
4634 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
4638 return SLCT_NotALiteral;
4640 case Stmt::ObjCStringLiteralClass:
4641 case Stmt::StringLiteralClass: {
4642 const StringLiteral *StrE = nullptr;
4644 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
4645 StrE = ObjCFExpr->getString();
4647 StrE = cast<StringLiteral>(E);
4650 if (Offset.isNegative() || Offset > StrE->getLength()) {
4651 // TODO: It would be better to have an explicit warning for out of
4653 return SLCT_NotALiteral;
4655 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
4656 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
4657 firstDataArg, Type, InFunctionCall, CallType,
4658 CheckedVarArgs, UncoveredArg);
4659 return SLCT_CheckedLiteral;
4662 return SLCT_NotALiteral;
4664 case Stmt::BinaryOperatorClass: {
4665 llvm::APSInt LResult;
4666 llvm::APSInt RResult;
4668 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
4670 // A string literal + an int offset is still a string literal.
4671 if (BinOp->isAdditiveOp()) {
4672 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
4673 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
4675 if (LIsInt != RIsInt) {
4676 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
4679 if (BinOpKind == BO_Add) {
4680 sumOffsets(Offset, LResult, BinOpKind, RIsInt);
4681 E = BinOp->getRHS();
4685 sumOffsets(Offset, RResult, BinOpKind, RIsInt);
4686 E = BinOp->getLHS();
4692 return SLCT_NotALiteral;
4694 case Stmt::UnaryOperatorClass: {
4695 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
4696 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
4697 if (UnaOp->getOpcode() == clang::UO_AddrOf && ASE) {
4698 llvm::APSInt IndexResult;
4699 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
4700 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
4706 return SLCT_NotALiteral;
4710 return SLCT_NotALiteral;
4714 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
4715 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
4716 .Case("scanf", FST_Scanf)
4717 .Cases("printf", "printf0", FST_Printf)
4718 .Cases("NSString", "CFString", FST_NSString)
4719 .Case("strftime", FST_Strftime)
4720 .Case("strfmon", FST_Strfmon)
4721 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
4722 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
4723 .Case("os_trace", FST_OSLog)
4724 .Case("os_log", FST_OSLog)
4725 .Default(FST_Unknown);
4728 /// CheckFormatArguments - Check calls to printf and scanf (and similar
4729 /// functions) for correct use of format strings.
4730 /// Returns true if a format string has been fully checked.
4731 bool Sema::CheckFormatArguments(const FormatAttr *Format,
4732 ArrayRef<const Expr *> Args,
4734 VariadicCallType CallType,
4735 SourceLocation Loc, SourceRange Range,
4736 llvm::SmallBitVector &CheckedVarArgs) {
4737 FormatStringInfo FSI;
4738 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
4739 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
4740 FSI.FirstDataArg, GetFormatStringType(Format),
4741 CallType, Loc, Range, CheckedVarArgs);
4745 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
4746 bool HasVAListArg, unsigned format_idx,
4747 unsigned firstDataArg, FormatStringType Type,
4748 VariadicCallType CallType,
4749 SourceLocation Loc, SourceRange Range,
4750 llvm::SmallBitVector &CheckedVarArgs) {
4751 // CHECK: printf/scanf-like function is called with no format string.
4752 if (format_idx >= Args.size()) {
4753 Diag(Loc, diag::warn_missing_format_string) << Range;
4757 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
4759 // CHECK: format string is not a string literal.
4761 // Dynamically generated format strings are difficult to
4762 // automatically vet at compile time. Requiring that format strings
4763 // are string literals: (1) permits the checking of format strings by
4764 // the compiler and thereby (2) can practically remove the source of
4765 // many format string exploits.
4767 // Format string can be either ObjC string (e.g. @"%d") or
4768 // C string (e.g. "%d")
4769 // ObjC string uses the same format specifiers as C string, so we can use
4770 // the same format string checking logic for both ObjC and C strings.
4771 UncoveredArgHandler UncoveredArg;
4772 StringLiteralCheckType CT =
4773 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
4774 format_idx, firstDataArg, Type, CallType,
4775 /*IsFunctionCall*/ true, CheckedVarArgs,
4777 /*no string offset*/ llvm::APSInt(64, false) = 0);
4779 // Generate a diagnostic where an uncovered argument is detected.
4780 if (UncoveredArg.hasUncoveredArg()) {
4781 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
4782 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
4783 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
4786 if (CT != SLCT_NotALiteral)
4787 // Literal format string found, check done!
4788 return CT == SLCT_CheckedLiteral;
4790 // Strftime is particular as it always uses a single 'time' argument,
4791 // so it is safe to pass a non-literal string.
4792 if (Type == FST_Strftime)
4795 // Do not emit diag when the string param is a macro expansion and the
4796 // format is either NSString or CFString. This is a hack to prevent
4797 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
4798 // which are usually used in place of NS and CF string literals.
4799 SourceLocation FormatLoc = Args[format_idx]->getLocStart();
4800 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
4803 // If there are no arguments specified, warn with -Wformat-security, otherwise
4804 // warn only with -Wformat-nonliteral.
4805 if (Args.size() == firstDataArg) {
4806 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
4807 << OrigFormatExpr->getSourceRange();
4812 case FST_FreeBSDKPrintf:
4814 Diag(FormatLoc, diag::note_format_security_fixit)
4815 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
4818 Diag(FormatLoc, diag::note_format_security_fixit)
4819 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
4823 Diag(FormatLoc, diag::warn_format_nonliteral)
4824 << OrigFormatExpr->getSourceRange();
4830 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
4833 const FormatStringLiteral *FExpr;
4834 const Expr *OrigFormatExpr;
4835 const Sema::FormatStringType FSType;
4836 const unsigned FirstDataArg;
4837 const unsigned NumDataArgs;
4838 const char *Beg; // Start of format string.
4839 const bool HasVAListArg;
4840 ArrayRef<const Expr *> Args;
4842 llvm::SmallBitVector CoveredArgs;
4843 bool usesPositionalArgs;
4845 bool inFunctionCall;
4846 Sema::VariadicCallType CallType;
4847 llvm::SmallBitVector &CheckedVarArgs;
4848 UncoveredArgHandler &UncoveredArg;
4851 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
4852 const Expr *origFormatExpr,
4853 const Sema::FormatStringType type, unsigned firstDataArg,
4854 unsigned numDataArgs, const char *beg, bool hasVAListArg,
4855 ArrayRef<const Expr *> Args, unsigned formatIdx,
4856 bool inFunctionCall, Sema::VariadicCallType callType,
4857 llvm::SmallBitVector &CheckedVarArgs,
4858 UncoveredArgHandler &UncoveredArg)
4859 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
4860 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
4861 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
4862 usesPositionalArgs(false), atFirstArg(true),
4863 inFunctionCall(inFunctionCall), CallType(callType),
4864 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
4865 CoveredArgs.resize(numDataArgs);
4866 CoveredArgs.reset();
4869 void DoneProcessing();
4871 void HandleIncompleteSpecifier(const char *startSpecifier,
4872 unsigned specifierLen) override;
4874 void HandleInvalidLengthModifier(
4875 const analyze_format_string::FormatSpecifier &FS,
4876 const analyze_format_string::ConversionSpecifier &CS,
4877 const char *startSpecifier, unsigned specifierLen,
4880 void HandleNonStandardLengthModifier(
4881 const analyze_format_string::FormatSpecifier &FS,
4882 const char *startSpecifier, unsigned specifierLen);
4884 void HandleNonStandardConversionSpecifier(
4885 const analyze_format_string::ConversionSpecifier &CS,
4886 const char *startSpecifier, unsigned specifierLen);
4888 void HandlePosition(const char *startPos, unsigned posLen) override;
4890 void HandleInvalidPosition(const char *startSpecifier,
4891 unsigned specifierLen,
4892 analyze_format_string::PositionContext p) override;
4894 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
4896 void HandleNullChar(const char *nullCharacter) override;
4898 template <typename Range>
4900 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
4901 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
4902 bool IsStringLocation, Range StringRange,
4903 ArrayRef<FixItHint> Fixit = None);
4906 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
4907 const char *startSpec,
4908 unsigned specifierLen,
4909 const char *csStart, unsigned csLen);
4911 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
4912 const char *startSpec,
4913 unsigned specifierLen);
4915 SourceRange getFormatStringRange();
4916 CharSourceRange getSpecifierRange(const char *startSpecifier,
4917 unsigned specifierLen);
4918 SourceLocation getLocationOfByte(const char *x);
4920 const Expr *getDataArg(unsigned i) const;
4922 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
4923 const analyze_format_string::ConversionSpecifier &CS,
4924 const char *startSpecifier, unsigned specifierLen,
4927 template <typename Range>
4928 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
4929 bool IsStringLocation, Range StringRange,
4930 ArrayRef<FixItHint> Fixit = None);
4932 } // end anonymous namespace
4934 SourceRange CheckFormatHandler::getFormatStringRange() {
4935 return OrigFormatExpr->getSourceRange();
4938 CharSourceRange CheckFormatHandler::
4939 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
4940 SourceLocation Start = getLocationOfByte(startSpecifier);
4941 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
4943 // Advance the end SourceLocation by one due to half-open ranges.
4944 End = End.getLocWithOffset(1);
4946 return CharSourceRange::getCharRange(Start, End);
4949 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
4950 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
4951 S.getLangOpts(), S.Context.getTargetInfo());
4954 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
4955 unsigned specifierLen){
4956 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
4957 getLocationOfByte(startSpecifier),
4958 /*IsStringLocation*/true,
4959 getSpecifierRange(startSpecifier, specifierLen));
4962 void CheckFormatHandler::HandleInvalidLengthModifier(
4963 const analyze_format_string::FormatSpecifier &FS,
4964 const analyze_format_string::ConversionSpecifier &CS,
4965 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
4966 using namespace analyze_format_string;
4968 const LengthModifier &LM = FS.getLengthModifier();
4969 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4971 // See if we know how to fix this length modifier.
4972 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
4974 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
4975 getLocationOfByte(LM.getStart()),
4976 /*IsStringLocation*/true,
4977 getSpecifierRange(startSpecifier, specifierLen));
4979 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
4980 << FixedLM->toString()
4981 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
4985 if (DiagID == diag::warn_format_nonsensical_length)
4986 Hint = FixItHint::CreateRemoval(LMRange);
4988 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
4989 getLocationOfByte(LM.getStart()),
4990 /*IsStringLocation*/true,
4991 getSpecifierRange(startSpecifier, specifierLen),
4996 void CheckFormatHandler::HandleNonStandardLengthModifier(
4997 const analyze_format_string::FormatSpecifier &FS,
4998 const char *startSpecifier, unsigned specifierLen) {
4999 using namespace analyze_format_string;
5001 const LengthModifier &LM = FS.getLengthModifier();
5002 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5004 // See if we know how to fix this length modifier.
5005 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
5007 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5008 << LM.toString() << 0,
5009 getLocationOfByte(LM.getStart()),
5010 /*IsStringLocation*/true,
5011 getSpecifierRange(startSpecifier, specifierLen));
5013 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5014 << FixedLM->toString()
5015 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5018 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5019 << LM.toString() << 0,
5020 getLocationOfByte(LM.getStart()),
5021 /*IsStringLocation*/true,
5022 getSpecifierRange(startSpecifier, specifierLen));
5026 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5027 const analyze_format_string::ConversionSpecifier &CS,
5028 const char *startSpecifier, unsigned specifierLen) {
5029 using namespace analyze_format_string;
5031 // See if we know how to fix this conversion specifier.
5032 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
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));
5040 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5041 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5042 << FixedCS->toString()
5043 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5045 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5046 << CS.toString() << /*conversion specifier*/1,
5047 getLocationOfByte(CS.getStart()),
5048 /*IsStringLocation*/true,
5049 getSpecifierRange(startSpecifier, specifierLen));
5053 void CheckFormatHandler::HandlePosition(const char *startPos,
5055 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5056 getLocationOfByte(startPos),
5057 /*IsStringLocation*/true,
5058 getSpecifierRange(startPos, posLen));
5062 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5063 analyze_format_string::PositionContext p) {
5064 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5066 getLocationOfByte(startPos), /*IsStringLocation*/true,
5067 getSpecifierRange(startPos, posLen));
5070 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
5072 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5073 getLocationOfByte(startPos),
5074 /*IsStringLocation*/true,
5075 getSpecifierRange(startPos, posLen));
5078 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
5079 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
5080 // The presence of a null character is likely an error.
5081 EmitFormatDiagnostic(
5082 S.PDiag(diag::warn_printf_format_string_contains_null_char),
5083 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
5084 getFormatStringRange());
5088 // Note that this may return NULL if there was an error parsing or building
5089 // one of the argument expressions.
5090 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
5091 return Args[FirstDataArg + i];
5094 void CheckFormatHandler::DoneProcessing() {
5095 // Does the number of data arguments exceed the number of
5096 // format conversions in the format string?
5097 if (!HasVAListArg) {
5098 // Find any arguments that weren't covered.
5100 signed notCoveredArg = CoveredArgs.find_first();
5101 if (notCoveredArg >= 0) {
5102 assert((unsigned)notCoveredArg < NumDataArgs);
5103 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
5105 UncoveredArg.setAllCovered();
5110 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
5111 const Expr *ArgExpr) {
5112 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
5118 SourceLocation Loc = ArgExpr->getLocStart();
5120 if (S.getSourceManager().isInSystemMacro(Loc))
5123 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
5124 for (auto E : DiagnosticExprs)
5125 PDiag << E->getSourceRange();
5127 CheckFormatHandler::EmitFormatDiagnostic(
5128 S, IsFunctionCall, DiagnosticExprs[0],
5129 PDiag, Loc, /*IsStringLocation*/false,
5130 DiagnosticExprs[0]->getSourceRange());
5134 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
5136 const char *startSpec,
5137 unsigned specifierLen,
5138 const char *csStart,
5140 bool keepGoing = true;
5141 if (argIndex < NumDataArgs) {
5142 // Consider the argument coverered, even though the specifier doesn't
5144 CoveredArgs.set(argIndex);
5147 // If argIndex exceeds the number of data arguments we
5148 // don't issue a warning because that is just a cascade of warnings (and
5149 // they may have intended '%%' anyway). We don't want to continue processing
5150 // the format string after this point, however, as we will like just get
5151 // gibberish when trying to match arguments.
5155 StringRef Specifier(csStart, csLen);
5157 // If the specifier in non-printable, it could be the first byte of a UTF-8
5158 // sequence. In that case, print the UTF-8 code point. If not, print the byte
5160 std::string CodePointStr;
5161 if (!llvm::sys::locale::isPrint(*csStart)) {
5162 llvm::UTF32 CodePoint;
5163 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
5164 const llvm::UTF8 *E =
5165 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
5166 llvm::ConversionResult Result =
5167 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
5169 if (Result != llvm::conversionOK) {
5170 unsigned char FirstChar = *csStart;
5171 CodePoint = (llvm::UTF32)FirstChar;
5174 llvm::raw_string_ostream OS(CodePointStr);
5175 if (CodePoint < 256)
5176 OS << "\\x" << llvm::format("%02x", CodePoint);
5177 else if (CodePoint <= 0xFFFF)
5178 OS << "\\u" << llvm::format("%04x", CodePoint);
5180 OS << "\\U" << llvm::format("%08x", CodePoint);
5182 Specifier = CodePointStr;
5185 EmitFormatDiagnostic(
5186 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
5187 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
5193 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
5194 const char *startSpec,
5195 unsigned specifierLen) {
5196 EmitFormatDiagnostic(
5197 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
5198 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
5202 CheckFormatHandler::CheckNumArgs(
5203 const analyze_format_string::FormatSpecifier &FS,
5204 const analyze_format_string::ConversionSpecifier &CS,
5205 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
5207 if (argIndex >= NumDataArgs) {
5208 PartialDiagnostic PDiag = FS.usesPositionalArg()
5209 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
5210 << (argIndex+1) << NumDataArgs)
5211 : S.PDiag(diag::warn_printf_insufficient_data_args);
5212 EmitFormatDiagnostic(
5213 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
5214 getSpecifierRange(startSpecifier, specifierLen));
5216 // Since more arguments than conversion tokens are given, by extension
5217 // all arguments are covered, so mark this as so.
5218 UncoveredArg.setAllCovered();
5224 template<typename Range>
5225 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
5227 bool IsStringLocation,
5229 ArrayRef<FixItHint> FixIt) {
5230 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
5231 Loc, IsStringLocation, StringRange, FixIt);
5234 /// \brief If the format string is not within the funcion call, emit a note
5235 /// so that the function call and string are in diagnostic messages.
5237 /// \param InFunctionCall if true, the format string is within the function
5238 /// call and only one diagnostic message will be produced. Otherwise, an
5239 /// extra note will be emitted pointing to location of the format string.
5241 /// \param ArgumentExpr the expression that is passed as the format string
5242 /// argument in the function call. Used for getting locations when two
5243 /// diagnostics are emitted.
5245 /// \param PDiag the callee should already have provided any strings for the
5246 /// diagnostic message. This function only adds locations and fixits
5249 /// \param Loc primary location for diagnostic. If two diagnostics are
5250 /// required, one will be at Loc and a new SourceLocation will be created for
5253 /// \param IsStringLocation if true, Loc points to the format string should be
5254 /// used for the note. Otherwise, Loc points to the argument list and will
5255 /// be used with PDiag.
5257 /// \param StringRange some or all of the string to highlight. This is
5258 /// templated so it can accept either a CharSourceRange or a SourceRange.
5260 /// \param FixIt optional fix it hint for the format string.
5261 template <typename Range>
5262 void CheckFormatHandler::EmitFormatDiagnostic(
5263 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
5264 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
5265 Range StringRange, ArrayRef<FixItHint> FixIt) {
5266 if (InFunctionCall) {
5267 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
5271 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
5272 << ArgumentExpr->getSourceRange();
5274 const Sema::SemaDiagnosticBuilder &Note =
5275 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
5276 diag::note_format_string_defined);
5278 Note << StringRange;
5283 //===--- CHECK: Printf format string checking ------------------------------===//
5286 class CheckPrintfHandler : public CheckFormatHandler {
5288 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
5289 const Expr *origFormatExpr,
5290 const Sema::FormatStringType type, unsigned firstDataArg,
5291 unsigned numDataArgs, bool isObjC, const char *beg,
5292 bool hasVAListArg, ArrayRef<const Expr *> Args,
5293 unsigned formatIdx, bool inFunctionCall,
5294 Sema::VariadicCallType CallType,
5295 llvm::SmallBitVector &CheckedVarArgs,
5296 UncoveredArgHandler &UncoveredArg)
5297 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
5298 numDataArgs, beg, hasVAListArg, Args, formatIdx,
5299 inFunctionCall, CallType, CheckedVarArgs,
5302 bool isObjCContext() const { return FSType == Sema::FST_NSString; }
5304 /// Returns true if '%@' specifiers are allowed in the format string.
5305 bool allowsObjCArg() const {
5306 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
5307 FSType == Sema::FST_OSTrace;
5310 bool HandleInvalidPrintfConversionSpecifier(
5311 const analyze_printf::PrintfSpecifier &FS,
5312 const char *startSpecifier,
5313 unsigned specifierLen) override;
5315 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
5316 const char *startSpecifier,
5317 unsigned specifierLen) override;
5318 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5319 const char *StartSpecifier,
5320 unsigned SpecifierLen,
5323 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
5324 const char *startSpecifier, unsigned specifierLen);
5325 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
5326 const analyze_printf::OptionalAmount &Amt,
5328 const char *startSpecifier, unsigned specifierLen);
5329 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5330 const analyze_printf::OptionalFlag &flag,
5331 const char *startSpecifier, unsigned specifierLen);
5332 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
5333 const analyze_printf::OptionalFlag &ignoredFlag,
5334 const analyze_printf::OptionalFlag &flag,
5335 const char *startSpecifier, unsigned specifierLen);
5336 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
5339 void HandleEmptyObjCModifierFlag(const char *startFlag,
5340 unsigned flagLen) override;
5342 void HandleInvalidObjCModifierFlag(const char *startFlag,
5343 unsigned flagLen) override;
5345 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
5346 const char *flagsEnd,
5347 const char *conversionPosition)
5350 } // end anonymous namespace
5352 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
5353 const analyze_printf::PrintfSpecifier &FS,
5354 const char *startSpecifier,
5355 unsigned specifierLen) {
5356 const analyze_printf::PrintfConversionSpecifier &CS =
5357 FS.getConversionSpecifier();
5359 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5360 getLocationOfByte(CS.getStart()),
5361 startSpecifier, specifierLen,
5362 CS.getStart(), CS.getLength());
5365 bool CheckPrintfHandler::HandleAmount(
5366 const analyze_format_string::OptionalAmount &Amt,
5367 unsigned k, const char *startSpecifier,
5368 unsigned specifierLen) {
5369 if (Amt.hasDataArgument()) {
5370 if (!HasVAListArg) {
5371 unsigned argIndex = Amt.getArgIndex();
5372 if (argIndex >= NumDataArgs) {
5373 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
5375 getLocationOfByte(Amt.getStart()),
5376 /*IsStringLocation*/true,
5377 getSpecifierRange(startSpecifier, specifierLen));
5378 // Don't do any more checking. We will just emit
5383 // Type check the data argument. It should be an 'int'.
5384 // Although not in conformance with C99, we also allow the argument to be
5385 // an 'unsigned int' as that is a reasonably safe case. GCC also
5386 // doesn't emit a warning for that case.
5387 CoveredArgs.set(argIndex);
5388 const Expr *Arg = getDataArg(argIndex);
5392 QualType T = Arg->getType();
5394 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
5395 assert(AT.isValid());
5397 if (!AT.matchesType(S.Context, T)) {
5398 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
5399 << k << AT.getRepresentativeTypeName(S.Context)
5400 << T << Arg->getSourceRange(),
5401 getLocationOfByte(Amt.getStart()),
5402 /*IsStringLocation*/true,
5403 getSpecifierRange(startSpecifier, specifierLen));
5404 // Don't do any more checking. We will just emit
5413 void CheckPrintfHandler::HandleInvalidAmount(
5414 const analyze_printf::PrintfSpecifier &FS,
5415 const analyze_printf::OptionalAmount &Amt,
5417 const char *startSpecifier,
5418 unsigned specifierLen) {
5419 const analyze_printf::PrintfConversionSpecifier &CS =
5420 FS.getConversionSpecifier();
5423 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
5424 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
5425 Amt.getConstantLength()))
5428 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
5429 << type << CS.toString(),
5430 getLocationOfByte(Amt.getStart()),
5431 /*IsStringLocation*/true,
5432 getSpecifierRange(startSpecifier, specifierLen),
5436 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5437 const analyze_printf::OptionalFlag &flag,
5438 const char *startSpecifier,
5439 unsigned specifierLen) {
5440 // Warn about pointless flag with a fixit removal.
5441 const analyze_printf::PrintfConversionSpecifier &CS =
5442 FS.getConversionSpecifier();
5443 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
5444 << flag.toString() << CS.toString(),
5445 getLocationOfByte(flag.getPosition()),
5446 /*IsStringLocation*/true,
5447 getSpecifierRange(startSpecifier, specifierLen),
5448 FixItHint::CreateRemoval(
5449 getSpecifierRange(flag.getPosition(), 1)));
5452 void CheckPrintfHandler::HandleIgnoredFlag(
5453 const analyze_printf::PrintfSpecifier &FS,
5454 const analyze_printf::OptionalFlag &ignoredFlag,
5455 const analyze_printf::OptionalFlag &flag,
5456 const char *startSpecifier,
5457 unsigned specifierLen) {
5458 // Warn about ignored flag with a fixit removal.
5459 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
5460 << ignoredFlag.toString() << flag.toString(),
5461 getLocationOfByte(ignoredFlag.getPosition()),
5462 /*IsStringLocation*/true,
5463 getSpecifierRange(startSpecifier, specifierLen),
5464 FixItHint::CreateRemoval(
5465 getSpecifierRange(ignoredFlag.getPosition(), 1)));
5468 // void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5469 // bool IsStringLocation, Range StringRange,
5470 // ArrayRef<FixItHint> Fixit = None);
5472 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
5474 // Warn about an empty flag.
5475 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
5476 getLocationOfByte(startFlag),
5477 /*IsStringLocation*/true,
5478 getSpecifierRange(startFlag, flagLen));
5481 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
5483 // Warn about an invalid flag.
5484 auto Range = getSpecifierRange(startFlag, flagLen);
5485 StringRef flag(startFlag, flagLen);
5486 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
5487 getLocationOfByte(startFlag),
5488 /*IsStringLocation*/true,
5489 Range, FixItHint::CreateRemoval(Range));
5492 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
5493 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
5494 // Warn about using '[...]' without a '@' conversion.
5495 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
5496 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
5497 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
5498 getLocationOfByte(conversionPosition),
5499 /*IsStringLocation*/true,
5500 Range, FixItHint::CreateRemoval(Range));
5503 // Determines if the specified is a C++ class or struct containing
5504 // a member with the specified name and kind (e.g. a CXXMethodDecl named
5506 template<typename MemberKind>
5507 static llvm::SmallPtrSet<MemberKind*, 1>
5508 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
5509 const RecordType *RT = Ty->getAs<RecordType>();
5510 llvm::SmallPtrSet<MemberKind*, 1> Results;
5514 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
5515 if (!RD || !RD->getDefinition())
5518 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
5519 Sema::LookupMemberName);
5520 R.suppressDiagnostics();
5522 // We just need to include all members of the right kind turned up by the
5523 // filter, at this point.
5524 if (S.LookupQualifiedName(R, RT->getDecl()))
5525 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5526 NamedDecl *decl = (*I)->getUnderlyingDecl();
5527 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
5533 /// Check if we could call '.c_str()' on an object.
5535 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
5536 /// allow the call, or if it would be ambiguous).
5537 bool Sema::hasCStrMethod(const Expr *E) {
5538 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5540 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
5541 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5543 if ((*MI)->getMinRequiredArguments() == 0)
5548 // Check if a (w)string was passed when a (w)char* was needed, and offer a
5549 // better diagnostic if so. AT is assumed to be valid.
5550 // Returns true when a c_str() conversion method is found.
5551 bool CheckPrintfHandler::checkForCStrMembers(
5552 const analyze_printf::ArgType &AT, const Expr *E) {
5553 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5556 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
5558 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5560 const CXXMethodDecl *Method = *MI;
5561 if (Method->getMinRequiredArguments() == 0 &&
5562 AT.matchesType(S.Context, Method->getReturnType())) {
5563 // FIXME: Suggest parens if the expression needs them.
5564 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
5565 S.Diag(E->getLocStart(), diag::note_printf_c_str)
5567 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
5576 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
5578 const char *startSpecifier,
5579 unsigned specifierLen) {
5580 using namespace analyze_format_string;
5581 using namespace analyze_printf;
5582 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
5584 if (FS.consumesDataArgument()) {
5587 usesPositionalArgs = FS.usesPositionalArg();
5589 else if (usesPositionalArgs != FS.usesPositionalArg()) {
5590 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5591 startSpecifier, specifierLen);
5596 // First check if the field width, precision, and conversion specifier
5597 // have matching data arguments.
5598 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
5599 startSpecifier, specifierLen)) {
5603 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
5604 startSpecifier, specifierLen)) {
5608 if (!CS.consumesDataArgument()) {
5609 // FIXME: Technically specifying a precision or field width here
5610 // makes no sense. Worth issuing a warning at some point.
5614 // Consume the argument.
5615 unsigned argIndex = FS.getArgIndex();
5616 if (argIndex < NumDataArgs) {
5617 // The check to see if the argIndex is valid will come later.
5618 // We set the bit here because we may exit early from this
5619 // function if we encounter some other error.
5620 CoveredArgs.set(argIndex);
5623 // FreeBSD kernel extensions.
5624 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
5625 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
5626 // We need at least two arguments.
5627 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
5630 // Claim the second argument.
5631 CoveredArgs.set(argIndex + 1);
5633 // Type check the first argument (int for %b, pointer for %D)
5634 const Expr *Ex = getDataArg(argIndex);
5635 const analyze_printf::ArgType &AT =
5636 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
5637 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
5638 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
5639 EmitFormatDiagnostic(
5640 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5641 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
5642 << false << Ex->getSourceRange(),
5643 Ex->getLocStart(), /*IsStringLocation*/false,
5644 getSpecifierRange(startSpecifier, specifierLen));
5646 // Type check the second argument (char * for both %b and %D)
5647 Ex = getDataArg(argIndex + 1);
5648 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
5649 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
5650 EmitFormatDiagnostic(
5651 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5652 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
5653 << false << Ex->getSourceRange(),
5654 Ex->getLocStart(), /*IsStringLocation*/false,
5655 getSpecifierRange(startSpecifier, specifierLen));
5660 // Check for using an Objective-C specific conversion specifier
5661 // in a non-ObjC literal.
5662 if (!allowsObjCArg() && CS.isObjCArg()) {
5663 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5667 // %P can only be used with os_log.
5668 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
5669 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5673 // %n is not allowed with os_log.
5674 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
5675 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
5676 getLocationOfByte(CS.getStart()),
5677 /*IsStringLocation*/ false,
5678 getSpecifierRange(startSpecifier, specifierLen));
5683 // Only scalars are allowed for os_trace.
5684 if (FSType == Sema::FST_OSTrace &&
5685 (CS.getKind() == ConversionSpecifier::PArg ||
5686 CS.getKind() == ConversionSpecifier::sArg ||
5687 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
5688 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5692 // Check for use of public/private annotation outside of os_log().
5693 if (FSType != Sema::FST_OSLog) {
5694 if (FS.isPublic().isSet()) {
5695 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
5697 getLocationOfByte(FS.isPublic().getPosition()),
5698 /*IsStringLocation*/ false,
5699 getSpecifierRange(startSpecifier, specifierLen));
5701 if (FS.isPrivate().isSet()) {
5702 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
5704 getLocationOfByte(FS.isPrivate().getPosition()),
5705 /*IsStringLocation*/ false,
5706 getSpecifierRange(startSpecifier, specifierLen));
5710 // Check for invalid use of field width
5711 if (!FS.hasValidFieldWidth()) {
5712 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
5713 startSpecifier, specifierLen);
5716 // Check for invalid use of precision
5717 if (!FS.hasValidPrecision()) {
5718 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
5719 startSpecifier, specifierLen);
5722 // Precision is mandatory for %P specifier.
5723 if (CS.getKind() == ConversionSpecifier::PArg &&
5724 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
5725 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
5726 getLocationOfByte(startSpecifier),
5727 /*IsStringLocation*/ false,
5728 getSpecifierRange(startSpecifier, specifierLen));
5731 // Check each flag does not conflict with any other component.
5732 if (!FS.hasValidThousandsGroupingPrefix())
5733 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
5734 if (!FS.hasValidLeadingZeros())
5735 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
5736 if (!FS.hasValidPlusPrefix())
5737 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
5738 if (!FS.hasValidSpacePrefix())
5739 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
5740 if (!FS.hasValidAlternativeForm())
5741 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
5742 if (!FS.hasValidLeftJustified())
5743 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
5745 // Check that flags are not ignored by another flag
5746 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
5747 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
5748 startSpecifier, specifierLen);
5749 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
5750 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
5751 startSpecifier, specifierLen);
5753 // Check the length modifier is valid with the given conversion specifier.
5754 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
5755 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5756 diag::warn_format_nonsensical_length);
5757 else if (!FS.hasStandardLengthModifier())
5758 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
5759 else if (!FS.hasStandardLengthConversionCombination())
5760 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5761 diag::warn_format_non_standard_conversion_spec);
5763 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
5764 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
5766 // The remaining checks depend on the data arguments.
5770 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
5773 const Expr *Arg = getDataArg(argIndex);
5777 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
5780 static bool requiresParensToAddCast(const Expr *E) {
5781 // FIXME: We should have a general way to reason about operator
5782 // precedence and whether parens are actually needed here.
5783 // Take care of a few common cases where they aren't.
5784 const Expr *Inside = E->IgnoreImpCasts();
5785 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
5786 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
5788 switch (Inside->getStmtClass()) {
5789 case Stmt::ArraySubscriptExprClass:
5790 case Stmt::CallExprClass:
5791 case Stmt::CharacterLiteralClass:
5792 case Stmt::CXXBoolLiteralExprClass:
5793 case Stmt::DeclRefExprClass:
5794 case Stmt::FloatingLiteralClass:
5795 case Stmt::IntegerLiteralClass:
5796 case Stmt::MemberExprClass:
5797 case Stmt::ObjCArrayLiteralClass:
5798 case Stmt::ObjCBoolLiteralExprClass:
5799 case Stmt::ObjCBoxedExprClass:
5800 case Stmt::ObjCDictionaryLiteralClass:
5801 case Stmt::ObjCEncodeExprClass:
5802 case Stmt::ObjCIvarRefExprClass:
5803 case Stmt::ObjCMessageExprClass:
5804 case Stmt::ObjCPropertyRefExprClass:
5805 case Stmt::ObjCStringLiteralClass:
5806 case Stmt::ObjCSubscriptRefExprClass:
5807 case Stmt::ParenExprClass:
5808 case Stmt::StringLiteralClass:
5809 case Stmt::UnaryOperatorClass:
5816 static std::pair<QualType, StringRef>
5817 shouldNotPrintDirectly(const ASTContext &Context,
5818 QualType IntendedTy,
5820 // Use a 'while' to peel off layers of typedefs.
5821 QualType TyTy = IntendedTy;
5822 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
5823 StringRef Name = UserTy->getDecl()->getName();
5824 QualType CastTy = llvm::StringSwitch<QualType>(Name)
5825 .Case("NSInteger", Context.LongTy)
5826 .Case("NSUInteger", Context.UnsignedLongTy)
5827 .Case("SInt32", Context.IntTy)
5828 .Case("UInt32", Context.UnsignedIntTy)
5829 .Default(QualType());
5831 if (!CastTy.isNull())
5832 return std::make_pair(CastTy, Name);
5834 TyTy = UserTy->desugar();
5837 // Strip parens if necessary.
5838 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
5839 return shouldNotPrintDirectly(Context,
5840 PE->getSubExpr()->getType(),
5843 // If this is a conditional expression, then its result type is constructed
5844 // via usual arithmetic conversions and thus there might be no necessary
5845 // typedef sugar there. Recurse to operands to check for NSInteger &
5846 // Co. usage condition.
5847 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5848 QualType TrueTy, FalseTy;
5849 StringRef TrueName, FalseName;
5851 std::tie(TrueTy, TrueName) =
5852 shouldNotPrintDirectly(Context,
5853 CO->getTrueExpr()->getType(),
5855 std::tie(FalseTy, FalseName) =
5856 shouldNotPrintDirectly(Context,
5857 CO->getFalseExpr()->getType(),
5858 CO->getFalseExpr());
5860 if (TrueTy == FalseTy)
5861 return std::make_pair(TrueTy, TrueName);
5862 else if (TrueTy.isNull())
5863 return std::make_pair(FalseTy, FalseName);
5864 else if (FalseTy.isNull())
5865 return std::make_pair(TrueTy, TrueName);
5868 return std::make_pair(QualType(), StringRef());
5872 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5873 const char *StartSpecifier,
5874 unsigned SpecifierLen,
5876 using namespace analyze_format_string;
5877 using namespace analyze_printf;
5878 // Now type check the data expression that matches the
5879 // format specifier.
5880 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
5884 QualType ExprTy = E->getType();
5885 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
5886 ExprTy = TET->getUnderlyingExpr()->getType();
5889 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
5891 if (match == analyze_printf::ArgType::Match) {
5895 // Look through argument promotions for our error message's reported type.
5896 // This includes the integral and floating promotions, but excludes array
5897 // and function pointer decay; seeing that an argument intended to be a
5898 // string has type 'char [6]' is probably more confusing than 'char *'.
5899 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5900 if (ICE->getCastKind() == CK_IntegralCast ||
5901 ICE->getCastKind() == CK_FloatingCast) {
5902 E = ICE->getSubExpr();
5903 ExprTy = E->getType();
5905 // Check if we didn't match because of an implicit cast from a 'char'
5906 // or 'short' to an 'int'. This is done because printf is a varargs
5908 if (ICE->getType() == S.Context.IntTy ||
5909 ICE->getType() == S.Context.UnsignedIntTy) {
5910 // All further checking is done on the subexpression.
5911 if (AT.matchesType(S.Context, ExprTy))
5915 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
5916 // Special case for 'a', which has type 'int' in C.
5917 // Note, however, that we do /not/ want to treat multibyte constants like
5918 // 'MooV' as characters! This form is deprecated but still exists.
5919 if (ExprTy == S.Context.IntTy)
5920 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
5921 ExprTy = S.Context.CharTy;
5924 // Look through enums to their underlying type.
5925 bool IsEnum = false;
5926 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
5927 ExprTy = EnumTy->getDecl()->getIntegerType();
5931 // %C in an Objective-C context prints a unichar, not a wchar_t.
5932 // If the argument is an integer of some kind, believe the %C and suggest
5933 // a cast instead of changing the conversion specifier.
5934 QualType IntendedTy = ExprTy;
5935 if (isObjCContext() &&
5936 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
5937 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
5938 !ExprTy->isCharType()) {
5939 // 'unichar' is defined as a typedef of unsigned short, but we should
5940 // prefer using the typedef if it is visible.
5941 IntendedTy = S.Context.UnsignedShortTy;
5943 // While we are here, check if the value is an IntegerLiteral that happens
5944 // to be within the valid range.
5945 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
5946 const llvm::APInt &V = IL->getValue();
5947 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
5951 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
5952 Sema::LookupOrdinaryName);
5953 if (S.LookupName(Result, S.getCurScope())) {
5954 NamedDecl *ND = Result.getFoundDecl();
5955 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
5956 if (TD->getUnderlyingType() == IntendedTy)
5957 IntendedTy = S.Context.getTypedefType(TD);
5962 // Special-case some of Darwin's platform-independence types by suggesting
5963 // casts to primitive types that are known to be large enough.
5964 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
5965 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
5967 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
5968 if (!CastTy.isNull()) {
5969 IntendedTy = CastTy;
5970 ShouldNotPrintDirectly = true;
5974 // We may be able to offer a FixItHint if it is a supported type.
5975 PrintfSpecifier fixedFS = FS;
5977 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
5980 // Get the fix string from the fixed format specifier
5981 SmallString<16> buf;
5982 llvm::raw_svector_ostream os(buf);
5983 fixedFS.toString(os);
5985 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
5987 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
5988 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5989 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
5990 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5992 // In this case, the specifier is wrong and should be changed to match
5994 EmitFormatDiagnostic(S.PDiag(diag)
5995 << AT.getRepresentativeTypeName(S.Context)
5996 << IntendedTy << IsEnum << E->getSourceRange(),
5998 /*IsStringLocation*/ false, SpecRange,
5999 FixItHint::CreateReplacement(SpecRange, os.str()));
6001 // The canonical type for formatting this value is different from the
6002 // actual type of the expression. (This occurs, for example, with Darwin's
6003 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
6004 // should be printed as 'long' for 64-bit compatibility.)
6005 // Rather than emitting a normal format/argument mismatch, we want to
6006 // add a cast to the recommended type (and correct the format string
6008 SmallString<16> CastBuf;
6009 llvm::raw_svector_ostream CastFix(CastBuf);
6011 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
6014 SmallVector<FixItHint,4> Hints;
6015 if (!AT.matchesType(S.Context, IntendedTy))
6016 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
6018 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
6019 // If there's already a cast present, just replace it.
6020 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
6021 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
6023 } else if (!requiresParensToAddCast(E)) {
6024 // If the expression has high enough precedence,
6025 // just write the C-style cast.
6026 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6029 // Otherwise, add parens around the expression as well as the cast.
6031 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6034 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
6035 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6038 if (ShouldNotPrintDirectly) {
6039 // The expression has a type that should not be printed directly.
6040 // We extract the name from the typedef because we don't want to show
6041 // the underlying type in the diagnostic.
6043 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6044 Name = TypedefTy->getDecl()->getName();
6047 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
6048 << Name << IntendedTy << IsEnum
6049 << E->getSourceRange(),
6050 E->getLocStart(), /*IsStringLocation=*/false,
6053 // In this case, the expression could be printed using a different
6054 // specifier, but we've decided that the specifier is probably correct
6055 // and we should cast instead. Just use the normal warning message.
6056 EmitFormatDiagnostic(
6057 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6058 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
6059 << E->getSourceRange(),
6060 E->getLocStart(), /*IsStringLocation*/false,
6065 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
6067 // Since the warning for passing non-POD types to variadic functions
6068 // was deferred until now, we emit a warning for non-POD
6070 switch (S.isValidVarArgType(ExprTy)) {
6071 case Sema::VAK_Valid:
6072 case Sema::VAK_ValidInCXX11: {
6073 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6074 if (match == analyze_printf::ArgType::NoMatchPedantic) {
6075 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6078 EmitFormatDiagnostic(
6079 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
6080 << IsEnum << CSR << E->getSourceRange(),
6081 E->getLocStart(), /*IsStringLocation*/ false, CSR);
6084 case Sema::VAK_Undefined:
6085 case Sema::VAK_MSVCUndefined:
6086 EmitFormatDiagnostic(
6087 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
6088 << S.getLangOpts().CPlusPlus11
6091 << AT.getRepresentativeTypeName(S.Context)
6093 << E->getSourceRange(),
6094 E->getLocStart(), /*IsStringLocation*/false, CSR);
6095 checkForCStrMembers(AT, E);
6098 case Sema::VAK_Invalid:
6099 if (ExprTy->isObjCObjectType())
6100 EmitFormatDiagnostic(
6101 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
6102 << S.getLangOpts().CPlusPlus11
6105 << AT.getRepresentativeTypeName(S.Context)
6107 << E->getSourceRange(),
6108 E->getLocStart(), /*IsStringLocation*/false, CSR);
6110 // FIXME: If this is an initializer list, suggest removing the braces
6111 // or inserting a cast to the target type.
6112 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
6113 << isa<InitListExpr>(E) << ExprTy << CallType
6114 << AT.getRepresentativeTypeName(S.Context)
6115 << E->getSourceRange();
6119 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
6120 "format string specifier index out of range");
6121 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
6127 //===--- CHECK: Scanf format string checking ------------------------------===//
6130 class CheckScanfHandler : public CheckFormatHandler {
6132 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
6133 const Expr *origFormatExpr, Sema::FormatStringType type,
6134 unsigned firstDataArg, unsigned numDataArgs,
6135 const char *beg, bool hasVAListArg,
6136 ArrayRef<const Expr *> Args, unsigned formatIdx,
6137 bool inFunctionCall, Sema::VariadicCallType CallType,
6138 llvm::SmallBitVector &CheckedVarArgs,
6139 UncoveredArgHandler &UncoveredArg)
6140 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6141 numDataArgs, beg, hasVAListArg, Args, formatIdx,
6142 inFunctionCall, CallType, CheckedVarArgs,
6145 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
6146 const char *startSpecifier,
6147 unsigned specifierLen) override;
6149 bool HandleInvalidScanfConversionSpecifier(
6150 const analyze_scanf::ScanfSpecifier &FS,
6151 const char *startSpecifier,
6152 unsigned specifierLen) override;
6154 void HandleIncompleteScanList(const char *start, const char *end) override;
6156 } // end anonymous namespace
6158 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
6160 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
6161 getLocationOfByte(end), /*IsStringLocation*/true,
6162 getSpecifierRange(start, end - start));
6165 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
6166 const analyze_scanf::ScanfSpecifier &FS,
6167 const char *startSpecifier,
6168 unsigned specifierLen) {
6170 const analyze_scanf::ScanfConversionSpecifier &CS =
6171 FS.getConversionSpecifier();
6173 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6174 getLocationOfByte(CS.getStart()),
6175 startSpecifier, specifierLen,
6176 CS.getStart(), CS.getLength());
6179 bool CheckScanfHandler::HandleScanfSpecifier(
6180 const analyze_scanf::ScanfSpecifier &FS,
6181 const char *startSpecifier,
6182 unsigned specifierLen) {
6183 using namespace analyze_scanf;
6184 using namespace analyze_format_string;
6186 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
6188 // Handle case where '%' and '*' don't consume an argument. These shouldn't
6189 // be used to decide if we are using positional arguments consistently.
6190 if (FS.consumesDataArgument()) {
6193 usesPositionalArgs = FS.usesPositionalArg();
6195 else if (usesPositionalArgs != FS.usesPositionalArg()) {
6196 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6197 startSpecifier, specifierLen);
6202 // Check if the field with is non-zero.
6203 const OptionalAmount &Amt = FS.getFieldWidth();
6204 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
6205 if (Amt.getConstantAmount() == 0) {
6206 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
6207 Amt.getConstantLength());
6208 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
6209 getLocationOfByte(Amt.getStart()),
6210 /*IsStringLocation*/true, R,
6211 FixItHint::CreateRemoval(R));
6215 if (!FS.consumesDataArgument()) {
6216 // FIXME: Technically specifying a precision or field width here
6217 // makes no sense. Worth issuing a warning at some point.
6221 // Consume the argument.
6222 unsigned argIndex = FS.getArgIndex();
6223 if (argIndex < NumDataArgs) {
6224 // The check to see if the argIndex is valid will come later.
6225 // We set the bit here because we may exit early from this
6226 // function if we encounter some other error.
6227 CoveredArgs.set(argIndex);
6230 // Check the length modifier is valid with the given conversion specifier.
6231 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
6232 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6233 diag::warn_format_nonsensical_length);
6234 else if (!FS.hasStandardLengthModifier())
6235 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
6236 else if (!FS.hasStandardLengthConversionCombination())
6237 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6238 diag::warn_format_non_standard_conversion_spec);
6240 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6241 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6243 // The remaining checks depend on the data arguments.
6247 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
6250 // Check that the argument type matches the format specifier.
6251 const Expr *Ex = getDataArg(argIndex);
6255 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
6257 if (!AT.isValid()) {
6261 analyze_format_string::ArgType::MatchKind match =
6262 AT.matchesType(S.Context, Ex->getType());
6263 if (match == analyze_format_string::ArgType::Match) {
6267 ScanfSpecifier fixedFS = FS;
6268 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
6269 S.getLangOpts(), S.Context);
6271 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6272 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6273 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6277 // Get the fix string from the fixed format specifier.
6278 SmallString<128> buf;
6279 llvm::raw_svector_ostream os(buf);
6280 fixedFS.toString(os);
6282 EmitFormatDiagnostic(
6283 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
6284 << Ex->getType() << false << Ex->getSourceRange(),
6286 /*IsStringLocation*/ false,
6287 getSpecifierRange(startSpecifier, specifierLen),
6288 FixItHint::CreateReplacement(
6289 getSpecifierRange(startSpecifier, specifierLen), os.str()));
6291 EmitFormatDiagnostic(S.PDiag(diag)
6292 << AT.getRepresentativeTypeName(S.Context)
6293 << Ex->getType() << false << Ex->getSourceRange(),
6295 /*IsStringLocation*/ false,
6296 getSpecifierRange(startSpecifier, specifierLen));
6302 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
6303 const Expr *OrigFormatExpr,
6304 ArrayRef<const Expr *> Args,
6305 bool HasVAListArg, unsigned format_idx,
6306 unsigned firstDataArg,
6307 Sema::FormatStringType Type,
6308 bool inFunctionCall,
6309 Sema::VariadicCallType CallType,
6310 llvm::SmallBitVector &CheckedVarArgs,
6311 UncoveredArgHandler &UncoveredArg) {
6312 // CHECK: is the format string a wide literal?
6313 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
6314 CheckFormatHandler::EmitFormatDiagnostic(
6315 S, inFunctionCall, Args[format_idx],
6316 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
6317 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
6321 // Str - The format string. NOTE: this is NOT null-terminated!
6322 StringRef StrRef = FExpr->getString();
6323 const char *Str = StrRef.data();
6324 // Account for cases where the string literal is truncated in a declaration.
6325 const ConstantArrayType *T =
6326 S.Context.getAsConstantArrayType(FExpr->getType());
6327 assert(T && "String literal not of constant array type!");
6328 size_t TypeSize = T->getSize().getZExtValue();
6329 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6330 const unsigned numDataArgs = Args.size() - firstDataArg;
6332 // Emit a warning if the string literal is truncated and does not contain an
6333 // embedded null character.
6334 if (TypeSize <= StrRef.size() &&
6335 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
6336 CheckFormatHandler::EmitFormatDiagnostic(
6337 S, inFunctionCall, Args[format_idx],
6338 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
6339 FExpr->getLocStart(),
6340 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
6344 // CHECK: empty format string?
6345 if (StrLen == 0 && numDataArgs > 0) {
6346 CheckFormatHandler::EmitFormatDiagnostic(
6347 S, inFunctionCall, Args[format_idx],
6348 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
6349 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
6353 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
6354 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
6355 Type == Sema::FST_OSTrace) {
6356 CheckPrintfHandler H(
6357 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
6358 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
6359 HasVAListArg, Args, format_idx, inFunctionCall, CallType,
6360 CheckedVarArgs, UncoveredArg);
6362 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
6364 S.Context.getTargetInfo(),
6365 Type == Sema::FST_FreeBSDKPrintf))
6367 } else if (Type == Sema::FST_Scanf) {
6368 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
6369 numDataArgs, Str, HasVAListArg, Args, format_idx,
6370 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
6372 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
6374 S.Context.getTargetInfo()))
6376 } // TODO: handle other formats
6379 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
6380 // Str - The format string. NOTE: this is NOT null-terminated!
6381 StringRef StrRef = FExpr->getString();
6382 const char *Str = StrRef.data();
6383 // Account for cases where the string literal is truncated in a declaration.
6384 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
6385 assert(T && "String literal not of constant array type!");
6386 size_t TypeSize = T->getSize().getZExtValue();
6387 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6388 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
6390 Context.getTargetInfo());
6393 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
6395 // Returns the related absolute value function that is larger, of 0 if one
6397 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
6398 switch (AbsFunction) {
6402 case Builtin::BI__builtin_abs:
6403 return Builtin::BI__builtin_labs;
6404 case Builtin::BI__builtin_labs:
6405 return Builtin::BI__builtin_llabs;
6406 case Builtin::BI__builtin_llabs:
6409 case Builtin::BI__builtin_fabsf:
6410 return Builtin::BI__builtin_fabs;
6411 case Builtin::BI__builtin_fabs:
6412 return Builtin::BI__builtin_fabsl;
6413 case Builtin::BI__builtin_fabsl:
6416 case Builtin::BI__builtin_cabsf:
6417 return Builtin::BI__builtin_cabs;
6418 case Builtin::BI__builtin_cabs:
6419 return Builtin::BI__builtin_cabsl;
6420 case Builtin::BI__builtin_cabsl:
6423 case Builtin::BIabs:
6424 return Builtin::BIlabs;
6425 case Builtin::BIlabs:
6426 return Builtin::BIllabs;
6427 case Builtin::BIllabs:
6430 case Builtin::BIfabsf:
6431 return Builtin::BIfabs;
6432 case Builtin::BIfabs:
6433 return Builtin::BIfabsl;
6434 case Builtin::BIfabsl:
6437 case Builtin::BIcabsf:
6438 return Builtin::BIcabs;
6439 case Builtin::BIcabs:
6440 return Builtin::BIcabsl;
6441 case Builtin::BIcabsl:
6446 // Returns the argument type of the absolute value function.
6447 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
6452 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
6453 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
6454 if (Error != ASTContext::GE_None)
6457 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
6461 if (FT->getNumParams() != 1)
6464 return FT->getParamType(0);
6467 // Returns the best absolute value function, or zero, based on type and
6468 // current absolute value function.
6469 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
6470 unsigned AbsFunctionKind) {
6471 unsigned BestKind = 0;
6472 uint64_t ArgSize = Context.getTypeSize(ArgType);
6473 for (unsigned Kind = AbsFunctionKind; Kind != 0;
6474 Kind = getLargerAbsoluteValueFunction(Kind)) {
6475 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
6476 if (Context.getTypeSize(ParamType) >= ArgSize) {
6479 else if (Context.hasSameType(ParamType, ArgType)) {
6488 enum AbsoluteValueKind {
6494 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
6495 if (T->isIntegralOrEnumerationType())
6497 if (T->isRealFloatingType())
6498 return AVK_Floating;
6499 if (T->isAnyComplexType())
6502 llvm_unreachable("Type not integer, floating, or complex");
6505 // Changes the absolute value function to a different type. Preserves whether
6506 // the function is a builtin.
6507 static unsigned changeAbsFunction(unsigned AbsKind,
6508 AbsoluteValueKind ValueKind) {
6509 switch (ValueKind) {
6514 case Builtin::BI__builtin_fabsf:
6515 case Builtin::BI__builtin_fabs:
6516 case Builtin::BI__builtin_fabsl:
6517 case Builtin::BI__builtin_cabsf:
6518 case Builtin::BI__builtin_cabs:
6519 case Builtin::BI__builtin_cabsl:
6520 return Builtin::BI__builtin_abs;
6521 case Builtin::BIfabsf:
6522 case Builtin::BIfabs:
6523 case Builtin::BIfabsl:
6524 case Builtin::BIcabsf:
6525 case Builtin::BIcabs:
6526 case Builtin::BIcabsl:
6527 return Builtin::BIabs;
6533 case Builtin::BI__builtin_abs:
6534 case Builtin::BI__builtin_labs:
6535 case Builtin::BI__builtin_llabs:
6536 case Builtin::BI__builtin_cabsf:
6537 case Builtin::BI__builtin_cabs:
6538 case Builtin::BI__builtin_cabsl:
6539 return Builtin::BI__builtin_fabsf;
6540 case Builtin::BIabs:
6541 case Builtin::BIlabs:
6542 case Builtin::BIllabs:
6543 case Builtin::BIcabsf:
6544 case Builtin::BIcabs:
6545 case Builtin::BIcabsl:
6546 return Builtin::BIfabsf;
6552 case Builtin::BI__builtin_abs:
6553 case Builtin::BI__builtin_labs:
6554 case Builtin::BI__builtin_llabs:
6555 case Builtin::BI__builtin_fabsf:
6556 case Builtin::BI__builtin_fabs:
6557 case Builtin::BI__builtin_fabsl:
6558 return Builtin::BI__builtin_cabsf;
6559 case Builtin::BIabs:
6560 case Builtin::BIlabs:
6561 case Builtin::BIllabs:
6562 case Builtin::BIfabsf:
6563 case Builtin::BIfabs:
6564 case Builtin::BIfabsl:
6565 return Builtin::BIcabsf;
6568 llvm_unreachable("Unable to convert function");
6571 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
6572 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
6576 switch (FDecl->getBuiltinID()) {
6579 case Builtin::BI__builtin_abs:
6580 case Builtin::BI__builtin_fabs:
6581 case Builtin::BI__builtin_fabsf:
6582 case Builtin::BI__builtin_fabsl:
6583 case Builtin::BI__builtin_labs:
6584 case Builtin::BI__builtin_llabs:
6585 case Builtin::BI__builtin_cabs:
6586 case Builtin::BI__builtin_cabsf:
6587 case Builtin::BI__builtin_cabsl:
6588 case Builtin::BIabs:
6589 case Builtin::BIlabs:
6590 case Builtin::BIllabs:
6591 case Builtin::BIfabs:
6592 case Builtin::BIfabsf:
6593 case Builtin::BIfabsl:
6594 case Builtin::BIcabs:
6595 case Builtin::BIcabsf:
6596 case Builtin::BIcabsl:
6597 return FDecl->getBuiltinID();
6599 llvm_unreachable("Unknown Builtin type");
6602 // If the replacement is valid, emit a note with replacement function.
6603 // Additionally, suggest including the proper header if not already included.
6604 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
6605 unsigned AbsKind, QualType ArgType) {
6606 bool EmitHeaderHint = true;
6607 const char *HeaderName = nullptr;
6608 const char *FunctionName = nullptr;
6609 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
6610 FunctionName = "std::abs";
6611 if (ArgType->isIntegralOrEnumerationType()) {
6612 HeaderName = "cstdlib";
6613 } else if (ArgType->isRealFloatingType()) {
6614 HeaderName = "cmath";
6616 llvm_unreachable("Invalid Type");
6619 // Lookup all std::abs
6620 if (NamespaceDecl *Std = S.getStdNamespace()) {
6621 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
6622 R.suppressDiagnostics();
6623 S.LookupQualifiedName(R, Std);
6625 for (const auto *I : R) {
6626 const FunctionDecl *FDecl = nullptr;
6627 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
6628 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
6630 FDecl = dyn_cast<FunctionDecl>(I);
6635 // Found std::abs(), check that they are the right ones.
6636 if (FDecl->getNumParams() != 1)
6639 // Check that the parameter type can handle the argument.
6640 QualType ParamType = FDecl->getParamDecl(0)->getType();
6641 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
6642 S.Context.getTypeSize(ArgType) <=
6643 S.Context.getTypeSize(ParamType)) {
6644 // Found a function, don't need the header hint.
6645 EmitHeaderHint = false;
6651 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
6652 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
6655 DeclarationName DN(&S.Context.Idents.get(FunctionName));
6656 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
6657 R.suppressDiagnostics();
6658 S.LookupName(R, S.getCurScope());
6660 if (R.isSingleResult()) {
6661 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
6662 if (FD && FD->getBuiltinID() == AbsKind) {
6663 EmitHeaderHint = false;
6667 } else if (!R.empty()) {
6673 S.Diag(Loc, diag::note_replace_abs_function)
6674 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
6679 if (!EmitHeaderHint)
6682 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
6686 template <std::size_t StrLen>
6687 static bool IsStdFunction(const FunctionDecl *FDecl,
6688 const char (&Str)[StrLen]) {
6691 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
6693 if (!FDecl->isInStdNamespace())
6699 // Warn when using the wrong abs() function.
6700 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
6701 const FunctionDecl *FDecl) {
6702 if (Call->getNumArgs() != 1)
6705 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
6706 bool IsStdAbs = IsStdFunction(FDecl, "abs");
6707 if (AbsKind == 0 && !IsStdAbs)
6710 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
6711 QualType ParamType = Call->getArg(0)->getType();
6713 // Unsigned types cannot be negative. Suggest removing the absolute value
6715 if (ArgType->isUnsignedIntegerType()) {
6716 const char *FunctionName =
6717 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
6718 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
6719 Diag(Call->getExprLoc(), diag::note_remove_abs)
6721 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
6725 // Taking the absolute value of a pointer is very suspicious, they probably
6726 // wanted to index into an array, dereference a pointer, call a function, etc.
6727 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
6728 unsigned DiagType = 0;
6729 if (ArgType->isFunctionType())
6731 else if (ArgType->isArrayType())
6734 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
6738 // std::abs has overloads which prevent most of the absolute value problems
6743 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
6744 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
6746 // The argument and parameter are the same kind. Check if they are the right
6748 if (ArgValueKind == ParamValueKind) {
6749 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
6752 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
6753 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
6754 << FDecl << ArgType << ParamType;
6756 if (NewAbsKind == 0)
6759 emitReplacement(*this, Call->getExprLoc(),
6760 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
6764 // ArgValueKind != ParamValueKind
6765 // The wrong type of absolute value function was used. Attempt to find the
6767 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
6768 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
6769 if (NewAbsKind == 0)
6772 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
6773 << FDecl << ParamValueKind << ArgValueKind;
6775 emitReplacement(*this, Call->getExprLoc(),
6776 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
6779 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
6780 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
6781 const FunctionDecl *FDecl) {
6782 if (!Call || !FDecl) return;
6784 // Ignore template specializations and macros.
6785 if (!ActiveTemplateInstantiations.empty()) return;
6786 if (Call->getExprLoc().isMacroID()) return;
6788 // Only care about the one template argument, two function parameter std::max
6789 if (Call->getNumArgs() != 2) return;
6790 if (!IsStdFunction(FDecl, "max")) return;
6791 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
6792 if (!ArgList) return;
6793 if (ArgList->size() != 1) return;
6795 // Check that template type argument is unsigned integer.
6796 const auto& TA = ArgList->get(0);
6797 if (TA.getKind() != TemplateArgument::Type) return;
6798 QualType ArgType = TA.getAsType();
6799 if (!ArgType->isUnsignedIntegerType()) return;
6801 // See if either argument is a literal zero.
6802 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
6803 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
6804 if (!MTE) return false;
6805 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
6806 if (!Num) return false;
6807 if (Num->getValue() != 0) return false;
6811 const Expr *FirstArg = Call->getArg(0);
6812 const Expr *SecondArg = Call->getArg(1);
6813 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
6814 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
6816 // Only warn when exactly one argument is zero.
6817 if (IsFirstArgZero == IsSecondArgZero) return;
6819 SourceRange FirstRange = FirstArg->getSourceRange();
6820 SourceRange SecondRange = SecondArg->getSourceRange();
6822 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
6824 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
6825 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
6827 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
6828 SourceRange RemovalRange;
6829 if (IsFirstArgZero) {
6830 RemovalRange = SourceRange(FirstRange.getBegin(),
6831 SecondRange.getBegin().getLocWithOffset(-1));
6833 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
6834 SecondRange.getEnd());
6837 Diag(Call->getExprLoc(), diag::note_remove_max_call)
6838 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
6839 << FixItHint::CreateRemoval(RemovalRange);
6842 //===--- CHECK: Standard memory functions ---------------------------------===//
6844 /// \brief Takes the expression passed to the size_t parameter of functions
6845 /// such as memcmp, strncat, etc and warns if it's a comparison.
6847 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
6848 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
6849 IdentifierInfo *FnName,
6850 SourceLocation FnLoc,
6851 SourceLocation RParenLoc) {
6852 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
6856 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
6857 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
6860 SourceRange SizeRange = Size->getSourceRange();
6861 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
6862 << SizeRange << FnName;
6863 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
6864 << FnName << FixItHint::CreateInsertion(
6865 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
6866 << FixItHint::CreateRemoval(RParenLoc);
6867 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
6868 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
6869 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
6875 /// \brief Determine whether the given type is or contains a dynamic class type
6876 /// (e.g., whether it has a vtable).
6877 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
6878 bool &IsContained) {
6879 // Look through array types while ignoring qualifiers.
6880 const Type *Ty = T->getBaseElementTypeUnsafe();
6881 IsContained = false;
6883 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
6884 RD = RD ? RD->getDefinition() : nullptr;
6885 if (!RD || RD->isInvalidDecl())
6888 if (RD->isDynamicClass())
6891 // Check all the fields. If any bases were dynamic, the class is dynamic.
6892 // It's impossible for a class to transitively contain itself by value, so
6893 // infinite recursion is impossible.
6894 for (auto *FD : RD->fields()) {
6896 if (const CXXRecordDecl *ContainedRD =
6897 getContainedDynamicClass(FD->getType(), SubContained)) {
6906 /// \brief If E is a sizeof expression, returns its argument expression,
6907 /// otherwise returns NULL.
6908 static const Expr *getSizeOfExprArg(const Expr *E) {
6909 if (const UnaryExprOrTypeTraitExpr *SizeOf =
6910 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
6911 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
6912 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
6917 /// \brief If E is a sizeof expression, returns its argument type.
6918 static QualType getSizeOfArgType(const Expr *E) {
6919 if (const UnaryExprOrTypeTraitExpr *SizeOf =
6920 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
6921 if (SizeOf->getKind() == clang::UETT_SizeOf)
6922 return SizeOf->getTypeOfArgument();
6927 /// \brief Check for dangerous or invalid arguments to memset().
6929 /// This issues warnings on known problematic, dangerous or unspecified
6930 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
6933 /// \param Call The call expression to diagnose.
6934 void Sema::CheckMemaccessArguments(const CallExpr *Call,
6936 IdentifierInfo *FnName) {
6939 // It is possible to have a non-standard definition of memset. Validate
6940 // we have enough arguments, and if not, abort further checking.
6941 unsigned ExpectedNumArgs =
6942 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
6943 if (Call->getNumArgs() < ExpectedNumArgs)
6946 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
6947 BId == Builtin::BIstrndup ? 1 : 2);
6949 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
6950 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
6952 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
6953 Call->getLocStart(), Call->getRParenLoc()))
6956 // We have special checking when the length is a sizeof expression.
6957 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
6958 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
6959 llvm::FoldingSetNodeID SizeOfArgID;
6961 // Although widely used, 'bzero' is not a standard function. Be more strict
6962 // with the argument types before allowing diagnostics and only allow the
6963 // form bzero(ptr, sizeof(...)).
6964 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
6965 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
6968 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
6969 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
6970 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
6972 QualType DestTy = Dest->getType();
6974 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
6975 PointeeTy = DestPtrTy->getPointeeType();
6977 // Never warn about void type pointers. This can be used to suppress
6979 if (PointeeTy->isVoidType())
6982 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
6983 // actually comparing the expressions for equality. Because computing the
6984 // expression IDs can be expensive, we only do this if the diagnostic is
6987 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
6988 SizeOfArg->getExprLoc())) {
6989 // We only compute IDs for expressions if the warning is enabled, and
6990 // cache the sizeof arg's ID.
6991 if (SizeOfArgID == llvm::FoldingSetNodeID())
6992 SizeOfArg->Profile(SizeOfArgID, Context, true);
6993 llvm::FoldingSetNodeID DestID;
6994 Dest->Profile(DestID, Context, true);
6995 if (DestID == SizeOfArgID) {
6996 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
6997 // over sizeof(src) as well.
6998 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
6999 StringRef ReadableName = FnName->getName();
7001 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
7002 if (UnaryOp->getOpcode() == UO_AddrOf)
7003 ActionIdx = 1; // If its an address-of operator, just remove it.
7004 if (!PointeeTy->isIncompleteType() &&
7005 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
7006 ActionIdx = 2; // If the pointee's size is sizeof(char),
7007 // suggest an explicit length.
7009 // If the function is defined as a builtin macro, do not show macro
7011 SourceLocation SL = SizeOfArg->getExprLoc();
7012 SourceRange DSR = Dest->getSourceRange();
7013 SourceRange SSR = SizeOfArg->getSourceRange();
7014 SourceManager &SM = getSourceManager();
7016 if (SM.isMacroArgExpansion(SL)) {
7017 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
7018 SL = SM.getSpellingLoc(SL);
7019 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
7020 SM.getSpellingLoc(DSR.getEnd()));
7021 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
7022 SM.getSpellingLoc(SSR.getEnd()));
7025 DiagRuntimeBehavior(SL, SizeOfArg,
7026 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
7032 DiagRuntimeBehavior(SL, SizeOfArg,
7033 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
7041 // Also check for cases where the sizeof argument is the exact same
7042 // type as the memory argument, and where it points to a user-defined
7044 if (SizeOfArgTy != QualType()) {
7045 if (PointeeTy->isRecordType() &&
7046 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
7047 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
7048 PDiag(diag::warn_sizeof_pointer_type_memaccess)
7049 << FnName << SizeOfArgTy << ArgIdx
7050 << PointeeTy << Dest->getSourceRange()
7051 << LenExpr->getSourceRange());
7055 } else if (DestTy->isArrayType()) {
7059 if (PointeeTy == QualType())
7062 // Always complain about dynamic classes.
7064 if (const CXXRecordDecl *ContainedRD =
7065 getContainedDynamicClass(PointeeTy, IsContained)) {
7067 unsigned OperationType = 0;
7068 // "overwritten" if we're warning about the destination for any call
7069 // but memcmp; otherwise a verb appropriate to the call.
7070 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
7071 if (BId == Builtin::BImemcpy)
7073 else if(BId == Builtin::BImemmove)
7075 else if (BId == Builtin::BImemcmp)
7079 DiagRuntimeBehavior(
7080 Dest->getExprLoc(), Dest,
7081 PDiag(diag::warn_dyn_class_memaccess)
7082 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
7083 << FnName << IsContained << ContainedRD << OperationType
7084 << Call->getCallee()->getSourceRange());
7085 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
7086 BId != Builtin::BImemset)
7087 DiagRuntimeBehavior(
7088 Dest->getExprLoc(), Dest,
7089 PDiag(diag::warn_arc_object_memaccess)
7090 << ArgIdx << FnName << PointeeTy
7091 << Call->getCallee()->getSourceRange());
7095 DiagRuntimeBehavior(
7096 Dest->getExprLoc(), Dest,
7097 PDiag(diag::note_bad_memaccess_silence)
7098 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
7103 // A little helper routine: ignore addition and subtraction of integer literals.
7104 // This intentionally does not ignore all integer constant expressions because
7105 // we don't want to remove sizeof().
7106 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
7107 Ex = Ex->IgnoreParenCasts();
7110 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
7111 if (!BO || !BO->isAdditiveOp())
7114 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
7115 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
7117 if (isa<IntegerLiteral>(RHS))
7119 else if (isa<IntegerLiteral>(LHS))
7128 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
7129 ASTContext &Context) {
7130 // Only handle constant-sized or VLAs, but not flexible members.
7131 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
7132 // Only issue the FIXIT for arrays of size > 1.
7133 if (CAT->getSize().getSExtValue() <= 1)
7135 } else if (!Ty->isVariableArrayType()) {
7141 // Warn if the user has made the 'size' argument to strlcpy or strlcat
7142 // be the size of the source, instead of the destination.
7143 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
7144 IdentifierInfo *FnName) {
7146 // Don't crash if the user has the wrong number of arguments
7147 unsigned NumArgs = Call->getNumArgs();
7148 if ((NumArgs != 3) && (NumArgs != 4))
7151 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
7152 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
7153 const Expr *CompareWithSrc = nullptr;
7155 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
7156 Call->getLocStart(), Call->getRParenLoc()))
7159 // Look for 'strlcpy(dst, x, sizeof(x))'
7160 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
7161 CompareWithSrc = Ex;
7163 // Look for 'strlcpy(dst, x, strlen(x))'
7164 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
7165 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
7166 SizeCall->getNumArgs() == 1)
7167 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
7171 if (!CompareWithSrc)
7174 // Determine if the argument to sizeof/strlen is equal to the source
7175 // argument. In principle there's all kinds of things you could do
7176 // here, for instance creating an == expression and evaluating it with
7177 // EvaluateAsBooleanCondition, but this uses a more direct technique:
7178 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
7182 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
7183 if (!CompareWithSrcDRE ||
7184 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
7187 const Expr *OriginalSizeArg = Call->getArg(2);
7188 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
7189 << OriginalSizeArg->getSourceRange() << FnName;
7191 // Output a FIXIT hint if the destination is an array (rather than a
7192 // pointer to an array). This could be enhanced to handle some
7193 // pointers if we know the actual size, like if DstArg is 'array+2'
7194 // we could say 'sizeof(array)-2'.
7195 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
7196 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
7199 SmallString<128> sizeString;
7200 llvm::raw_svector_ostream OS(sizeString);
7202 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7205 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
7206 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
7210 /// Check if two expressions refer to the same declaration.
7211 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
7212 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
7213 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
7214 return D1->getDecl() == D2->getDecl();
7218 static const Expr *getStrlenExprArg(const Expr *E) {
7219 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7220 const FunctionDecl *FD = CE->getDirectCallee();
7221 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
7223 return CE->getArg(0)->IgnoreParenCasts();
7228 // Warn on anti-patterns as the 'size' argument to strncat.
7229 // The correct size argument should look like following:
7230 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
7231 void Sema::CheckStrncatArguments(const CallExpr *CE,
7232 IdentifierInfo *FnName) {
7233 // Don't crash if the user has the wrong number of arguments.
7234 if (CE->getNumArgs() < 3)
7236 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
7237 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
7238 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
7240 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
7241 CE->getRParenLoc()))
7244 // Identify common expressions, which are wrongly used as the size argument
7245 // to strncat and may lead to buffer overflows.
7246 unsigned PatternType = 0;
7247 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
7249 if (referToTheSameDecl(SizeOfArg, DstArg))
7252 else if (referToTheSameDecl(SizeOfArg, SrcArg))
7254 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
7255 if (BE->getOpcode() == BO_Sub) {
7256 const Expr *L = BE->getLHS()->IgnoreParenCasts();
7257 const Expr *R = BE->getRHS()->IgnoreParenCasts();
7258 // - sizeof(dst) - strlen(dst)
7259 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
7260 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
7262 // - sizeof(src) - (anything)
7263 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
7268 if (PatternType == 0)
7271 // Generate the diagnostic.
7272 SourceLocation SL = LenArg->getLocStart();
7273 SourceRange SR = LenArg->getSourceRange();
7274 SourceManager &SM = getSourceManager();
7276 // If the function is defined as a builtin macro, do not show macro expansion.
7277 if (SM.isMacroArgExpansion(SL)) {
7278 SL = SM.getSpellingLoc(SL);
7279 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
7280 SM.getSpellingLoc(SR.getEnd()));
7283 // Check if the destination is an array (rather than a pointer to an array).
7284 QualType DstTy = DstArg->getType();
7285 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
7287 if (!isKnownSizeArray) {
7288 if (PatternType == 1)
7289 Diag(SL, diag::warn_strncat_wrong_size) << SR;
7291 Diag(SL, diag::warn_strncat_src_size) << SR;
7295 if (PatternType == 1)
7296 Diag(SL, diag::warn_strncat_large_size) << SR;
7298 Diag(SL, diag::warn_strncat_src_size) << SR;
7300 SmallString<128> sizeString;
7301 llvm::raw_svector_ostream OS(sizeString);
7303 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7306 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7309 Diag(SL, diag::note_strncat_wrong_size)
7310 << FixItHint::CreateReplacement(SR, OS.str());
7313 //===--- CHECK: Return Address of Stack Variable --------------------------===//
7315 static const Expr *EvalVal(const Expr *E,
7316 SmallVectorImpl<const DeclRefExpr *> &refVars,
7317 const Decl *ParentDecl);
7318 static const Expr *EvalAddr(const Expr *E,
7319 SmallVectorImpl<const DeclRefExpr *> &refVars,
7320 const Decl *ParentDecl);
7322 /// CheckReturnStackAddr - Check if a return statement returns the address
7323 /// of a stack variable.
7325 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
7326 SourceLocation ReturnLoc) {
7328 const Expr *stackE = nullptr;
7329 SmallVector<const DeclRefExpr *, 8> refVars;
7331 // Perform checking for returned stack addresses, local blocks,
7332 // label addresses or references to temporaries.
7333 if (lhsType->isPointerType() ||
7334 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
7335 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
7336 } else if (lhsType->isReferenceType()) {
7337 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
7341 return; // Nothing suspicious was found.
7343 // Parameters are initalized in the calling scope, so taking the address
7344 // of a parameter reference doesn't need a warning.
7345 for (auto *DRE : refVars)
7346 if (isa<ParmVarDecl>(DRE->getDecl()))
7349 SourceLocation diagLoc;
7350 SourceRange diagRange;
7351 if (refVars.empty()) {
7352 diagLoc = stackE->getLocStart();
7353 diagRange = stackE->getSourceRange();
7355 // We followed through a reference variable. 'stackE' contains the
7356 // problematic expression but we will warn at the return statement pointing
7357 // at the reference variable. We will later display the "trail" of
7358 // reference variables using notes.
7359 diagLoc = refVars[0]->getLocStart();
7360 diagRange = refVars[0]->getSourceRange();
7363 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
7364 // address of local var
7365 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
7366 << DR->getDecl()->getDeclName() << diagRange;
7367 } else if (isa<BlockExpr>(stackE)) { // local block.
7368 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
7369 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
7370 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
7371 } else { // local temporary.
7372 // If there is an LValue->RValue conversion, then the value of the
7373 // reference type is used, not the reference.
7374 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
7375 if (ICE->getCastKind() == CK_LValueToRValue) {
7379 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
7380 << lhsType->isReferenceType() << diagRange;
7383 // Display the "trail" of reference variables that we followed until we
7384 // found the problematic expression using notes.
7385 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
7386 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
7387 // If this var binds to another reference var, show the range of the next
7388 // var, otherwise the var binds to the problematic expression, in which case
7389 // show the range of the expression.
7390 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
7391 : stackE->getSourceRange();
7392 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
7393 << VD->getDeclName() << range;
7397 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
7398 /// check if the expression in a return statement evaluates to an address
7399 /// to a location on the stack, a local block, an address of a label, or a
7400 /// reference to local temporary. The recursion is used to traverse the
7401 /// AST of the return expression, with recursion backtracking when we
7402 /// encounter a subexpression that (1) clearly does not lead to one of the
7403 /// above problematic expressions (2) is something we cannot determine leads to
7404 /// a problematic expression based on such local checking.
7406 /// Both EvalAddr and EvalVal follow through reference variables to evaluate
7407 /// the expression that they point to. Such variables are added to the
7408 /// 'refVars' vector so that we know what the reference variable "trail" was.
7410 /// EvalAddr processes expressions that are pointers that are used as
7411 /// references (and not L-values). EvalVal handles all other values.
7412 /// At the base case of the recursion is a check for the above problematic
7415 /// This implementation handles:
7417 /// * pointer-to-pointer casts
7418 /// * implicit conversions from array references to pointers
7419 /// * taking the address of fields
7420 /// * arbitrary interplay between "&" and "*" operators
7421 /// * pointer arithmetic from an address of a stack variable
7422 /// * taking the address of an array element where the array is on the stack
7423 static const Expr *EvalAddr(const Expr *E,
7424 SmallVectorImpl<const DeclRefExpr *> &refVars,
7425 const Decl *ParentDecl) {
7426 if (E->isTypeDependent())
7429 // We should only be called for evaluating pointer expressions.
7430 assert((E->getType()->isAnyPointerType() ||
7431 E->getType()->isBlockPointerType() ||
7432 E->getType()->isObjCQualifiedIdType()) &&
7433 "EvalAddr only works on pointers");
7435 E = E->IgnoreParens();
7437 // Our "symbolic interpreter" is just a dispatch off the currently
7438 // viewed AST node. We then recursively traverse the AST by calling
7439 // EvalAddr and EvalVal appropriately.
7440 switch (E->getStmtClass()) {
7441 case Stmt::DeclRefExprClass: {
7442 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7444 // If we leave the immediate function, the lifetime isn't about to end.
7445 if (DR->refersToEnclosingVariableOrCapture())
7448 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
7449 // If this is a reference variable, follow through to the expression that
7451 if (V->hasLocalStorage() &&
7452 V->getType()->isReferenceType() && V->hasInit()) {
7453 // Add the reference variable to the "trail".
7454 refVars.push_back(DR);
7455 return EvalAddr(V->getInit(), refVars, ParentDecl);
7461 case Stmt::UnaryOperatorClass: {
7462 // The only unary operator that make sense to handle here
7463 // is AddrOf. All others don't make sense as pointers.
7464 const UnaryOperator *U = cast<UnaryOperator>(E);
7466 if (U->getOpcode() == UO_AddrOf)
7467 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
7471 case Stmt::BinaryOperatorClass: {
7472 // Handle pointer arithmetic. All other binary operators are not valid
7474 const BinaryOperator *B = cast<BinaryOperator>(E);
7475 BinaryOperatorKind op = B->getOpcode();
7477 if (op != BO_Add && op != BO_Sub)
7480 const Expr *Base = B->getLHS();
7482 // Determine which argument is the real pointer base. It could be
7483 // the RHS argument instead of the LHS.
7484 if (!Base->getType()->isPointerType())
7487 assert(Base->getType()->isPointerType());
7488 return EvalAddr(Base, refVars, ParentDecl);
7491 // For conditional operators we need to see if either the LHS or RHS are
7492 // valid DeclRefExpr*s. If one of them is valid, we return it.
7493 case Stmt::ConditionalOperatorClass: {
7494 const ConditionalOperator *C = cast<ConditionalOperator>(E);
7496 // Handle the GNU extension for missing LHS.
7497 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
7498 if (const Expr *LHSExpr = C->getLHS()) {
7499 // In C++, we can have a throw-expression, which has 'void' type.
7500 if (!LHSExpr->getType()->isVoidType())
7501 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
7505 // In C++, we can have a throw-expression, which has 'void' type.
7506 if (C->getRHS()->getType()->isVoidType())
7509 return EvalAddr(C->getRHS(), refVars, ParentDecl);
7512 case Stmt::BlockExprClass:
7513 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
7514 return E; // local block.
7517 case Stmt::AddrLabelExprClass:
7518 return E; // address of label.
7520 case Stmt::ExprWithCleanupsClass:
7521 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7524 // For casts, we need to handle conversions from arrays to
7525 // pointer values, and pointer-to-pointer conversions.
7526 case Stmt::ImplicitCastExprClass:
7527 case Stmt::CStyleCastExprClass:
7528 case Stmt::CXXFunctionalCastExprClass:
7529 case Stmt::ObjCBridgedCastExprClass:
7530 case Stmt::CXXStaticCastExprClass:
7531 case Stmt::CXXDynamicCastExprClass:
7532 case Stmt::CXXConstCastExprClass:
7533 case Stmt::CXXReinterpretCastExprClass: {
7534 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
7535 switch (cast<CastExpr>(E)->getCastKind()) {
7536 case CK_LValueToRValue:
7538 case CK_BaseToDerived:
7539 case CK_DerivedToBase:
7540 case CK_UncheckedDerivedToBase:
7542 case CK_CPointerToObjCPointerCast:
7543 case CK_BlockPointerToObjCPointerCast:
7544 case CK_AnyPointerToBlockPointerCast:
7545 return EvalAddr(SubExpr, refVars, ParentDecl);
7547 case CK_ArrayToPointerDecay:
7548 return EvalVal(SubExpr, refVars, ParentDecl);
7551 if (SubExpr->getType()->isAnyPointerType() ||
7552 SubExpr->getType()->isBlockPointerType() ||
7553 SubExpr->getType()->isObjCQualifiedIdType())
7554 return EvalAddr(SubExpr, refVars, ParentDecl);
7563 case Stmt::MaterializeTemporaryExprClass:
7564 if (const Expr *Result =
7565 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7566 refVars, ParentDecl))
7570 // Everything else: we simply don't reason about them.
7576 /// EvalVal - This function is complements EvalAddr in the mutual recursion.
7577 /// See the comments for EvalAddr for more details.
7578 static const Expr *EvalVal(const Expr *E,
7579 SmallVectorImpl<const DeclRefExpr *> &refVars,
7580 const Decl *ParentDecl) {
7582 // We should only be called for evaluating non-pointer expressions, or
7583 // expressions with a pointer type that are not used as references but
7585 // are l-values (e.g., DeclRefExpr with a pointer type).
7587 // Our "symbolic interpreter" is just a dispatch off the currently
7588 // viewed AST node. We then recursively traverse the AST by calling
7589 // EvalAddr and EvalVal appropriately.
7591 E = E->IgnoreParens();
7592 switch (E->getStmtClass()) {
7593 case Stmt::ImplicitCastExprClass: {
7594 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
7595 if (IE->getValueKind() == VK_LValue) {
7596 E = IE->getSubExpr();
7602 case Stmt::ExprWithCleanupsClass:
7603 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7606 case Stmt::DeclRefExprClass: {
7607 // When we hit a DeclRefExpr we are looking at code that refers to a
7608 // variable's name. If it's not a reference variable we check if it has
7609 // local storage within the function, and if so, return the expression.
7610 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7612 // If we leave the immediate function, the lifetime isn't about to end.
7613 if (DR->refersToEnclosingVariableOrCapture())
7616 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
7617 // Check if it refers to itself, e.g. "int& i = i;".
7618 if (V == ParentDecl)
7621 if (V->hasLocalStorage()) {
7622 if (!V->getType()->isReferenceType())
7625 // Reference variable, follow through to the expression that
7628 // Add the reference variable to the "trail".
7629 refVars.push_back(DR);
7630 return EvalVal(V->getInit(), refVars, V);
7638 case Stmt::UnaryOperatorClass: {
7639 // The only unary operator that make sense to handle here
7640 // is Deref. All others don't resolve to a "name." This includes
7641 // handling all sorts of rvalues passed to a unary operator.
7642 const UnaryOperator *U = cast<UnaryOperator>(E);
7644 if (U->getOpcode() == UO_Deref)
7645 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
7650 case Stmt::ArraySubscriptExprClass: {
7651 // Array subscripts are potential references to data on the stack. We
7652 // retrieve the DeclRefExpr* for the array variable if it indeed
7653 // has local storage.
7654 const auto *ASE = cast<ArraySubscriptExpr>(E);
7655 if (ASE->isTypeDependent())
7657 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
7660 case Stmt::OMPArraySectionExprClass: {
7661 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
7665 case Stmt::ConditionalOperatorClass: {
7666 // For conditional operators we need to see if either the LHS or RHS are
7667 // non-NULL Expr's. If one is non-NULL, we return it.
7668 const ConditionalOperator *C = cast<ConditionalOperator>(E);
7670 // Handle the GNU extension for missing LHS.
7671 if (const Expr *LHSExpr = C->getLHS()) {
7672 // In C++, we can have a throw-expression, which has 'void' type.
7673 if (!LHSExpr->getType()->isVoidType())
7674 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
7678 // In C++, we can have a throw-expression, which has 'void' type.
7679 if (C->getRHS()->getType()->isVoidType())
7682 return EvalVal(C->getRHS(), refVars, ParentDecl);
7685 // Accesses to members are potential references to data on the stack.
7686 case Stmt::MemberExprClass: {
7687 const MemberExpr *M = cast<MemberExpr>(E);
7689 // Check for indirect access. We only want direct field accesses.
7693 // Check whether the member type is itself a reference, in which case
7694 // we're not going to refer to the member, but to what the member refers
7696 if (M->getMemberDecl()->getType()->isReferenceType())
7699 return EvalVal(M->getBase(), refVars, ParentDecl);
7702 case Stmt::MaterializeTemporaryExprClass:
7703 if (const Expr *Result =
7704 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7705 refVars, ParentDecl))
7710 // Check that we don't return or take the address of a reference to a
7711 // temporary. This is only useful in C++.
7712 if (!E->isTypeDependent() && E->isRValue())
7715 // Everything else: we simply don't reason about them.
7722 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
7723 SourceLocation ReturnLoc,
7725 const AttrVec *Attrs,
7726 const FunctionDecl *FD) {
7727 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
7729 // Check if the return value is null but should not be.
7730 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
7731 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
7732 CheckNonNullExpr(*this, RetValExp))
7733 Diag(ReturnLoc, diag::warn_null_ret)
7734 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
7736 // C++11 [basic.stc.dynamic.allocation]p4:
7737 // If an allocation function declared with a non-throwing
7738 // exception-specification fails to allocate storage, it shall return
7739 // a null pointer. Any other allocation function that fails to allocate
7740 // storage shall indicate failure only by throwing an exception [...]
7742 OverloadedOperatorKind Op = FD->getOverloadedOperator();
7743 if (Op == OO_New || Op == OO_Array_New) {
7744 const FunctionProtoType *Proto
7745 = FD->getType()->castAs<FunctionProtoType>();
7746 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
7747 CheckNonNullExpr(*this, RetValExp))
7748 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
7749 << FD << getLangOpts().CPlusPlus11;
7754 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
7756 /// Check for comparisons of floating point operands using != and ==.
7757 /// Issue a warning if these are no self-comparisons, as they are not likely
7758 /// to do what the programmer intended.
7759 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
7760 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
7761 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
7763 // Special case: check for x == x (which is OK).
7764 // Do not emit warnings for such cases.
7765 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
7766 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
7767 if (DRL->getDecl() == DRR->getDecl())
7770 // Special case: check for comparisons against literals that can be exactly
7771 // represented by APFloat. In such cases, do not emit a warning. This
7772 // is a heuristic: often comparison against such literals are used to
7773 // detect if a value in a variable has not changed. This clearly can
7774 // lead to false negatives.
7775 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
7779 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
7783 // Check for comparisons with builtin types.
7784 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
7785 if (CL->getBuiltinCallee())
7788 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
7789 if (CR->getBuiltinCallee())
7792 // Emit the diagnostic.
7793 Diag(Loc, diag::warn_floatingpoint_eq)
7794 << LHS->getSourceRange() << RHS->getSourceRange();
7797 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
7798 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
7802 /// Structure recording the 'active' range of an integer-valued
7805 /// The number of bits active in the int.
7808 /// True if the int is known not to have negative values.
7811 IntRange(unsigned Width, bool NonNegative)
7812 : Width(Width), NonNegative(NonNegative)
7815 /// Returns the range of the bool type.
7816 static IntRange forBoolType() {
7817 return IntRange(1, true);
7820 /// Returns the range of an opaque value of the given integral type.
7821 static IntRange forValueOfType(ASTContext &C, QualType T) {
7822 return forValueOfCanonicalType(C,
7823 T->getCanonicalTypeInternal().getTypePtr());
7826 /// Returns the range of an opaque value of a canonical integral type.
7827 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
7828 assert(T->isCanonicalUnqualified());
7830 if (const VectorType *VT = dyn_cast<VectorType>(T))
7831 T = VT->getElementType().getTypePtr();
7832 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
7833 T = CT->getElementType().getTypePtr();
7834 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7835 T = AT->getValueType().getTypePtr();
7837 // For enum types, use the known bit width of the enumerators.
7838 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
7839 EnumDecl *Enum = ET->getDecl();
7840 if (!Enum->isCompleteDefinition())
7841 return IntRange(C.getIntWidth(QualType(T, 0)), false);
7843 unsigned NumPositive = Enum->getNumPositiveBits();
7844 unsigned NumNegative = Enum->getNumNegativeBits();
7846 if (NumNegative == 0)
7847 return IntRange(NumPositive, true/*NonNegative*/);
7849 return IntRange(std::max(NumPositive + 1, NumNegative),
7850 false/*NonNegative*/);
7853 const BuiltinType *BT = cast<BuiltinType>(T);
7854 assert(BT->isInteger());
7856 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7859 /// Returns the "target" range of a canonical integral type, i.e.
7860 /// the range of values expressible in the type.
7862 /// This matches forValueOfCanonicalType except that enums have the
7863 /// full range of their type, not the range of their enumerators.
7864 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
7865 assert(T->isCanonicalUnqualified());
7867 if (const VectorType *VT = dyn_cast<VectorType>(T))
7868 T = VT->getElementType().getTypePtr();
7869 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
7870 T = CT->getElementType().getTypePtr();
7871 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7872 T = AT->getValueType().getTypePtr();
7873 if (const EnumType *ET = dyn_cast<EnumType>(T))
7874 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
7876 const BuiltinType *BT = cast<BuiltinType>(T);
7877 assert(BT->isInteger());
7879 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7882 /// Returns the supremum of two ranges: i.e. their conservative merge.
7883 static IntRange join(IntRange L, IntRange R) {
7884 return IntRange(std::max(L.Width, R.Width),
7885 L.NonNegative && R.NonNegative);
7888 /// Returns the infinum of two ranges: i.e. their aggressive merge.
7889 static IntRange meet(IntRange L, IntRange R) {
7890 return IntRange(std::min(L.Width, R.Width),
7891 L.NonNegative || R.NonNegative);
7895 IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
7896 if (value.isSigned() && value.isNegative())
7897 return IntRange(value.getMinSignedBits(), false);
7899 if (value.getBitWidth() > MaxWidth)
7900 value = value.trunc(MaxWidth);
7902 // isNonNegative() just checks the sign bit without considering
7904 return IntRange(value.getActiveBits(), true);
7907 IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
7908 unsigned MaxWidth) {
7910 return GetValueRange(C, result.getInt(), MaxWidth);
7912 if (result.isVector()) {
7913 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
7914 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
7915 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
7916 R = IntRange::join(R, El);
7921 if (result.isComplexInt()) {
7922 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
7923 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
7924 return IntRange::join(R, I);
7927 // This can happen with lossless casts to intptr_t of "based" lvalues.
7928 // Assume it might use arbitrary bits.
7929 // FIXME: The only reason we need to pass the type in here is to get
7930 // the sign right on this one case. It would be nice if APValue
7932 assert(result.isLValue() || result.isAddrLabelDiff());
7933 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
7936 QualType GetExprType(const Expr *E) {
7937 QualType Ty = E->getType();
7938 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
7939 Ty = AtomicRHS->getValueType();
7943 /// Pseudo-evaluate the given integer expression, estimating the
7944 /// range of values it might take.
7946 /// \param MaxWidth - the width to which the value will be truncated
7947 IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
7948 E = E->IgnoreParens();
7950 // Try a full evaluation first.
7951 Expr::EvalResult result;
7952 if (E->EvaluateAsRValue(result, C))
7953 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
7955 // I think we only want to look through implicit casts here; if the
7956 // user has an explicit widening cast, we should treat the value as
7957 // being of the new, wider type.
7958 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
7959 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
7960 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
7962 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
7964 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
7965 CE->getCastKind() == CK_BooleanToSignedIntegral;
7967 // Assume that non-integer casts can span the full range of the type.
7969 return OutputTypeRange;
7972 = GetExprRange(C, CE->getSubExpr(),
7973 std::min(MaxWidth, OutputTypeRange.Width));
7975 // Bail out if the subexpr's range is as wide as the cast type.
7976 if (SubRange.Width >= OutputTypeRange.Width)
7977 return OutputTypeRange;
7979 // Otherwise, we take the smaller width, and we're non-negative if
7980 // either the output type or the subexpr is.
7981 return IntRange(SubRange.Width,
7982 SubRange.NonNegative || OutputTypeRange.NonNegative);
7985 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
7986 // If we can fold the condition, just take that operand.
7988 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
7989 return GetExprRange(C, CondResult ? CO->getTrueExpr()
7990 : CO->getFalseExpr(),
7993 // Otherwise, conservatively merge.
7994 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
7995 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
7996 return IntRange::join(L, R);
7999 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
8000 switch (BO->getOpcode()) {
8002 // Boolean-valued operations are single-bit and positive.
8011 return IntRange::forBoolType();
8013 // The type of the assignments is the type of the LHS, so the RHS
8014 // is not necessarily the same type.
8023 return IntRange::forValueOfType(C, GetExprType(E));
8025 // Simple assignments just pass through the RHS, which will have
8026 // been coerced to the LHS type.
8029 return GetExprRange(C, BO->getRHS(), MaxWidth);
8031 // Operations with opaque sources are black-listed.
8034 return IntRange::forValueOfType(C, GetExprType(E));
8036 // Bitwise-and uses the *infinum* of the two source ranges.
8039 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
8040 GetExprRange(C, BO->getRHS(), MaxWidth));
8042 // Left shift gets black-listed based on a judgement call.
8044 // ...except that we want to treat '1 << (blah)' as logically
8045 // positive. It's an important idiom.
8046 if (IntegerLiteral *I
8047 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
8048 if (I->getValue() == 1) {
8049 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
8050 return IntRange(R.Width, /*NonNegative*/ true);
8056 return IntRange::forValueOfType(C, GetExprType(E));
8058 // Right shift by a constant can narrow its left argument.
8060 case BO_ShrAssign: {
8061 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8063 // If the shift amount is a positive constant, drop the width by
8066 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
8067 shift.isNonNegative()) {
8068 unsigned zext = shift.getZExtValue();
8069 if (zext >= L.Width)
8070 L.Width = (L.NonNegative ? 0 : 1);
8078 // Comma acts as its right operand.
8080 return GetExprRange(C, BO->getRHS(), MaxWidth);
8082 // Black-list pointer subtractions.
8084 if (BO->getLHS()->getType()->isPointerType())
8085 return IntRange::forValueOfType(C, GetExprType(E));
8088 // The width of a division result is mostly determined by the size
8091 // Don't 'pre-truncate' the operands.
8092 unsigned opWidth = C.getIntWidth(GetExprType(E));
8093 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8095 // If the divisor is constant, use that.
8096 llvm::APSInt divisor;
8097 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
8098 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
8099 if (log2 >= L.Width)
8100 L.Width = (L.NonNegative ? 0 : 1);
8102 L.Width = std::min(L.Width - log2, MaxWidth);
8106 // Otherwise, just use the LHS's width.
8107 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8108 return IntRange(L.Width, L.NonNegative && R.NonNegative);
8111 // The result of a remainder can't be larger than the result of
8114 // Don't 'pre-truncate' the operands.
8115 unsigned opWidth = C.getIntWidth(GetExprType(E));
8116 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8117 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8119 IntRange meet = IntRange::meet(L, R);
8120 meet.Width = std::min(meet.Width, MaxWidth);
8124 // The default behavior is okay for these.
8132 // The default case is to treat the operation as if it were closed
8133 // on the narrowest type that encompasses both operands.
8134 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8135 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
8136 return IntRange::join(L, R);
8139 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
8140 switch (UO->getOpcode()) {
8141 // Boolean-valued operations are white-listed.
8143 return IntRange::forBoolType();
8145 // Operations with opaque sources are black-listed.
8147 case UO_AddrOf: // should be impossible
8148 return IntRange::forValueOfType(C, GetExprType(E));
8151 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
8155 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
8156 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
8158 if (const auto *BitField = E->getSourceBitField())
8159 return IntRange(BitField->getBitWidthValue(C),
8160 BitField->getType()->isUnsignedIntegerOrEnumerationType());
8162 return IntRange::forValueOfType(C, GetExprType(E));
8165 IntRange GetExprRange(ASTContext &C, const Expr *E) {
8166 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
8169 /// Checks whether the given value, which currently has the given
8170 /// source semantics, has the same value when coerced through the
8171 /// target semantics.
8172 bool IsSameFloatAfterCast(const llvm::APFloat &value,
8173 const llvm::fltSemantics &Src,
8174 const llvm::fltSemantics &Tgt) {
8175 llvm::APFloat truncated = value;
8178 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
8179 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
8181 return truncated.bitwiseIsEqual(value);
8184 /// Checks whether the given value, which currently has the given
8185 /// source semantics, has the same value when coerced through the
8186 /// target semantics.
8188 /// The value might be a vector of floats (or a complex number).
8189 bool IsSameFloatAfterCast(const APValue &value,
8190 const llvm::fltSemantics &Src,
8191 const llvm::fltSemantics &Tgt) {
8192 if (value.isFloat())
8193 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
8195 if (value.isVector()) {
8196 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
8197 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
8202 assert(value.isComplexFloat());
8203 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
8204 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
8207 void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
8209 bool IsZero(Sema &S, Expr *E) {
8210 // Suppress cases where we are comparing against an enum constant.
8211 if (const DeclRefExpr *DR =
8212 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
8213 if (isa<EnumConstantDecl>(DR->getDecl()))
8216 // Suppress cases where the '0' value is expanded from a macro.
8217 if (E->getLocStart().isMacroID())
8221 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
8224 bool HasEnumType(Expr *E) {
8225 // Strip off implicit integral promotions.
8226 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8227 if (ICE->getCastKind() != CK_IntegralCast &&
8228 ICE->getCastKind() != CK_NoOp)
8230 E = ICE->getSubExpr();
8233 return E->getType()->isEnumeralType();
8236 void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
8237 // Disable warning in template instantiations.
8238 if (!S.ActiveTemplateInstantiations.empty())
8241 BinaryOperatorKind op = E->getOpcode();
8242 if (E->isValueDependent())
8245 if (op == BO_LT && IsZero(S, E->getRHS())) {
8246 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
8247 << "< 0" << "false" << HasEnumType(E->getLHS())
8248 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8249 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
8250 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
8251 << ">= 0" << "true" << HasEnumType(E->getLHS())
8252 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8253 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
8254 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
8255 << "0 >" << "false" << HasEnumType(E->getRHS())
8256 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8257 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
8258 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
8259 << "0 <=" << "true" << HasEnumType(E->getRHS())
8260 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8264 void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant,
8265 Expr *Other, const llvm::APSInt &Value,
8267 // Disable warning in template instantiations.
8268 if (!S.ActiveTemplateInstantiations.empty())
8271 // TODO: Investigate using GetExprRange() to get tighter bounds
8272 // on the bit ranges.
8273 QualType OtherT = Other->getType();
8274 if (const auto *AT = OtherT->getAs<AtomicType>())
8275 OtherT = AT->getValueType();
8276 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
8277 unsigned OtherWidth = OtherRange.Width;
8279 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
8281 // 0 values are handled later by CheckTrivialUnsignedComparison().
8282 if ((Value == 0) && (!OtherIsBooleanType))
8285 BinaryOperatorKind op = E->getOpcode();
8288 // Used for diagnostic printout.
8290 LiteralConstant = 0,
8293 } LiteralOrBoolConstant = LiteralConstant;
8295 if (!OtherIsBooleanType) {
8296 QualType ConstantT = Constant->getType();
8297 QualType CommonT = E->getLHS()->getType();
8299 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
8301 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
8302 "comparison with non-integer type");
8304 bool ConstantSigned = ConstantT->isSignedIntegerType();
8305 bool CommonSigned = CommonT->isSignedIntegerType();
8307 bool EqualityOnly = false;
8310 // The common type is signed, therefore no signed to unsigned conversion.
8311 if (!OtherRange.NonNegative) {
8312 // Check that the constant is representable in type OtherT.
8313 if (ConstantSigned) {
8314 if (OtherWidth >= Value.getMinSignedBits())
8316 } else { // !ConstantSigned
8317 if (OtherWidth >= Value.getActiveBits() + 1)
8320 } else { // !OtherSigned
8321 // Check that the constant is representable in type OtherT.
8322 // Negative values are out of range.
8323 if (ConstantSigned) {
8324 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
8326 } else { // !ConstantSigned
8327 if (OtherWidth >= Value.getActiveBits())
8331 } else { // !CommonSigned
8332 if (OtherRange.NonNegative) {
8333 if (OtherWidth >= Value.getActiveBits())
8335 } else { // OtherSigned
8336 assert(!ConstantSigned &&
8337 "Two signed types converted to unsigned types.");
8338 // Check to see if the constant is representable in OtherT.
8339 if (OtherWidth > Value.getActiveBits())
8341 // Check to see if the constant is equivalent to a negative value
8343 if (S.Context.getIntWidth(ConstantT) ==
8344 S.Context.getIntWidth(CommonT) &&
8345 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
8347 // The constant value rests between values that OtherT can represent
8348 // after conversion. Relational comparison still works, but equality
8349 // comparisons will be tautological.
8350 EqualityOnly = true;
8354 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
8356 if (op == BO_EQ || op == BO_NE) {
8357 IsTrue = op == BO_NE;
8358 } else if (EqualityOnly) {
8360 } else if (RhsConstant) {
8361 if (op == BO_GT || op == BO_GE)
8362 IsTrue = !PositiveConstant;
8363 else // op == BO_LT || op == BO_LE
8364 IsTrue = PositiveConstant;
8366 if (op == BO_LT || op == BO_LE)
8367 IsTrue = !PositiveConstant;
8368 else // op == BO_GT || op == BO_GE
8369 IsTrue = PositiveConstant;
8372 // Other isKnownToHaveBooleanValue
8373 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
8374 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
8375 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
8377 static const struct LinkedConditions {
8378 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
8379 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
8380 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
8381 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
8382 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
8383 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
8386 // Constant on LHS. | Constant on RHS. |
8387 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
8388 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
8389 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
8390 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
8391 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
8392 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
8393 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
8396 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
8398 enum ConstantValue ConstVal = Zero;
8399 if (Value.isUnsigned() || Value.isNonNegative()) {
8401 LiteralOrBoolConstant =
8402 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
8404 } else if (Value == 1) {
8405 LiteralOrBoolConstant =
8406 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
8409 LiteralOrBoolConstant = LiteralConstant;
8416 CompareBoolWithConstantResult CmpRes;
8420 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
8423 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
8426 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
8429 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
8432 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
8435 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
8442 if (CmpRes == AFals) {
8444 } else if (CmpRes == ATrue) {
8451 // If this is a comparison to an enum constant, include that
8452 // constant in the diagnostic.
8453 const EnumConstantDecl *ED = nullptr;
8454 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
8455 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
8457 SmallString<64> PrettySourceValue;
8458 llvm::raw_svector_ostream OS(PrettySourceValue);
8460 OS << '\'' << *ED << "' (" << Value << ")";
8464 S.DiagRuntimeBehavior(
8465 E->getOperatorLoc(), E,
8466 S.PDiag(diag::warn_out_of_range_compare)
8467 << OS.str() << LiteralOrBoolConstant
8468 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
8469 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
8472 /// Analyze the operands of the given comparison. Implements the
8473 /// fallback case from AnalyzeComparison.
8474 void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
8475 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8476 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
8479 /// \brief Implements -Wsign-compare.
8481 /// \param E the binary operator to check for warnings
8482 void AnalyzeComparison(Sema &S, BinaryOperator *E) {
8483 // The type the comparison is being performed in.
8484 QualType T = E->getLHS()->getType();
8486 // Only analyze comparison operators where both sides have been converted to
8488 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
8489 return AnalyzeImpConvsInComparison(S, E);
8491 // Don't analyze value-dependent comparisons directly.
8492 if (E->isValueDependent())
8493 return AnalyzeImpConvsInComparison(S, E);
8495 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
8496 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
8498 bool IsComparisonConstant = false;
8500 // Check whether an integer constant comparison results in a value
8501 // of 'true' or 'false'.
8502 if (T->isIntegralType(S.Context)) {
8503 llvm::APSInt RHSValue;
8504 bool IsRHSIntegralLiteral =
8505 RHS->isIntegerConstantExpr(RHSValue, S.Context);
8506 llvm::APSInt LHSValue;
8507 bool IsLHSIntegralLiteral =
8508 LHS->isIntegerConstantExpr(LHSValue, S.Context);
8509 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
8510 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
8511 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
8512 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
8514 IsComparisonConstant =
8515 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
8516 } else if (!T->hasUnsignedIntegerRepresentation())
8517 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
8519 // We don't do anything special if this isn't an unsigned integral
8520 // comparison: we're only interested in integral comparisons, and
8521 // signed comparisons only happen in cases we don't care to warn about.
8523 // We also don't care about value-dependent expressions or expressions
8524 // whose result is a constant.
8525 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
8526 return AnalyzeImpConvsInComparison(S, E);
8528 // Check to see if one of the (unmodified) operands is of different
8530 Expr *signedOperand, *unsignedOperand;
8531 if (LHS->getType()->hasSignedIntegerRepresentation()) {
8532 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
8533 "unsigned comparison between two signed integer expressions?");
8534 signedOperand = LHS;
8535 unsignedOperand = RHS;
8536 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
8537 signedOperand = RHS;
8538 unsignedOperand = LHS;
8540 CheckTrivialUnsignedComparison(S, E);
8541 return AnalyzeImpConvsInComparison(S, E);
8544 // Otherwise, calculate the effective range of the signed operand.
8545 IntRange signedRange = GetExprRange(S.Context, signedOperand);
8547 // Go ahead and analyze implicit conversions in the operands. Note
8548 // that we skip the implicit conversions on both sides.
8549 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
8550 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
8552 // If the signed range is non-negative, -Wsign-compare won't fire,
8553 // but we should still check for comparisons which are always true
8555 if (signedRange.NonNegative)
8556 return CheckTrivialUnsignedComparison(S, E);
8558 // For (in)equality comparisons, if the unsigned operand is a
8559 // constant which cannot collide with a overflowed signed operand,
8560 // then reinterpreting the signed operand as unsigned will not
8561 // change the result of the comparison.
8562 if (E->isEqualityOp()) {
8563 unsigned comparisonWidth = S.Context.getIntWidth(T);
8564 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
8566 // We should never be unable to prove that the unsigned operand is
8568 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
8570 if (unsignedRange.Width < comparisonWidth)
8574 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
8575 S.PDiag(diag::warn_mixed_sign_comparison)
8576 << LHS->getType() << RHS->getType()
8577 << LHS->getSourceRange() << RHS->getSourceRange());
8580 /// Analyzes an attempt to assign the given value to a bitfield.
8582 /// Returns true if there was something fishy about the attempt.
8583 bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
8584 SourceLocation InitLoc) {
8585 assert(Bitfield->isBitField());
8586 if (Bitfield->isInvalidDecl())
8589 // White-list bool bitfields.
8590 QualType BitfieldType = Bitfield->getType();
8591 if (BitfieldType->isBooleanType())
8594 if (BitfieldType->isEnumeralType()) {
8595 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
8596 // If the underlying enum type was not explicitly specified as an unsigned
8597 // type and the enum contain only positive values, MSVC++ will cause an
8598 // inconsistency by storing this as a signed type.
8599 if (S.getLangOpts().CPlusPlus11 &&
8600 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
8601 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
8602 BitfieldEnumDecl->getNumNegativeBits() == 0) {
8603 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
8604 << BitfieldEnumDecl->getNameAsString();
8608 if (Bitfield->getType()->isBooleanType())
8611 // Ignore value- or type-dependent expressions.
8612 if (Bitfield->getBitWidth()->isValueDependent() ||
8613 Bitfield->getBitWidth()->isTypeDependent() ||
8614 Init->isValueDependent() ||
8615 Init->isTypeDependent())
8618 Expr *OriginalInit = Init->IgnoreParenImpCasts();
8621 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
8624 unsigned OriginalWidth = Value.getBitWidth();
8625 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
8627 if (!Value.isSigned() || Value.isNegative())
8628 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
8629 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
8630 OriginalWidth = Value.getMinSignedBits();
8632 if (OriginalWidth <= FieldWidth)
8635 // Compute the value which the bitfield will contain.
8636 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
8637 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
8639 // Check whether the stored value is equal to the original value.
8640 TruncatedValue = TruncatedValue.extend(OriginalWidth);
8641 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
8644 // Special-case bitfields of width 1: booleans are naturally 0/1, and
8645 // therefore don't strictly fit into a signed bitfield of width 1.
8646 if (FieldWidth == 1 && Value == 1)
8649 std::string PrettyValue = Value.toString(10);
8650 std::string PrettyTrunc = TruncatedValue.toString(10);
8652 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
8653 << PrettyValue << PrettyTrunc << OriginalInit->getType()
8654 << Init->getSourceRange();
8659 /// Analyze the given simple or compound assignment for warning-worthy
8661 void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
8662 // Just recurse on the LHS.
8663 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8665 // We want to recurse on the RHS as normal unless we're assigning to
8667 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
8668 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
8669 E->getOperatorLoc())) {
8670 // Recurse, ignoring any implicit conversions on the RHS.
8671 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
8672 E->getOperatorLoc());
8676 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
8679 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
8680 void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
8681 SourceLocation CContext, unsigned diag,
8682 bool pruneControlFlow = false) {
8683 if (pruneControlFlow) {
8684 S.DiagRuntimeBehavior(E->getExprLoc(), E,
8686 << SourceType << T << E->getSourceRange()
8687 << SourceRange(CContext));
8690 S.Diag(E->getExprLoc(), diag)
8691 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
8694 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
8695 void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
8696 unsigned diag, bool pruneControlFlow = false) {
8697 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
8701 /// Diagnose an implicit cast from a floating point value to an integer value.
8702 void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
8704 SourceLocation CContext) {
8705 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
8706 const bool PruneWarnings = !S.ActiveTemplateInstantiations.empty();
8708 Expr *InnerE = E->IgnoreParenImpCasts();
8709 // We also want to warn on, e.g., "int i = -1.234"
8710 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
8711 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
8712 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
8714 const bool IsLiteral =
8715 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
8717 llvm::APFloat Value(0.0);
8719 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
8721 return DiagnoseImpCast(S, E, T, CContext,
8722 diag::warn_impcast_float_integer, PruneWarnings);
8725 bool isExact = false;
8727 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
8728 T->hasUnsignedIntegerRepresentation());
8729 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
8730 &isExact) == llvm::APFloat::opOK &&
8732 if (IsLiteral) return;
8733 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
8737 unsigned DiagID = 0;
8739 // Warn on floating point literal to integer.
8740 DiagID = diag::warn_impcast_literal_float_to_integer;
8741 } else if (IntegerValue == 0) {
8742 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
8743 return DiagnoseImpCast(S, E, T, CContext,
8744 diag::warn_impcast_float_integer, PruneWarnings);
8746 // Warn on non-zero to zero conversion.
8747 DiagID = diag::warn_impcast_float_to_integer_zero;
8749 if (IntegerValue.isUnsigned()) {
8750 if (!IntegerValue.isMaxValue()) {
8751 return DiagnoseImpCast(S, E, T, CContext,
8752 diag::warn_impcast_float_integer, PruneWarnings);
8754 } else { // IntegerValue.isSigned()
8755 if (!IntegerValue.isMaxSignedValue() &&
8756 !IntegerValue.isMinSignedValue()) {
8757 return DiagnoseImpCast(S, E, T, CContext,
8758 diag::warn_impcast_float_integer, PruneWarnings);
8761 // Warn on evaluatable floating point expression to integer conversion.
8762 DiagID = diag::warn_impcast_float_to_integer;
8765 // FIXME: Force the precision of the source value down so we don't print
8766 // digits which are usually useless (we don't really care here if we
8767 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
8768 // would automatically print the shortest representation, but it's a bit
8769 // tricky to implement.
8770 SmallString<16> PrettySourceValue;
8771 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
8772 precision = (precision * 59 + 195) / 196;
8773 Value.toString(PrettySourceValue, precision);
8775 SmallString<16> PrettyTargetValue;
8777 PrettyTargetValue = Value.isZero() ? "false" : "true";
8779 IntegerValue.toString(PrettyTargetValue);
8781 if (PruneWarnings) {
8782 S.DiagRuntimeBehavior(E->getExprLoc(), E,
8784 << E->getType() << T.getUnqualifiedType()
8785 << PrettySourceValue << PrettyTargetValue
8786 << E->getSourceRange() << SourceRange(CContext));
8788 S.Diag(E->getExprLoc(), DiagID)
8789 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
8790 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
8794 std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
8795 if (!Range.Width) return "0";
8797 llvm::APSInt ValueInRange = Value;
8798 ValueInRange.setIsSigned(!Range.NonNegative);
8799 ValueInRange = ValueInRange.trunc(Range.Width);
8800 return ValueInRange.toString(10);
8803 bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
8804 if (!isa<ImplicitCastExpr>(Ex))
8807 Expr *InnerE = Ex->IgnoreParenImpCasts();
8808 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
8809 const Type *Source =
8810 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
8811 if (Target->isDependentType())
8814 const BuiltinType *FloatCandidateBT =
8815 dyn_cast<BuiltinType>(ToBool ? Source : Target);
8816 const Type *BoolCandidateType = ToBool ? Target : Source;
8818 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
8819 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
8822 void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
8823 SourceLocation CC) {
8824 unsigned NumArgs = TheCall->getNumArgs();
8825 for (unsigned i = 0; i < NumArgs; ++i) {
8826 Expr *CurrA = TheCall->getArg(i);
8827 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
8830 bool IsSwapped = ((i > 0) &&
8831 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
8832 IsSwapped |= ((i < (NumArgs - 1)) &&
8833 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
8835 // Warn on this floating-point to bool conversion.
8836 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
8837 CurrA->getType(), CC,
8838 diag::warn_impcast_floating_point_to_bool);
8843 void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
8844 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
8848 // Don't warn on functions which have return type nullptr_t.
8849 if (isa<CallExpr>(E))
8852 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
8853 const Expr::NullPointerConstantKind NullKind =
8854 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
8855 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
8858 // Return if target type is a safe conversion.
8859 if (T->isAnyPointerType() || T->isBlockPointerType() ||
8860 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
8863 SourceLocation Loc = E->getSourceRange().getBegin();
8865 // Venture through the macro stacks to get to the source of macro arguments.
8866 // The new location is a better location than the complete location that was
8868 while (S.SourceMgr.isMacroArgExpansion(Loc))
8869 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
8871 while (S.SourceMgr.isMacroArgExpansion(CC))
8872 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
8874 // __null is usually wrapped in a macro. Go up a macro if that is the case.
8875 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
8876 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
8877 Loc, S.SourceMgr, S.getLangOpts());
8878 if (MacroName == "NULL")
8879 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
8882 // Only warn if the null and context location are in the same macro expansion.
8883 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
8886 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
8887 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
8888 << FixItHint::CreateReplacement(Loc,
8889 S.getFixItZeroLiteralForType(T, Loc));
8892 void checkObjCArrayLiteral(Sema &S, QualType TargetType,
8893 ObjCArrayLiteral *ArrayLiteral);
8894 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
8895 ObjCDictionaryLiteral *DictionaryLiteral);
8897 /// Check a single element within a collection literal against the
8898 /// target element type.
8899 void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
8900 Expr *Element, unsigned ElementKind) {
8901 // Skip a bitcast to 'id' or qualified 'id'.
8902 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
8903 if (ICE->getCastKind() == CK_BitCast &&
8904 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
8905 Element = ICE->getSubExpr();
8908 QualType ElementType = Element->getType();
8909 ExprResult ElementResult(Element);
8910 if (ElementType->getAs<ObjCObjectPointerType>() &&
8911 S.CheckSingleAssignmentConstraints(TargetElementType,
8914 != Sema::Compatible) {
8915 S.Diag(Element->getLocStart(),
8916 diag::warn_objc_collection_literal_element)
8917 << ElementType << ElementKind << TargetElementType
8918 << Element->getSourceRange();
8921 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
8922 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
8923 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
8924 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
8927 /// Check an Objective-C array literal being converted to the given
8929 void checkObjCArrayLiteral(Sema &S, QualType TargetType,
8930 ObjCArrayLiteral *ArrayLiteral) {
8934 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
8938 if (TargetObjCPtr->isUnspecialized() ||
8939 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
8940 != S.NSArrayDecl->getCanonicalDecl())
8943 auto TypeArgs = TargetObjCPtr->getTypeArgs();
8944 if (TypeArgs.size() != 1)
8947 QualType TargetElementType = TypeArgs[0];
8948 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
8949 checkObjCCollectionLiteralElement(S, TargetElementType,
8950 ArrayLiteral->getElement(I),
8955 /// Check an Objective-C dictionary literal being converted to the given
8957 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
8958 ObjCDictionaryLiteral *DictionaryLiteral) {
8959 if (!S.NSDictionaryDecl)
8962 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
8966 if (TargetObjCPtr->isUnspecialized() ||
8967 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
8968 != S.NSDictionaryDecl->getCanonicalDecl())
8971 auto TypeArgs = TargetObjCPtr->getTypeArgs();
8972 if (TypeArgs.size() != 2)
8975 QualType TargetKeyType = TypeArgs[0];
8976 QualType TargetObjectType = TypeArgs[1];
8977 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
8978 auto Element = DictionaryLiteral->getKeyValueElement(I);
8979 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
8980 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
8984 // Helper function to filter out cases for constant width constant conversion.
8985 // Don't warn on char array initialization or for non-decimal values.
8986 bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
8987 SourceLocation CC) {
8988 // If initializing from a constant, and the constant starts with '0',
8989 // then it is a binary, octal, or hexadecimal. Allow these constants
8990 // to fill all the bits, even if there is a sign change.
8991 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
8992 const char FirstLiteralCharacter =
8993 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
8994 if (FirstLiteralCharacter == '0')
8998 // If the CC location points to a '{', and the type is char, then assume
8999 // assume it is an array initialization.
9000 if (CC.isValid() && T->isCharType()) {
9001 const char FirstContextCharacter =
9002 S.getSourceManager().getCharacterData(CC)[0];
9003 if (FirstContextCharacter == '{')
9010 void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
9011 SourceLocation CC, bool *ICContext = nullptr) {
9012 if (E->isTypeDependent() || E->isValueDependent()) return;
9014 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
9015 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
9016 if (Source == Target) return;
9017 if (Target->isDependentType()) return;
9019 // If the conversion context location is invalid don't complain. We also
9020 // don't want to emit a warning if the issue occurs from the expansion of
9021 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
9022 // delay this check as long as possible. Once we detect we are in that
9023 // scenario, we just return.
9027 // Diagnose implicit casts to bool.
9028 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
9029 if (isa<StringLiteral>(E))
9030 // Warn on string literal to bool. Checks for string literals in logical
9031 // and expressions, for instance, assert(0 && "error here"), are
9032 // prevented by a check in AnalyzeImplicitConversions().
9033 return DiagnoseImpCast(S, E, T, CC,
9034 diag::warn_impcast_string_literal_to_bool);
9035 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
9036 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
9037 // This covers the literal expressions that evaluate to Objective-C
9039 return DiagnoseImpCast(S, E, T, CC,
9040 diag::warn_impcast_objective_c_literal_to_bool);
9042 if (Source->isPointerType() || Source->canDecayToPointerType()) {
9043 // Warn on pointer to bool conversion that is always true.
9044 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
9049 // Check implicit casts from Objective-C collection literals to specialized
9050 // collection types, e.g., NSArray<NSString *> *.
9051 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
9052 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
9053 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
9054 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
9056 // Strip vector types.
9057 if (isa<VectorType>(Source)) {
9058 if (!isa<VectorType>(Target)) {
9059 if (S.SourceMgr.isInSystemMacro(CC))
9061 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
9064 // If the vector cast is cast between two vectors of the same size, it is
9065 // a bitcast, not a conversion.
9066 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
9069 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
9070 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
9072 if (auto VecTy = dyn_cast<VectorType>(Target))
9073 Target = VecTy->getElementType().getTypePtr();
9075 // Strip complex types.
9076 if (isa<ComplexType>(Source)) {
9077 if (!isa<ComplexType>(Target)) {
9078 if (S.SourceMgr.isInSystemMacro(CC))
9081 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
9084 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
9085 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
9088 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
9089 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
9091 // If the source is floating point...
9092 if (SourceBT && SourceBT->isFloatingPoint()) {
9093 // ...and the target is floating point...
9094 if (TargetBT && TargetBT->isFloatingPoint()) {
9095 // ...then warn if we're dropping FP rank.
9097 // Builtin FP kinds are ordered by increasing FP rank.
9098 if (SourceBT->getKind() > TargetBT->getKind()) {
9099 // Don't warn about float constants that are precisely
9100 // representable in the target type.
9101 Expr::EvalResult result;
9102 if (E->EvaluateAsRValue(result, S.Context)) {
9103 // Value might be a float, a float vector, or a float complex.
9104 if (IsSameFloatAfterCast(result.Val,
9105 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
9106 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
9110 if (S.SourceMgr.isInSystemMacro(CC))
9113 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
9115 // ... or possibly if we're increasing rank, too
9116 else if (TargetBT->getKind() > SourceBT->getKind()) {
9117 if (S.SourceMgr.isInSystemMacro(CC))
9120 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
9125 // If the target is integral, always warn.
9126 if (TargetBT && TargetBT->isInteger()) {
9127 if (S.SourceMgr.isInSystemMacro(CC))
9130 DiagnoseFloatingImpCast(S, E, T, CC);
9133 // Detect the case where a call result is converted from floating-point to
9134 // to bool, and the final argument to the call is converted from bool, to
9135 // discover this typo:
9137 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
9139 // FIXME: This is an incredibly special case; is there some more general
9140 // way to detect this class of misplaced-parentheses bug?
9141 if (Target->isBooleanType() && isa<CallExpr>(E)) {
9142 // Check last argument of function call to see if it is an
9143 // implicit cast from a type matching the type the result
9144 // is being cast to.
9145 CallExpr *CEx = cast<CallExpr>(E);
9146 if (unsigned NumArgs = CEx->getNumArgs()) {
9147 Expr *LastA = CEx->getArg(NumArgs - 1);
9148 Expr *InnerE = LastA->IgnoreParenImpCasts();
9149 if (isa<ImplicitCastExpr>(LastA) &&
9150 InnerE->getType()->isBooleanType()) {
9151 // Warn on this floating-point to bool conversion
9152 DiagnoseImpCast(S, E, T, CC,
9153 diag::warn_impcast_floating_point_to_bool);
9160 DiagnoseNullConversion(S, E, T, CC);
9162 S.DiscardMisalignedMemberAddress(Target, E);
9164 if (!Source->isIntegerType() || !Target->isIntegerType())
9167 // TODO: remove this early return once the false positives for constant->bool
9168 // in templates, macros, etc, are reduced or removed.
9169 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
9172 IntRange SourceRange = GetExprRange(S.Context, E);
9173 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
9175 if (SourceRange.Width > TargetRange.Width) {
9176 // If the source is a constant, use a default-on diagnostic.
9177 // TODO: this should happen for bitfield stores, too.
9178 llvm::APSInt Value(32);
9179 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
9180 if (S.SourceMgr.isInSystemMacro(CC))
9183 std::string PrettySourceValue = Value.toString(10);
9184 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
9186 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9187 S.PDiag(diag::warn_impcast_integer_precision_constant)
9188 << PrettySourceValue << PrettyTargetValue
9189 << E->getType() << T << E->getSourceRange()
9190 << clang::SourceRange(CC));
9194 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
9195 if (S.SourceMgr.isInSystemMacro(CC))
9198 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
9199 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
9200 /* pruneControlFlow */ true);
9201 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
9204 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
9205 SourceRange.NonNegative && Source->isSignedIntegerType()) {
9206 // Warn when doing a signed to signed conversion, warn if the positive
9207 // source value is exactly the width of the target type, which will
9208 // cause a negative value to be stored.
9211 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
9212 !S.SourceMgr.isInSystemMacro(CC)) {
9213 if (isSameWidthConstantConversion(S, E, T, CC)) {
9214 std::string PrettySourceValue = Value.toString(10);
9215 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
9217 S.DiagRuntimeBehavior(
9219 S.PDiag(diag::warn_impcast_integer_precision_constant)
9220 << PrettySourceValue << PrettyTargetValue << E->getType() << T
9221 << E->getSourceRange() << clang::SourceRange(CC));
9226 // Fall through for non-constants to give a sign conversion warning.
9229 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
9230 (!TargetRange.NonNegative && SourceRange.NonNegative &&
9231 SourceRange.Width == TargetRange.Width)) {
9232 if (S.SourceMgr.isInSystemMacro(CC))
9235 unsigned DiagID = diag::warn_impcast_integer_sign;
9237 // Traditionally, gcc has warned about this under -Wsign-compare.
9238 // We also want to warn about it in -Wconversion.
9239 // So if -Wconversion is off, use a completely identical diagnostic
9240 // in the sign-compare group.
9241 // The conditional-checking code will
9243 DiagID = diag::warn_impcast_integer_sign_conditional;
9247 return DiagnoseImpCast(S, E, T, CC, DiagID);
9250 // Diagnose conversions between different enumeration types.
9251 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
9252 // type, to give us better diagnostics.
9253 QualType SourceType = E->getType();
9254 if (!S.getLangOpts().CPlusPlus) {
9255 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9256 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
9257 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
9258 SourceType = S.Context.getTypeDeclType(Enum);
9259 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
9263 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
9264 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
9265 if (SourceEnum->getDecl()->hasNameForLinkage() &&
9266 TargetEnum->getDecl()->hasNameForLinkage() &&
9267 SourceEnum != TargetEnum) {
9268 if (S.SourceMgr.isInSystemMacro(CC))
9271 return DiagnoseImpCast(S, E, SourceType, T, CC,
9272 diag::warn_impcast_different_enum_types);
9276 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9277 SourceLocation CC, QualType T);
9279 void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
9280 SourceLocation CC, bool &ICContext) {
9281 E = E->IgnoreParenImpCasts();
9283 if (isa<ConditionalOperator>(E))
9284 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
9286 AnalyzeImplicitConversions(S, E, CC);
9287 if (E->getType() != T)
9288 return CheckImplicitConversion(S, E, T, CC, &ICContext);
9291 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9292 SourceLocation CC, QualType T) {
9293 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
9295 bool Suspicious = false;
9296 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
9297 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
9299 // If -Wconversion would have warned about either of the candidates
9300 // for a signedness conversion to the context type...
9301 if (!Suspicious) return;
9303 // ...but it's currently ignored...
9304 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
9307 // ...then check whether it would have warned about either of the
9308 // candidates for a signedness conversion to the condition type.
9309 if (E->getType() == T) return;
9312 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
9313 E->getType(), CC, &Suspicious);
9315 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
9316 E->getType(), CC, &Suspicious);
9319 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9320 /// Input argument E is a logical expression.
9321 void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
9322 if (S.getLangOpts().Bool)
9324 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
9327 /// AnalyzeImplicitConversions - Find and report any interesting
9328 /// implicit conversions in the given expression. There are a couple
9329 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
9330 void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
9331 QualType T = OrigE->getType();
9332 Expr *E = OrigE->IgnoreParenImpCasts();
9334 if (E->isTypeDependent() || E->isValueDependent())
9337 // For conditional operators, we analyze the arguments as if they
9338 // were being fed directly into the output.
9339 if (isa<ConditionalOperator>(E)) {
9340 ConditionalOperator *CO = cast<ConditionalOperator>(E);
9341 CheckConditionalOperator(S, CO, CC, T);
9345 // Check implicit argument conversions for function calls.
9346 if (CallExpr *Call = dyn_cast<CallExpr>(E))
9347 CheckImplicitArgumentConversions(S, Call, CC);
9349 // Go ahead and check any implicit conversions we might have skipped.
9350 // The non-canonical typecheck is just an optimization;
9351 // CheckImplicitConversion will filter out dead implicit conversions.
9352 if (E->getType() != T)
9353 CheckImplicitConversion(S, E, T, CC);
9355 // Now continue drilling into this expression.
9357 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
9358 // The bound subexpressions in a PseudoObjectExpr are not reachable
9359 // as transitive children.
9360 // FIXME: Use a more uniform representation for this.
9361 for (auto *SE : POE->semantics())
9362 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
9363 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
9366 // Skip past explicit casts.
9367 if (isa<ExplicitCastExpr>(E)) {
9368 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
9369 return AnalyzeImplicitConversions(S, E, CC);
9372 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9373 // Do a somewhat different check with comparison operators.
9374 if (BO->isComparisonOp())
9375 return AnalyzeComparison(S, BO);
9377 // And with simple assignments.
9378 if (BO->getOpcode() == BO_Assign)
9379 return AnalyzeAssignment(S, BO);
9382 // These break the otherwise-useful invariant below. Fortunately,
9383 // we don't really need to recurse into them, because any internal
9384 // expressions should have been analyzed already when they were
9385 // built into statements.
9386 if (isa<StmtExpr>(E)) return;
9388 // Don't descend into unevaluated contexts.
9389 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
9391 // Now just recurse over the expression's children.
9392 CC = E->getExprLoc();
9393 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
9394 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
9395 for (Stmt *SubStmt : E->children()) {
9396 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
9400 if (IsLogicalAndOperator &&
9401 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
9402 // Ignore checking string literals that are in logical and operators.
9403 // This is a common pattern for asserts.
9405 AnalyzeImplicitConversions(S, ChildExpr, CC);
9408 if (BO && BO->isLogicalOp()) {
9409 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
9410 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
9411 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
9413 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
9414 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
9415 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
9418 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
9419 if (U->getOpcode() == UO_LNot)
9420 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
9423 } // end anonymous namespace
9425 /// Diagnose integer type and any valid implicit convertion to it.
9426 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
9427 // Taking into account implicit conversions,
9428 // allow any integer.
9429 if (!E->getType()->isIntegerType()) {
9430 S.Diag(E->getLocStart(),
9431 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
9434 // Potentially emit standard warnings for implicit conversions if enabled
9435 // using -Wconversion.
9436 CheckImplicitConversion(S, E, IntT, E->getLocStart());
9440 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
9441 // Returns true when emitting a warning about taking the address of a reference.
9442 static bool CheckForReference(Sema &SemaRef, const Expr *E,
9443 const PartialDiagnostic &PD) {
9444 E = E->IgnoreParenImpCasts();
9446 const FunctionDecl *FD = nullptr;
9448 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9449 if (!DRE->getDecl()->getType()->isReferenceType())
9451 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9452 if (!M->getMemberDecl()->getType()->isReferenceType())
9454 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
9455 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
9457 FD = Call->getDirectCallee();
9462 SemaRef.Diag(E->getExprLoc(), PD);
9464 // If possible, point to location of function.
9466 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
9472 // Returns true if the SourceLocation is expanded from any macro body.
9473 // Returns false if the SourceLocation is invalid, is from not in a macro
9474 // expansion, or is from expanded from a top-level macro argument.
9475 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
9476 if (Loc.isInvalid())
9479 while (Loc.isMacroID()) {
9480 if (SM.isMacroBodyExpansion(Loc))
9482 Loc = SM.getImmediateMacroCallerLoc(Loc);
9488 /// \brief Diagnose pointers that are always non-null.
9489 /// \param E the expression containing the pointer
9490 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
9491 /// compared to a null pointer
9492 /// \param IsEqual True when the comparison is equal to a null pointer
9493 /// \param Range Extra SourceRange to highlight in the diagnostic
9494 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
9495 Expr::NullPointerConstantKind NullKind,
9496 bool IsEqual, SourceRange Range) {
9500 // Don't warn inside macros.
9501 if (E->getExprLoc().isMacroID()) {
9502 const SourceManager &SM = getSourceManager();
9503 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
9504 IsInAnyMacroBody(SM, Range.getBegin()))
9507 E = E->IgnoreImpCasts();
9509 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
9511 if (isa<CXXThisExpr>(E)) {
9512 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
9513 : diag::warn_this_bool_conversion;
9514 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
9518 bool IsAddressOf = false;
9520 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9521 if (UO->getOpcode() != UO_AddrOf)
9524 E = UO->getSubExpr();
9528 unsigned DiagID = IsCompare
9529 ? diag::warn_address_of_reference_null_compare
9530 : diag::warn_address_of_reference_bool_conversion;
9531 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
9533 if (CheckForReference(*this, E, PD)) {
9538 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
9539 bool IsParam = isa<NonNullAttr>(NonnullAttr);
9541 llvm::raw_string_ostream S(Str);
9542 E->printPretty(S, nullptr, getPrintingPolicy());
9543 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
9544 : diag::warn_cast_nonnull_to_bool;
9545 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
9546 << E->getSourceRange() << Range << IsEqual;
9547 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
9550 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
9551 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
9552 if (auto *Callee = Call->getDirectCallee()) {
9553 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
9554 ComplainAboutNonnullParamOrCall(A);
9560 // Expect to find a single Decl. Skip anything more complicated.
9561 ValueDecl *D = nullptr;
9562 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
9564 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9565 D = M->getMemberDecl();
9568 // Weak Decls can be null.
9569 if (!D || D->isWeak())
9572 // Check for parameter decl with nonnull attribute
9573 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
9574 if (getCurFunction() &&
9575 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
9576 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
9577 ComplainAboutNonnullParamOrCall(A);
9581 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
9582 auto ParamIter = llvm::find(FD->parameters(), PV);
9583 assert(ParamIter != FD->param_end());
9584 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
9586 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
9587 if (!NonNull->args_size()) {
9588 ComplainAboutNonnullParamOrCall(NonNull);
9592 for (unsigned ArgNo : NonNull->args()) {
9593 if (ArgNo == ParamNo) {
9594 ComplainAboutNonnullParamOrCall(NonNull);
9603 QualType T = D->getType();
9604 const bool IsArray = T->isArrayType();
9605 const bool IsFunction = T->isFunctionType();
9607 // Address of function is used to silence the function warning.
9608 if (IsAddressOf && IsFunction) {
9613 if (!IsAddressOf && !IsFunction && !IsArray)
9616 // Pretty print the expression for the diagnostic.
9618 llvm::raw_string_ostream S(Str);
9619 E->printPretty(S, nullptr, getPrintingPolicy());
9621 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
9622 : diag::warn_impcast_pointer_to_bool;
9629 DiagType = AddressOf;
9630 else if (IsFunction)
9631 DiagType = FunctionPointer;
9633 DiagType = ArrayPointer;
9635 llvm_unreachable("Could not determine diagnostic.");
9636 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
9637 << Range << IsEqual;
9642 // Suggest '&' to silence the function warning.
9643 Diag(E->getExprLoc(), diag::note_function_warning_silence)
9644 << FixItHint::CreateInsertion(E->getLocStart(), "&");
9646 // Check to see if '()' fixit should be emitted.
9647 QualType ReturnType;
9648 UnresolvedSet<4> NonTemplateOverloads;
9649 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
9650 if (ReturnType.isNull())
9654 // There are two cases here. If there is null constant, the only suggest
9655 // for a pointer return type. If the null is 0, then suggest if the return
9656 // type is a pointer or an integer type.
9657 if (!ReturnType->isPointerType()) {
9658 if (NullKind == Expr::NPCK_ZeroExpression ||
9659 NullKind == Expr::NPCK_ZeroLiteral) {
9660 if (!ReturnType->isIntegerType())
9666 } else { // !IsCompare
9667 // For function to bool, only suggest if the function pointer has bool
9669 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
9672 Diag(E->getExprLoc(), diag::note_function_to_function_call)
9673 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
9676 /// Diagnoses "dangerous" implicit conversions within the given
9677 /// expression (which is a full expression). Implements -Wconversion
9678 /// and -Wsign-compare.
9680 /// \param CC the "context" location of the implicit conversion, i.e.
9681 /// the most location of the syntactic entity requiring the implicit
9683 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
9684 // Don't diagnose in unevaluated contexts.
9685 if (isUnevaluatedContext())
9688 // Don't diagnose for value- or type-dependent expressions.
9689 if (E->isTypeDependent() || E->isValueDependent())
9692 // Check for array bounds violations in cases where the check isn't triggered
9693 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
9694 // ArraySubscriptExpr is on the RHS of a variable initialization.
9695 CheckArrayAccess(E);
9697 // This is not the right CC for (e.g.) a variable initialization.
9698 AnalyzeImplicitConversions(*this, E, CC);
9701 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9702 /// Input argument E is a logical expression.
9703 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
9704 ::CheckBoolLikeConversion(*this, E, CC);
9707 /// Diagnose when expression is an integer constant expression and its evaluation
9708 /// results in integer overflow
9709 void Sema::CheckForIntOverflow (Expr *E) {
9710 // Use a work list to deal with nested struct initializers.
9711 SmallVector<Expr *, 2> Exprs(1, E);
9714 Expr *E = Exprs.pop_back_val();
9716 if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
9717 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
9721 if (auto InitList = dyn_cast<InitListExpr>(E))
9722 Exprs.append(InitList->inits().begin(), InitList->inits().end());
9723 } while (!Exprs.empty());
9727 /// \brief Visitor for expressions which looks for unsequenced operations on the
9729 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
9730 typedef EvaluatedExprVisitor<SequenceChecker> Base;
9732 /// \brief A tree of sequenced regions within an expression. Two regions are
9733 /// unsequenced if one is an ancestor or a descendent of the other. When we
9734 /// finish processing an expression with sequencing, such as a comma
9735 /// expression, we fold its tree nodes into its parent, since they are
9736 /// unsequenced with respect to nodes we will visit later.
9737 class SequenceTree {
9739 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
9740 unsigned Parent : 31;
9741 unsigned Merged : 1;
9743 SmallVector<Value, 8> Values;
9746 /// \brief A region within an expression which may be sequenced with respect
9747 /// to some other region.
9749 explicit Seq(unsigned N) : Index(N) {}
9751 friend class SequenceTree;
9756 SequenceTree() { Values.push_back(Value(0)); }
9757 Seq root() const { return Seq(0); }
9759 /// \brief Create a new sequence of operations, which is an unsequenced
9760 /// subset of \p Parent. This sequence of operations is sequenced with
9761 /// respect to other children of \p Parent.
9762 Seq allocate(Seq Parent) {
9763 Values.push_back(Value(Parent.Index));
9764 return Seq(Values.size() - 1);
9767 /// \brief Merge a sequence of operations into its parent.
9769 Values[S.Index].Merged = true;
9772 /// \brief Determine whether two operations are unsequenced. This operation
9773 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
9774 /// should have been merged into its parent as appropriate.
9775 bool isUnsequenced(Seq Cur, Seq Old) {
9776 unsigned C = representative(Cur.Index);
9777 unsigned Target = representative(Old.Index);
9778 while (C >= Target) {
9781 C = Values[C].Parent;
9787 /// \brief Pick a representative for a sequence.
9788 unsigned representative(unsigned K) {
9789 if (Values[K].Merged)
9790 // Perform path compression as we go.
9791 return Values[K].Parent = representative(Values[K].Parent);
9796 /// An object for which we can track unsequenced uses.
9797 typedef NamedDecl *Object;
9799 /// Different flavors of object usage which we track. We only track the
9800 /// least-sequenced usage of each kind.
9802 /// A read of an object. Multiple unsequenced reads are OK.
9804 /// A modification of an object which is sequenced before the value
9805 /// computation of the expression, such as ++n in C++.
9807 /// A modification of an object which is not sequenced before the value
9808 /// computation of the expression, such as n++.
9811 UK_Count = UK_ModAsSideEffect + 1
9815 Usage() : Use(nullptr), Seq() {}
9817 SequenceTree::Seq Seq;
9821 UsageInfo() : Diagnosed(false) {}
9822 Usage Uses[UK_Count];
9823 /// Have we issued a diagnostic for this variable already?
9826 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
9829 /// Sequenced regions within the expression.
9831 /// Declaration modifications and references which we have seen.
9832 UsageInfoMap UsageMap;
9833 /// The region we are currently within.
9834 SequenceTree::Seq Region;
9835 /// Filled in with declarations which were modified as a side-effect
9836 /// (that is, post-increment operations).
9837 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
9838 /// Expressions to check later. We defer checking these to reduce
9840 SmallVectorImpl<Expr *> &WorkList;
9842 /// RAII object wrapping the visitation of a sequenced subexpression of an
9843 /// expression. At the end of this process, the side-effects of the evaluation
9844 /// become sequenced with respect to the value computation of the result, so
9845 /// we downgrade any UK_ModAsSideEffect within the evaluation to
9847 struct SequencedSubexpression {
9848 SequencedSubexpression(SequenceChecker &Self)
9849 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
9850 Self.ModAsSideEffect = &ModAsSideEffect;
9852 ~SequencedSubexpression() {
9853 for (auto &M : llvm::reverse(ModAsSideEffect)) {
9854 UsageInfo &U = Self.UsageMap[M.first];
9855 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
9856 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
9857 SideEffectUsage = M.second;
9859 Self.ModAsSideEffect = OldModAsSideEffect;
9862 SequenceChecker &Self;
9863 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
9864 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
9867 /// RAII object wrapping the visitation of a subexpression which we might
9868 /// choose to evaluate as a constant. If any subexpression is evaluated and
9869 /// found to be non-constant, this allows us to suppress the evaluation of
9870 /// the outer expression.
9871 class EvaluationTracker {
9873 EvaluationTracker(SequenceChecker &Self)
9874 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
9875 Self.EvalTracker = this;
9877 ~EvaluationTracker() {
9878 Self.EvalTracker = Prev;
9880 Prev->EvalOK &= EvalOK;
9883 bool evaluate(const Expr *E, bool &Result) {
9884 if (!EvalOK || E->isValueDependent())
9886 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
9891 SequenceChecker &Self;
9892 EvaluationTracker *Prev;
9896 /// \brief Find the object which is produced by the specified expression,
9898 Object getObject(Expr *E, bool Mod) const {
9899 E = E->IgnoreParenCasts();
9900 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9901 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
9902 return getObject(UO->getSubExpr(), Mod);
9903 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9904 if (BO->getOpcode() == BO_Comma)
9905 return getObject(BO->getRHS(), Mod);
9906 if (Mod && BO->isAssignmentOp())
9907 return getObject(BO->getLHS(), Mod);
9908 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
9909 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
9910 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
9911 return ME->getMemberDecl();
9912 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9913 // FIXME: If this is a reference, map through to its value.
9914 return DRE->getDecl();
9918 /// \brief Note that an object was modified or used by an expression.
9919 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
9920 Usage &U = UI.Uses[UK];
9921 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
9922 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
9923 ModAsSideEffect->push_back(std::make_pair(O, U));
9928 /// \brief Check whether a modification or use conflicts with a prior usage.
9929 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
9934 const Usage &U = UI.Uses[OtherKind];
9935 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
9939 Expr *ModOrUse = Ref;
9940 if (OtherKind == UK_Use)
9941 std::swap(Mod, ModOrUse);
9943 SemaRef.Diag(Mod->getExprLoc(),
9944 IsModMod ? diag::warn_unsequenced_mod_mod
9945 : diag::warn_unsequenced_mod_use)
9946 << O << SourceRange(ModOrUse->getExprLoc());
9947 UI.Diagnosed = true;
9950 void notePreUse(Object O, Expr *Use) {
9951 UsageInfo &U = UsageMap[O];
9952 // Uses conflict with other modifications.
9953 checkUsage(O, U, Use, UK_ModAsValue, false);
9955 void notePostUse(Object O, Expr *Use) {
9956 UsageInfo &U = UsageMap[O];
9957 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
9958 addUsage(U, O, Use, UK_Use);
9961 void notePreMod(Object O, Expr *Mod) {
9962 UsageInfo &U = UsageMap[O];
9963 // Modifications conflict with other modifications and with uses.
9964 checkUsage(O, U, Mod, UK_ModAsValue, true);
9965 checkUsage(O, U, Mod, UK_Use, false);
9967 void notePostMod(Object O, Expr *Use, UsageKind UK) {
9968 UsageInfo &U = UsageMap[O];
9969 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
9970 addUsage(U, O, Use, UK);
9974 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
9975 : Base(S.Context), SemaRef(S), Region(Tree.root()),
9976 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
9980 void VisitStmt(Stmt *S) {
9981 // Skip all statements which aren't expressions for now.
9984 void VisitExpr(Expr *E) {
9985 // By default, just recurse to evaluated subexpressions.
9989 void VisitCastExpr(CastExpr *E) {
9990 Object O = Object();
9991 if (E->getCastKind() == CK_LValueToRValue)
9992 O = getObject(E->getSubExpr(), false);
10001 void VisitBinComma(BinaryOperator *BO) {
10002 // C++11 [expr.comma]p1:
10003 // Every value computation and side effect associated with the left
10004 // expression is sequenced before every value computation and side
10005 // effect associated with the right expression.
10006 SequenceTree::Seq LHS = Tree.allocate(Region);
10007 SequenceTree::Seq RHS = Tree.allocate(Region);
10008 SequenceTree::Seq OldRegion = Region;
10011 SequencedSubexpression SeqLHS(*this);
10013 Visit(BO->getLHS());
10017 Visit(BO->getRHS());
10019 Region = OldRegion;
10021 // Forget that LHS and RHS are sequenced. They are both unsequenced
10022 // with respect to other stuff.
10027 void VisitBinAssign(BinaryOperator *BO) {
10028 // The modification is sequenced after the value computation of the LHS
10029 // and RHS, so check it before inspecting the operands and update the
10031 Object O = getObject(BO->getLHS(), true);
10033 return VisitExpr(BO);
10037 // C++11 [expr.ass]p7:
10038 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
10041 // Therefore, for a compound assignment operator, O is considered used
10042 // everywhere except within the evaluation of E1 itself.
10043 if (isa<CompoundAssignOperator>(BO))
10046 Visit(BO->getLHS());
10048 if (isa<CompoundAssignOperator>(BO))
10049 notePostUse(O, BO);
10051 Visit(BO->getRHS());
10053 // C++11 [expr.ass]p1:
10054 // the assignment is sequenced [...] before the value computation of the
10055 // assignment expression.
10056 // C11 6.5.16/3 has no such rule.
10057 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10058 : UK_ModAsSideEffect);
10061 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
10062 VisitBinAssign(CAO);
10065 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10066 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10067 void VisitUnaryPreIncDec(UnaryOperator *UO) {
10068 Object O = getObject(UO->getSubExpr(), true);
10070 return VisitExpr(UO);
10073 Visit(UO->getSubExpr());
10074 // C++11 [expr.pre.incr]p1:
10075 // the expression ++x is equivalent to x+=1
10076 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10077 : UK_ModAsSideEffect);
10080 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10081 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10082 void VisitUnaryPostIncDec(UnaryOperator *UO) {
10083 Object O = getObject(UO->getSubExpr(), true);
10085 return VisitExpr(UO);
10088 Visit(UO->getSubExpr());
10089 notePostMod(O, UO, UK_ModAsSideEffect);
10092 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
10093 void VisitBinLOr(BinaryOperator *BO) {
10094 // The side-effects of the LHS of an '&&' are sequenced before the
10095 // value computation of the RHS, and hence before the value computation
10096 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
10097 // as if they were unconditionally sequenced.
10098 EvaluationTracker Eval(*this);
10100 SequencedSubexpression Sequenced(*this);
10101 Visit(BO->getLHS());
10105 if (Eval.evaluate(BO->getLHS(), Result)) {
10107 Visit(BO->getRHS());
10109 // Check for unsequenced operations in the RHS, treating it as an
10110 // entirely separate evaluation.
10112 // FIXME: If there are operations in the RHS which are unsequenced
10113 // with respect to operations outside the RHS, and those operations
10114 // are unconditionally evaluated, diagnose them.
10115 WorkList.push_back(BO->getRHS());
10118 void VisitBinLAnd(BinaryOperator *BO) {
10119 EvaluationTracker Eval(*this);
10121 SequencedSubexpression Sequenced(*this);
10122 Visit(BO->getLHS());
10126 if (Eval.evaluate(BO->getLHS(), Result)) {
10128 Visit(BO->getRHS());
10130 WorkList.push_back(BO->getRHS());
10134 // Only visit the condition, unless we can be sure which subexpression will
10136 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
10137 EvaluationTracker Eval(*this);
10139 SequencedSubexpression Sequenced(*this);
10140 Visit(CO->getCond());
10144 if (Eval.evaluate(CO->getCond(), Result))
10145 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
10147 WorkList.push_back(CO->getTrueExpr());
10148 WorkList.push_back(CO->getFalseExpr());
10152 void VisitCallExpr(CallExpr *CE) {
10153 // C++11 [intro.execution]p15:
10154 // When calling a function [...], every value computation and side effect
10155 // associated with any argument expression, or with the postfix expression
10156 // designating the called function, is sequenced before execution of every
10157 // expression or statement in the body of the function [and thus before
10158 // the value computation of its result].
10159 SequencedSubexpression Sequenced(*this);
10160 Base::VisitCallExpr(CE);
10162 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
10165 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
10166 // This is a call, so all subexpressions are sequenced before the result.
10167 SequencedSubexpression Sequenced(*this);
10169 if (!CCE->isListInitialization())
10170 return VisitExpr(CCE);
10172 // In C++11, list initializations are sequenced.
10173 SmallVector<SequenceTree::Seq, 32> Elts;
10174 SequenceTree::Seq Parent = Region;
10175 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
10176 E = CCE->arg_end();
10178 Region = Tree.allocate(Parent);
10179 Elts.push_back(Region);
10183 // Forget that the initializers are sequenced.
10185 for (unsigned I = 0; I < Elts.size(); ++I)
10186 Tree.merge(Elts[I]);
10189 void VisitInitListExpr(InitListExpr *ILE) {
10190 if (!SemaRef.getLangOpts().CPlusPlus11)
10191 return VisitExpr(ILE);
10193 // In C++11, list initializations are sequenced.
10194 SmallVector<SequenceTree::Seq, 32> Elts;
10195 SequenceTree::Seq Parent = Region;
10196 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
10197 Expr *E = ILE->getInit(I);
10199 Region = Tree.allocate(Parent);
10200 Elts.push_back(Region);
10204 // Forget that the initializers are sequenced.
10206 for (unsigned I = 0; I < Elts.size(); ++I)
10207 Tree.merge(Elts[I]);
10210 } // end anonymous namespace
10212 void Sema::CheckUnsequencedOperations(Expr *E) {
10213 SmallVector<Expr *, 8> WorkList;
10214 WorkList.push_back(E);
10215 while (!WorkList.empty()) {
10216 Expr *Item = WorkList.pop_back_val();
10217 SequenceChecker(*this, Item, WorkList);
10221 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
10222 bool IsConstexpr) {
10223 CheckImplicitConversions(E, CheckLoc);
10224 if (!E->isInstantiationDependent())
10225 CheckUnsequencedOperations(E);
10226 if (!IsConstexpr && !E->isValueDependent())
10227 CheckForIntOverflow(E);
10228 DiagnoseMisalignedMembers();
10231 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
10232 FieldDecl *BitField,
10234 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
10237 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
10238 SourceLocation Loc) {
10239 if (!PType->isVariablyModifiedType())
10241 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
10242 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
10245 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
10246 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
10249 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
10250 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
10254 const ArrayType *AT = S.Context.getAsArrayType(PType);
10258 if (AT->getSizeModifier() != ArrayType::Star) {
10259 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
10263 S.Diag(Loc, diag::err_array_star_in_function_definition);
10266 /// CheckParmsForFunctionDef - Check that the parameters of the given
10267 /// function are appropriate for the definition of a function. This
10268 /// takes care of any checks that cannot be performed on the
10269 /// declaration itself, e.g., that the types of each of the function
10270 /// parameters are complete.
10271 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
10272 bool CheckParameterNames) {
10273 bool HasInvalidParm = false;
10274 for (ParmVarDecl *Param : Parameters) {
10275 // C99 6.7.5.3p4: the parameters in a parameter type list in a
10276 // function declarator that is part of a function definition of
10277 // that function shall not have incomplete type.
10279 // This is also C++ [dcl.fct]p6.
10280 if (!Param->isInvalidDecl() &&
10281 RequireCompleteType(Param->getLocation(), Param->getType(),
10282 diag::err_typecheck_decl_incomplete_type)) {
10283 Param->setInvalidDecl();
10284 HasInvalidParm = true;
10287 // C99 6.9.1p5: If the declarator includes a parameter type list, the
10288 // declaration of each parameter shall include an identifier.
10289 if (CheckParameterNames &&
10290 Param->getIdentifier() == nullptr &&
10291 !Param->isImplicit() &&
10292 !getLangOpts().CPlusPlus)
10293 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
10296 // If the function declarator is not part of a definition of that
10297 // function, parameters may have incomplete type and may use the [*]
10298 // notation in their sequences of declarator specifiers to specify
10299 // variable length array types.
10300 QualType PType = Param->getOriginalType();
10301 // FIXME: This diagnostic should point the '[*]' if source-location
10302 // information is added for it.
10303 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
10305 // MSVC destroys objects passed by value in the callee. Therefore a
10306 // function definition which takes such a parameter must be able to call the
10307 // object's destructor. However, we don't perform any direct access check
10309 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
10311 .areArgsDestroyedLeftToRightInCallee()) {
10312 if (!Param->isInvalidDecl()) {
10313 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
10314 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
10315 if (!ClassDecl->isInvalidDecl() &&
10316 !ClassDecl->hasIrrelevantDestructor() &&
10317 !ClassDecl->isDependentContext()) {
10318 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10319 MarkFunctionReferenced(Param->getLocation(), Destructor);
10320 DiagnoseUseOfDecl(Destructor, Param->getLocation());
10326 // Parameters with the pass_object_size attribute only need to be marked
10327 // constant at function definitions. Because we lack information about
10328 // whether we're on a declaration or definition when we're instantiating the
10329 // attribute, we need to check for constness here.
10330 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
10331 if (!Param->getType().isConstQualified())
10332 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
10333 << Attr->getSpelling() << 1;
10336 return HasInvalidParm;
10339 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr
10341 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
10342 ASTContext &Context) {
10343 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
10344 return Context.getDeclAlign(DRE->getDecl());
10346 if (const auto *ME = dyn_cast<MemberExpr>(E))
10347 return Context.getDeclAlign(ME->getMemberDecl());
10352 /// CheckCastAlign - Implements -Wcast-align, which warns when a
10353 /// pointer cast increases the alignment requirements.
10354 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
10355 // This is actually a lot of work to potentially be doing on every
10356 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
10357 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
10360 // Ignore dependent types.
10361 if (T->isDependentType() || Op->getType()->isDependentType())
10364 // Require that the destination be a pointer type.
10365 const PointerType *DestPtr = T->getAs<PointerType>();
10366 if (!DestPtr) return;
10368 // If the destination has alignment 1, we're done.
10369 QualType DestPointee = DestPtr->getPointeeType();
10370 if (DestPointee->isIncompleteType()) return;
10371 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
10372 if (DestAlign.isOne()) return;
10374 // Require that the source be a pointer type.
10375 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
10376 if (!SrcPtr) return;
10377 QualType SrcPointee = SrcPtr->getPointeeType();
10379 // Whitelist casts from cv void*. We already implicitly
10380 // whitelisted casts to cv void*, since they have alignment 1.
10381 // Also whitelist casts involving incomplete types, which implicitly
10382 // includes 'void'.
10383 if (SrcPointee->isIncompleteType()) return;
10385 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
10387 if (auto *CE = dyn_cast<CastExpr>(Op)) {
10388 if (CE->getCastKind() == CK_ArrayToPointerDecay)
10389 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
10390 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
10391 if (UO->getOpcode() == UO_AddrOf)
10392 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
10395 if (SrcAlign >= DestAlign) return;
10397 Diag(TRange.getBegin(), diag::warn_cast_align)
10398 << Op->getType() << T
10399 << static_cast<unsigned>(SrcAlign.getQuantity())
10400 << static_cast<unsigned>(DestAlign.getQuantity())
10401 << TRange << Op->getSourceRange();
10404 /// \brief Check whether this array fits the idiom of a size-one tail padded
10405 /// array member of a struct.
10407 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
10408 /// commonly used to emulate flexible arrays in C89 code.
10409 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
10410 const NamedDecl *ND) {
10411 if (Size != 1 || !ND) return false;
10413 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
10414 if (!FD) return false;
10416 // Don't consider sizes resulting from macro expansions or template argument
10417 // substitution to form C89 tail-padded arrays.
10419 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
10421 TypeLoc TL = TInfo->getTypeLoc();
10422 // Look through typedefs.
10423 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
10424 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
10425 TInfo = TDL->getTypeSourceInfo();
10428 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
10429 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
10430 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
10436 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
10437 if (!RD) return false;
10438 if (RD->isUnion()) return false;
10439 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10440 if (!CRD->isStandardLayout()) return false;
10443 // See if this is the last field decl in the record.
10444 const Decl *D = FD;
10445 while ((D = D->getNextDeclInContext()))
10446 if (isa<FieldDecl>(D))
10451 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
10452 const ArraySubscriptExpr *ASE,
10453 bool AllowOnePastEnd, bool IndexNegated) {
10454 IndexExpr = IndexExpr->IgnoreParenImpCasts();
10455 if (IndexExpr->isValueDependent())
10458 const Type *EffectiveType =
10459 BaseExpr->getType()->getPointeeOrArrayElementType();
10460 BaseExpr = BaseExpr->IgnoreParenCasts();
10461 const ConstantArrayType *ArrayTy =
10462 Context.getAsConstantArrayType(BaseExpr->getType());
10466 llvm::APSInt index;
10467 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
10472 const NamedDecl *ND = nullptr;
10473 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10474 ND = dyn_cast<NamedDecl>(DRE->getDecl());
10475 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
10476 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
10478 if (index.isUnsigned() || !index.isNegative()) {
10479 llvm::APInt size = ArrayTy->getSize();
10480 if (!size.isStrictlyPositive())
10483 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
10484 if (BaseType != EffectiveType) {
10485 // Make sure we're comparing apples to apples when comparing index to size
10486 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
10487 uint64_t array_typesize = Context.getTypeSize(BaseType);
10488 // Handle ptrarith_typesize being zero, such as when casting to void*
10489 if (!ptrarith_typesize) ptrarith_typesize = 1;
10490 if (ptrarith_typesize != array_typesize) {
10491 // There's a cast to a different size type involved
10492 uint64_t ratio = array_typesize / ptrarith_typesize;
10493 // TODO: Be smarter about handling cases where array_typesize is not a
10494 // multiple of ptrarith_typesize
10495 if (ptrarith_typesize * ratio == array_typesize)
10496 size *= llvm::APInt(size.getBitWidth(), ratio);
10500 if (size.getBitWidth() > index.getBitWidth())
10501 index = index.zext(size.getBitWidth());
10502 else if (size.getBitWidth() < index.getBitWidth())
10503 size = size.zext(index.getBitWidth());
10505 // For array subscripting the index must be less than size, but for pointer
10506 // arithmetic also allow the index (offset) to be equal to size since
10507 // computing the next address after the end of the array is legal and
10508 // commonly done e.g. in C++ iterators and range-based for loops.
10509 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
10512 // Also don't warn for arrays of size 1 which are members of some
10513 // structure. These are often used to approximate flexible arrays in C89
10515 if (IsTailPaddedMemberArray(*this, size, ND))
10518 // Suppress the warning if the subscript expression (as identified by the
10519 // ']' location) and the index expression are both from macro expansions
10520 // within a system header.
10522 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
10523 ASE->getRBracketLoc());
10524 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
10525 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
10526 IndexExpr->getLocStart());
10527 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
10532 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
10534 DiagID = diag::warn_array_index_exceeds_bounds;
10536 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10537 PDiag(DiagID) << index.toString(10, true)
10538 << size.toString(10, true)
10539 << (unsigned)size.getLimitedValue(~0U)
10540 << IndexExpr->getSourceRange());
10542 unsigned DiagID = diag::warn_array_index_precedes_bounds;
10544 DiagID = diag::warn_ptr_arith_precedes_bounds;
10545 if (index.isNegative()) index = -index;
10548 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10549 PDiag(DiagID) << index.toString(10, true)
10550 << IndexExpr->getSourceRange());
10554 // Try harder to find a NamedDecl to point at in the note.
10555 while (const ArraySubscriptExpr *ASE =
10556 dyn_cast<ArraySubscriptExpr>(BaseExpr))
10557 BaseExpr = ASE->getBase()->IgnoreParenCasts();
10558 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10559 ND = dyn_cast<NamedDecl>(DRE->getDecl());
10560 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
10561 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
10565 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
10566 PDiag(diag::note_array_index_out_of_bounds)
10567 << ND->getDeclName());
10570 void Sema::CheckArrayAccess(const Expr *expr) {
10571 int AllowOnePastEnd = 0;
10573 expr = expr->IgnoreParenImpCasts();
10574 switch (expr->getStmtClass()) {
10575 case Stmt::ArraySubscriptExprClass: {
10576 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
10577 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
10578 AllowOnePastEnd > 0);
10581 case Stmt::OMPArraySectionExprClass: {
10582 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
10583 if (ASE->getLowerBound())
10584 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
10585 /*ASE=*/nullptr, AllowOnePastEnd > 0);
10588 case Stmt::UnaryOperatorClass: {
10589 // Only unwrap the * and & unary operators
10590 const UnaryOperator *UO = cast<UnaryOperator>(expr);
10591 expr = UO->getSubExpr();
10592 switch (UO->getOpcode()) {
10604 case Stmt::ConditionalOperatorClass: {
10605 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
10606 if (const Expr *lhs = cond->getLHS())
10607 CheckArrayAccess(lhs);
10608 if (const Expr *rhs = cond->getRHS())
10609 CheckArrayAccess(rhs);
10618 //===--- CHECK: Objective-C retain cycles ----------------------------------//
10621 struct RetainCycleOwner {
10622 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
10625 SourceLocation Loc;
10628 void setLocsFrom(Expr *e) {
10629 Loc = e->getExprLoc();
10630 Range = e->getSourceRange();
10633 } // end anonymous namespace
10635 /// Consider whether capturing the given variable can possibly lead to
10636 /// a retain cycle.
10637 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
10638 // In ARC, it's captured strongly iff the variable has __strong
10639 // lifetime. In MRR, it's captured strongly if the variable is
10640 // __block and has an appropriate type.
10641 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10644 owner.Variable = var;
10646 owner.setLocsFrom(ref);
10650 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
10652 e = e->IgnoreParens();
10653 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
10654 switch (cast->getCastKind()) {
10656 case CK_LValueBitCast:
10657 case CK_LValueToRValue:
10658 case CK_ARCReclaimReturnedObject:
10659 e = cast->getSubExpr();
10667 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
10668 ObjCIvarDecl *ivar = ref->getDecl();
10669 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10672 // Try to find a retain cycle in the base.
10673 if (!findRetainCycleOwner(S, ref->getBase(), owner))
10676 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
10677 owner.Indirect = true;
10681 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
10682 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
10683 if (!var) return false;
10684 return considerVariable(var, ref, owner);
10687 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
10688 if (member->isArrow()) return false;
10690 // Don't count this as an indirect ownership.
10691 e = member->getBase();
10695 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
10696 // Only pay attention to pseudo-objects on property references.
10697 ObjCPropertyRefExpr *pre
10698 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
10700 if (!pre) return false;
10701 if (pre->isImplicitProperty()) return false;
10702 ObjCPropertyDecl *property = pre->getExplicitProperty();
10703 if (!property->isRetaining() &&
10704 !(property->getPropertyIvarDecl() &&
10705 property->getPropertyIvarDecl()->getType()
10706 .getObjCLifetime() == Qualifiers::OCL_Strong))
10709 owner.Indirect = true;
10710 if (pre->isSuperReceiver()) {
10711 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
10712 if (!owner.Variable)
10714 owner.Loc = pre->getLocation();
10715 owner.Range = pre->getSourceRange();
10718 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
10719 ->getSourceExpr());
10730 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
10731 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
10732 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
10733 Context(Context), Variable(variable), Capturer(nullptr),
10734 VarWillBeReased(false) {}
10735 ASTContext &Context;
10738 bool VarWillBeReased;
10740 void VisitDeclRefExpr(DeclRefExpr *ref) {
10741 if (ref->getDecl() == Variable && !Capturer)
10745 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
10746 if (Capturer) return;
10747 Visit(ref->getBase());
10748 if (Capturer && ref->isFreeIvar())
10752 void VisitBlockExpr(BlockExpr *block) {
10753 // Look inside nested blocks
10754 if (block->getBlockDecl()->capturesVariable(Variable))
10755 Visit(block->getBlockDecl()->getBody());
10758 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
10759 if (Capturer) return;
10760 if (OVE->getSourceExpr())
10761 Visit(OVE->getSourceExpr());
10763 void VisitBinaryOperator(BinaryOperator *BinOp) {
10764 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
10766 Expr *LHS = BinOp->getLHS();
10767 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
10768 if (DRE->getDecl() != Variable)
10770 if (Expr *RHS = BinOp->getRHS()) {
10771 RHS = RHS->IgnoreParenCasts();
10772 llvm::APSInt Value;
10774 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
10779 } // end anonymous namespace
10781 /// Check whether the given argument is a block which captures a
10783 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
10784 assert(owner.Variable && owner.Loc.isValid());
10786 e = e->IgnoreParenCasts();
10788 // Look through [^{...} copy] and Block_copy(^{...}).
10789 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
10790 Selector Cmd = ME->getSelector();
10791 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
10792 e = ME->getInstanceReceiver();
10795 e = e->IgnoreParenCasts();
10797 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
10798 if (CE->getNumArgs() == 1) {
10799 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
10801 const IdentifierInfo *FnI = Fn->getIdentifier();
10802 if (FnI && FnI->isStr("_Block_copy")) {
10803 e = CE->getArg(0)->IgnoreParenCasts();
10809 BlockExpr *block = dyn_cast<BlockExpr>(e);
10810 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
10813 FindCaptureVisitor visitor(S.Context, owner.Variable);
10814 visitor.Visit(block->getBlockDecl()->getBody());
10815 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
10818 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
10819 RetainCycleOwner &owner) {
10821 assert(owner.Variable && owner.Loc.isValid());
10823 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
10824 << owner.Variable << capturer->getSourceRange();
10825 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
10826 << owner.Indirect << owner.Range;
10829 /// Check for a keyword selector that starts with the word 'add' or
10831 static bool isSetterLikeSelector(Selector sel) {
10832 if (sel.isUnarySelector()) return false;
10834 StringRef str = sel.getNameForSlot(0);
10835 while (!str.empty() && str.front() == '_') str = str.substr(1);
10836 if (str.startswith("set"))
10837 str = str.substr(3);
10838 else if (str.startswith("add")) {
10839 // Specially whitelist 'addOperationWithBlock:'.
10840 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
10842 str = str.substr(3);
10847 if (str.empty()) return true;
10848 return !isLowercase(str.front());
10851 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
10852 ObjCMessageExpr *Message) {
10853 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
10854 Message->getReceiverInterface(),
10855 NSAPI::ClassId_NSMutableArray);
10856 if (!IsMutableArray) {
10860 Selector Sel = Message->getSelector();
10862 Optional<NSAPI::NSArrayMethodKind> MKOpt =
10863 S.NSAPIObj->getNSArrayMethodKind(Sel);
10868 NSAPI::NSArrayMethodKind MK = *MKOpt;
10871 case NSAPI::NSMutableArr_addObject:
10872 case NSAPI::NSMutableArr_insertObjectAtIndex:
10873 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
10875 case NSAPI::NSMutableArr_replaceObjectAtIndex:
10886 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
10887 ObjCMessageExpr *Message) {
10888 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
10889 Message->getReceiverInterface(),
10890 NSAPI::ClassId_NSMutableDictionary);
10891 if (!IsMutableDictionary) {
10895 Selector Sel = Message->getSelector();
10897 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
10898 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
10903 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
10906 case NSAPI::NSMutableDict_setObjectForKey:
10907 case NSAPI::NSMutableDict_setValueForKey:
10908 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
10918 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
10919 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
10920 Message->getReceiverInterface(),
10921 NSAPI::ClassId_NSMutableSet);
10923 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
10924 Message->getReceiverInterface(),
10925 NSAPI::ClassId_NSMutableOrderedSet);
10926 if (!IsMutableSet && !IsMutableOrderedSet) {
10930 Selector Sel = Message->getSelector();
10932 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
10937 NSAPI::NSSetMethodKind MK = *MKOpt;
10940 case NSAPI::NSMutableSet_addObject:
10941 case NSAPI::NSOrderedSet_setObjectAtIndex:
10942 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
10943 case NSAPI::NSOrderedSet_insertObjectAtIndex:
10945 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
10952 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
10953 if (!Message->isInstanceMessage()) {
10957 Optional<int> ArgOpt;
10959 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
10960 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
10961 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
10965 int ArgIndex = *ArgOpt;
10967 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
10968 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
10969 Arg = OE->getSourceExpr()->IgnoreImpCasts();
10972 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
10973 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
10974 if (ArgRE->isObjCSelfExpr()) {
10975 Diag(Message->getSourceRange().getBegin(),
10976 diag::warn_objc_circular_container)
10977 << ArgRE->getDecl()->getName() << StringRef("super");
10981 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
10983 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
10984 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
10987 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
10988 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
10989 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
10990 ValueDecl *Decl = ReceiverRE->getDecl();
10991 Diag(Message->getSourceRange().getBegin(),
10992 diag::warn_objc_circular_container)
10993 << Decl->getName() << Decl->getName();
10994 if (!ArgRE->isObjCSelfExpr()) {
10995 Diag(Decl->getLocation(),
10996 diag::note_objc_circular_container_declared_here)
10997 << Decl->getName();
11001 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
11002 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
11003 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
11004 ObjCIvarDecl *Decl = IvarRE->getDecl();
11005 Diag(Message->getSourceRange().getBegin(),
11006 diag::warn_objc_circular_container)
11007 << Decl->getName() << Decl->getName();
11008 Diag(Decl->getLocation(),
11009 diag::note_objc_circular_container_declared_here)
11010 << Decl->getName();
11017 /// Check a message send to see if it's likely to cause a retain cycle.
11018 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
11019 // Only check instance methods whose selector looks like a setter.
11020 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
11023 // Try to find a variable that the receiver is strongly owned by.
11024 RetainCycleOwner owner;
11025 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
11026 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
11029 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
11030 owner.Variable = getCurMethodDecl()->getSelfDecl();
11031 owner.Loc = msg->getSuperLoc();
11032 owner.Range = msg->getSuperLoc();
11035 // Check whether the receiver is captured by any of the arguments.
11036 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
11037 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
11038 return diagnoseRetainCycle(*this, capturer, owner);
11041 /// Check a property assign to see if it's likely to cause a retain cycle.
11042 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
11043 RetainCycleOwner owner;
11044 if (!findRetainCycleOwner(*this, receiver, owner))
11047 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
11048 diagnoseRetainCycle(*this, capturer, owner);
11051 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
11052 RetainCycleOwner Owner;
11053 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
11056 // Because we don't have an expression for the variable, we have to set the
11057 // location explicitly here.
11058 Owner.Loc = Var->getLocation();
11059 Owner.Range = Var->getSourceRange();
11061 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
11062 diagnoseRetainCycle(*this, Capturer, Owner);
11065 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
11066 Expr *RHS, bool isProperty) {
11067 // Check if RHS is an Objective-C object literal, which also can get
11068 // immediately zapped in a weak reference. Note that we explicitly
11069 // allow ObjCStringLiterals, since those are designed to never really die.
11070 RHS = RHS->IgnoreParenImpCasts();
11072 // This enum needs to match with the 'select' in
11073 // warn_objc_arc_literal_assign (off-by-1).
11074 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
11075 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
11078 S.Diag(Loc, diag::warn_arc_literal_assign)
11080 << (isProperty ? 0 : 1)
11081 << RHS->getSourceRange();
11086 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
11087 Qualifiers::ObjCLifetime LT,
11088 Expr *RHS, bool isProperty) {
11089 // Strip off any implicit cast added to get to the one ARC-specific.
11090 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11091 if (cast->getCastKind() == CK_ARCConsumeObject) {
11092 S.Diag(Loc, diag::warn_arc_retained_assign)
11093 << (LT == Qualifiers::OCL_ExplicitNone)
11094 << (isProperty ? 0 : 1)
11095 << RHS->getSourceRange();
11098 RHS = cast->getSubExpr();
11101 if (LT == Qualifiers::OCL_Weak &&
11102 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
11108 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
11109 QualType LHS, Expr *RHS) {
11110 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
11112 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
11115 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
11121 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
11122 Expr *LHS, Expr *RHS) {
11124 // PropertyRef on LHS type need be directly obtained from
11125 // its declaration as it has a PseudoType.
11126 ObjCPropertyRefExpr *PRE
11127 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
11128 if (PRE && !PRE->isImplicitProperty()) {
11129 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11131 LHSType = PD->getType();
11134 if (LHSType.isNull())
11135 LHSType = LHS->getType();
11137 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
11139 if (LT == Qualifiers::OCL_Weak) {
11140 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
11141 getCurFunction()->markSafeWeakUse(LHS);
11144 if (checkUnsafeAssigns(Loc, LHSType, RHS))
11147 // FIXME. Check for other life times.
11148 if (LT != Qualifiers::OCL_None)
11152 if (PRE->isImplicitProperty())
11154 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11158 unsigned Attributes = PD->getPropertyAttributes();
11159 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
11160 // when 'assign' attribute was not explicitly specified
11161 // by user, ignore it and rely on property type itself
11162 // for lifetime info.
11163 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
11164 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
11165 LHSType->isObjCRetainableType())
11168 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11169 if (cast->getCastKind() == CK_ARCConsumeObject) {
11170 Diag(Loc, diag::warn_arc_retained_property_assign)
11171 << RHS->getSourceRange();
11174 RHS = cast->getSubExpr();
11177 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
11178 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
11184 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
11187 bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
11188 SourceLocation StmtLoc,
11189 const NullStmt *Body) {
11190 // Do not warn if the body is a macro that expands to nothing, e.g:
11196 if (Body->hasLeadingEmptyMacro())
11199 // Get line numbers of statement and body.
11200 bool StmtLineInvalid;
11201 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
11203 if (StmtLineInvalid)
11206 bool BodyLineInvalid;
11207 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
11209 if (BodyLineInvalid)
11212 // Warn if null statement and body are on the same line.
11213 if (StmtLine != BodyLine)
11218 } // end anonymous namespace
11220 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
11223 // Since this is a syntactic check, don't emit diagnostic for template
11224 // instantiations, this just adds noise.
11225 if (CurrentInstantiationScope)
11228 // The body should be a null statement.
11229 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11233 // Do the usual checks.
11234 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11237 Diag(NBody->getSemiLoc(), DiagID);
11238 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11241 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
11242 const Stmt *PossibleBody) {
11243 assert(!CurrentInstantiationScope); // Ensured by caller
11245 SourceLocation StmtLoc;
11248 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
11249 StmtLoc = FS->getRParenLoc();
11250 Body = FS->getBody();
11251 DiagID = diag::warn_empty_for_body;
11252 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
11253 StmtLoc = WS->getCond()->getSourceRange().getEnd();
11254 Body = WS->getBody();
11255 DiagID = diag::warn_empty_while_body;
11257 return; // Neither `for' nor `while'.
11259 // The body should be a null statement.
11260 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11264 // Skip expensive checks if diagnostic is disabled.
11265 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
11268 // Do the usual checks.
11269 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11272 // `for(...);' and `while(...);' are popular idioms, so in order to keep
11273 // noise level low, emit diagnostics only if for/while is followed by a
11274 // CompoundStmt, e.g.:
11275 // for (int i = 0; i < n; i++);
11279 // or if for/while is followed by a statement with more indentation
11280 // than for/while itself:
11281 // for (int i = 0; i < n; i++);
11283 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
11284 if (!ProbableTypo) {
11285 bool BodyColInvalid;
11286 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
11287 PossibleBody->getLocStart(),
11289 if (BodyColInvalid)
11292 bool StmtColInvalid;
11293 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
11296 if (StmtColInvalid)
11299 if (BodyCol > StmtCol)
11300 ProbableTypo = true;
11303 if (ProbableTypo) {
11304 Diag(NBody->getSemiLoc(), DiagID);
11305 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11309 //===--- CHECK: Warn on self move with std::move. -------------------------===//
11311 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
11312 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
11313 SourceLocation OpLoc) {
11314 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
11317 if (!ActiveTemplateInstantiations.empty())
11320 // Strip parens and casts away.
11321 LHSExpr = LHSExpr->IgnoreParenImpCasts();
11322 RHSExpr = RHSExpr->IgnoreParenImpCasts();
11324 // Check for a call expression
11325 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
11326 if (!CE || CE->getNumArgs() != 1)
11329 // Check for a call to std::move
11330 const FunctionDecl *FD = CE->getDirectCallee();
11331 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
11332 !FD->getIdentifier()->isStr("move"))
11335 // Get argument from std::move
11336 RHSExpr = CE->getArg(0);
11338 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11339 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11341 // Two DeclRefExpr's, check that the decls are the same.
11342 if (LHSDeclRef && RHSDeclRef) {
11343 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11345 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11346 RHSDeclRef->getDecl()->getCanonicalDecl())
11349 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11350 << LHSExpr->getSourceRange()
11351 << RHSExpr->getSourceRange();
11355 // Member variables require a different approach to check for self moves.
11356 // MemberExpr's are the same if every nested MemberExpr refers to the same
11357 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
11358 // the base Expr's are CXXThisExpr's.
11359 const Expr *LHSBase = LHSExpr;
11360 const Expr *RHSBase = RHSExpr;
11361 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
11362 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
11363 if (!LHSME || !RHSME)
11366 while (LHSME && RHSME) {
11367 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
11368 RHSME->getMemberDecl()->getCanonicalDecl())
11371 LHSBase = LHSME->getBase();
11372 RHSBase = RHSME->getBase();
11373 LHSME = dyn_cast<MemberExpr>(LHSBase);
11374 RHSME = dyn_cast<MemberExpr>(RHSBase);
11377 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
11378 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
11379 if (LHSDeclRef && RHSDeclRef) {
11380 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11382 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11383 RHSDeclRef->getDecl()->getCanonicalDecl())
11386 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11387 << LHSExpr->getSourceRange()
11388 << RHSExpr->getSourceRange();
11392 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
11393 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11394 << LHSExpr->getSourceRange()
11395 << RHSExpr->getSourceRange();
11398 //===--- Layout compatibility ----------------------------------------------//
11402 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
11404 /// \brief Check if two enumeration types are layout-compatible.
11405 bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
11406 // C++11 [dcl.enum] p8:
11407 // Two enumeration types are layout-compatible if they have the same
11408 // underlying type.
11409 return ED1->isComplete() && ED2->isComplete() &&
11410 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
11413 /// \brief Check if two fields are layout-compatible.
11414 bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
11415 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
11418 if (Field1->isBitField() != Field2->isBitField())
11421 if (Field1->isBitField()) {
11422 // Make sure that the bit-fields are the same length.
11423 unsigned Bits1 = Field1->getBitWidthValue(C);
11424 unsigned Bits2 = Field2->getBitWidthValue(C);
11426 if (Bits1 != Bits2)
11433 /// \brief Check if two standard-layout structs are layout-compatible.
11434 /// (C++11 [class.mem] p17)
11435 bool isLayoutCompatibleStruct(ASTContext &C,
11438 // If both records are C++ classes, check that base classes match.
11439 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
11440 // If one of records is a CXXRecordDecl we are in C++ mode,
11441 // thus the other one is a CXXRecordDecl, too.
11442 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
11443 // Check number of base classes.
11444 if (D1CXX->getNumBases() != D2CXX->getNumBases())
11447 // Check the base classes.
11448 for (CXXRecordDecl::base_class_const_iterator
11449 Base1 = D1CXX->bases_begin(),
11450 BaseEnd1 = D1CXX->bases_end(),
11451 Base2 = D2CXX->bases_begin();
11453 ++Base1, ++Base2) {
11454 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
11457 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
11458 // If only RD2 is a C++ class, it should have zero base classes.
11459 if (D2CXX->getNumBases() > 0)
11463 // Check the fields.
11464 RecordDecl::field_iterator Field2 = RD2->field_begin(),
11465 Field2End = RD2->field_end(),
11466 Field1 = RD1->field_begin(),
11467 Field1End = RD1->field_end();
11468 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
11469 if (!isLayoutCompatible(C, *Field1, *Field2))
11472 if (Field1 != Field1End || Field2 != Field2End)
11478 /// \brief Check if two standard-layout unions are layout-compatible.
11479 /// (C++11 [class.mem] p18)
11480 bool isLayoutCompatibleUnion(ASTContext &C,
11483 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
11484 for (auto *Field2 : RD2->fields())
11485 UnmatchedFields.insert(Field2);
11487 for (auto *Field1 : RD1->fields()) {
11488 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
11489 I = UnmatchedFields.begin(),
11490 E = UnmatchedFields.end();
11492 for ( ; I != E; ++I) {
11493 if (isLayoutCompatible(C, Field1, *I)) {
11494 bool Result = UnmatchedFields.erase(*I);
11504 return UnmatchedFields.empty();
11507 bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
11508 if (RD1->isUnion() != RD2->isUnion())
11511 if (RD1->isUnion())
11512 return isLayoutCompatibleUnion(C, RD1, RD2);
11514 return isLayoutCompatibleStruct(C, RD1, RD2);
11517 /// \brief Check if two types are layout-compatible in C++11 sense.
11518 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
11519 if (T1.isNull() || T2.isNull())
11522 // C++11 [basic.types] p11:
11523 // If two types T1 and T2 are the same type, then T1 and T2 are
11524 // layout-compatible types.
11525 if (C.hasSameType(T1, T2))
11528 T1 = T1.getCanonicalType().getUnqualifiedType();
11529 T2 = T2.getCanonicalType().getUnqualifiedType();
11531 const Type::TypeClass TC1 = T1->getTypeClass();
11532 const Type::TypeClass TC2 = T2->getTypeClass();
11537 if (TC1 == Type::Enum) {
11538 return isLayoutCompatible(C,
11539 cast<EnumType>(T1)->getDecl(),
11540 cast<EnumType>(T2)->getDecl());
11541 } else if (TC1 == Type::Record) {
11542 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
11545 return isLayoutCompatible(C,
11546 cast<RecordType>(T1)->getDecl(),
11547 cast<RecordType>(T2)->getDecl());
11552 } // end anonymous namespace
11554 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
11557 /// \brief Given a type tag expression find the type tag itself.
11559 /// \param TypeExpr Type tag expression, as it appears in user's code.
11561 /// \param VD Declaration of an identifier that appears in a type tag.
11563 /// \param MagicValue Type tag magic value.
11564 bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
11565 const ValueDecl **VD, uint64_t *MagicValue) {
11570 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
11572 switch (TypeExpr->getStmtClass()) {
11573 case Stmt::UnaryOperatorClass: {
11574 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
11575 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
11576 TypeExpr = UO->getSubExpr();
11582 case Stmt::DeclRefExprClass: {
11583 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
11584 *VD = DRE->getDecl();
11588 case Stmt::IntegerLiteralClass: {
11589 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
11590 llvm::APInt MagicValueAPInt = IL->getValue();
11591 if (MagicValueAPInt.getActiveBits() <= 64) {
11592 *MagicValue = MagicValueAPInt.getZExtValue();
11598 case Stmt::BinaryConditionalOperatorClass:
11599 case Stmt::ConditionalOperatorClass: {
11600 const AbstractConditionalOperator *ACO =
11601 cast<AbstractConditionalOperator>(TypeExpr);
11603 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
11605 TypeExpr = ACO->getTrueExpr();
11607 TypeExpr = ACO->getFalseExpr();
11613 case Stmt::BinaryOperatorClass: {
11614 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
11615 if (BO->getOpcode() == BO_Comma) {
11616 TypeExpr = BO->getRHS();
11628 /// \brief Retrieve the C type corresponding to type tag TypeExpr.
11630 /// \param TypeExpr Expression that specifies a type tag.
11632 /// \param MagicValues Registered magic values.
11634 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
11637 /// \param TypeInfo Information about the corresponding C type.
11639 /// \returns true if the corresponding C type was found.
11640 bool GetMatchingCType(
11641 const IdentifierInfo *ArgumentKind,
11642 const Expr *TypeExpr, const ASTContext &Ctx,
11643 const llvm::DenseMap<Sema::TypeTagMagicValue,
11644 Sema::TypeTagData> *MagicValues,
11645 bool &FoundWrongKind,
11646 Sema::TypeTagData &TypeInfo) {
11647 FoundWrongKind = false;
11649 // Variable declaration that has type_tag_for_datatype attribute.
11650 const ValueDecl *VD = nullptr;
11652 uint64_t MagicValue;
11654 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
11658 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
11659 if (I->getArgumentKind() != ArgumentKind) {
11660 FoundWrongKind = true;
11663 TypeInfo.Type = I->getMatchingCType();
11664 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
11665 TypeInfo.MustBeNull = I->getMustBeNull();
11674 llvm::DenseMap<Sema::TypeTagMagicValue,
11675 Sema::TypeTagData>::const_iterator I =
11676 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
11677 if (I == MagicValues->end())
11680 TypeInfo = I->second;
11683 } // end anonymous namespace
11685 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
11686 uint64_t MagicValue, QualType Type,
11687 bool LayoutCompatible,
11689 if (!TypeTagForDatatypeMagicValues)
11690 TypeTagForDatatypeMagicValues.reset(
11691 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
11693 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
11694 (*TypeTagForDatatypeMagicValues)[Magic] =
11695 TypeTagData(Type, LayoutCompatible, MustBeNull);
11699 bool IsSameCharType(QualType T1, QualType T2) {
11700 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
11704 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
11708 BuiltinType::Kind T1Kind = BT1->getKind();
11709 BuiltinType::Kind T2Kind = BT2->getKind();
11711 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
11712 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
11713 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
11714 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
11716 } // end anonymous namespace
11718 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
11719 const Expr * const *ExprArgs) {
11720 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
11721 bool IsPointerAttr = Attr->getIsPointer();
11723 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
11724 bool FoundWrongKind;
11725 TypeTagData TypeInfo;
11726 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
11727 TypeTagForDatatypeMagicValues.get(),
11728 FoundWrongKind, TypeInfo)) {
11729 if (FoundWrongKind)
11730 Diag(TypeTagExpr->getExprLoc(),
11731 diag::warn_type_tag_for_datatype_wrong_kind)
11732 << TypeTagExpr->getSourceRange();
11736 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
11737 if (IsPointerAttr) {
11738 // Skip implicit cast of pointer to `void *' (as a function argument).
11739 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
11740 if (ICE->getType()->isVoidPointerType() &&
11741 ICE->getCastKind() == CK_BitCast)
11742 ArgumentExpr = ICE->getSubExpr();
11744 QualType ArgumentType = ArgumentExpr->getType();
11746 // Passing a `void*' pointer shouldn't trigger a warning.
11747 if (IsPointerAttr && ArgumentType->isVoidPointerType())
11750 if (TypeInfo.MustBeNull) {
11751 // Type tag with matching void type requires a null pointer.
11752 if (!ArgumentExpr->isNullPointerConstant(Context,
11753 Expr::NPC_ValueDependentIsNotNull)) {
11754 Diag(ArgumentExpr->getExprLoc(),
11755 diag::warn_type_safety_null_pointer_required)
11756 << ArgumentKind->getName()
11757 << ArgumentExpr->getSourceRange()
11758 << TypeTagExpr->getSourceRange();
11763 QualType RequiredType = TypeInfo.Type;
11765 RequiredType = Context.getPointerType(RequiredType);
11767 bool mismatch = false;
11768 if (!TypeInfo.LayoutCompatible) {
11769 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
11771 // C++11 [basic.fundamental] p1:
11772 // Plain char, signed char, and unsigned char are three distinct types.
11774 // But we treat plain `char' as equivalent to `signed char' or `unsigned
11775 // char' depending on the current char signedness mode.
11777 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
11778 RequiredType->getPointeeType())) ||
11779 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
11783 mismatch = !isLayoutCompatible(Context,
11784 ArgumentType->getPointeeType(),
11785 RequiredType->getPointeeType());
11787 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
11790 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
11791 << ArgumentType << ArgumentKind
11792 << TypeInfo.LayoutCompatible << RequiredType
11793 << ArgumentExpr->getSourceRange()
11794 << TypeTagExpr->getSourceRange();
11797 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
11798 CharUnits Alignment) {
11799 MisalignedMembers.emplace_back(E, RD, MD, Alignment);
11802 void Sema::DiagnoseMisalignedMembers() {
11803 for (MisalignedMember &m : MisalignedMembers) {
11804 const NamedDecl *ND = m.RD;
11805 if (ND->getName().empty()) {
11806 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
11809 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
11810 << m.MD << ND << m.E->getSourceRange();
11812 MisalignedMembers.clear();
11815 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
11816 E = E->IgnoreParens();
11817 if (!T->isPointerType() && !T->isIntegerType())
11819 if (isa<UnaryOperator>(E) &&
11820 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
11821 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
11822 if (isa<MemberExpr>(Op)) {
11823 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
11824 MisalignedMember(Op));
11825 if (MA != MisalignedMembers.end() &&
11826 (T->isIntegerType() ||
11827 (T->isPointerType() &&
11828 Context.getTypeAlignInChars(T->getPointeeType()) <= MA->Alignment)))
11829 MisalignedMembers.erase(MA);
11834 void Sema::RefersToMemberWithReducedAlignment(
11836 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
11838 const auto *ME = dyn_cast<MemberExpr>(E);
11842 // For a chain of MemberExpr like "a.b.c.d" this list
11843 // will keep FieldDecl's like [d, c, b].
11844 SmallVector<FieldDecl *, 4> ReverseMemberChain;
11845 const MemberExpr *TopME = nullptr;
11846 bool AnyIsPacked = false;
11848 QualType BaseType = ME->getBase()->getType();
11850 BaseType = BaseType->getPointeeType();
11851 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
11853 ValueDecl *MD = ME->getMemberDecl();
11854 auto *FD = dyn_cast<FieldDecl>(MD);
11855 // We do not care about non-data members.
11856 if (!FD || FD->isInvalidDecl())
11860 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
11861 ReverseMemberChain.push_back(FD);
11864 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
11866 assert(TopME && "We did not compute a topmost MemberExpr!");
11868 // Not the scope of this diagnostic.
11872 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
11873 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
11874 // TODO: The innermost base of the member expression may be too complicated.
11875 // For now, just disregard these cases. This is left for future
11877 if (!DRE && !isa<CXXThisExpr>(TopBase))
11880 // Alignment expected by the whole expression.
11881 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
11883 // No need to do anything else with this case.
11884 if (ExpectedAlignment.isOne())
11887 // Synthesize offset of the whole access.
11889 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
11891 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
11894 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
11895 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
11896 ReverseMemberChain.back()->getParent()->getTypeForDecl());
11898 // The base expression of the innermost MemberExpr may give
11899 // stronger guarantees than the class containing the member.
11900 if (DRE && !TopME->isArrow()) {
11901 const ValueDecl *VD = DRE->getDecl();
11902 if (!VD->getType()->isReferenceType())
11903 CompleteObjectAlignment =
11904 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
11907 // Check if the synthesized offset fulfills the alignment.
11908 if (Offset % ExpectedAlignment != 0 ||
11909 // It may fulfill the offset it but the effective alignment may still be
11910 // lower than the expected expression alignment.
11911 CompleteObjectAlignment < ExpectedAlignment) {
11912 // If this happens, we want to determine a sensible culprit of this.
11913 // Intuitively, watching the chain of member expressions from right to
11914 // left, we start with the required alignment (as required by the field
11915 // type) but some packed attribute in that chain has reduced the alignment.
11916 // It may happen that another packed structure increases it again. But if
11917 // we are here such increase has not been enough. So pointing the first
11918 // FieldDecl that either is packed or else its RecordDecl is,
11919 // seems reasonable.
11920 FieldDecl *FD = nullptr;
11921 CharUnits Alignment;
11922 for (FieldDecl *FDI : ReverseMemberChain) {
11923 if (FDI->hasAttr<PackedAttr>() ||
11924 FDI->getParent()->hasAttr<PackedAttr>()) {
11926 Alignment = std::min(
11927 Context.getTypeAlignInChars(FD->getType()),
11928 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
11932 assert(FD && "We did not find a packed FieldDecl!");
11933 Action(E, FD->getParent(), FD, Alignment);
11937 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
11938 using namespace std::placeholders;
11939 RefersToMemberWithReducedAlignment(
11940 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,