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.inTemplateInstantiation())
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_builtin_expected_type)
313 << TheCall->getDirectCallee() << "block";
316 return checkOpenCLBlockArgs(S, BlockArg);
319 /// Diagnose integer type and any valid implicit conversion to it.
320 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
321 const QualType &IntType);
323 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
324 unsigned Start, unsigned End) {
325 bool IllegalParams = false;
326 for (unsigned I = Start; I <= End; ++I)
327 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
328 S.Context.getSizeType());
329 return IllegalParams;
332 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
333 /// 'local void*' parameter of passed block.
334 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
336 unsigned NumNonVarArgs) {
337 const BlockPointerType *BPT =
338 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
339 unsigned NumBlockParams =
340 BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
341 unsigned TotalNumArgs = TheCall->getNumArgs();
343 // For each argument passed to the block, a corresponding uint needs to
344 // be passed to describe the size of the local memory.
345 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
346 S.Diag(TheCall->getLocStart(),
347 diag::err_opencl_enqueue_kernel_local_size_args);
351 // Check that the sizes of the local memory are specified by integers.
352 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
356 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
357 /// overload formats specified in Table 6.13.17.1.
358 /// int enqueue_kernel(queue_t queue,
359 /// kernel_enqueue_flags_t flags,
360 /// const ndrange_t ndrange,
361 /// void (^block)(void))
362 /// int enqueue_kernel(queue_t queue,
363 /// kernel_enqueue_flags_t flags,
364 /// const ndrange_t ndrange,
365 /// uint num_events_in_wait_list,
366 /// clk_event_t *event_wait_list,
367 /// clk_event_t *event_ret,
368 /// void (^block)(void))
369 /// int enqueue_kernel(queue_t queue,
370 /// kernel_enqueue_flags_t flags,
371 /// const ndrange_t ndrange,
372 /// void (^block)(local void*, ...),
374 /// int enqueue_kernel(queue_t queue,
375 /// kernel_enqueue_flags_t flags,
376 /// const ndrange_t ndrange,
377 /// uint num_events_in_wait_list,
378 /// clk_event_t *event_wait_list,
379 /// clk_event_t *event_ret,
380 /// void (^block)(local void*, ...),
382 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
383 unsigned NumArgs = TheCall->getNumArgs();
386 S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args);
390 Expr *Arg0 = TheCall->getArg(0);
391 Expr *Arg1 = TheCall->getArg(1);
392 Expr *Arg2 = TheCall->getArg(2);
393 Expr *Arg3 = TheCall->getArg(3);
395 // First argument always needs to be a queue_t type.
396 if (!Arg0->getType()->isQueueT()) {
397 S.Diag(TheCall->getArg(0)->getLocStart(),
398 diag::err_opencl_builtin_expected_type)
399 << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
403 // Second argument always needs to be a kernel_enqueue_flags_t enum value.
404 if (!Arg1->getType()->isIntegerType()) {
405 S.Diag(TheCall->getArg(1)->getLocStart(),
406 diag::err_opencl_builtin_expected_type)
407 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
411 // Third argument is always an ndrange_t type.
412 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
413 S.Diag(TheCall->getArg(2)->getLocStart(),
414 diag::err_opencl_builtin_expected_type)
415 << TheCall->getDirectCallee() << "'ndrange_t'";
419 // With four arguments, there is only one form that the function could be
420 // called in: no events and no variable arguments.
422 // check that the last argument is the right block type.
423 if (!isBlockPointer(Arg3)) {
424 S.Diag(Arg3->getLocStart(), diag::err_opencl_builtin_expected_type)
425 << TheCall->getDirectCallee() << "block";
428 // we have a block type, check the prototype
429 const BlockPointerType *BPT =
430 cast<BlockPointerType>(Arg3->getType().getCanonicalType());
431 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
432 S.Diag(Arg3->getLocStart(),
433 diag::err_opencl_enqueue_kernel_blocks_no_args);
438 // we can have block + varargs.
439 if (isBlockPointer(Arg3))
440 return (checkOpenCLBlockArgs(S, Arg3) ||
441 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
442 // last two cases with either exactly 7 args or 7 args and varargs.
444 // check common block argument.
445 Expr *Arg6 = TheCall->getArg(6);
446 if (!isBlockPointer(Arg6)) {
447 S.Diag(Arg6->getLocStart(), diag::err_opencl_builtin_expected_type)
448 << TheCall->getDirectCallee() << "block";
451 if (checkOpenCLBlockArgs(S, Arg6))
454 // Forth argument has to be any integer type.
455 if (!Arg3->getType()->isIntegerType()) {
456 S.Diag(TheCall->getArg(3)->getLocStart(),
457 diag::err_opencl_builtin_expected_type)
458 << TheCall->getDirectCallee() << "integer";
461 // check remaining common arguments.
462 Expr *Arg4 = TheCall->getArg(4);
463 Expr *Arg5 = TheCall->getArg(5);
465 // Fifth argument is always passed as a pointer to clk_event_t.
466 if (!Arg4->isNullPointerConstant(S.Context,
467 Expr::NPC_ValueDependentIsNotNull) &&
468 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
469 S.Diag(TheCall->getArg(4)->getLocStart(),
470 diag::err_opencl_builtin_expected_type)
471 << TheCall->getDirectCallee()
472 << S.Context.getPointerType(S.Context.OCLClkEventTy);
476 // Sixth argument is always passed as a pointer to clk_event_t.
477 if (!Arg5->isNullPointerConstant(S.Context,
478 Expr::NPC_ValueDependentIsNotNull) &&
479 !(Arg5->getType()->isPointerType() &&
480 Arg5->getType()->getPointeeType()->isClkEventT())) {
481 S.Diag(TheCall->getArg(5)->getLocStart(),
482 diag::err_opencl_builtin_expected_type)
483 << TheCall->getDirectCallee()
484 << S.Context.getPointerType(S.Context.OCLClkEventTy);
491 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
494 // None of the specific case has been detected, give generic error
495 S.Diag(TheCall->getLocStart(),
496 diag::err_opencl_enqueue_kernel_incorrect_args);
500 /// Returns OpenCL access qual.
501 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
502 return D->getAttr<OpenCLAccessAttr>();
505 /// Returns true if pipe element type is different from the pointer.
506 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
507 const Expr *Arg0 = Call->getArg(0);
508 // First argument type should always be pipe.
509 if (!Arg0->getType()->isPipeType()) {
510 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
511 << Call->getDirectCallee() << Arg0->getSourceRange();
514 OpenCLAccessAttr *AccessQual =
515 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
516 // Validates the access qualifier is compatible with the call.
517 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
518 // read_only and write_only, and assumed to be read_only if no qualifier is
520 switch (Call->getDirectCallee()->getBuiltinID()) {
521 case Builtin::BIread_pipe:
522 case Builtin::BIreserve_read_pipe:
523 case Builtin::BIcommit_read_pipe:
524 case Builtin::BIwork_group_reserve_read_pipe:
525 case Builtin::BIsub_group_reserve_read_pipe:
526 case Builtin::BIwork_group_commit_read_pipe:
527 case Builtin::BIsub_group_commit_read_pipe:
528 if (!(!AccessQual || AccessQual->isReadOnly())) {
529 S.Diag(Arg0->getLocStart(),
530 diag::err_opencl_builtin_pipe_invalid_access_modifier)
531 << "read_only" << Arg0->getSourceRange();
535 case Builtin::BIwrite_pipe:
536 case Builtin::BIreserve_write_pipe:
537 case Builtin::BIcommit_write_pipe:
538 case Builtin::BIwork_group_reserve_write_pipe:
539 case Builtin::BIsub_group_reserve_write_pipe:
540 case Builtin::BIwork_group_commit_write_pipe:
541 case Builtin::BIsub_group_commit_write_pipe:
542 if (!(AccessQual && AccessQual->isWriteOnly())) {
543 S.Diag(Arg0->getLocStart(),
544 diag::err_opencl_builtin_pipe_invalid_access_modifier)
545 << "write_only" << Arg0->getSourceRange();
555 /// Returns true if pipe element type is different from the pointer.
556 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
557 const Expr *Arg0 = Call->getArg(0);
558 const Expr *ArgIdx = Call->getArg(Idx);
559 const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
560 const QualType EltTy = PipeTy->getElementType();
561 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
562 // The Idx argument should be a pointer and the type of the pointer and
563 // the type of pipe element should also be the same.
565 !S.Context.hasSameType(
566 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
567 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
568 << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
569 << ArgIdx->getType() << ArgIdx->getSourceRange();
575 // \brief Performs semantic analysis for the read/write_pipe call.
576 // \param S Reference to the semantic analyzer.
577 // \param Call A pointer to the builtin call.
578 // \return True if a semantic error has been found, false otherwise.
579 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
580 // OpenCL v2.0 s6.13.16.2 - The built-in read/write
581 // functions have two forms.
582 switch (Call->getNumArgs()) {
584 if (checkOpenCLPipeArg(S, Call))
586 // The call with 2 arguments should be
587 // read/write_pipe(pipe T, T*).
588 // Check packet type T.
589 if (checkOpenCLPipePacketType(S, Call, 1))
594 if (checkOpenCLPipeArg(S, Call))
596 // The call with 4 arguments should be
597 // read/write_pipe(pipe T, reserve_id_t, uint, T*).
598 // Check reserve_id_t.
599 if (!Call->getArg(1)->getType()->isReserveIDT()) {
600 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
601 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
602 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
607 const Expr *Arg2 = Call->getArg(2);
608 if (!Arg2->getType()->isIntegerType() &&
609 !Arg2->getType()->isUnsignedIntegerType()) {
610 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
611 << Call->getDirectCallee() << S.Context.UnsignedIntTy
612 << Arg2->getType() << Arg2->getSourceRange();
616 // Check packet type T.
617 if (checkOpenCLPipePacketType(S, Call, 3))
621 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
622 << Call->getDirectCallee() << Call->getSourceRange();
629 // \brief Performs a semantic analysis on the {work_group_/sub_group_
630 // /_}reserve_{read/write}_pipe
631 // \param S Reference to the semantic analyzer.
632 // \param Call The call to the builtin function to be analyzed.
633 // \return True if a semantic error was found, false otherwise.
634 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
635 if (checkArgCount(S, Call, 2))
638 if (checkOpenCLPipeArg(S, Call))
641 // Check the reserve size.
642 if (!Call->getArg(1)->getType()->isIntegerType() &&
643 !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
644 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
645 << Call->getDirectCallee() << S.Context.UnsignedIntTy
646 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
653 // \brief Performs a semantic analysis on {work_group_/sub_group_
654 // /_}commit_{read/write}_pipe
655 // \param S Reference to the semantic analyzer.
656 // \param Call The call to the builtin function to be analyzed.
657 // \return True if a semantic error was found, false otherwise.
658 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
659 if (checkArgCount(S, Call, 2))
662 if (checkOpenCLPipeArg(S, Call))
665 // Check reserve_id_t.
666 if (!Call->getArg(1)->getType()->isReserveIDT()) {
667 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
668 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
669 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
676 // \brief Performs a semantic analysis on the call to built-in Pipe
678 // \param S Reference to the semantic analyzer.
679 // \param Call The call to the builtin function to be analyzed.
680 // \return True if a semantic error was found, false otherwise.
681 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
682 if (checkArgCount(S, Call, 1))
685 if (!Call->getArg(0)->getType()->isPipeType()) {
686 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
687 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
693 // \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions.
694 // \brief Performs semantic analysis for the to_global/local/private call.
695 // \param S Reference to the semantic analyzer.
696 // \param BuiltinID ID of the builtin function.
697 // \param Call A pointer to the builtin call.
698 // \return True if a semantic error has been found, false otherwise.
699 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
701 if (Call->getNumArgs() != 1) {
702 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num)
703 << Call->getDirectCallee() << Call->getSourceRange();
707 auto RT = Call->getArg(0)->getType();
708 if (!RT->isPointerType() || RT->getPointeeType()
709 .getAddressSpace() == LangAS::opencl_constant) {
710 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
711 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
715 RT = RT->getPointeeType();
716 auto Qual = RT.getQualifiers();
718 case Builtin::BIto_global:
719 Qual.setAddressSpace(LangAS::opencl_global);
721 case Builtin::BIto_local:
722 Qual.setAddressSpace(LangAS::opencl_local);
725 Qual.removeAddressSpace();
727 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
728 RT.getUnqualifiedType(), Qual)));
734 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
736 ExprResult TheCallResult(TheCall);
738 // Find out if any arguments are required to be integer constant expressions.
739 unsigned ICEArguments = 0;
740 ASTContext::GetBuiltinTypeError Error;
741 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
742 if (Error != ASTContext::GE_None)
743 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
745 // If any arguments are required to be ICE's, check and diagnose.
746 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
747 // Skip arguments not required to be ICE's.
748 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
751 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
753 ICEArguments &= ~(1 << ArgNo);
757 case Builtin::BI__builtin___CFStringMakeConstantString:
758 assert(TheCall->getNumArgs() == 1 &&
759 "Wrong # arguments to builtin CFStringMakeConstantString");
760 if (CheckObjCString(TheCall->getArg(0)))
763 case Builtin::BI__builtin_ms_va_start:
764 case Builtin::BI__builtin_stdarg_start:
765 case Builtin::BI__builtin_va_start:
766 if (SemaBuiltinVAStart(BuiltinID, TheCall))
769 case Builtin::BI__va_start: {
770 switch (Context.getTargetInfo().getTriple().getArch()) {
771 case llvm::Triple::arm:
772 case llvm::Triple::thumb:
773 if (SemaBuiltinVAStartARM(TheCall))
777 if (SemaBuiltinVAStart(BuiltinID, TheCall))
783 case Builtin::BI__builtin_isgreater:
784 case Builtin::BI__builtin_isgreaterequal:
785 case Builtin::BI__builtin_isless:
786 case Builtin::BI__builtin_islessequal:
787 case Builtin::BI__builtin_islessgreater:
788 case Builtin::BI__builtin_isunordered:
789 if (SemaBuiltinUnorderedCompare(TheCall))
792 case Builtin::BI__builtin_fpclassify:
793 if (SemaBuiltinFPClassification(TheCall, 6))
796 case Builtin::BI__builtin_isfinite:
797 case Builtin::BI__builtin_isinf:
798 case Builtin::BI__builtin_isinf_sign:
799 case Builtin::BI__builtin_isnan:
800 case Builtin::BI__builtin_isnormal:
801 if (SemaBuiltinFPClassification(TheCall, 1))
804 case Builtin::BI__builtin_shufflevector:
805 return SemaBuiltinShuffleVector(TheCall);
806 // TheCall will be freed by the smart pointer here, but that's fine, since
807 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
808 case Builtin::BI__builtin_prefetch:
809 if (SemaBuiltinPrefetch(TheCall))
812 case Builtin::BI__builtin_alloca_with_align:
813 if (SemaBuiltinAllocaWithAlign(TheCall))
816 case Builtin::BI__assume:
817 case Builtin::BI__builtin_assume:
818 if (SemaBuiltinAssume(TheCall))
821 case Builtin::BI__builtin_assume_aligned:
822 if (SemaBuiltinAssumeAligned(TheCall))
825 case Builtin::BI__builtin_object_size:
826 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
829 case Builtin::BI__builtin_longjmp:
830 if (SemaBuiltinLongjmp(TheCall))
833 case Builtin::BI__builtin_setjmp:
834 if (SemaBuiltinSetjmp(TheCall))
837 case Builtin::BI_setjmp:
838 case Builtin::BI_setjmpex:
839 if (checkArgCount(*this, TheCall, 1))
843 case Builtin::BI__builtin_classify_type:
844 if (checkArgCount(*this, TheCall, 1)) return true;
845 TheCall->setType(Context.IntTy);
847 case Builtin::BI__builtin_constant_p:
848 if (checkArgCount(*this, TheCall, 1)) return true;
849 TheCall->setType(Context.IntTy);
851 case Builtin::BI__sync_fetch_and_add:
852 case Builtin::BI__sync_fetch_and_add_1:
853 case Builtin::BI__sync_fetch_and_add_2:
854 case Builtin::BI__sync_fetch_and_add_4:
855 case Builtin::BI__sync_fetch_and_add_8:
856 case Builtin::BI__sync_fetch_and_add_16:
857 case Builtin::BI__sync_fetch_and_sub:
858 case Builtin::BI__sync_fetch_and_sub_1:
859 case Builtin::BI__sync_fetch_and_sub_2:
860 case Builtin::BI__sync_fetch_and_sub_4:
861 case Builtin::BI__sync_fetch_and_sub_8:
862 case Builtin::BI__sync_fetch_and_sub_16:
863 case Builtin::BI__sync_fetch_and_or:
864 case Builtin::BI__sync_fetch_and_or_1:
865 case Builtin::BI__sync_fetch_and_or_2:
866 case Builtin::BI__sync_fetch_and_or_4:
867 case Builtin::BI__sync_fetch_and_or_8:
868 case Builtin::BI__sync_fetch_and_or_16:
869 case Builtin::BI__sync_fetch_and_and:
870 case Builtin::BI__sync_fetch_and_and_1:
871 case Builtin::BI__sync_fetch_and_and_2:
872 case Builtin::BI__sync_fetch_and_and_4:
873 case Builtin::BI__sync_fetch_and_and_8:
874 case Builtin::BI__sync_fetch_and_and_16:
875 case Builtin::BI__sync_fetch_and_xor:
876 case Builtin::BI__sync_fetch_and_xor_1:
877 case Builtin::BI__sync_fetch_and_xor_2:
878 case Builtin::BI__sync_fetch_and_xor_4:
879 case Builtin::BI__sync_fetch_and_xor_8:
880 case Builtin::BI__sync_fetch_and_xor_16:
881 case Builtin::BI__sync_fetch_and_nand:
882 case Builtin::BI__sync_fetch_and_nand_1:
883 case Builtin::BI__sync_fetch_and_nand_2:
884 case Builtin::BI__sync_fetch_and_nand_4:
885 case Builtin::BI__sync_fetch_and_nand_8:
886 case Builtin::BI__sync_fetch_and_nand_16:
887 case Builtin::BI__sync_add_and_fetch:
888 case Builtin::BI__sync_add_and_fetch_1:
889 case Builtin::BI__sync_add_and_fetch_2:
890 case Builtin::BI__sync_add_and_fetch_4:
891 case Builtin::BI__sync_add_and_fetch_8:
892 case Builtin::BI__sync_add_and_fetch_16:
893 case Builtin::BI__sync_sub_and_fetch:
894 case Builtin::BI__sync_sub_and_fetch_1:
895 case Builtin::BI__sync_sub_and_fetch_2:
896 case Builtin::BI__sync_sub_and_fetch_4:
897 case Builtin::BI__sync_sub_and_fetch_8:
898 case Builtin::BI__sync_sub_and_fetch_16:
899 case Builtin::BI__sync_and_and_fetch:
900 case Builtin::BI__sync_and_and_fetch_1:
901 case Builtin::BI__sync_and_and_fetch_2:
902 case Builtin::BI__sync_and_and_fetch_4:
903 case Builtin::BI__sync_and_and_fetch_8:
904 case Builtin::BI__sync_and_and_fetch_16:
905 case Builtin::BI__sync_or_and_fetch:
906 case Builtin::BI__sync_or_and_fetch_1:
907 case Builtin::BI__sync_or_and_fetch_2:
908 case Builtin::BI__sync_or_and_fetch_4:
909 case Builtin::BI__sync_or_and_fetch_8:
910 case Builtin::BI__sync_or_and_fetch_16:
911 case Builtin::BI__sync_xor_and_fetch:
912 case Builtin::BI__sync_xor_and_fetch_1:
913 case Builtin::BI__sync_xor_and_fetch_2:
914 case Builtin::BI__sync_xor_and_fetch_4:
915 case Builtin::BI__sync_xor_and_fetch_8:
916 case Builtin::BI__sync_xor_and_fetch_16:
917 case Builtin::BI__sync_nand_and_fetch:
918 case Builtin::BI__sync_nand_and_fetch_1:
919 case Builtin::BI__sync_nand_and_fetch_2:
920 case Builtin::BI__sync_nand_and_fetch_4:
921 case Builtin::BI__sync_nand_and_fetch_8:
922 case Builtin::BI__sync_nand_and_fetch_16:
923 case Builtin::BI__sync_val_compare_and_swap:
924 case Builtin::BI__sync_val_compare_and_swap_1:
925 case Builtin::BI__sync_val_compare_and_swap_2:
926 case Builtin::BI__sync_val_compare_and_swap_4:
927 case Builtin::BI__sync_val_compare_and_swap_8:
928 case Builtin::BI__sync_val_compare_and_swap_16:
929 case Builtin::BI__sync_bool_compare_and_swap:
930 case Builtin::BI__sync_bool_compare_and_swap_1:
931 case Builtin::BI__sync_bool_compare_and_swap_2:
932 case Builtin::BI__sync_bool_compare_and_swap_4:
933 case Builtin::BI__sync_bool_compare_and_swap_8:
934 case Builtin::BI__sync_bool_compare_and_swap_16:
935 case Builtin::BI__sync_lock_test_and_set:
936 case Builtin::BI__sync_lock_test_and_set_1:
937 case Builtin::BI__sync_lock_test_and_set_2:
938 case Builtin::BI__sync_lock_test_and_set_4:
939 case Builtin::BI__sync_lock_test_and_set_8:
940 case Builtin::BI__sync_lock_test_and_set_16:
941 case Builtin::BI__sync_lock_release:
942 case Builtin::BI__sync_lock_release_1:
943 case Builtin::BI__sync_lock_release_2:
944 case Builtin::BI__sync_lock_release_4:
945 case Builtin::BI__sync_lock_release_8:
946 case Builtin::BI__sync_lock_release_16:
947 case Builtin::BI__sync_swap:
948 case Builtin::BI__sync_swap_1:
949 case Builtin::BI__sync_swap_2:
950 case Builtin::BI__sync_swap_4:
951 case Builtin::BI__sync_swap_8:
952 case Builtin::BI__sync_swap_16:
953 return SemaBuiltinAtomicOverloaded(TheCallResult);
954 case Builtin::BI__builtin_nontemporal_load:
955 case Builtin::BI__builtin_nontemporal_store:
956 return SemaBuiltinNontemporalOverloaded(TheCallResult);
957 #define BUILTIN(ID, TYPE, ATTRS)
958 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
959 case Builtin::BI##ID: \
960 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
961 #include "clang/Basic/Builtins.def"
962 case Builtin::BI__builtin_annotation:
963 if (SemaBuiltinAnnotation(*this, TheCall))
966 case Builtin::BI__builtin_addressof:
967 if (SemaBuiltinAddressof(*this, TheCall))
970 case Builtin::BI__builtin_add_overflow:
971 case Builtin::BI__builtin_sub_overflow:
972 case Builtin::BI__builtin_mul_overflow:
973 if (SemaBuiltinOverflow(*this, TheCall))
976 case Builtin::BI__builtin_operator_new:
977 case Builtin::BI__builtin_operator_delete:
978 if (!getLangOpts().CPlusPlus) {
979 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
980 << (BuiltinID == Builtin::BI__builtin_operator_new
981 ? "__builtin_operator_new"
982 : "__builtin_operator_delete")
986 // CodeGen assumes it can find the global new and delete to call,
987 // so ensure that they are declared.
988 DeclareGlobalNewDelete();
991 // check secure string manipulation functions where overflows
992 // are detectable at compile time
993 case Builtin::BI__builtin___memcpy_chk:
994 case Builtin::BI__builtin___memmove_chk:
995 case Builtin::BI__builtin___memset_chk:
996 case Builtin::BI__builtin___strlcat_chk:
997 case Builtin::BI__builtin___strlcpy_chk:
998 case Builtin::BI__builtin___strncat_chk:
999 case Builtin::BI__builtin___strncpy_chk:
1000 case Builtin::BI__builtin___stpncpy_chk:
1001 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
1003 case Builtin::BI__builtin___memccpy_chk:
1004 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
1006 case Builtin::BI__builtin___snprintf_chk:
1007 case Builtin::BI__builtin___vsnprintf_chk:
1008 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
1010 case Builtin::BI__builtin_call_with_static_chain:
1011 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1014 case Builtin::BI__exception_code:
1015 case Builtin::BI_exception_code:
1016 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1017 diag::err_seh___except_block))
1020 case Builtin::BI__exception_info:
1021 case Builtin::BI_exception_info:
1022 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1023 diag::err_seh___except_filter))
1026 case Builtin::BI__GetExceptionInfo:
1027 if (checkArgCount(*this, TheCall, 1))
1030 if (CheckCXXThrowOperand(
1031 TheCall->getLocStart(),
1032 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1036 TheCall->setType(Context.VoidPtrTy);
1038 // OpenCL v2.0, s6.13.16 - Pipe functions
1039 case Builtin::BIread_pipe:
1040 case Builtin::BIwrite_pipe:
1041 // Since those two functions are declared with var args, we need a semantic
1042 // check for the argument.
1043 if (SemaBuiltinRWPipe(*this, TheCall))
1045 TheCall->setType(Context.IntTy);
1047 case Builtin::BIreserve_read_pipe:
1048 case Builtin::BIreserve_write_pipe:
1049 case Builtin::BIwork_group_reserve_read_pipe:
1050 case Builtin::BIwork_group_reserve_write_pipe:
1051 case Builtin::BIsub_group_reserve_read_pipe:
1052 case Builtin::BIsub_group_reserve_write_pipe:
1053 if (SemaBuiltinReserveRWPipe(*this, TheCall))
1055 // Since return type of reserve_read/write_pipe built-in function is
1056 // reserve_id_t, which is not defined in the builtin def file , we used int
1057 // as return type and need to override the return type of these functions.
1058 TheCall->setType(Context.OCLReserveIDTy);
1060 case Builtin::BIcommit_read_pipe:
1061 case Builtin::BIcommit_write_pipe:
1062 case Builtin::BIwork_group_commit_read_pipe:
1063 case Builtin::BIwork_group_commit_write_pipe:
1064 case Builtin::BIsub_group_commit_read_pipe:
1065 case Builtin::BIsub_group_commit_write_pipe:
1066 if (SemaBuiltinCommitRWPipe(*this, TheCall))
1069 case Builtin::BIget_pipe_num_packets:
1070 case Builtin::BIget_pipe_max_packets:
1071 if (SemaBuiltinPipePackets(*this, TheCall))
1073 TheCall->setType(Context.UnsignedIntTy);
1075 case Builtin::BIto_global:
1076 case Builtin::BIto_local:
1077 case Builtin::BIto_private:
1078 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1081 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1082 case Builtin::BIenqueue_kernel:
1083 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1086 case Builtin::BIget_kernel_work_group_size:
1087 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1088 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1091 case Builtin::BI__builtin_os_log_format:
1092 case Builtin::BI__builtin_os_log_format_buffer_size:
1093 if (SemaBuiltinOSLogFormat(TheCall)) {
1099 // Since the target specific builtins for each arch overlap, only check those
1100 // of the arch we are compiling for.
1101 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1102 switch (Context.getTargetInfo().getTriple().getArch()) {
1103 case llvm::Triple::arm:
1104 case llvm::Triple::armeb:
1105 case llvm::Triple::thumb:
1106 case llvm::Triple::thumbeb:
1107 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1110 case llvm::Triple::aarch64:
1111 case llvm::Triple::aarch64_be:
1112 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
1115 case llvm::Triple::mips:
1116 case llvm::Triple::mipsel:
1117 case llvm::Triple::mips64:
1118 case llvm::Triple::mips64el:
1119 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1122 case llvm::Triple::systemz:
1123 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1126 case llvm::Triple::x86:
1127 case llvm::Triple::x86_64:
1128 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1131 case llvm::Triple::ppc:
1132 case llvm::Triple::ppc64:
1133 case llvm::Triple::ppc64le:
1134 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1142 return TheCallResult;
1145 // Get the valid immediate range for the specified NEON type code.
1146 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1147 NeonTypeFlags Type(t);
1148 int IsQuad = ForceQuad ? true : Type.isQuad();
1149 switch (Type.getEltType()) {
1150 case NeonTypeFlags::Int8:
1151 case NeonTypeFlags::Poly8:
1152 return shift ? 7 : (8 << IsQuad) - 1;
1153 case NeonTypeFlags::Int16:
1154 case NeonTypeFlags::Poly16:
1155 return shift ? 15 : (4 << IsQuad) - 1;
1156 case NeonTypeFlags::Int32:
1157 return shift ? 31 : (2 << IsQuad) - 1;
1158 case NeonTypeFlags::Int64:
1159 case NeonTypeFlags::Poly64:
1160 return shift ? 63 : (1 << IsQuad) - 1;
1161 case NeonTypeFlags::Poly128:
1162 return shift ? 127 : (1 << IsQuad) - 1;
1163 case NeonTypeFlags::Float16:
1164 assert(!shift && "cannot shift float types!");
1165 return (4 << IsQuad) - 1;
1166 case NeonTypeFlags::Float32:
1167 assert(!shift && "cannot shift float types!");
1168 return (2 << IsQuad) - 1;
1169 case NeonTypeFlags::Float64:
1170 assert(!shift && "cannot shift float types!");
1171 return (1 << IsQuad) - 1;
1173 llvm_unreachable("Invalid NeonTypeFlag!");
1176 /// getNeonEltType - Return the QualType corresponding to the elements of
1177 /// the vector type specified by the NeonTypeFlags. This is used to check
1178 /// the pointer arguments for Neon load/store intrinsics.
1179 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
1180 bool IsPolyUnsigned, bool IsInt64Long) {
1181 switch (Flags.getEltType()) {
1182 case NeonTypeFlags::Int8:
1183 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1184 case NeonTypeFlags::Int16:
1185 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1186 case NeonTypeFlags::Int32:
1187 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1188 case NeonTypeFlags::Int64:
1190 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1192 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1193 : Context.LongLongTy;
1194 case NeonTypeFlags::Poly8:
1195 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
1196 case NeonTypeFlags::Poly16:
1197 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
1198 case NeonTypeFlags::Poly64:
1200 return Context.UnsignedLongTy;
1202 return Context.UnsignedLongLongTy;
1203 case NeonTypeFlags::Poly128:
1205 case NeonTypeFlags::Float16:
1206 return Context.HalfTy;
1207 case NeonTypeFlags::Float32:
1208 return Context.FloatTy;
1209 case NeonTypeFlags::Float64:
1210 return Context.DoubleTy;
1212 llvm_unreachable("Invalid NeonTypeFlag!");
1215 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1216 llvm::APSInt Result;
1220 bool HasConstPtr = false;
1221 switch (BuiltinID) {
1222 #define GET_NEON_OVERLOAD_CHECK
1223 #include "clang/Basic/arm_neon.inc"
1224 #undef GET_NEON_OVERLOAD_CHECK
1227 // For NEON intrinsics which are overloaded on vector element type, validate
1228 // the immediate which specifies which variant to emit.
1229 unsigned ImmArg = TheCall->getNumArgs()-1;
1231 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1234 TV = Result.getLimitedValue(64);
1235 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1236 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
1237 << TheCall->getArg(ImmArg)->getSourceRange();
1240 if (PtrArgNum >= 0) {
1241 // Check that pointer arguments have the specified type.
1242 Expr *Arg = TheCall->getArg(PtrArgNum);
1243 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1244 Arg = ICE->getSubExpr();
1245 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1246 QualType RHSTy = RHS.get()->getType();
1248 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
1249 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1250 Arch == llvm::Triple::aarch64_be;
1252 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1254 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
1256 EltTy = EltTy.withConst();
1257 QualType LHSTy = Context.getPointerType(EltTy);
1258 AssignConvertType ConvTy;
1259 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1260 if (RHS.isInvalid())
1262 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1263 RHS.get(), AA_Assigning))
1267 // For NEON intrinsics which take an immediate value as part of the
1268 // instruction, range check them here.
1269 unsigned i = 0, l = 0, u = 0;
1270 switch (BuiltinID) {
1273 #define GET_NEON_IMMEDIATE_CHECK
1274 #include "clang/Basic/arm_neon.inc"
1275 #undef GET_NEON_IMMEDIATE_CHECK
1278 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1281 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1282 unsigned MaxWidth) {
1283 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
1284 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1285 BuiltinID == ARM::BI__builtin_arm_strex ||
1286 BuiltinID == ARM::BI__builtin_arm_stlex ||
1287 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1288 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1289 BuiltinID == AArch64::BI__builtin_arm_strex ||
1290 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
1291 "unexpected ARM builtin");
1292 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
1293 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1294 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1295 BuiltinID == AArch64::BI__builtin_arm_ldaex;
1297 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1299 // Ensure that we have the proper number of arguments.
1300 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1303 // Inspect the pointer argument of the atomic builtin. This should always be
1304 // a pointer type, whose element is an integral scalar or pointer type.
1305 // Because it is a pointer type, we don't have to worry about any implicit
1307 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1308 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1309 if (PointerArgRes.isInvalid())
1311 PointerArg = PointerArgRes.get();
1313 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1315 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1316 << PointerArg->getType() << PointerArg->getSourceRange();
1320 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1321 // task is to insert the appropriate casts into the AST. First work out just
1322 // what the appropriate type is.
1323 QualType ValType = pointerType->getPointeeType();
1324 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1326 AddrType.addConst();
1328 // Issue a warning if the cast is dodgy.
1329 CastKind CastNeeded = CK_NoOp;
1330 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1331 CastNeeded = CK_BitCast;
1332 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1333 << PointerArg->getType()
1334 << Context.getPointerType(AddrType)
1335 << AA_Passing << PointerArg->getSourceRange();
1338 // Finally, do the cast and replace the argument with the corrected version.
1339 AddrType = Context.getPointerType(AddrType);
1340 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1341 if (PointerArgRes.isInvalid())
1343 PointerArg = PointerArgRes.get();
1345 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1347 // In general, we allow ints, floats and pointers to be loaded and stored.
1348 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1349 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1350 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1351 << PointerArg->getType() << PointerArg->getSourceRange();
1355 // But ARM doesn't have instructions to deal with 128-bit versions.
1356 if (Context.getTypeSize(ValType) > MaxWidth) {
1357 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
1358 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1359 << PointerArg->getType() << PointerArg->getSourceRange();
1363 switch (ValType.getObjCLifetime()) {
1364 case Qualifiers::OCL_None:
1365 case Qualifiers::OCL_ExplicitNone:
1369 case Qualifiers::OCL_Weak:
1370 case Qualifiers::OCL_Strong:
1371 case Qualifiers::OCL_Autoreleasing:
1372 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1373 << ValType << PointerArg->getSourceRange();
1378 TheCall->setType(ValType);
1382 // Initialize the argument to be stored.
1383 ExprResult ValArg = TheCall->getArg(0);
1384 InitializedEntity Entity = InitializedEntity::InitializeParameter(
1385 Context, ValType, /*consume*/ false);
1386 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1387 if (ValArg.isInvalid())
1389 TheCall->setArg(0, ValArg.get());
1391 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1392 // but the custom checker bypasses all default analysis.
1393 TheCall->setType(Context.IntTy);
1397 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1398 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
1399 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1400 BuiltinID == ARM::BI__builtin_arm_strex ||
1401 BuiltinID == ARM::BI__builtin_arm_stlex) {
1402 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
1405 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1406 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1407 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1410 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1411 BuiltinID == ARM::BI__builtin_arm_wsr64)
1412 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1414 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1415 BuiltinID == ARM::BI__builtin_arm_rsrp ||
1416 BuiltinID == ARM::BI__builtin_arm_wsr ||
1417 BuiltinID == ARM::BI__builtin_arm_wsrp)
1418 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1420 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1423 // For intrinsics which take an immediate value as part of the instruction,
1424 // range check them here.
1425 unsigned i = 0, l = 0, u = 0;
1426 switch (BuiltinID) {
1427 default: return false;
1428 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
1429 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
1430 case ARM::BI__builtin_arm_vcvtr_f:
1431 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
1432 case ARM::BI__builtin_arm_dmb:
1433 case ARM::BI__builtin_arm_dsb:
1434 case ARM::BI__builtin_arm_isb:
1435 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
1438 // FIXME: VFP Intrinsics should error if VFP not present.
1439 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1442 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
1443 CallExpr *TheCall) {
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_sldi_b: i = 2; l = 0; u = 15; break;
1623 // These intrinsics take an unsigned 3 bit immediate.
1624 case Mips::BI__builtin_msa_copy_s_h:
1625 case Mips::BI__builtin_msa_copy_u_h:
1626 case Mips::BI__builtin_msa_insve_h:
1627 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
1628 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
1629 // These intrinsics take an unsigned 2 bit immediate.
1630 case Mips::BI__builtin_msa_copy_s_w:
1631 case Mips::BI__builtin_msa_copy_u_w:
1632 case Mips::BI__builtin_msa_insve_w:
1633 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
1634 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
1635 // These intrinsics take an unsigned 1 bit immediate.
1636 case Mips::BI__builtin_msa_copy_s_d:
1637 case Mips::BI__builtin_msa_copy_u_d:
1638 case Mips::BI__builtin_msa_insve_d:
1639 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
1640 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
1641 // Memory offsets and immediate loads.
1642 // These intrinsics take a signed 10 bit immediate.
1643 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
1644 case Mips::BI__builtin_msa_ldi_h:
1645 case Mips::BI__builtin_msa_ldi_w:
1646 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
1647 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
1648 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
1649 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
1650 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
1651 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
1652 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
1653 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
1654 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
1658 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1660 return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
1661 SemaBuiltinConstantArgMultiple(TheCall, i, m);
1664 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1665 unsigned i = 0, l = 0, u = 0;
1666 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1667 BuiltinID == PPC::BI__builtin_divdeu ||
1668 BuiltinID == PPC::BI__builtin_bpermd;
1669 bool IsTarget64Bit = Context.getTargetInfo()
1670 .getTypeWidth(Context
1672 .getIntPtrType()) == 64;
1673 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1674 BuiltinID == PPC::BI__builtin_divweu ||
1675 BuiltinID == PPC::BI__builtin_divde ||
1676 BuiltinID == PPC::BI__builtin_divdeu;
1678 if (Is64BitBltin && !IsTarget64Bit)
1679 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1680 << TheCall->getSourceRange();
1682 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1683 (BuiltinID == PPC::BI__builtin_bpermd &&
1684 !Context.getTargetInfo().hasFeature("bpermd")))
1685 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1686 << TheCall->getSourceRange();
1688 switch (BuiltinID) {
1689 default: return false;
1690 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1691 case PPC::BI__builtin_altivec_crypto_vshasigmad:
1692 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1693 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1694 case PPC::BI__builtin_tbegin:
1695 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1696 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1697 case PPC::BI__builtin_tabortwc:
1698 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1699 case PPC::BI__builtin_tabortwci:
1700 case PPC::BI__builtin_tabortdci:
1701 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1702 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
1703 case PPC::BI__builtin_vsx_xxpermdi:
1704 case PPC::BI__builtin_vsx_xxsldwi:
1705 return SemaBuiltinVSX(TheCall);
1707 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1710 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1711 CallExpr *TheCall) {
1712 if (BuiltinID == SystemZ::BI__builtin_tabort) {
1713 Expr *Arg = TheCall->getArg(0);
1714 llvm::APSInt AbortCode(32);
1715 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1716 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1717 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1718 << Arg->getSourceRange();
1721 // For intrinsics which take an immediate value as part of the instruction,
1722 // range check them here.
1723 unsigned i = 0, l = 0, u = 0;
1724 switch (BuiltinID) {
1725 default: return false;
1726 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1727 case SystemZ::BI__builtin_s390_verimb:
1728 case SystemZ::BI__builtin_s390_verimh:
1729 case SystemZ::BI__builtin_s390_verimf:
1730 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1731 case SystemZ::BI__builtin_s390_vfaeb:
1732 case SystemZ::BI__builtin_s390_vfaeh:
1733 case SystemZ::BI__builtin_s390_vfaef:
1734 case SystemZ::BI__builtin_s390_vfaebs:
1735 case SystemZ::BI__builtin_s390_vfaehs:
1736 case SystemZ::BI__builtin_s390_vfaefs:
1737 case SystemZ::BI__builtin_s390_vfaezb:
1738 case SystemZ::BI__builtin_s390_vfaezh:
1739 case SystemZ::BI__builtin_s390_vfaezf:
1740 case SystemZ::BI__builtin_s390_vfaezbs:
1741 case SystemZ::BI__builtin_s390_vfaezhs:
1742 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1743 case SystemZ::BI__builtin_s390_vfisb:
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_vftcisb:
1748 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1749 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1750 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1751 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1752 case SystemZ::BI__builtin_s390_vstrcb:
1753 case SystemZ::BI__builtin_s390_vstrch:
1754 case SystemZ::BI__builtin_s390_vstrcf:
1755 case SystemZ::BI__builtin_s390_vstrczb:
1756 case SystemZ::BI__builtin_s390_vstrczh:
1757 case SystemZ::BI__builtin_s390_vstrczf:
1758 case SystemZ::BI__builtin_s390_vstrcbs:
1759 case SystemZ::BI__builtin_s390_vstrchs:
1760 case SystemZ::BI__builtin_s390_vstrcfs:
1761 case SystemZ::BI__builtin_s390_vstrczbs:
1762 case SystemZ::BI__builtin_s390_vstrczhs:
1763 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1764 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
1765 case SystemZ::BI__builtin_s390_vfminsb:
1766 case SystemZ::BI__builtin_s390_vfmaxsb:
1767 case SystemZ::BI__builtin_s390_vfmindb:
1768 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
1770 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1773 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1774 /// This checks that the target supports __builtin_cpu_supports and
1775 /// that the string argument is constant and valid.
1776 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1777 Expr *Arg = TheCall->getArg(0);
1779 // Check if the argument is a string literal.
1780 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1781 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1782 << Arg->getSourceRange();
1784 // Check the contents of the string.
1786 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1787 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1788 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1789 << Arg->getSourceRange();
1793 // Check if the rounding mode is legal.
1794 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
1795 // Indicates if this instruction has rounding control or just SAE.
1798 unsigned ArgNum = 0;
1799 switch (BuiltinID) {
1802 case X86::BI__builtin_ia32_vcvttsd2si32:
1803 case X86::BI__builtin_ia32_vcvttsd2si64:
1804 case X86::BI__builtin_ia32_vcvttsd2usi32:
1805 case X86::BI__builtin_ia32_vcvttsd2usi64:
1806 case X86::BI__builtin_ia32_vcvttss2si32:
1807 case X86::BI__builtin_ia32_vcvttss2si64:
1808 case X86::BI__builtin_ia32_vcvttss2usi32:
1809 case X86::BI__builtin_ia32_vcvttss2usi64:
1812 case X86::BI__builtin_ia32_cvtps2pd512_mask:
1813 case X86::BI__builtin_ia32_cvttpd2dq512_mask:
1814 case X86::BI__builtin_ia32_cvttpd2qq512_mask:
1815 case X86::BI__builtin_ia32_cvttpd2udq512_mask:
1816 case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
1817 case X86::BI__builtin_ia32_cvttps2dq512_mask:
1818 case X86::BI__builtin_ia32_cvttps2qq512_mask:
1819 case X86::BI__builtin_ia32_cvttps2udq512_mask:
1820 case X86::BI__builtin_ia32_cvttps2uqq512_mask:
1821 case X86::BI__builtin_ia32_exp2pd_mask:
1822 case X86::BI__builtin_ia32_exp2ps_mask:
1823 case X86::BI__builtin_ia32_getexppd512_mask:
1824 case X86::BI__builtin_ia32_getexpps512_mask:
1825 case X86::BI__builtin_ia32_rcp28pd_mask:
1826 case X86::BI__builtin_ia32_rcp28ps_mask:
1827 case X86::BI__builtin_ia32_rsqrt28pd_mask:
1828 case X86::BI__builtin_ia32_rsqrt28ps_mask:
1829 case X86::BI__builtin_ia32_vcomisd:
1830 case X86::BI__builtin_ia32_vcomiss:
1831 case X86::BI__builtin_ia32_vcvtph2ps512_mask:
1834 case X86::BI__builtin_ia32_cmppd512_mask:
1835 case X86::BI__builtin_ia32_cmpps512_mask:
1836 case X86::BI__builtin_ia32_cmpsd_mask:
1837 case X86::BI__builtin_ia32_cmpss_mask:
1838 case X86::BI__builtin_ia32_cvtss2sd_round_mask:
1839 case X86::BI__builtin_ia32_getexpsd128_round_mask:
1840 case X86::BI__builtin_ia32_getexpss128_round_mask:
1841 case X86::BI__builtin_ia32_maxpd512_mask:
1842 case X86::BI__builtin_ia32_maxps512_mask:
1843 case X86::BI__builtin_ia32_maxsd_round_mask:
1844 case X86::BI__builtin_ia32_maxss_round_mask:
1845 case X86::BI__builtin_ia32_minpd512_mask:
1846 case X86::BI__builtin_ia32_minps512_mask:
1847 case X86::BI__builtin_ia32_minsd_round_mask:
1848 case X86::BI__builtin_ia32_minss_round_mask:
1849 case X86::BI__builtin_ia32_rcp28sd_round_mask:
1850 case X86::BI__builtin_ia32_rcp28ss_round_mask:
1851 case X86::BI__builtin_ia32_reducepd512_mask:
1852 case X86::BI__builtin_ia32_reduceps512_mask:
1853 case X86::BI__builtin_ia32_rndscalepd_mask:
1854 case X86::BI__builtin_ia32_rndscaleps_mask:
1855 case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
1856 case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
1859 case X86::BI__builtin_ia32_fixupimmpd512_mask:
1860 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
1861 case X86::BI__builtin_ia32_fixupimmps512_mask:
1862 case X86::BI__builtin_ia32_fixupimmps512_maskz:
1863 case X86::BI__builtin_ia32_fixupimmsd_mask:
1864 case X86::BI__builtin_ia32_fixupimmsd_maskz:
1865 case X86::BI__builtin_ia32_fixupimmss_mask:
1866 case X86::BI__builtin_ia32_fixupimmss_maskz:
1867 case X86::BI__builtin_ia32_rangepd512_mask:
1868 case X86::BI__builtin_ia32_rangeps512_mask:
1869 case X86::BI__builtin_ia32_rangesd128_round_mask:
1870 case X86::BI__builtin_ia32_rangess128_round_mask:
1871 case X86::BI__builtin_ia32_reducesd_mask:
1872 case X86::BI__builtin_ia32_reducess_mask:
1873 case X86::BI__builtin_ia32_rndscalesd_round_mask:
1874 case X86::BI__builtin_ia32_rndscaless_round_mask:
1877 case X86::BI__builtin_ia32_vcvtsd2si64:
1878 case X86::BI__builtin_ia32_vcvtsd2si32:
1879 case X86::BI__builtin_ia32_vcvtsd2usi32:
1880 case X86::BI__builtin_ia32_vcvtsd2usi64:
1881 case X86::BI__builtin_ia32_vcvtss2si32:
1882 case X86::BI__builtin_ia32_vcvtss2si64:
1883 case X86::BI__builtin_ia32_vcvtss2usi32:
1884 case X86::BI__builtin_ia32_vcvtss2usi64:
1888 case X86::BI__builtin_ia32_cvtsi2sd64:
1889 case X86::BI__builtin_ia32_cvtsi2ss32:
1890 case X86::BI__builtin_ia32_cvtsi2ss64:
1891 case X86::BI__builtin_ia32_cvtusi2sd64:
1892 case X86::BI__builtin_ia32_cvtusi2ss32:
1893 case X86::BI__builtin_ia32_cvtusi2ss64:
1897 case X86::BI__builtin_ia32_cvtdq2ps512_mask:
1898 case X86::BI__builtin_ia32_cvtudq2ps512_mask:
1899 case X86::BI__builtin_ia32_cvtpd2ps512_mask:
1900 case X86::BI__builtin_ia32_cvtpd2qq512_mask:
1901 case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
1902 case X86::BI__builtin_ia32_cvtps2qq512_mask:
1903 case X86::BI__builtin_ia32_cvtps2uqq512_mask:
1904 case X86::BI__builtin_ia32_cvtqq2pd512_mask:
1905 case X86::BI__builtin_ia32_cvtqq2ps512_mask:
1906 case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
1907 case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
1908 case X86::BI__builtin_ia32_sqrtpd512_mask:
1909 case X86::BI__builtin_ia32_sqrtps512_mask:
1913 case X86::BI__builtin_ia32_addpd512_mask:
1914 case X86::BI__builtin_ia32_addps512_mask:
1915 case X86::BI__builtin_ia32_divpd512_mask:
1916 case X86::BI__builtin_ia32_divps512_mask:
1917 case X86::BI__builtin_ia32_mulpd512_mask:
1918 case X86::BI__builtin_ia32_mulps512_mask:
1919 case X86::BI__builtin_ia32_subpd512_mask:
1920 case X86::BI__builtin_ia32_subps512_mask:
1921 case X86::BI__builtin_ia32_addss_round_mask:
1922 case X86::BI__builtin_ia32_addsd_round_mask:
1923 case X86::BI__builtin_ia32_divss_round_mask:
1924 case X86::BI__builtin_ia32_divsd_round_mask:
1925 case X86::BI__builtin_ia32_mulss_round_mask:
1926 case X86::BI__builtin_ia32_mulsd_round_mask:
1927 case X86::BI__builtin_ia32_subss_round_mask:
1928 case X86::BI__builtin_ia32_subsd_round_mask:
1929 case X86::BI__builtin_ia32_scalefpd512_mask:
1930 case X86::BI__builtin_ia32_scalefps512_mask:
1931 case X86::BI__builtin_ia32_scalefsd_round_mask:
1932 case X86::BI__builtin_ia32_scalefss_round_mask:
1933 case X86::BI__builtin_ia32_getmantpd512_mask:
1934 case X86::BI__builtin_ia32_getmantps512_mask:
1935 case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
1936 case X86::BI__builtin_ia32_sqrtsd_round_mask:
1937 case X86::BI__builtin_ia32_sqrtss_round_mask:
1938 case X86::BI__builtin_ia32_vfmaddpd512_mask:
1939 case X86::BI__builtin_ia32_vfmaddpd512_mask3:
1940 case X86::BI__builtin_ia32_vfmaddpd512_maskz:
1941 case X86::BI__builtin_ia32_vfmaddps512_mask:
1942 case X86::BI__builtin_ia32_vfmaddps512_mask3:
1943 case X86::BI__builtin_ia32_vfmaddps512_maskz:
1944 case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
1945 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
1946 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
1947 case X86::BI__builtin_ia32_vfmaddsubps512_mask:
1948 case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
1949 case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
1950 case X86::BI__builtin_ia32_vfmsubpd512_mask3:
1951 case X86::BI__builtin_ia32_vfmsubps512_mask3:
1952 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
1953 case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
1954 case X86::BI__builtin_ia32_vfnmaddpd512_mask:
1955 case X86::BI__builtin_ia32_vfnmaddps512_mask:
1956 case X86::BI__builtin_ia32_vfnmsubpd512_mask:
1957 case X86::BI__builtin_ia32_vfnmsubpd512_mask3:
1958 case X86::BI__builtin_ia32_vfnmsubps512_mask:
1959 case X86::BI__builtin_ia32_vfnmsubps512_mask3:
1960 case X86::BI__builtin_ia32_vfmaddsd3_mask:
1961 case X86::BI__builtin_ia32_vfmaddsd3_maskz:
1962 case X86::BI__builtin_ia32_vfmaddsd3_mask3:
1963 case X86::BI__builtin_ia32_vfmaddss3_mask:
1964 case X86::BI__builtin_ia32_vfmaddss3_maskz:
1965 case X86::BI__builtin_ia32_vfmaddss3_mask3:
1969 case X86::BI__builtin_ia32_getmantsd_round_mask:
1970 case X86::BI__builtin_ia32_getmantss_round_mask:
1976 llvm::APSInt Result;
1978 // We can't check the value of a dependent argument.
1979 Expr *Arg = TheCall->getArg(ArgNum);
1980 if (Arg->isTypeDependent() || Arg->isValueDependent())
1983 // Check constant-ness first.
1984 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
1987 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
1988 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
1989 // combined with ROUND_NO_EXC.
1990 if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
1991 Result == 8/*ROUND_NO_EXC*/ ||
1992 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
1995 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
1996 << Arg->getSourceRange();
1999 // Check if the gather/scatter scale is legal.
2000 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
2001 CallExpr *TheCall) {
2002 unsigned ArgNum = 0;
2003 switch (BuiltinID) {
2006 case X86::BI__builtin_ia32_gatherpfdpd:
2007 case X86::BI__builtin_ia32_gatherpfdps:
2008 case X86::BI__builtin_ia32_gatherpfqpd:
2009 case X86::BI__builtin_ia32_gatherpfqps:
2010 case X86::BI__builtin_ia32_scatterpfdpd:
2011 case X86::BI__builtin_ia32_scatterpfdps:
2012 case X86::BI__builtin_ia32_scatterpfqpd:
2013 case X86::BI__builtin_ia32_scatterpfqps:
2016 case X86::BI__builtin_ia32_gatherd_pd:
2017 case X86::BI__builtin_ia32_gatherd_pd256:
2018 case X86::BI__builtin_ia32_gatherq_pd:
2019 case X86::BI__builtin_ia32_gatherq_pd256:
2020 case X86::BI__builtin_ia32_gatherd_ps:
2021 case X86::BI__builtin_ia32_gatherd_ps256:
2022 case X86::BI__builtin_ia32_gatherq_ps:
2023 case X86::BI__builtin_ia32_gatherq_ps256:
2024 case X86::BI__builtin_ia32_gatherd_q:
2025 case X86::BI__builtin_ia32_gatherd_q256:
2026 case X86::BI__builtin_ia32_gatherq_q:
2027 case X86::BI__builtin_ia32_gatherq_q256:
2028 case X86::BI__builtin_ia32_gatherd_d:
2029 case X86::BI__builtin_ia32_gatherd_d256:
2030 case X86::BI__builtin_ia32_gatherq_d:
2031 case X86::BI__builtin_ia32_gatherq_d256:
2032 case X86::BI__builtin_ia32_gather3div2df:
2033 case X86::BI__builtin_ia32_gather3div2di:
2034 case X86::BI__builtin_ia32_gather3div4df:
2035 case X86::BI__builtin_ia32_gather3div4di:
2036 case X86::BI__builtin_ia32_gather3div4sf:
2037 case X86::BI__builtin_ia32_gather3div4si:
2038 case X86::BI__builtin_ia32_gather3div8sf:
2039 case X86::BI__builtin_ia32_gather3div8si:
2040 case X86::BI__builtin_ia32_gather3siv2df:
2041 case X86::BI__builtin_ia32_gather3siv2di:
2042 case X86::BI__builtin_ia32_gather3siv4df:
2043 case X86::BI__builtin_ia32_gather3siv4di:
2044 case X86::BI__builtin_ia32_gather3siv4sf:
2045 case X86::BI__builtin_ia32_gather3siv4si:
2046 case X86::BI__builtin_ia32_gather3siv8sf:
2047 case X86::BI__builtin_ia32_gather3siv8si:
2048 case X86::BI__builtin_ia32_gathersiv8df:
2049 case X86::BI__builtin_ia32_gathersiv16sf:
2050 case X86::BI__builtin_ia32_gatherdiv8df:
2051 case X86::BI__builtin_ia32_gatherdiv16sf:
2052 case X86::BI__builtin_ia32_gathersiv8di:
2053 case X86::BI__builtin_ia32_gathersiv16si:
2054 case X86::BI__builtin_ia32_gatherdiv8di:
2055 case X86::BI__builtin_ia32_gatherdiv16si:
2056 case X86::BI__builtin_ia32_scatterdiv2df:
2057 case X86::BI__builtin_ia32_scatterdiv2di:
2058 case X86::BI__builtin_ia32_scatterdiv4df:
2059 case X86::BI__builtin_ia32_scatterdiv4di:
2060 case X86::BI__builtin_ia32_scatterdiv4sf:
2061 case X86::BI__builtin_ia32_scatterdiv4si:
2062 case X86::BI__builtin_ia32_scatterdiv8sf:
2063 case X86::BI__builtin_ia32_scatterdiv8si:
2064 case X86::BI__builtin_ia32_scattersiv2df:
2065 case X86::BI__builtin_ia32_scattersiv2di:
2066 case X86::BI__builtin_ia32_scattersiv4df:
2067 case X86::BI__builtin_ia32_scattersiv4di:
2068 case X86::BI__builtin_ia32_scattersiv4sf:
2069 case X86::BI__builtin_ia32_scattersiv4si:
2070 case X86::BI__builtin_ia32_scattersiv8sf:
2071 case X86::BI__builtin_ia32_scattersiv8si:
2072 case X86::BI__builtin_ia32_scattersiv8df:
2073 case X86::BI__builtin_ia32_scattersiv16sf:
2074 case X86::BI__builtin_ia32_scatterdiv8df:
2075 case X86::BI__builtin_ia32_scatterdiv16sf:
2076 case X86::BI__builtin_ia32_scattersiv8di:
2077 case X86::BI__builtin_ia32_scattersiv16si:
2078 case X86::BI__builtin_ia32_scatterdiv8di:
2079 case X86::BI__builtin_ia32_scatterdiv16si:
2084 llvm::APSInt Result;
2086 // We can't check the value of a dependent argument.
2087 Expr *Arg = TheCall->getArg(ArgNum);
2088 if (Arg->isTypeDependent() || Arg->isValueDependent())
2091 // Check constant-ness first.
2092 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2095 if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
2098 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale)
2099 << Arg->getSourceRange();
2102 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2103 if (BuiltinID == X86::BI__builtin_cpu_supports)
2104 return SemaBuiltinCpuSupports(*this, TheCall);
2106 // If the intrinsic has rounding or SAE make sure its valid.
2107 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
2110 // If the intrinsic has a gather/scatter scale immediate make sure its valid.
2111 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
2114 // For intrinsics which take an immediate value as part of the instruction,
2115 // range check them here.
2116 int i = 0, l = 0, u = 0;
2117 switch (BuiltinID) {
2120 case X86::BI_mm_prefetch:
2121 i = 1; l = 0; u = 3;
2123 case X86::BI__builtin_ia32_sha1rnds4:
2124 case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
2125 case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
2126 case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
2127 case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
2128 i = 2; l = 0; u = 3;
2130 case X86::BI__builtin_ia32_vpermil2pd:
2131 case X86::BI__builtin_ia32_vpermil2pd256:
2132 case X86::BI__builtin_ia32_vpermil2ps:
2133 case X86::BI__builtin_ia32_vpermil2ps256:
2134 i = 3; l = 0; u = 3;
2136 case X86::BI__builtin_ia32_cmpb128_mask:
2137 case X86::BI__builtin_ia32_cmpw128_mask:
2138 case X86::BI__builtin_ia32_cmpd128_mask:
2139 case X86::BI__builtin_ia32_cmpq128_mask:
2140 case X86::BI__builtin_ia32_cmpb256_mask:
2141 case X86::BI__builtin_ia32_cmpw256_mask:
2142 case X86::BI__builtin_ia32_cmpd256_mask:
2143 case X86::BI__builtin_ia32_cmpq256_mask:
2144 case X86::BI__builtin_ia32_cmpb512_mask:
2145 case X86::BI__builtin_ia32_cmpw512_mask:
2146 case X86::BI__builtin_ia32_cmpd512_mask:
2147 case X86::BI__builtin_ia32_cmpq512_mask:
2148 case X86::BI__builtin_ia32_ucmpb128_mask:
2149 case X86::BI__builtin_ia32_ucmpw128_mask:
2150 case X86::BI__builtin_ia32_ucmpd128_mask:
2151 case X86::BI__builtin_ia32_ucmpq128_mask:
2152 case X86::BI__builtin_ia32_ucmpb256_mask:
2153 case X86::BI__builtin_ia32_ucmpw256_mask:
2154 case X86::BI__builtin_ia32_ucmpd256_mask:
2155 case X86::BI__builtin_ia32_ucmpq256_mask:
2156 case X86::BI__builtin_ia32_ucmpb512_mask:
2157 case X86::BI__builtin_ia32_ucmpw512_mask:
2158 case X86::BI__builtin_ia32_ucmpd512_mask:
2159 case X86::BI__builtin_ia32_ucmpq512_mask:
2160 case X86::BI__builtin_ia32_vpcomub:
2161 case X86::BI__builtin_ia32_vpcomuw:
2162 case X86::BI__builtin_ia32_vpcomud:
2163 case X86::BI__builtin_ia32_vpcomuq:
2164 case X86::BI__builtin_ia32_vpcomb:
2165 case X86::BI__builtin_ia32_vpcomw:
2166 case X86::BI__builtin_ia32_vpcomd:
2167 case X86::BI__builtin_ia32_vpcomq:
2168 i = 2; l = 0; u = 7;
2170 case X86::BI__builtin_ia32_roundps:
2171 case X86::BI__builtin_ia32_roundpd:
2172 case X86::BI__builtin_ia32_roundps256:
2173 case X86::BI__builtin_ia32_roundpd256:
2174 i = 1; l = 0; u = 15;
2176 case X86::BI__builtin_ia32_roundss:
2177 case X86::BI__builtin_ia32_roundsd:
2178 case X86::BI__builtin_ia32_rangepd128_mask:
2179 case X86::BI__builtin_ia32_rangepd256_mask:
2180 case X86::BI__builtin_ia32_rangepd512_mask:
2181 case X86::BI__builtin_ia32_rangeps128_mask:
2182 case X86::BI__builtin_ia32_rangeps256_mask:
2183 case X86::BI__builtin_ia32_rangeps512_mask:
2184 case X86::BI__builtin_ia32_getmantsd_round_mask:
2185 case X86::BI__builtin_ia32_getmantss_round_mask:
2186 i = 2; l = 0; u = 15;
2188 case X86::BI__builtin_ia32_cmpps:
2189 case X86::BI__builtin_ia32_cmpss:
2190 case X86::BI__builtin_ia32_cmppd:
2191 case X86::BI__builtin_ia32_cmpsd:
2192 case X86::BI__builtin_ia32_cmpps256:
2193 case X86::BI__builtin_ia32_cmppd256:
2194 case X86::BI__builtin_ia32_cmpps128_mask:
2195 case X86::BI__builtin_ia32_cmppd128_mask:
2196 case X86::BI__builtin_ia32_cmpps256_mask:
2197 case X86::BI__builtin_ia32_cmppd256_mask:
2198 case X86::BI__builtin_ia32_cmpps512_mask:
2199 case X86::BI__builtin_ia32_cmppd512_mask:
2200 case X86::BI__builtin_ia32_cmpsd_mask:
2201 case X86::BI__builtin_ia32_cmpss_mask:
2202 i = 2; l = 0; u = 31;
2204 case X86::BI__builtin_ia32_xabort:
2205 i = 0; l = -128; u = 255;
2207 case X86::BI__builtin_ia32_pshufw:
2208 case X86::BI__builtin_ia32_aeskeygenassist128:
2209 i = 1; l = -128; u = 255;
2211 case X86::BI__builtin_ia32_vcvtps2ph:
2212 case X86::BI__builtin_ia32_vcvtps2ph256:
2213 case X86::BI__builtin_ia32_rndscaleps_128_mask:
2214 case X86::BI__builtin_ia32_rndscalepd_128_mask:
2215 case X86::BI__builtin_ia32_rndscaleps_256_mask:
2216 case X86::BI__builtin_ia32_rndscalepd_256_mask:
2217 case X86::BI__builtin_ia32_rndscaleps_mask:
2218 case X86::BI__builtin_ia32_rndscalepd_mask:
2219 case X86::BI__builtin_ia32_reducepd128_mask:
2220 case X86::BI__builtin_ia32_reducepd256_mask:
2221 case X86::BI__builtin_ia32_reducepd512_mask:
2222 case X86::BI__builtin_ia32_reduceps128_mask:
2223 case X86::BI__builtin_ia32_reduceps256_mask:
2224 case X86::BI__builtin_ia32_reduceps512_mask:
2225 case X86::BI__builtin_ia32_prold512_mask:
2226 case X86::BI__builtin_ia32_prolq512_mask:
2227 case X86::BI__builtin_ia32_prold128_mask:
2228 case X86::BI__builtin_ia32_prold256_mask:
2229 case X86::BI__builtin_ia32_prolq128_mask:
2230 case X86::BI__builtin_ia32_prolq256_mask:
2231 case X86::BI__builtin_ia32_prord128_mask:
2232 case X86::BI__builtin_ia32_prord256_mask:
2233 case X86::BI__builtin_ia32_prorq128_mask:
2234 case X86::BI__builtin_ia32_prorq256_mask:
2235 case X86::BI__builtin_ia32_fpclasspd128_mask:
2236 case X86::BI__builtin_ia32_fpclasspd256_mask:
2237 case X86::BI__builtin_ia32_fpclassps128_mask:
2238 case X86::BI__builtin_ia32_fpclassps256_mask:
2239 case X86::BI__builtin_ia32_fpclassps512_mask:
2240 case X86::BI__builtin_ia32_fpclasspd512_mask:
2241 case X86::BI__builtin_ia32_fpclasssd_mask:
2242 case X86::BI__builtin_ia32_fpclassss_mask:
2243 i = 1; l = 0; u = 255;
2245 case X86::BI__builtin_ia32_palignr:
2246 case X86::BI__builtin_ia32_insertps128:
2247 case X86::BI__builtin_ia32_dpps:
2248 case X86::BI__builtin_ia32_dppd:
2249 case X86::BI__builtin_ia32_dpps256:
2250 case X86::BI__builtin_ia32_mpsadbw128:
2251 case X86::BI__builtin_ia32_mpsadbw256:
2252 case X86::BI__builtin_ia32_pcmpistrm128:
2253 case X86::BI__builtin_ia32_pcmpistri128:
2254 case X86::BI__builtin_ia32_pcmpistria128:
2255 case X86::BI__builtin_ia32_pcmpistric128:
2256 case X86::BI__builtin_ia32_pcmpistrio128:
2257 case X86::BI__builtin_ia32_pcmpistris128:
2258 case X86::BI__builtin_ia32_pcmpistriz128:
2259 case X86::BI__builtin_ia32_pclmulqdq128:
2260 case X86::BI__builtin_ia32_vperm2f128_pd256:
2261 case X86::BI__builtin_ia32_vperm2f128_ps256:
2262 case X86::BI__builtin_ia32_vperm2f128_si256:
2263 case X86::BI__builtin_ia32_permti256:
2264 i = 2; l = -128; u = 255;
2266 case X86::BI__builtin_ia32_palignr128:
2267 case X86::BI__builtin_ia32_palignr256:
2268 case X86::BI__builtin_ia32_palignr512_mask:
2269 case X86::BI__builtin_ia32_vcomisd:
2270 case X86::BI__builtin_ia32_vcomiss:
2271 case X86::BI__builtin_ia32_shuf_f32x4_mask:
2272 case X86::BI__builtin_ia32_shuf_f64x2_mask:
2273 case X86::BI__builtin_ia32_shuf_i32x4_mask:
2274 case X86::BI__builtin_ia32_shuf_i64x2_mask:
2275 case X86::BI__builtin_ia32_dbpsadbw128_mask:
2276 case X86::BI__builtin_ia32_dbpsadbw256_mask:
2277 case X86::BI__builtin_ia32_dbpsadbw512_mask:
2278 i = 2; l = 0; u = 255;
2280 case X86::BI__builtin_ia32_fixupimmpd512_mask:
2281 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2282 case X86::BI__builtin_ia32_fixupimmps512_mask:
2283 case X86::BI__builtin_ia32_fixupimmps512_maskz:
2284 case X86::BI__builtin_ia32_fixupimmsd_mask:
2285 case X86::BI__builtin_ia32_fixupimmsd_maskz:
2286 case X86::BI__builtin_ia32_fixupimmss_mask:
2287 case X86::BI__builtin_ia32_fixupimmss_maskz:
2288 case X86::BI__builtin_ia32_fixupimmpd128_mask:
2289 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2290 case X86::BI__builtin_ia32_fixupimmpd256_mask:
2291 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2292 case X86::BI__builtin_ia32_fixupimmps128_mask:
2293 case X86::BI__builtin_ia32_fixupimmps128_maskz:
2294 case X86::BI__builtin_ia32_fixupimmps256_mask:
2295 case X86::BI__builtin_ia32_fixupimmps256_maskz:
2296 case X86::BI__builtin_ia32_pternlogd512_mask:
2297 case X86::BI__builtin_ia32_pternlogd512_maskz:
2298 case X86::BI__builtin_ia32_pternlogq512_mask:
2299 case X86::BI__builtin_ia32_pternlogq512_maskz:
2300 case X86::BI__builtin_ia32_pternlogd128_mask:
2301 case X86::BI__builtin_ia32_pternlogd128_maskz:
2302 case X86::BI__builtin_ia32_pternlogd256_mask:
2303 case X86::BI__builtin_ia32_pternlogd256_maskz:
2304 case X86::BI__builtin_ia32_pternlogq128_mask:
2305 case X86::BI__builtin_ia32_pternlogq128_maskz:
2306 case X86::BI__builtin_ia32_pternlogq256_mask:
2307 case X86::BI__builtin_ia32_pternlogq256_maskz:
2308 i = 3; l = 0; u = 255;
2310 case X86::BI__builtin_ia32_gatherpfdpd:
2311 case X86::BI__builtin_ia32_gatherpfdps:
2312 case X86::BI__builtin_ia32_gatherpfqpd:
2313 case X86::BI__builtin_ia32_gatherpfqps:
2314 case X86::BI__builtin_ia32_scatterpfdpd:
2315 case X86::BI__builtin_ia32_scatterpfdps:
2316 case X86::BI__builtin_ia32_scatterpfqpd:
2317 case X86::BI__builtin_ia32_scatterpfqps:
2318 i = 4; l = 2; u = 3;
2320 case X86::BI__builtin_ia32_pcmpestrm128:
2321 case X86::BI__builtin_ia32_pcmpestri128:
2322 case X86::BI__builtin_ia32_pcmpestria128:
2323 case X86::BI__builtin_ia32_pcmpestric128:
2324 case X86::BI__builtin_ia32_pcmpestrio128:
2325 case X86::BI__builtin_ia32_pcmpestris128:
2326 case X86::BI__builtin_ia32_pcmpestriz128:
2327 i = 4; l = -128; u = 255;
2329 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2330 case X86::BI__builtin_ia32_rndscaless_round_mask:
2331 i = 4; l = 0; u = 255;
2334 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2337 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2338 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
2339 /// Returns true when the format fits the function and the FormatStringInfo has
2341 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2342 FormatStringInfo *FSI) {
2343 FSI->HasVAListArg = Format->getFirstArg() == 0;
2344 FSI->FormatIdx = Format->getFormatIdx() - 1;
2345 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
2347 // The way the format attribute works in GCC, the implicit this argument
2348 // of member functions is counted. However, it doesn't appear in our own
2349 // lists, so decrement format_idx in that case.
2351 if(FSI->FormatIdx == 0)
2354 if (FSI->FirstDataArg != 0)
2355 --FSI->FirstDataArg;
2360 /// Checks if a the given expression evaluates to null.
2362 /// \brief Returns true if the value evaluates to null.
2363 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
2364 // If the expression has non-null type, it doesn't evaluate to null.
2365 if (auto nullability
2366 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2367 if (*nullability == NullabilityKind::NonNull)
2371 // As a special case, transparent unions initialized with zero are
2372 // considered null for the purposes of the nonnull attribute.
2373 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
2374 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2375 if (const CompoundLiteralExpr *CLE =
2376 dyn_cast<CompoundLiteralExpr>(Expr))
2377 if (const InitListExpr *ILE =
2378 dyn_cast<InitListExpr>(CLE->getInitializer()))
2379 Expr = ILE->getInit(0);
2383 return (!Expr->isValueDependent() &&
2384 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2388 static void CheckNonNullArgument(Sema &S,
2389 const Expr *ArgExpr,
2390 SourceLocation CallSiteLoc) {
2391 if (CheckNonNullExpr(S, ArgExpr))
2392 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2393 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
2396 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2397 FormatStringInfo FSI;
2398 if ((GetFormatStringType(Format) == FST_NSString) &&
2399 getFormatStringInfo(Format, false, &FSI)) {
2400 Idx = FSI.FormatIdx;
2405 /// \brief Diagnose use of %s directive in an NSString which is being passed
2406 /// as formatting string to formatting method.
2408 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
2409 const NamedDecl *FDecl,
2413 bool Format = false;
2414 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2415 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
2420 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2421 if (S.GetFormatNSStringIdx(I, Idx)) {
2426 if (!Format || NumArgs <= Idx)
2428 const Expr *FormatExpr = Args[Idx];
2429 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2430 FormatExpr = CSCE->getSubExpr();
2431 const StringLiteral *FormatString;
2432 if (const ObjCStringLiteral *OSL =
2433 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2434 FormatString = OSL->getString();
2436 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2439 if (S.FormatStringHasSArg(FormatString)) {
2440 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2442 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2443 << FDecl->getDeclName();
2447 /// Determine whether the given type has a non-null nullability annotation.
2448 static bool isNonNullType(ASTContext &ctx, QualType type) {
2449 if (auto nullability = type->getNullability(ctx))
2450 return *nullability == NullabilityKind::NonNull;
2455 static void CheckNonNullArguments(Sema &S,
2456 const NamedDecl *FDecl,
2457 const FunctionProtoType *Proto,
2458 ArrayRef<const Expr *> Args,
2459 SourceLocation CallSiteLoc) {
2460 assert((FDecl || Proto) && "Need a function declaration or prototype");
2462 // Check the attributes attached to the method/function itself.
2463 llvm::SmallBitVector NonNullArgs;
2465 // Handle the nonnull attribute on the function/method declaration itself.
2466 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2467 if (!NonNull->args_size()) {
2468 // Easy case: all pointer arguments are nonnull.
2469 for (const auto *Arg : Args)
2470 if (S.isValidPointerAttrType(Arg->getType()))
2471 CheckNonNullArgument(S, Arg, CallSiteLoc);
2475 for (unsigned Val : NonNull->args()) {
2476 if (Val >= Args.size())
2478 if (NonNullArgs.empty())
2479 NonNullArgs.resize(Args.size());
2480 NonNullArgs.set(Val);
2485 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2486 // Handle the nonnull attribute on the parameters of the
2488 ArrayRef<ParmVarDecl*> parms;
2489 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2490 parms = FD->parameters();
2492 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2494 unsigned ParamIndex = 0;
2495 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2496 I != E; ++I, ++ParamIndex) {
2497 const ParmVarDecl *PVD = *I;
2498 if (PVD->hasAttr<NonNullAttr>() ||
2499 isNonNullType(S.Context, PVD->getType())) {
2500 if (NonNullArgs.empty())
2501 NonNullArgs.resize(Args.size());
2503 NonNullArgs.set(ParamIndex);
2507 // If we have a non-function, non-method declaration but no
2508 // function prototype, try to dig out the function prototype.
2510 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2511 QualType type = VD->getType().getNonReferenceType();
2512 if (auto pointerType = type->getAs<PointerType>())
2513 type = pointerType->getPointeeType();
2514 else if (auto blockType = type->getAs<BlockPointerType>())
2515 type = blockType->getPointeeType();
2516 // FIXME: data member pointers?
2518 // Dig out the function prototype, if there is one.
2519 Proto = type->getAs<FunctionProtoType>();
2523 // Fill in non-null argument information from the nullability
2524 // information on the parameter types (if we have them).
2527 for (auto paramType : Proto->getParamTypes()) {
2528 if (isNonNullType(S.Context, paramType)) {
2529 if (NonNullArgs.empty())
2530 NonNullArgs.resize(Args.size());
2532 NonNullArgs.set(Index);
2540 // Check for non-null arguments.
2541 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2542 ArgIndex != ArgIndexEnd; ++ArgIndex) {
2543 if (NonNullArgs[ArgIndex])
2544 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
2548 /// Handles the checks for format strings, non-POD arguments to vararg
2549 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
2551 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
2552 const Expr *ThisArg, ArrayRef<const Expr *> Args,
2553 bool IsMemberFunction, SourceLocation Loc,
2554 SourceRange Range, VariadicCallType CallType) {
2555 // FIXME: We should check as much as we can in the template definition.
2556 if (CurContext->isDependentContext())
2559 // Printf and scanf checking.
2560 llvm::SmallBitVector CheckedVarArgs;
2562 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2563 // Only create vector if there are format attributes.
2564 CheckedVarArgs.resize(Args.size());
2566 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
2571 // Refuse POD arguments that weren't caught by the format string
2573 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
2574 if (CallType != VariadicDoesNotApply &&
2575 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
2576 unsigned NumParams = Proto ? Proto->getNumParams()
2577 : FDecl && isa<FunctionDecl>(FDecl)
2578 ? cast<FunctionDecl>(FDecl)->getNumParams()
2579 : FDecl && isa<ObjCMethodDecl>(FDecl)
2580 ? cast<ObjCMethodDecl>(FDecl)->param_size()
2583 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
2584 // Args[ArgIdx] can be null in malformed code.
2585 if (const Expr *Arg = Args[ArgIdx]) {
2586 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
2587 checkVariadicArgument(Arg, CallType);
2592 if (FDecl || Proto) {
2593 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
2595 // Type safety checking.
2597 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
2598 CheckArgumentWithTypeTag(I, Args.data());
2603 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
2606 /// CheckConstructorCall - Check a constructor call for correctness and safety
2607 /// properties not enforced by the C type system.
2608 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
2609 ArrayRef<const Expr *> Args,
2610 const FunctionProtoType *Proto,
2611 SourceLocation Loc) {
2612 VariadicCallType CallType =
2613 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
2614 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
2615 Loc, SourceRange(), CallType);
2618 /// CheckFunctionCall - Check a direct function call for various correctness
2619 /// and safety properties not strictly enforced by the C type system.
2620 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2621 const FunctionProtoType *Proto) {
2622 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2623 isa<CXXMethodDecl>(FDecl);
2624 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2625 IsMemberOperatorCall;
2626 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2627 TheCall->getCallee());
2628 Expr** Args = TheCall->getArgs();
2629 unsigned NumArgs = TheCall->getNumArgs();
2631 Expr *ImplicitThis = nullptr;
2632 if (IsMemberOperatorCall) {
2633 // If this is a call to a member operator, hide the first argument
2635 // FIXME: Our choice of AST representation here is less than ideal.
2636 ImplicitThis = Args[0];
2639 } else if (IsMemberFunction)
2641 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
2643 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
2644 IsMemberFunction, TheCall->getRParenLoc(),
2645 TheCall->getCallee()->getSourceRange(), CallType);
2647 IdentifierInfo *FnInfo = FDecl->getIdentifier();
2648 // None of the checks below are needed for functions that don't have
2649 // simple names (e.g., C++ conversion functions).
2653 CheckAbsoluteValueFunction(TheCall, FDecl);
2654 CheckMaxUnsignedZero(TheCall, FDecl);
2656 if (getLangOpts().ObjC1)
2657 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
2659 unsigned CMId = FDecl->getMemoryFunctionKind();
2663 // Handle memory setting and copying functions.
2664 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
2665 CheckStrlcpycatArguments(TheCall, FnInfo);
2666 else if (CMId == Builtin::BIstrncat)
2667 CheckStrncatArguments(TheCall, FnInfo);
2669 CheckMemaccessArguments(TheCall, CMId, FnInfo);
2674 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
2675 ArrayRef<const Expr *> Args) {
2676 VariadicCallType CallType =
2677 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
2679 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
2680 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
2686 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2687 const FunctionProtoType *Proto) {
2689 if (const auto *V = dyn_cast<VarDecl>(NDecl))
2690 Ty = V->getType().getNonReferenceType();
2691 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
2692 Ty = F->getType().getNonReferenceType();
2696 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2697 !Ty->isFunctionProtoType())
2700 VariadicCallType CallType;
2701 if (!Proto || !Proto->isVariadic()) {
2702 CallType = VariadicDoesNotApply;
2703 } else if (Ty->isBlockPointerType()) {
2704 CallType = VariadicBlock;
2705 } else { // Ty->isFunctionPointerType()
2706 CallType = VariadicFunction;
2709 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
2710 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2711 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
2712 TheCall->getCallee()->getSourceRange(), CallType);
2717 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2718 /// such as function pointers returned from functions.
2719 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
2720 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
2721 TheCall->getCallee());
2722 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
2723 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2724 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
2725 TheCall->getCallee()->getSourceRange(), CallType);
2730 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
2731 if (!llvm::isValidAtomicOrderingCABI(Ordering))
2734 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
2736 case AtomicExpr::AO__c11_atomic_init:
2737 llvm_unreachable("There is no ordering argument for an init");
2739 case AtomicExpr::AO__c11_atomic_load:
2740 case AtomicExpr::AO__atomic_load_n:
2741 case AtomicExpr::AO__atomic_load:
2742 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2743 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2745 case AtomicExpr::AO__c11_atomic_store:
2746 case AtomicExpr::AO__atomic_store:
2747 case AtomicExpr::AO__atomic_store_n:
2748 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2749 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2750 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2757 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2758 AtomicExpr::AtomicOp Op) {
2759 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2760 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2762 // All these operations take one of the following forms:
2764 // C __c11_atomic_init(A *, C)
2766 // C __c11_atomic_load(A *, int)
2768 // void __atomic_load(A *, CP, int)
2770 // void __atomic_store(A *, CP, int)
2772 // C __c11_atomic_add(A *, M, int)
2774 // C __atomic_exchange_n(A *, CP, int)
2776 // void __atomic_exchange(A *, C *, CP, int)
2778 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
2780 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
2783 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2784 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
2786 // C is an appropriate type,
2787 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
2788 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
2789 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
2790 // the int parameters are for orderings.
2792 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
2793 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
2794 AtomicExpr::AO__atomic_load,
2795 "need to update code for modified C11 atomics");
2796 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
2797 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
2798 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
2799 Op == AtomicExpr::AO__atomic_store_n ||
2800 Op == AtomicExpr::AO__atomic_exchange_n ||
2801 Op == AtomicExpr::AO__atomic_compare_exchange_n;
2802 bool IsAddSub = false;
2805 case AtomicExpr::AO__c11_atomic_init:
2809 case AtomicExpr::AO__c11_atomic_load:
2810 case AtomicExpr::AO__atomic_load_n:
2814 case AtomicExpr::AO__atomic_load:
2818 case AtomicExpr::AO__c11_atomic_store:
2819 case AtomicExpr::AO__atomic_store:
2820 case AtomicExpr::AO__atomic_store_n:
2824 case AtomicExpr::AO__c11_atomic_fetch_add:
2825 case AtomicExpr::AO__c11_atomic_fetch_sub:
2826 case AtomicExpr::AO__atomic_fetch_add:
2827 case AtomicExpr::AO__atomic_fetch_sub:
2828 case AtomicExpr::AO__atomic_add_fetch:
2829 case AtomicExpr::AO__atomic_sub_fetch:
2832 case AtomicExpr::AO__c11_atomic_fetch_and:
2833 case AtomicExpr::AO__c11_atomic_fetch_or:
2834 case AtomicExpr::AO__c11_atomic_fetch_xor:
2835 case AtomicExpr::AO__atomic_fetch_and:
2836 case AtomicExpr::AO__atomic_fetch_or:
2837 case AtomicExpr::AO__atomic_fetch_xor:
2838 case AtomicExpr::AO__atomic_fetch_nand:
2839 case AtomicExpr::AO__atomic_and_fetch:
2840 case AtomicExpr::AO__atomic_or_fetch:
2841 case AtomicExpr::AO__atomic_xor_fetch:
2842 case AtomicExpr::AO__atomic_nand_fetch:
2846 case AtomicExpr::AO__c11_atomic_exchange:
2847 case AtomicExpr::AO__atomic_exchange_n:
2851 case AtomicExpr::AO__atomic_exchange:
2855 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
2856 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
2860 case AtomicExpr::AO__atomic_compare_exchange:
2861 case AtomicExpr::AO__atomic_compare_exchange_n:
2866 // Check we have the right number of arguments.
2867 if (TheCall->getNumArgs() < NumArgs[Form]) {
2868 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
2869 << 0 << NumArgs[Form] << TheCall->getNumArgs()
2870 << TheCall->getCallee()->getSourceRange();
2872 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
2873 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
2874 diag::err_typecheck_call_too_many_args)
2875 << 0 << NumArgs[Form] << TheCall->getNumArgs()
2876 << TheCall->getCallee()->getSourceRange();
2880 // Inspect the first argument of the atomic operation.
2881 Expr *Ptr = TheCall->getArg(0);
2882 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
2883 if (ConvertedPtr.isInvalid())
2886 Ptr = ConvertedPtr.get();
2887 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
2889 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
2890 << Ptr->getType() << Ptr->getSourceRange();
2894 // For a __c11 builtin, this should be a pointer to an _Atomic type.
2895 QualType AtomTy = pointerType->getPointeeType(); // 'A'
2896 QualType ValType = AtomTy; // 'C'
2898 if (!AtomTy->isAtomicType()) {
2899 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
2900 << Ptr->getType() << Ptr->getSourceRange();
2903 if (AtomTy.isConstQualified()) {
2904 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
2905 << Ptr->getType() << Ptr->getSourceRange();
2908 ValType = AtomTy->getAs<AtomicType>()->getValueType();
2909 } else if (Form != Load && Form != LoadCopy) {
2910 if (ValType.isConstQualified()) {
2911 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
2912 << Ptr->getType() << Ptr->getSourceRange();
2917 // For an arithmetic operation, the implied arithmetic must be well-formed.
2918 if (Form == Arithmetic) {
2919 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
2920 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
2921 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
2922 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2925 if (!IsAddSub && !ValType->isIntegerType()) {
2926 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
2927 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2930 if (IsC11 && ValType->isPointerType() &&
2931 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
2932 diag::err_incomplete_type)) {
2935 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
2936 // For __atomic_*_n operations, the value type must be a scalar integral or
2937 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
2938 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
2939 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2943 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
2944 !AtomTy->isScalarType()) {
2945 // For GNU atomics, require a trivially-copyable type. This is not part of
2946 // the GNU atomics specification, but we enforce it for sanity.
2947 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
2948 << Ptr->getType() << Ptr->getSourceRange();
2952 switch (ValType.getObjCLifetime()) {
2953 case Qualifiers::OCL_None:
2954 case Qualifiers::OCL_ExplicitNone:
2958 case Qualifiers::OCL_Weak:
2959 case Qualifiers::OCL_Strong:
2960 case Qualifiers::OCL_Autoreleasing:
2961 // FIXME: Can this happen? By this point, ValType should be known
2962 // to be trivially copyable.
2963 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
2964 << ValType << Ptr->getSourceRange();
2968 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
2969 // volatile-ness of the pointee-type inject itself into the result or the
2970 // other operands. Similarly atomic_load can take a pointer to a const 'A'.
2971 ValType.removeLocalVolatile();
2972 ValType.removeLocalConst();
2973 QualType ResultType = ValType;
2974 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init)
2975 ResultType = Context.VoidTy;
2976 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
2977 ResultType = Context.BoolTy;
2979 // The type of a parameter passed 'by value'. In the GNU atomics, such
2980 // arguments are actually passed as pointers.
2981 QualType ByValType = ValType; // 'CP'
2983 ByValType = Ptr->getType();
2985 // The first argument --- the pointer --- has a fixed type; we
2986 // deduce the types of the rest of the arguments accordingly. Walk
2987 // the remaining arguments, converting them to the deduced value type.
2988 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
2990 if (i < NumVals[Form] + 1) {
2993 // The second argument is the non-atomic operand. For arithmetic, this
2994 // is always passed by value, and for a compare_exchange it is always
2995 // passed by address. For the rest, GNU uses by-address and C11 uses
2997 assert(Form != Load);
2998 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
3000 else if (Form == Copy || Form == Xchg)
3002 else if (Form == Arithmetic)
3003 Ty = Context.getPointerDiffType();
3005 Expr *ValArg = TheCall->getArg(i);
3006 // Treat this argument as _Nonnull as we want to show a warning if
3007 // NULL is passed into it.
3008 CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
3010 // Keep address space of non-atomic pointer type.
3011 if (const PointerType *PtrTy =
3012 ValArg->getType()->getAs<PointerType>()) {
3013 AS = PtrTy->getPointeeType().getAddressSpace();
3015 Ty = Context.getPointerType(
3016 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
3020 // The third argument to compare_exchange / GNU exchange is a
3021 // (pointer to a) desired value.
3025 // The fourth argument to GNU compare_exchange is a 'weak' flag.
3026 Ty = Context.BoolTy;
3030 // The order(s) are always converted to int.
3034 InitializedEntity Entity =
3035 InitializedEntity::InitializeParameter(Context, Ty, false);
3036 ExprResult Arg = TheCall->getArg(i);
3037 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3038 if (Arg.isInvalid())
3040 TheCall->setArg(i, Arg.get());
3043 // Permute the arguments into a 'consistent' order.
3044 SmallVector<Expr*, 5> SubExprs;
3045 SubExprs.push_back(Ptr);
3048 // Note, AtomicExpr::getVal1() has a special case for this atomic.
3049 SubExprs.push_back(TheCall->getArg(1)); // Val1
3052 SubExprs.push_back(TheCall->getArg(1)); // Order
3058 SubExprs.push_back(TheCall->getArg(2)); // Order
3059 SubExprs.push_back(TheCall->getArg(1)); // Val1
3062 // Note, AtomicExpr::getVal2() has a special case for this atomic.
3063 SubExprs.push_back(TheCall->getArg(3)); // Order
3064 SubExprs.push_back(TheCall->getArg(1)); // Val1
3065 SubExprs.push_back(TheCall->getArg(2)); // Val2
3068 SubExprs.push_back(TheCall->getArg(3)); // Order
3069 SubExprs.push_back(TheCall->getArg(1)); // Val1
3070 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
3071 SubExprs.push_back(TheCall->getArg(2)); // Val2
3074 SubExprs.push_back(TheCall->getArg(4)); // Order
3075 SubExprs.push_back(TheCall->getArg(1)); // Val1
3076 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
3077 SubExprs.push_back(TheCall->getArg(2)); // Val2
3078 SubExprs.push_back(TheCall->getArg(3)); // Weak
3082 if (SubExprs.size() >= 2 && Form != Init) {
3083 llvm::APSInt Result(32);
3084 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
3085 !isValidOrderingForOp(Result.getSExtValue(), Op))
3086 Diag(SubExprs[1]->getLocStart(),
3087 diag::warn_atomic_op_has_invalid_memory_order)
3088 << SubExprs[1]->getSourceRange();
3091 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
3092 SubExprs, ResultType, Op,
3093 TheCall->getRParenLoc());
3095 if ((Op == AtomicExpr::AO__c11_atomic_load ||
3096 (Op == AtomicExpr::AO__c11_atomic_store)) &&
3097 Context.AtomicUsesUnsupportedLibcall(AE))
3098 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
3099 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
3104 /// checkBuiltinArgument - Given a call to a builtin function, perform
3105 /// normal type-checking on the given argument, updating the call in
3106 /// place. This is useful when a builtin function requires custom
3107 /// type-checking for some of its arguments but not necessarily all of
3110 /// Returns true on error.
3111 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
3112 FunctionDecl *Fn = E->getDirectCallee();
3113 assert(Fn && "builtin call without direct callee!");
3115 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
3116 InitializedEntity Entity =
3117 InitializedEntity::InitializeParameter(S.Context, Param);
3119 ExprResult Arg = E->getArg(0);
3120 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
3121 if (Arg.isInvalid())
3124 E->setArg(ArgIndex, Arg.get());
3128 /// SemaBuiltinAtomicOverloaded - We have a call to a function like
3129 /// __sync_fetch_and_add, which is an overloaded function based on the pointer
3130 /// type of its first argument. The main ActOnCallExpr routines have already
3131 /// promoted the types of arguments because all of these calls are prototyped as
3134 /// This function goes through and does final semantic checking for these
3137 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
3138 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3139 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3140 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3142 // Ensure that we have at least one argument to do type inference from.
3143 if (TheCall->getNumArgs() < 1) {
3144 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3145 << 0 << 1 << TheCall->getNumArgs()
3146 << TheCall->getCallee()->getSourceRange();
3150 // Inspect the first argument of the atomic builtin. This should always be
3151 // a pointer type, whose element is an integral scalar or pointer type.
3152 // Because it is a pointer type, we don't have to worry about any implicit
3154 // FIXME: We don't allow floating point scalars as input.
3155 Expr *FirstArg = TheCall->getArg(0);
3156 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3157 if (FirstArgResult.isInvalid())
3159 FirstArg = FirstArgResult.get();
3160 TheCall->setArg(0, FirstArg);
3162 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3164 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3165 << FirstArg->getType() << FirstArg->getSourceRange();
3169 QualType ValType = pointerType->getPointeeType();
3170 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3171 !ValType->isBlockPointerType()) {
3172 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3173 << FirstArg->getType() << FirstArg->getSourceRange();
3177 switch (ValType.getObjCLifetime()) {
3178 case Qualifiers::OCL_None:
3179 case Qualifiers::OCL_ExplicitNone:
3183 case Qualifiers::OCL_Weak:
3184 case Qualifiers::OCL_Strong:
3185 case Qualifiers::OCL_Autoreleasing:
3186 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3187 << ValType << FirstArg->getSourceRange();
3191 // Strip any qualifiers off ValType.
3192 ValType = ValType.getUnqualifiedType();
3194 // The majority of builtins return a value, but a few have special return
3195 // types, so allow them to override appropriately below.
3196 QualType ResultType = ValType;
3198 // We need to figure out which concrete builtin this maps onto. For example,
3199 // __sync_fetch_and_add with a 2 byte object turns into
3200 // __sync_fetch_and_add_2.
3201 #define BUILTIN_ROW(x) \
3202 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3203 Builtin::BI##x##_8, Builtin::BI##x##_16 }
3205 static const unsigned BuiltinIndices[][5] = {
3206 BUILTIN_ROW(__sync_fetch_and_add),
3207 BUILTIN_ROW(__sync_fetch_and_sub),
3208 BUILTIN_ROW(__sync_fetch_and_or),
3209 BUILTIN_ROW(__sync_fetch_and_and),
3210 BUILTIN_ROW(__sync_fetch_and_xor),
3211 BUILTIN_ROW(__sync_fetch_and_nand),
3213 BUILTIN_ROW(__sync_add_and_fetch),
3214 BUILTIN_ROW(__sync_sub_and_fetch),
3215 BUILTIN_ROW(__sync_and_and_fetch),
3216 BUILTIN_ROW(__sync_or_and_fetch),
3217 BUILTIN_ROW(__sync_xor_and_fetch),
3218 BUILTIN_ROW(__sync_nand_and_fetch),
3220 BUILTIN_ROW(__sync_val_compare_and_swap),
3221 BUILTIN_ROW(__sync_bool_compare_and_swap),
3222 BUILTIN_ROW(__sync_lock_test_and_set),
3223 BUILTIN_ROW(__sync_lock_release),
3224 BUILTIN_ROW(__sync_swap)
3228 // Determine the index of the size.
3230 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
3231 case 1: SizeIndex = 0; break;
3232 case 2: SizeIndex = 1; break;
3233 case 4: SizeIndex = 2; break;
3234 case 8: SizeIndex = 3; break;
3235 case 16: SizeIndex = 4; break;
3237 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3238 << FirstArg->getType() << FirstArg->getSourceRange();
3242 // Each of these builtins has one pointer argument, followed by some number of
3243 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3244 // that we ignore. Find out which row of BuiltinIndices to read from as well
3245 // as the number of fixed args.
3246 unsigned BuiltinID = FDecl->getBuiltinID();
3247 unsigned BuiltinIndex, NumFixed = 1;
3248 bool WarnAboutSemanticsChange = false;
3249 switch (BuiltinID) {
3250 default: llvm_unreachable("Unknown overloaded atomic builtin!");
3251 case Builtin::BI__sync_fetch_and_add:
3252 case Builtin::BI__sync_fetch_and_add_1:
3253 case Builtin::BI__sync_fetch_and_add_2:
3254 case Builtin::BI__sync_fetch_and_add_4:
3255 case Builtin::BI__sync_fetch_and_add_8:
3256 case Builtin::BI__sync_fetch_and_add_16:
3260 case Builtin::BI__sync_fetch_and_sub:
3261 case Builtin::BI__sync_fetch_and_sub_1:
3262 case Builtin::BI__sync_fetch_and_sub_2:
3263 case Builtin::BI__sync_fetch_and_sub_4:
3264 case Builtin::BI__sync_fetch_and_sub_8:
3265 case Builtin::BI__sync_fetch_and_sub_16:
3269 case Builtin::BI__sync_fetch_and_or:
3270 case Builtin::BI__sync_fetch_and_or_1:
3271 case Builtin::BI__sync_fetch_and_or_2:
3272 case Builtin::BI__sync_fetch_and_or_4:
3273 case Builtin::BI__sync_fetch_and_or_8:
3274 case Builtin::BI__sync_fetch_and_or_16:
3278 case Builtin::BI__sync_fetch_and_and:
3279 case Builtin::BI__sync_fetch_and_and_1:
3280 case Builtin::BI__sync_fetch_and_and_2:
3281 case Builtin::BI__sync_fetch_and_and_4:
3282 case Builtin::BI__sync_fetch_and_and_8:
3283 case Builtin::BI__sync_fetch_and_and_16:
3287 case Builtin::BI__sync_fetch_and_xor:
3288 case Builtin::BI__sync_fetch_and_xor_1:
3289 case Builtin::BI__sync_fetch_and_xor_2:
3290 case Builtin::BI__sync_fetch_and_xor_4:
3291 case Builtin::BI__sync_fetch_and_xor_8:
3292 case Builtin::BI__sync_fetch_and_xor_16:
3296 case Builtin::BI__sync_fetch_and_nand:
3297 case Builtin::BI__sync_fetch_and_nand_1:
3298 case Builtin::BI__sync_fetch_and_nand_2:
3299 case Builtin::BI__sync_fetch_and_nand_4:
3300 case Builtin::BI__sync_fetch_and_nand_8:
3301 case Builtin::BI__sync_fetch_and_nand_16:
3303 WarnAboutSemanticsChange = true;
3306 case Builtin::BI__sync_add_and_fetch:
3307 case Builtin::BI__sync_add_and_fetch_1:
3308 case Builtin::BI__sync_add_and_fetch_2:
3309 case Builtin::BI__sync_add_and_fetch_4:
3310 case Builtin::BI__sync_add_and_fetch_8:
3311 case Builtin::BI__sync_add_and_fetch_16:
3315 case Builtin::BI__sync_sub_and_fetch:
3316 case Builtin::BI__sync_sub_and_fetch_1:
3317 case Builtin::BI__sync_sub_and_fetch_2:
3318 case Builtin::BI__sync_sub_and_fetch_4:
3319 case Builtin::BI__sync_sub_and_fetch_8:
3320 case Builtin::BI__sync_sub_and_fetch_16:
3324 case Builtin::BI__sync_and_and_fetch:
3325 case Builtin::BI__sync_and_and_fetch_1:
3326 case Builtin::BI__sync_and_and_fetch_2:
3327 case Builtin::BI__sync_and_and_fetch_4:
3328 case Builtin::BI__sync_and_and_fetch_8:
3329 case Builtin::BI__sync_and_and_fetch_16:
3333 case Builtin::BI__sync_or_and_fetch:
3334 case Builtin::BI__sync_or_and_fetch_1:
3335 case Builtin::BI__sync_or_and_fetch_2:
3336 case Builtin::BI__sync_or_and_fetch_4:
3337 case Builtin::BI__sync_or_and_fetch_8:
3338 case Builtin::BI__sync_or_and_fetch_16:
3342 case Builtin::BI__sync_xor_and_fetch:
3343 case Builtin::BI__sync_xor_and_fetch_1:
3344 case Builtin::BI__sync_xor_and_fetch_2:
3345 case Builtin::BI__sync_xor_and_fetch_4:
3346 case Builtin::BI__sync_xor_and_fetch_8:
3347 case Builtin::BI__sync_xor_and_fetch_16:
3351 case Builtin::BI__sync_nand_and_fetch:
3352 case Builtin::BI__sync_nand_and_fetch_1:
3353 case Builtin::BI__sync_nand_and_fetch_2:
3354 case Builtin::BI__sync_nand_and_fetch_4:
3355 case Builtin::BI__sync_nand_and_fetch_8:
3356 case Builtin::BI__sync_nand_and_fetch_16:
3358 WarnAboutSemanticsChange = true;
3361 case Builtin::BI__sync_val_compare_and_swap:
3362 case Builtin::BI__sync_val_compare_and_swap_1:
3363 case Builtin::BI__sync_val_compare_and_swap_2:
3364 case Builtin::BI__sync_val_compare_and_swap_4:
3365 case Builtin::BI__sync_val_compare_and_swap_8:
3366 case Builtin::BI__sync_val_compare_and_swap_16:
3371 case Builtin::BI__sync_bool_compare_and_swap:
3372 case Builtin::BI__sync_bool_compare_and_swap_1:
3373 case Builtin::BI__sync_bool_compare_and_swap_2:
3374 case Builtin::BI__sync_bool_compare_and_swap_4:
3375 case Builtin::BI__sync_bool_compare_and_swap_8:
3376 case Builtin::BI__sync_bool_compare_and_swap_16:
3379 ResultType = Context.BoolTy;
3382 case Builtin::BI__sync_lock_test_and_set:
3383 case Builtin::BI__sync_lock_test_and_set_1:
3384 case Builtin::BI__sync_lock_test_and_set_2:
3385 case Builtin::BI__sync_lock_test_and_set_4:
3386 case Builtin::BI__sync_lock_test_and_set_8:
3387 case Builtin::BI__sync_lock_test_and_set_16:
3391 case Builtin::BI__sync_lock_release:
3392 case Builtin::BI__sync_lock_release_1:
3393 case Builtin::BI__sync_lock_release_2:
3394 case Builtin::BI__sync_lock_release_4:
3395 case Builtin::BI__sync_lock_release_8:
3396 case Builtin::BI__sync_lock_release_16:
3399 ResultType = Context.VoidTy;
3402 case Builtin::BI__sync_swap:
3403 case Builtin::BI__sync_swap_1:
3404 case Builtin::BI__sync_swap_2:
3405 case Builtin::BI__sync_swap_4:
3406 case Builtin::BI__sync_swap_8:
3407 case Builtin::BI__sync_swap_16:
3412 // Now that we know how many fixed arguments we expect, first check that we
3413 // have at least that many.
3414 if (TheCall->getNumArgs() < 1+NumFixed) {
3415 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3416 << 0 << 1+NumFixed << TheCall->getNumArgs()
3417 << TheCall->getCallee()->getSourceRange();
3421 if (WarnAboutSemanticsChange) {
3422 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
3423 << TheCall->getCallee()->getSourceRange();
3426 // Get the decl for the concrete builtin from this, we can tell what the
3427 // concrete integer type we should convert to is.
3428 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
3429 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
3430 FunctionDecl *NewBuiltinDecl;
3431 if (NewBuiltinID == BuiltinID)
3432 NewBuiltinDecl = FDecl;
3434 // Perform builtin lookup to avoid redeclaring it.
3435 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
3436 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
3437 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
3438 assert(Res.getFoundDecl());
3439 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
3440 if (!NewBuiltinDecl)
3444 // The first argument --- the pointer --- has a fixed type; we
3445 // deduce the types of the rest of the arguments accordingly. Walk
3446 // the remaining arguments, converting them to the deduced value type.
3447 for (unsigned i = 0; i != NumFixed; ++i) {
3448 ExprResult Arg = TheCall->getArg(i+1);
3450 // GCC does an implicit conversion to the pointer or integer ValType. This
3451 // can fail in some cases (1i -> int**), check for this error case now.
3452 // Initialize the argument.
3453 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3454 ValType, /*consume*/ false);
3455 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3456 if (Arg.isInvalid())
3459 // Okay, we have something that *can* be converted to the right type. Check
3460 // to see if there is a potentially weird extension going on here. This can
3461 // happen when you do an atomic operation on something like an char* and
3462 // pass in 42. The 42 gets converted to char. This is even more strange
3463 // for things like 45.123 -> char, etc.
3464 // FIXME: Do this check.
3465 TheCall->setArg(i+1, Arg.get());
3468 ASTContext& Context = this->getASTContext();
3470 // Create a new DeclRefExpr to refer to the new decl.
3471 DeclRefExpr* NewDRE = DeclRefExpr::Create(
3473 DRE->getQualifierLoc(),
3476 /*enclosing*/ false,
3478 Context.BuiltinFnTy,
3479 DRE->getValueKind());
3481 // Set the callee in the CallExpr.
3482 // FIXME: This loses syntactic information.
3483 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
3484 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
3485 CK_BuiltinFnToFnPtr);
3486 TheCall->setCallee(PromotedCall.get());
3488 // Change the result type of the call to match the original value type. This
3489 // is arbitrary, but the codegen for these builtins ins design to handle it
3491 TheCall->setType(ResultType);
3493 return TheCallResult;
3496 /// SemaBuiltinNontemporalOverloaded - We have a call to
3497 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3498 /// overloaded function based on the pointer type of its last argument.
3500 /// This function goes through and does final semantic checking for these
3502 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
3503 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3505 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3506 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3507 unsigned BuiltinID = FDecl->getBuiltinID();
3508 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
3509 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
3510 "Unexpected nontemporal load/store builtin!");
3511 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3512 unsigned numArgs = isStore ? 2 : 1;
3514 // Ensure that we have the proper number of arguments.
3515 if (checkArgCount(*this, TheCall, numArgs))
3518 // Inspect the last argument of the nontemporal builtin. This should always
3519 // be a pointer type, from which we imply the type of the memory access.
3520 // Because it is a pointer type, we don't have to worry about any implicit
3522 Expr *PointerArg = TheCall->getArg(numArgs - 1);
3523 ExprResult PointerArgResult =
3524 DefaultFunctionArrayLvalueConversion(PointerArg);
3526 if (PointerArgResult.isInvalid())
3528 PointerArg = PointerArgResult.get();
3529 TheCall->setArg(numArgs - 1, PointerArg);
3531 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3533 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3534 << PointerArg->getType() << PointerArg->getSourceRange();
3538 QualType ValType = pointerType->getPointeeType();
3540 // Strip any qualifiers off ValType.
3541 ValType = ValType.getUnqualifiedType();
3542 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3543 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
3544 !ValType->isVectorType()) {
3545 Diag(DRE->getLocStart(),
3546 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3547 << PointerArg->getType() << PointerArg->getSourceRange();
3552 TheCall->setType(ValType);
3553 return TheCallResult;
3556 ExprResult ValArg = TheCall->getArg(0);
3557 InitializedEntity Entity = InitializedEntity::InitializeParameter(
3558 Context, ValType, /*consume*/ false);
3559 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3560 if (ValArg.isInvalid())
3563 TheCall->setArg(0, ValArg.get());
3564 TheCall->setType(Context.VoidTy);
3565 return TheCallResult;
3568 /// CheckObjCString - Checks that the argument to the builtin
3569 /// CFString constructor is correct
3570 /// Note: It might also make sense to do the UTF-16 conversion here (would
3571 /// simplify the backend).
3572 bool Sema::CheckObjCString(Expr *Arg) {
3573 Arg = Arg->IgnoreParenCasts();
3574 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
3576 if (!Literal || !Literal->isAscii()) {
3577 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
3578 << Arg->getSourceRange();
3582 if (Literal->containsNonAsciiOrNull()) {
3583 StringRef String = Literal->getString();
3584 unsigned NumBytes = String.size();
3585 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
3586 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3587 llvm::UTF16 *ToPtr = &ToBuf[0];
3589 llvm::ConversionResult Result =
3590 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3591 ToPtr + NumBytes, llvm::strictConversion);
3592 // Check for conversion failure.
3593 if (Result != llvm::conversionOK)
3594 Diag(Arg->getLocStart(),
3595 diag::warn_cfstring_truncated) << Arg->getSourceRange();
3600 /// CheckObjCString - Checks that the format string argument to the os_log()
3601 /// and os_trace() functions is correct, and converts it to const char *.
3602 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
3603 Arg = Arg->IgnoreParenCasts();
3604 auto *Literal = dyn_cast<StringLiteral>(Arg);
3606 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
3607 Literal = ObjcLiteral->getString();
3611 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
3613 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
3614 << Arg->getSourceRange());
3617 ExprResult Result(Literal);
3618 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
3619 InitializedEntity Entity =
3620 InitializedEntity::InitializeParameter(Context, ResultTy, false);
3621 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
3625 /// Check that the user is calling the appropriate va_start builtin for the
3626 /// target and calling convention.
3627 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
3628 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
3629 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
3630 bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
3631 bool IsWindows = TT.isOSWindows();
3632 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
3633 if (IsX64 || IsAArch64) {
3634 clang::CallingConv CC = CC_C;
3635 if (const FunctionDecl *FD = S.getCurFunctionDecl())
3636 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3638 // Don't allow this in System V ABI functions.
3639 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
3640 return S.Diag(Fn->getLocStart(),
3641 diag::err_ms_va_start_used_in_sysv_function);
3643 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
3644 // On x64 Windows, don't allow this in System V ABI functions.
3645 // (Yes, that means there's no corresponding way to support variadic
3646 // System V ABI functions on Windows.)
3647 if ((IsWindows && CC == CC_X86_64SysV) ||
3648 (!IsWindows && CC == CC_Win64))
3649 return S.Diag(Fn->getLocStart(),
3650 diag::err_va_start_used_in_wrong_abi_function)
3657 return S.Diag(Fn->getLocStart(), diag::err_builtin_x64_aarch64_only);
3661 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
3662 ParmVarDecl **LastParam = nullptr) {
3663 // Determine whether the current function, block, or obj-c method is variadic
3664 // and get its parameter list.
3665 bool IsVariadic = false;
3666 ArrayRef<ParmVarDecl *> Params;
3667 DeclContext *Caller = S.CurContext;
3668 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
3669 IsVariadic = Block->isVariadic();
3670 Params = Block->parameters();
3671 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
3672 IsVariadic = FD->isVariadic();
3673 Params = FD->parameters();
3674 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
3675 IsVariadic = MD->isVariadic();
3676 // FIXME: This isn't correct for methods (results in bogus warning).
3677 Params = MD->parameters();
3678 } else if (isa<CapturedDecl>(Caller)) {
3679 // We don't support va_start in a CapturedDecl.
3680 S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt);
3683 // This must be some other declcontext that parses exprs.
3684 S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function);
3689 S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function);
3694 *LastParam = Params.empty() ? nullptr : Params.back();
3699 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
3700 /// for validity. Emit an error and return true on failure; return false
3702 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
3703 Expr *Fn = TheCall->getCallee();
3705 if (checkVAStartABI(*this, BuiltinID, Fn))
3708 if (TheCall->getNumArgs() > 2) {
3709 Diag(TheCall->getArg(2)->getLocStart(),
3710 diag::err_typecheck_call_too_many_args)
3711 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3712 << Fn->getSourceRange()
3713 << SourceRange(TheCall->getArg(2)->getLocStart(),
3714 (*(TheCall->arg_end()-1))->getLocEnd());
3718 if (TheCall->getNumArgs() < 2) {
3719 return Diag(TheCall->getLocEnd(),
3720 diag::err_typecheck_call_too_few_args_at_least)
3721 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
3724 // Type-check the first argument normally.
3725 if (checkBuiltinArgument(*this, TheCall, 0))
3728 // Check that the current function is variadic, and get its last parameter.
3729 ParmVarDecl *LastParam;
3730 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
3733 // Verify that the second argument to the builtin is the last argument of the
3734 // current function or method.
3735 bool SecondArgIsLastNamedArgument = false;
3736 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
3738 // These are valid if SecondArgIsLastNamedArgument is false after the next
3741 SourceLocation ParamLoc;
3742 bool IsCRegister = false;
3744 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
3745 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
3746 SecondArgIsLastNamedArgument = PV == LastParam;
3748 Type = PV->getType();
3749 ParamLoc = PV->getLocation();
3751 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
3755 if (!SecondArgIsLastNamedArgument)
3756 Diag(TheCall->getArg(1)->getLocStart(),
3757 diag::warn_second_arg_of_va_start_not_last_named_param);
3758 else if (IsCRegister || Type->isReferenceType() ||
3759 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
3760 // Promotable integers are UB, but enumerations need a bit of
3761 // extra checking to see what their promotable type actually is.
3762 if (!Type->isPromotableIntegerType())
3764 if (!Type->isEnumeralType())
3766 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3768 Context.typesAreCompatible(ED->getPromotionType(), Type));
3770 unsigned Reason = 0;
3771 if (Type->isReferenceType()) Reason = 1;
3772 else if (IsCRegister) Reason = 2;
3773 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
3774 Diag(ParamLoc, diag::note_parameter_type) << Type;
3777 TheCall->setType(Context.VoidTy);
3781 bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
3782 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
3783 // const char *named_addr);
3785 Expr *Func = Call->getCallee();
3787 if (Call->getNumArgs() < 3)
3788 return Diag(Call->getLocEnd(),
3789 diag::err_typecheck_call_too_few_args_at_least)
3790 << 0 /*function call*/ << 3 << Call->getNumArgs();
3792 // Type-check the first argument normally.
3793 if (checkBuiltinArgument(*this, Call, 0))
3796 // Check that the current function is variadic.
3797 if (checkVAStartIsInVariadicFunction(*this, Func))
3803 } ArgumentTypes[] = {
3804 { 1, Context.getPointerType(Context.CharTy.withConst()) },
3805 { 2, Context.getSizeType() },
3808 for (const auto &AT : ArgumentTypes) {
3809 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
3810 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
3812 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
3813 << Arg->getType() << AT.Type << 1 /* different class */
3814 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
3815 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
3821 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
3822 /// friends. This is declared to take (...), so we have to check everything.
3823 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
3824 if (TheCall->getNumArgs() < 2)
3825 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
3826 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
3827 if (TheCall->getNumArgs() > 2)
3828 return Diag(TheCall->getArg(2)->getLocStart(),
3829 diag::err_typecheck_call_too_many_args)
3830 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3831 << SourceRange(TheCall->getArg(2)->getLocStart(),
3832 (*(TheCall->arg_end()-1))->getLocEnd());
3834 ExprResult OrigArg0 = TheCall->getArg(0);
3835 ExprResult OrigArg1 = TheCall->getArg(1);
3837 // Do standard promotions between the two arguments, returning their common
3839 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
3840 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
3843 // Make sure any conversions are pushed back into the call; this is
3844 // type safe since unordered compare builtins are declared as "_Bool
3846 TheCall->setArg(0, OrigArg0.get());
3847 TheCall->setArg(1, OrigArg1.get());
3849 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
3852 // If the common type isn't a real floating type, then the arguments were
3853 // invalid for this operation.
3854 if (Res.isNull() || !Res->isRealFloatingType())
3855 return Diag(OrigArg0.get()->getLocStart(),
3856 diag::err_typecheck_call_invalid_ordered_compare)
3857 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
3858 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
3863 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
3864 /// __builtin_isnan and friends. This is declared to take (...), so we have
3865 /// to check everything. We expect the last argument to be a floating point
3867 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
3868 if (TheCall->getNumArgs() < NumArgs)
3869 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
3870 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
3871 if (TheCall->getNumArgs() > NumArgs)
3872 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
3873 diag::err_typecheck_call_too_many_args)
3874 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
3875 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
3876 (*(TheCall->arg_end()-1))->getLocEnd());
3878 Expr *OrigArg = TheCall->getArg(NumArgs-1);
3880 if (OrigArg->isTypeDependent())
3883 // This operation requires a non-_Complex floating-point number.
3884 if (!OrigArg->getType()->isRealFloatingType())
3885 return Diag(OrigArg->getLocStart(),
3886 diag::err_typecheck_call_invalid_unary_fp)
3887 << OrigArg->getType() << OrigArg->getSourceRange();
3889 // If this is an implicit conversion from float -> float or double, remove it.
3890 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
3891 // Only remove standard FloatCasts, leaving other casts inplace
3892 if (Cast->getCastKind() == CK_FloatingCast) {
3893 Expr *CastArg = Cast->getSubExpr();
3894 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
3895 assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
3896 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) &&
3897 "promotion from float to either float or double is the only expected cast here");
3898 Cast->setSubExpr(nullptr);
3899 TheCall->setArg(NumArgs-1, CastArg);
3907 // Customized Sema Checking for VSX builtins that have the following signature:
3908 // vector [...] builtinName(vector [...], vector [...], const int);
3909 // Which takes the same type of vectors (any legal vector type) for the first
3910 // two arguments and takes compile time constant for the third argument.
3911 // Example builtins are :
3912 // vector double vec_xxpermdi(vector double, vector double, int);
3913 // vector short vec_xxsldwi(vector short, vector short, int);
3914 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
3915 unsigned ExpectedNumArgs = 3;
3916 if (TheCall->getNumArgs() < ExpectedNumArgs)
3917 return Diag(TheCall->getLocEnd(),
3918 diag::err_typecheck_call_too_few_args_at_least)
3919 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
3920 << TheCall->getSourceRange();
3922 if (TheCall->getNumArgs() > ExpectedNumArgs)
3923 return Diag(TheCall->getLocEnd(),
3924 diag::err_typecheck_call_too_many_args_at_most)
3925 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
3926 << TheCall->getSourceRange();
3928 // Check the third argument is a compile time constant
3930 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
3931 return Diag(TheCall->getLocStart(),
3932 diag::err_vsx_builtin_nonconstant_argument)
3933 << 3 /* argument index */ << TheCall->getDirectCallee()
3934 << SourceRange(TheCall->getArg(2)->getLocStart(),
3935 TheCall->getArg(2)->getLocEnd());
3937 QualType Arg1Ty = TheCall->getArg(0)->getType();
3938 QualType Arg2Ty = TheCall->getArg(1)->getType();
3940 // Check the type of argument 1 and argument 2 are vectors.
3941 SourceLocation BuiltinLoc = TheCall->getLocStart();
3942 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
3943 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
3944 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
3945 << TheCall->getDirectCallee()
3946 << SourceRange(TheCall->getArg(0)->getLocStart(),
3947 TheCall->getArg(1)->getLocEnd());
3950 // Check the first two arguments are the same type.
3951 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
3952 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
3953 << TheCall->getDirectCallee()
3954 << SourceRange(TheCall->getArg(0)->getLocStart(),
3955 TheCall->getArg(1)->getLocEnd());
3958 // When default clang type checking is turned off and the customized type
3959 // checking is used, the returning type of the function must be explicitly
3960 // set. Otherwise it is _Bool by default.
3961 TheCall->setType(Arg1Ty);
3966 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
3967 // This is declared to take (...), so we have to check everything.
3968 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
3969 if (TheCall->getNumArgs() < 2)
3970 return ExprError(Diag(TheCall->getLocEnd(),
3971 diag::err_typecheck_call_too_few_args_at_least)
3972 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3973 << TheCall->getSourceRange());
3975 // Determine which of the following types of shufflevector we're checking:
3976 // 1) unary, vector mask: (lhs, mask)
3977 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
3978 QualType resType = TheCall->getArg(0)->getType();
3979 unsigned numElements = 0;
3981 if (!TheCall->getArg(0)->isTypeDependent() &&
3982 !TheCall->getArg(1)->isTypeDependent()) {
3983 QualType LHSType = TheCall->getArg(0)->getType();
3984 QualType RHSType = TheCall->getArg(1)->getType();
3986 if (!LHSType->isVectorType() || !RHSType->isVectorType())
3987 return ExprError(Diag(TheCall->getLocStart(),
3988 diag::err_vec_builtin_non_vector)
3989 << TheCall->getDirectCallee()
3990 << SourceRange(TheCall->getArg(0)->getLocStart(),
3991 TheCall->getArg(1)->getLocEnd()));
3993 numElements = LHSType->getAs<VectorType>()->getNumElements();
3994 unsigned numResElements = TheCall->getNumArgs() - 2;
3996 // Check to see if we have a call with 2 vector arguments, the unary shuffle
3997 // with mask. If so, verify that RHS is an integer vector type with the
3998 // same number of elts as lhs.
3999 if (TheCall->getNumArgs() == 2) {
4000 if (!RHSType->hasIntegerRepresentation() ||
4001 RHSType->getAs<VectorType>()->getNumElements() != numElements)
4002 return ExprError(Diag(TheCall->getLocStart(),
4003 diag::err_vec_builtin_incompatible_vector)
4004 << TheCall->getDirectCallee()
4005 << SourceRange(TheCall->getArg(1)->getLocStart(),
4006 TheCall->getArg(1)->getLocEnd()));
4007 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
4008 return ExprError(Diag(TheCall->getLocStart(),
4009 diag::err_vec_builtin_incompatible_vector)
4010 << TheCall->getDirectCallee()
4011 << SourceRange(TheCall->getArg(0)->getLocStart(),
4012 TheCall->getArg(1)->getLocEnd()));
4013 } else if (numElements != numResElements) {
4014 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
4015 resType = Context.getVectorType(eltType, numResElements,
4016 VectorType::GenericVector);
4020 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
4021 if (TheCall->getArg(i)->isTypeDependent() ||
4022 TheCall->getArg(i)->isValueDependent())
4025 llvm::APSInt Result(32);
4026 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
4027 return ExprError(Diag(TheCall->getLocStart(),
4028 diag::err_shufflevector_nonconstant_argument)
4029 << TheCall->getArg(i)->getSourceRange());
4031 // Allow -1 which will be translated to undef in the IR.
4032 if (Result.isSigned() && Result.isAllOnesValue())
4035 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
4036 return ExprError(Diag(TheCall->getLocStart(),
4037 diag::err_shufflevector_argument_too_large)
4038 << TheCall->getArg(i)->getSourceRange());
4041 SmallVector<Expr*, 32> exprs;
4043 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
4044 exprs.push_back(TheCall->getArg(i));
4045 TheCall->setArg(i, nullptr);
4048 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
4049 TheCall->getCallee()->getLocStart(),
4050 TheCall->getRParenLoc());
4053 /// SemaConvertVectorExpr - Handle __builtin_convertvector
4054 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
4055 SourceLocation BuiltinLoc,
4056 SourceLocation RParenLoc) {
4057 ExprValueKind VK = VK_RValue;
4058 ExprObjectKind OK = OK_Ordinary;
4059 QualType DstTy = TInfo->getType();
4060 QualType SrcTy = E->getType();
4062 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
4063 return ExprError(Diag(BuiltinLoc,
4064 diag::err_convertvector_non_vector)
4065 << E->getSourceRange());
4066 if (!DstTy->isVectorType() && !DstTy->isDependentType())
4067 return ExprError(Diag(BuiltinLoc,
4068 diag::err_convertvector_non_vector_type));
4070 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
4071 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
4072 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
4073 if (SrcElts != DstElts)
4074 return ExprError(Diag(BuiltinLoc,
4075 diag::err_convertvector_incompatible_vector)
4076 << E->getSourceRange());
4079 return new (Context)
4080 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
4083 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
4084 // This is declared to take (const void*, ...) and can take two
4085 // optional constant int args.
4086 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
4087 unsigned NumArgs = TheCall->getNumArgs();
4090 return Diag(TheCall->getLocEnd(),
4091 diag::err_typecheck_call_too_many_args_at_most)
4092 << 0 /*function call*/ << 3 << NumArgs
4093 << TheCall->getSourceRange();
4095 // Argument 0 is checked for us and the remaining arguments must be
4096 // constant integers.
4097 for (unsigned i = 1; i != NumArgs; ++i)
4098 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
4104 /// SemaBuiltinAssume - Handle __assume (MS Extension).
4105 // __assume does not evaluate its arguments, and should warn if its argument
4106 // has side effects.
4107 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
4108 Expr *Arg = TheCall->getArg(0);
4109 if (Arg->isInstantiationDependent()) return false;
4111 if (Arg->HasSideEffects(Context))
4112 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
4113 << Arg->getSourceRange()
4114 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
4119 /// Handle __builtin_alloca_with_align. This is declared
4120 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
4122 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
4123 // The alignment must be a constant integer.
4124 Expr *Arg = TheCall->getArg(1);
4126 // We can't check the value of a dependent argument.
4127 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4128 if (const auto *UE =
4129 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
4130 if (UE->getKind() == UETT_AlignOf)
4131 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
4132 << Arg->getSourceRange();
4134 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
4136 if (!Result.isPowerOf2())
4137 return Diag(TheCall->getLocStart(),
4138 diag::err_alignment_not_power_of_two)
4139 << Arg->getSourceRange();
4141 if (Result < Context.getCharWidth())
4142 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
4143 << (unsigned)Context.getCharWidth()
4144 << Arg->getSourceRange();
4146 if (Result > INT32_MAX)
4147 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
4149 << Arg->getSourceRange();
4155 /// Handle __builtin_assume_aligned. This is declared
4156 /// as (const void*, size_t, ...) and can take one optional constant int arg.
4157 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
4158 unsigned NumArgs = TheCall->getNumArgs();
4161 return Diag(TheCall->getLocEnd(),
4162 diag::err_typecheck_call_too_many_args_at_most)
4163 << 0 /*function call*/ << 3 << NumArgs
4164 << TheCall->getSourceRange();
4166 // The alignment must be a constant integer.
4167 Expr *Arg = TheCall->getArg(1);
4169 // We can't check the value of a dependent argument.
4170 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4171 llvm::APSInt Result;
4172 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4175 if (!Result.isPowerOf2())
4176 return Diag(TheCall->getLocStart(),
4177 diag::err_alignment_not_power_of_two)
4178 << Arg->getSourceRange();
4182 ExprResult Arg(TheCall->getArg(2));
4183 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
4184 Context.getSizeType(), false);
4185 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4186 if (Arg.isInvalid()) return true;
4187 TheCall->setArg(2, Arg.get());
4193 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
4194 unsigned BuiltinID =
4195 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
4196 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
4198 unsigned NumArgs = TheCall->getNumArgs();
4199 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
4200 if (NumArgs < NumRequiredArgs) {
4201 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4202 << 0 /* function call */ << NumRequiredArgs << NumArgs
4203 << TheCall->getSourceRange();
4205 if (NumArgs >= NumRequiredArgs + 0x100) {
4206 return Diag(TheCall->getLocEnd(),
4207 diag::err_typecheck_call_too_many_args_at_most)
4208 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
4209 << TheCall->getSourceRange();
4213 // For formatting call, check buffer arg.
4215 ExprResult Arg(TheCall->getArg(i));
4216 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4217 Context, Context.VoidPtrTy, false);
4218 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4219 if (Arg.isInvalid())
4221 TheCall->setArg(i, Arg.get());
4225 // Check string literal arg.
4226 unsigned FormatIdx = i;
4228 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4229 if (Arg.isInvalid())
4231 TheCall->setArg(i, Arg.get());
4235 // Make sure variadic args are scalar.
4236 unsigned FirstDataArg = i;
4237 while (i < NumArgs) {
4238 ExprResult Arg = DefaultVariadicArgumentPromotion(
4239 TheCall->getArg(i), VariadicFunction, nullptr);
4240 if (Arg.isInvalid())
4242 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4243 if (ArgSize.getQuantity() >= 0x100) {
4244 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4245 << i << (int)ArgSize.getQuantity() << 0xff
4246 << TheCall->getSourceRange();
4248 TheCall->setArg(i, Arg.get());
4252 // Check formatting specifiers. NOTE: We're only doing this for the non-size
4253 // call to avoid duplicate diagnostics.
4255 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4256 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4257 bool Success = CheckFormatArguments(
4258 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4259 VariadicFunction, TheCall->getLocStart(), SourceRange(),
4266 TheCall->setType(Context.getSizeType());
4268 TheCall->setType(Context.VoidPtrTy);
4273 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4274 /// TheCall is a constant expression.
4275 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4276 llvm::APSInt &Result) {
4277 Expr *Arg = TheCall->getArg(ArgNum);
4278 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4279 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4281 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
4283 if (!Arg->isIntegerConstantExpr(Result, Context))
4284 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
4285 << FDecl->getDeclName() << Arg->getSourceRange();
4290 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
4291 /// TheCall is a constant expression in the range [Low, High].
4292 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
4293 int Low, int High) {
4294 llvm::APSInt Result;
4296 // We can't check the value of a dependent argument.
4297 Expr *Arg = TheCall->getArg(ArgNum);
4298 if (Arg->isTypeDependent() || Arg->isValueDependent())
4301 // Check constant-ness first.
4302 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4305 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
4306 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
4307 << Low << High << Arg->getSourceRange();
4312 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
4313 /// TheCall is a constant expression is a multiple of Num..
4314 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
4316 llvm::APSInt Result;
4318 // We can't check the value of a dependent argument.
4319 Expr *Arg = TheCall->getArg(ArgNum);
4320 if (Arg->isTypeDependent() || Arg->isValueDependent())
4323 // Check constant-ness first.
4324 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4327 if (Result.getSExtValue() % Num != 0)
4328 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
4329 << Num << Arg->getSourceRange();
4334 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
4335 /// TheCall is an ARM/AArch64 special register string literal.
4336 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
4337 int ArgNum, unsigned ExpectedFieldNum,
4339 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
4340 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
4341 BuiltinID == ARM::BI__builtin_arm_rsr ||
4342 BuiltinID == ARM::BI__builtin_arm_rsrp ||
4343 BuiltinID == ARM::BI__builtin_arm_wsr ||
4344 BuiltinID == ARM::BI__builtin_arm_wsrp;
4345 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
4346 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
4347 BuiltinID == AArch64::BI__builtin_arm_rsr ||
4348 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
4349 BuiltinID == AArch64::BI__builtin_arm_wsr ||
4350 BuiltinID == AArch64::BI__builtin_arm_wsrp;
4351 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
4353 // We can't check the value of a dependent argument.
4354 Expr *Arg = TheCall->getArg(ArgNum);
4355 if (Arg->isTypeDependent() || Arg->isValueDependent())
4358 // Check if the argument is a string literal.
4359 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4360 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
4361 << Arg->getSourceRange();
4363 // Check the type of special register given.
4364 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4365 SmallVector<StringRef, 6> Fields;
4366 Reg.split(Fields, ":");
4368 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
4369 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4370 << Arg->getSourceRange();
4372 // If the string is the name of a register then we cannot check that it is
4373 // valid here but if the string is of one the forms described in ACLE then we
4374 // can check that the supplied fields are integers and within the valid
4376 if (Fields.size() > 1) {
4377 bool FiveFields = Fields.size() == 5;
4379 bool ValidString = true;
4381 ValidString &= Fields[0].startswith_lower("cp") ||
4382 Fields[0].startswith_lower("p");
4385 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
4387 ValidString &= Fields[2].startswith_lower("c");
4389 Fields[2] = Fields[2].drop_front(1);
4392 ValidString &= Fields[3].startswith_lower("c");
4394 Fields[3] = Fields[3].drop_front(1);
4398 SmallVector<int, 5> Ranges;
4400 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
4402 Ranges.append({15, 7, 15});
4404 for (unsigned i=0; i<Fields.size(); ++i) {
4406 ValidString &= !Fields[i].getAsInteger(10, IntField);
4407 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
4411 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4412 << Arg->getSourceRange();
4414 } else if (IsAArch64Builtin && Fields.size() == 1) {
4415 // If the register name is one of those that appear in the condition below
4416 // and the special register builtin being used is one of the write builtins,
4417 // then we require that the argument provided for writing to the register
4418 // is an integer constant expression. This is because it will be lowered to
4419 // an MSR (immediate) instruction, so we need to know the immediate at
4421 if (TheCall->getNumArgs() != 2)
4424 std::string RegLower = Reg.lower();
4425 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
4426 RegLower != "pan" && RegLower != "uao")
4429 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4435 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
4436 /// This checks that the target supports __builtin_longjmp and
4437 /// that val is a constant 1.
4438 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
4439 if (!Context.getTargetInfo().hasSjLjLowering())
4440 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
4441 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4443 Expr *Arg = TheCall->getArg(1);
4444 llvm::APSInt Result;
4446 // TODO: This is less than ideal. Overload this to take a value.
4447 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4451 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
4452 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
4457 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
4458 /// This checks that the target supports __builtin_setjmp.
4459 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
4460 if (!Context.getTargetInfo().hasSjLjLowering())
4461 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
4462 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4467 class UncoveredArgHandler {
4468 enum { Unknown = -1, AllCovered = -2 };
4469 signed FirstUncoveredArg;
4470 SmallVector<const Expr *, 4> DiagnosticExprs;
4473 UncoveredArgHandler() : FirstUncoveredArg(Unknown) { }
4475 bool hasUncoveredArg() const {
4476 return (FirstUncoveredArg >= 0);
4479 unsigned getUncoveredArg() const {
4480 assert(hasUncoveredArg() && "no uncovered argument");
4481 return FirstUncoveredArg;
4484 void setAllCovered() {
4485 // A string has been found with all arguments covered, so clear out
4487 DiagnosticExprs.clear();
4488 FirstUncoveredArg = AllCovered;
4491 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
4492 assert(NewFirstUncoveredArg >= 0 && "Outside range");
4494 // Don't update if a previous string covers all arguments.
4495 if (FirstUncoveredArg == AllCovered)
4498 // UncoveredArgHandler tracks the highest uncovered argument index
4499 // and with it all the strings that match this index.
4500 if (NewFirstUncoveredArg == FirstUncoveredArg)
4501 DiagnosticExprs.push_back(StrExpr);
4502 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
4503 DiagnosticExprs.clear();
4504 DiagnosticExprs.push_back(StrExpr);
4505 FirstUncoveredArg = NewFirstUncoveredArg;
4509 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
4512 enum StringLiteralCheckType {
4514 SLCT_UncheckedLiteral,
4517 } // end anonymous namespace
4519 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
4520 BinaryOperatorKind BinOpKind,
4521 bool AddendIsRight) {
4522 unsigned BitWidth = Offset.getBitWidth();
4523 unsigned AddendBitWidth = Addend.getBitWidth();
4524 // There might be negative interim results.
4525 if (Addend.isUnsigned()) {
4526 Addend = Addend.zext(++AddendBitWidth);
4527 Addend.setIsSigned(true);
4529 // Adjust the bit width of the APSInts.
4530 if (AddendBitWidth > BitWidth) {
4531 Offset = Offset.sext(AddendBitWidth);
4532 BitWidth = AddendBitWidth;
4533 } else if (BitWidth > AddendBitWidth) {
4534 Addend = Addend.sext(BitWidth);
4538 llvm::APSInt ResOffset = Offset;
4539 if (BinOpKind == BO_Add)
4540 ResOffset = Offset.sadd_ov(Addend, Ov);
4542 assert(AddendIsRight && BinOpKind == BO_Sub &&
4543 "operator must be add or sub with addend on the right");
4544 ResOffset = Offset.ssub_ov(Addend, Ov);
4547 // We add an offset to a pointer here so we should support an offset as big as
4550 assert(BitWidth <= UINT_MAX / 2 && "index (intermediate) result too big");
4551 Offset = Offset.sext(2 * BitWidth);
4552 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
4560 // This is a wrapper class around StringLiteral to support offsetted string
4561 // literals as format strings. It takes the offset into account when returning
4562 // the string and its length or the source locations to display notes correctly.
4563 class FormatStringLiteral {
4564 const StringLiteral *FExpr;
4568 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
4569 : FExpr(fexpr), Offset(Offset) {}
4571 StringRef getString() const {
4572 return FExpr->getString().drop_front(Offset);
4575 unsigned getByteLength() const {
4576 return FExpr->getByteLength() - getCharByteWidth() * Offset;
4578 unsigned getLength() const { return FExpr->getLength() - Offset; }
4579 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
4581 StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
4583 QualType getType() const { return FExpr->getType(); }
4585 bool isAscii() const { return FExpr->isAscii(); }
4586 bool isWide() const { return FExpr->isWide(); }
4587 bool isUTF8() const { return FExpr->isUTF8(); }
4588 bool isUTF16() const { return FExpr->isUTF16(); }
4589 bool isUTF32() const { return FExpr->isUTF32(); }
4590 bool isPascal() const { return FExpr->isPascal(); }
4592 SourceLocation getLocationOfByte(
4593 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
4594 const TargetInfo &Target, unsigned *StartToken = nullptr,
4595 unsigned *StartTokenByteOffset = nullptr) const {
4596 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
4597 StartToken, StartTokenByteOffset);
4600 SourceLocation getLocStart() const LLVM_READONLY {
4601 return FExpr->getLocStart().getLocWithOffset(Offset);
4603 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
4605 } // end anonymous namespace
4607 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
4608 const Expr *OrigFormatExpr,
4609 ArrayRef<const Expr *> Args,
4610 bool HasVAListArg, unsigned format_idx,
4611 unsigned firstDataArg,
4612 Sema::FormatStringType Type,
4613 bool inFunctionCall,
4614 Sema::VariadicCallType CallType,
4615 llvm::SmallBitVector &CheckedVarArgs,
4616 UncoveredArgHandler &UncoveredArg);
4618 // Determine if an expression is a string literal or constant string.
4619 // If this function returns false on the arguments to a function expecting a
4620 // format string, we will usually need to emit a warning.
4621 // True string literals are then checked by CheckFormatString.
4622 static StringLiteralCheckType
4623 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
4624 bool HasVAListArg, unsigned format_idx,
4625 unsigned firstDataArg, Sema::FormatStringType Type,
4626 Sema::VariadicCallType CallType, bool InFunctionCall,
4627 llvm::SmallBitVector &CheckedVarArgs,
4628 UncoveredArgHandler &UncoveredArg,
4629 llvm::APSInt Offset) {
4631 assert(Offset.isSigned() && "invalid offset");
4633 if (E->isTypeDependent() || E->isValueDependent())
4634 return SLCT_NotALiteral;
4636 E = E->IgnoreParenCasts();
4638 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
4639 // Technically -Wformat-nonliteral does not warn about this case.
4640 // The behavior of printf and friends in this case is implementation
4641 // dependent. Ideally if the format string cannot be null then
4642 // it should have a 'nonnull' attribute in the function prototype.
4643 return SLCT_UncheckedLiteral;
4645 switch (E->getStmtClass()) {
4646 case Stmt::BinaryConditionalOperatorClass:
4647 case Stmt::ConditionalOperatorClass: {
4648 // The expression is a literal if both sub-expressions were, and it was
4649 // completely checked only if both sub-expressions were checked.
4650 const AbstractConditionalOperator *C =
4651 cast<AbstractConditionalOperator>(E);
4653 // Determine whether it is necessary to check both sub-expressions, for
4654 // example, because the condition expression is a constant that can be
4655 // evaluated at compile time.
4656 bool CheckLeft = true, CheckRight = true;
4659 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
4666 // We need to maintain the offsets for the right and the left hand side
4667 // separately to check if every possible indexed expression is a valid
4668 // string literal. They might have different offsets for different string
4669 // literals in the end.
4670 StringLiteralCheckType Left;
4672 Left = SLCT_UncheckedLiteral;
4674 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
4675 HasVAListArg, format_idx, firstDataArg,
4676 Type, CallType, InFunctionCall,
4677 CheckedVarArgs, UncoveredArg, Offset);
4678 if (Left == SLCT_NotALiteral || !CheckRight) {
4683 StringLiteralCheckType Right =
4684 checkFormatStringExpr(S, C->getFalseExpr(), Args,
4685 HasVAListArg, format_idx, firstDataArg,
4686 Type, CallType, InFunctionCall, CheckedVarArgs,
4687 UncoveredArg, Offset);
4689 return (CheckLeft && Left < Right) ? Left : Right;
4692 case Stmt::ImplicitCastExprClass: {
4693 E = cast<ImplicitCastExpr>(E)->getSubExpr();
4697 case Stmt::OpaqueValueExprClass:
4698 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
4702 return SLCT_NotALiteral;
4704 case Stmt::PredefinedExprClass:
4705 // While __func__, etc., are technically not string literals, they
4706 // cannot contain format specifiers and thus are not a security
4708 return SLCT_UncheckedLiteral;
4710 case Stmt::DeclRefExprClass: {
4711 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
4713 // As an exception, do not flag errors for variables binding to
4714 // const string literals.
4715 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
4716 bool isConstant = false;
4717 QualType T = DR->getType();
4719 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
4720 isConstant = AT->getElementType().isConstant(S.Context);
4721 } else if (const PointerType *PT = T->getAs<PointerType>()) {
4722 isConstant = T.isConstant(S.Context) &&
4723 PT->getPointeeType().isConstant(S.Context);
4724 } else if (T->isObjCObjectPointerType()) {
4725 // In ObjC, there is usually no "const ObjectPointer" type,
4726 // so don't check if the pointee type is constant.
4727 isConstant = T.isConstant(S.Context);
4731 if (const Expr *Init = VD->getAnyInitializer()) {
4732 // Look through initializers like const char c[] = { "foo" }
4733 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4734 if (InitList->isStringLiteralInit())
4735 Init = InitList->getInit(0)->IgnoreParenImpCasts();
4737 return checkFormatStringExpr(S, Init, Args,
4738 HasVAListArg, format_idx,
4739 firstDataArg, Type, CallType,
4740 /*InFunctionCall*/ false, CheckedVarArgs,
4741 UncoveredArg, Offset);
4745 // For vprintf* functions (i.e., HasVAListArg==true), we add a
4746 // special check to see if the format string is a function parameter
4747 // of the function calling the printf function. If the function
4748 // has an attribute indicating it is a printf-like function, then we
4749 // should suppress warnings concerning non-literals being used in a call
4750 // to a vprintf function. For example:
4753 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
4755 // va_start(ap, fmt);
4756 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
4760 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
4761 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
4762 int PVIndex = PV->getFunctionScopeIndex() + 1;
4763 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
4764 // adjust for implicit parameter
4765 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4766 if (MD->isInstance())
4768 // We also check if the formats are compatible.
4769 // We can't pass a 'scanf' string to a 'printf' function.
4770 if (PVIndex == PVFormat->getFormatIdx() &&
4771 Type == S.GetFormatStringType(PVFormat))
4772 return SLCT_UncheckedLiteral;
4779 return SLCT_NotALiteral;
4782 case Stmt::CallExprClass:
4783 case Stmt::CXXMemberCallExprClass: {
4784 const CallExpr *CE = cast<CallExpr>(E);
4785 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
4786 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
4787 unsigned ArgIndex = FA->getFormatIdx();
4788 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4789 if (MD->isInstance())
4791 const Expr *Arg = CE->getArg(ArgIndex - 1);
4793 return checkFormatStringExpr(S, Arg, Args,
4794 HasVAListArg, format_idx, firstDataArg,
4795 Type, CallType, InFunctionCall,
4796 CheckedVarArgs, UncoveredArg, Offset);
4797 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4798 unsigned BuiltinID = FD->getBuiltinID();
4799 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
4800 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
4801 const Expr *Arg = CE->getArg(0);
4802 return checkFormatStringExpr(S, Arg, Args,
4803 HasVAListArg, format_idx,
4804 firstDataArg, Type, CallType,
4805 InFunctionCall, CheckedVarArgs,
4806 UncoveredArg, Offset);
4811 return SLCT_NotALiteral;
4813 case Stmt::ObjCMessageExprClass: {
4814 const auto *ME = cast<ObjCMessageExpr>(E);
4815 if (const auto *ND = ME->getMethodDecl()) {
4816 if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
4817 unsigned ArgIndex = FA->getFormatIdx();
4818 const Expr *Arg = ME->getArg(ArgIndex - 1);
4819 return checkFormatStringExpr(
4820 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
4821 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
4825 return SLCT_NotALiteral;
4827 case Stmt::ObjCStringLiteralClass:
4828 case Stmt::StringLiteralClass: {
4829 const StringLiteral *StrE = nullptr;
4831 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
4832 StrE = ObjCFExpr->getString();
4834 StrE = cast<StringLiteral>(E);
4837 if (Offset.isNegative() || Offset > StrE->getLength()) {
4838 // TODO: It would be better to have an explicit warning for out of
4840 return SLCT_NotALiteral;
4842 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
4843 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
4844 firstDataArg, Type, InFunctionCall, CallType,
4845 CheckedVarArgs, UncoveredArg);
4846 return SLCT_CheckedLiteral;
4849 return SLCT_NotALiteral;
4851 case Stmt::BinaryOperatorClass: {
4852 llvm::APSInt LResult;
4853 llvm::APSInt RResult;
4855 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
4857 // A string literal + an int offset is still a string literal.
4858 if (BinOp->isAdditiveOp()) {
4859 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
4860 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
4862 if (LIsInt != RIsInt) {
4863 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
4866 if (BinOpKind == BO_Add) {
4867 sumOffsets(Offset, LResult, BinOpKind, RIsInt);
4868 E = BinOp->getRHS();
4872 sumOffsets(Offset, RResult, BinOpKind, RIsInt);
4873 E = BinOp->getLHS();
4879 return SLCT_NotALiteral;
4881 case Stmt::UnaryOperatorClass: {
4882 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
4883 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
4884 if (UnaOp->getOpcode() == clang::UO_AddrOf && ASE) {
4885 llvm::APSInt IndexResult;
4886 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
4887 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
4893 return SLCT_NotALiteral;
4897 return SLCT_NotALiteral;
4901 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
4902 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
4903 .Case("scanf", FST_Scanf)
4904 .Cases("printf", "printf0", FST_Printf)
4905 .Cases("NSString", "CFString", FST_NSString)
4906 .Case("strftime", FST_Strftime)
4907 .Case("strfmon", FST_Strfmon)
4908 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
4909 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
4910 .Case("os_trace", FST_OSLog)
4911 .Case("os_log", FST_OSLog)
4912 .Default(FST_Unknown);
4915 /// CheckFormatArguments - Check calls to printf and scanf (and similar
4916 /// functions) for correct use of format strings.
4917 /// Returns true if a format string has been fully checked.
4918 bool Sema::CheckFormatArguments(const FormatAttr *Format,
4919 ArrayRef<const Expr *> Args,
4921 VariadicCallType CallType,
4922 SourceLocation Loc, SourceRange Range,
4923 llvm::SmallBitVector &CheckedVarArgs) {
4924 FormatStringInfo FSI;
4925 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
4926 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
4927 FSI.FirstDataArg, GetFormatStringType(Format),
4928 CallType, Loc, Range, CheckedVarArgs);
4932 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
4933 bool HasVAListArg, unsigned format_idx,
4934 unsigned firstDataArg, FormatStringType Type,
4935 VariadicCallType CallType,
4936 SourceLocation Loc, SourceRange Range,
4937 llvm::SmallBitVector &CheckedVarArgs) {
4938 // CHECK: printf/scanf-like function is called with no format string.
4939 if (format_idx >= Args.size()) {
4940 Diag(Loc, diag::warn_missing_format_string) << Range;
4944 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
4946 // CHECK: format string is not a string literal.
4948 // Dynamically generated format strings are difficult to
4949 // automatically vet at compile time. Requiring that format strings
4950 // are string literals: (1) permits the checking of format strings by
4951 // the compiler and thereby (2) can practically remove the source of
4952 // many format string exploits.
4954 // Format string can be either ObjC string (e.g. @"%d") or
4955 // C string (e.g. "%d")
4956 // ObjC string uses the same format specifiers as C string, so we can use
4957 // the same format string checking logic for both ObjC and C strings.
4958 UncoveredArgHandler UncoveredArg;
4959 StringLiteralCheckType CT =
4960 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
4961 format_idx, firstDataArg, Type, CallType,
4962 /*IsFunctionCall*/ true, CheckedVarArgs,
4964 /*no string offset*/ llvm::APSInt(64, false) = 0);
4966 // Generate a diagnostic where an uncovered argument is detected.
4967 if (UncoveredArg.hasUncoveredArg()) {
4968 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
4969 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
4970 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
4973 if (CT != SLCT_NotALiteral)
4974 // Literal format string found, check done!
4975 return CT == SLCT_CheckedLiteral;
4977 // Strftime is particular as it always uses a single 'time' argument,
4978 // so it is safe to pass a non-literal string.
4979 if (Type == FST_Strftime)
4982 // Do not emit diag when the string param is a macro expansion and the
4983 // format is either NSString or CFString. This is a hack to prevent
4984 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
4985 // which are usually used in place of NS and CF string literals.
4986 SourceLocation FormatLoc = Args[format_idx]->getLocStart();
4987 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
4990 // If there are no arguments specified, warn with -Wformat-security, otherwise
4991 // warn only with -Wformat-nonliteral.
4992 if (Args.size() == firstDataArg) {
4993 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
4994 << OrigFormatExpr->getSourceRange();
4999 case FST_FreeBSDKPrintf:
5001 Diag(FormatLoc, diag::note_format_security_fixit)
5002 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
5005 Diag(FormatLoc, diag::note_format_security_fixit)
5006 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
5010 Diag(FormatLoc, diag::warn_format_nonliteral)
5011 << OrigFormatExpr->getSourceRange();
5017 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
5020 const FormatStringLiteral *FExpr;
5021 const Expr *OrigFormatExpr;
5022 const Sema::FormatStringType FSType;
5023 const unsigned FirstDataArg;
5024 const unsigned NumDataArgs;
5025 const char *Beg; // Start of format string.
5026 const bool HasVAListArg;
5027 ArrayRef<const Expr *> Args;
5029 llvm::SmallBitVector CoveredArgs;
5030 bool usesPositionalArgs;
5032 bool inFunctionCall;
5033 Sema::VariadicCallType CallType;
5034 llvm::SmallBitVector &CheckedVarArgs;
5035 UncoveredArgHandler &UncoveredArg;
5038 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
5039 const Expr *origFormatExpr,
5040 const Sema::FormatStringType type, unsigned firstDataArg,
5041 unsigned numDataArgs, const char *beg, bool hasVAListArg,
5042 ArrayRef<const Expr *> Args, unsigned formatIdx,
5043 bool inFunctionCall, Sema::VariadicCallType callType,
5044 llvm::SmallBitVector &CheckedVarArgs,
5045 UncoveredArgHandler &UncoveredArg)
5046 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
5047 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
5048 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
5049 usesPositionalArgs(false), atFirstArg(true),
5050 inFunctionCall(inFunctionCall), CallType(callType),
5051 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
5052 CoveredArgs.resize(numDataArgs);
5053 CoveredArgs.reset();
5056 void DoneProcessing();
5058 void HandleIncompleteSpecifier(const char *startSpecifier,
5059 unsigned specifierLen) override;
5061 void HandleInvalidLengthModifier(
5062 const analyze_format_string::FormatSpecifier &FS,
5063 const analyze_format_string::ConversionSpecifier &CS,
5064 const char *startSpecifier, unsigned specifierLen,
5067 void HandleNonStandardLengthModifier(
5068 const analyze_format_string::FormatSpecifier &FS,
5069 const char *startSpecifier, unsigned specifierLen);
5071 void HandleNonStandardConversionSpecifier(
5072 const analyze_format_string::ConversionSpecifier &CS,
5073 const char *startSpecifier, unsigned specifierLen);
5075 void HandlePosition(const char *startPos, unsigned posLen) override;
5077 void HandleInvalidPosition(const char *startSpecifier,
5078 unsigned specifierLen,
5079 analyze_format_string::PositionContext p) override;
5081 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
5083 void HandleNullChar(const char *nullCharacter) override;
5085 template <typename Range>
5087 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
5088 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
5089 bool IsStringLocation, Range StringRange,
5090 ArrayRef<FixItHint> Fixit = None);
5093 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
5094 const char *startSpec,
5095 unsigned specifierLen,
5096 const char *csStart, unsigned csLen);
5098 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
5099 const char *startSpec,
5100 unsigned specifierLen);
5102 SourceRange getFormatStringRange();
5103 CharSourceRange getSpecifierRange(const char *startSpecifier,
5104 unsigned specifierLen);
5105 SourceLocation getLocationOfByte(const char *x);
5107 const Expr *getDataArg(unsigned i) const;
5109 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
5110 const analyze_format_string::ConversionSpecifier &CS,
5111 const char *startSpecifier, unsigned specifierLen,
5114 template <typename Range>
5115 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5116 bool IsStringLocation, Range StringRange,
5117 ArrayRef<FixItHint> Fixit = None);
5119 } // end anonymous namespace
5121 SourceRange CheckFormatHandler::getFormatStringRange() {
5122 return OrigFormatExpr->getSourceRange();
5125 CharSourceRange CheckFormatHandler::
5126 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
5127 SourceLocation Start = getLocationOfByte(startSpecifier);
5128 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
5130 // Advance the end SourceLocation by one due to half-open ranges.
5131 End = End.getLocWithOffset(1);
5133 return CharSourceRange::getCharRange(Start, End);
5136 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
5137 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
5138 S.getLangOpts(), S.Context.getTargetInfo());
5141 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
5142 unsigned specifierLen){
5143 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
5144 getLocationOfByte(startSpecifier),
5145 /*IsStringLocation*/true,
5146 getSpecifierRange(startSpecifier, specifierLen));
5149 void CheckFormatHandler::HandleInvalidLengthModifier(
5150 const analyze_format_string::FormatSpecifier &FS,
5151 const analyze_format_string::ConversionSpecifier &CS,
5152 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
5153 using namespace analyze_format_string;
5155 const LengthModifier &LM = FS.getLengthModifier();
5156 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5158 // See if we know how to fix this length modifier.
5159 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
5161 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
5162 getLocationOfByte(LM.getStart()),
5163 /*IsStringLocation*/true,
5164 getSpecifierRange(startSpecifier, specifierLen));
5166 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5167 << FixedLM->toString()
5168 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5172 if (DiagID == diag::warn_format_nonsensical_length)
5173 Hint = FixItHint::CreateRemoval(LMRange);
5175 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
5176 getLocationOfByte(LM.getStart()),
5177 /*IsStringLocation*/true,
5178 getSpecifierRange(startSpecifier, specifierLen),
5183 void CheckFormatHandler::HandleNonStandardLengthModifier(
5184 const analyze_format_string::FormatSpecifier &FS,
5185 const char *startSpecifier, unsigned specifierLen) {
5186 using namespace analyze_format_string;
5188 const LengthModifier &LM = FS.getLengthModifier();
5189 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5191 // See if we know how to fix this length modifier.
5192 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
5194 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5195 << LM.toString() << 0,
5196 getLocationOfByte(LM.getStart()),
5197 /*IsStringLocation*/true,
5198 getSpecifierRange(startSpecifier, specifierLen));
5200 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5201 << FixedLM->toString()
5202 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5205 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5206 << LM.toString() << 0,
5207 getLocationOfByte(LM.getStart()),
5208 /*IsStringLocation*/true,
5209 getSpecifierRange(startSpecifier, specifierLen));
5213 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5214 const analyze_format_string::ConversionSpecifier &CS,
5215 const char *startSpecifier, unsigned specifierLen) {
5216 using namespace analyze_format_string;
5218 // See if we know how to fix this conversion specifier.
5219 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
5221 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5222 << CS.toString() << /*conversion specifier*/1,
5223 getLocationOfByte(CS.getStart()),
5224 /*IsStringLocation*/true,
5225 getSpecifierRange(startSpecifier, specifierLen));
5227 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5228 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5229 << FixedCS->toString()
5230 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5232 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5233 << CS.toString() << /*conversion specifier*/1,
5234 getLocationOfByte(CS.getStart()),
5235 /*IsStringLocation*/true,
5236 getSpecifierRange(startSpecifier, specifierLen));
5240 void CheckFormatHandler::HandlePosition(const char *startPos,
5242 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5243 getLocationOfByte(startPos),
5244 /*IsStringLocation*/true,
5245 getSpecifierRange(startPos, posLen));
5249 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5250 analyze_format_string::PositionContext p) {
5251 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5253 getLocationOfByte(startPos), /*IsStringLocation*/true,
5254 getSpecifierRange(startPos, posLen));
5257 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
5259 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5260 getLocationOfByte(startPos),
5261 /*IsStringLocation*/true,
5262 getSpecifierRange(startPos, posLen));
5265 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
5266 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
5267 // The presence of a null character is likely an error.
5268 EmitFormatDiagnostic(
5269 S.PDiag(diag::warn_printf_format_string_contains_null_char),
5270 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
5271 getFormatStringRange());
5275 // Note that this may return NULL if there was an error parsing or building
5276 // one of the argument expressions.
5277 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
5278 return Args[FirstDataArg + i];
5281 void CheckFormatHandler::DoneProcessing() {
5282 // Does the number of data arguments exceed the number of
5283 // format conversions in the format string?
5284 if (!HasVAListArg) {
5285 // Find any arguments that weren't covered.
5287 signed notCoveredArg = CoveredArgs.find_first();
5288 if (notCoveredArg >= 0) {
5289 assert((unsigned)notCoveredArg < NumDataArgs);
5290 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
5292 UncoveredArg.setAllCovered();
5297 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
5298 const Expr *ArgExpr) {
5299 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
5305 SourceLocation Loc = ArgExpr->getLocStart();
5307 if (S.getSourceManager().isInSystemMacro(Loc))
5310 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
5311 for (auto E : DiagnosticExprs)
5312 PDiag << E->getSourceRange();
5314 CheckFormatHandler::EmitFormatDiagnostic(
5315 S, IsFunctionCall, DiagnosticExprs[0],
5316 PDiag, Loc, /*IsStringLocation*/false,
5317 DiagnosticExprs[0]->getSourceRange());
5321 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
5323 const char *startSpec,
5324 unsigned specifierLen,
5325 const char *csStart,
5327 bool keepGoing = true;
5328 if (argIndex < NumDataArgs) {
5329 // Consider the argument coverered, even though the specifier doesn't
5331 CoveredArgs.set(argIndex);
5334 // If argIndex exceeds the number of data arguments we
5335 // don't issue a warning because that is just a cascade of warnings (and
5336 // they may have intended '%%' anyway). We don't want to continue processing
5337 // the format string after this point, however, as we will like just get
5338 // gibberish when trying to match arguments.
5342 StringRef Specifier(csStart, csLen);
5344 // If the specifier in non-printable, it could be the first byte of a UTF-8
5345 // sequence. In that case, print the UTF-8 code point. If not, print the byte
5347 std::string CodePointStr;
5348 if (!llvm::sys::locale::isPrint(*csStart)) {
5349 llvm::UTF32 CodePoint;
5350 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
5351 const llvm::UTF8 *E =
5352 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
5353 llvm::ConversionResult Result =
5354 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
5356 if (Result != llvm::conversionOK) {
5357 unsigned char FirstChar = *csStart;
5358 CodePoint = (llvm::UTF32)FirstChar;
5361 llvm::raw_string_ostream OS(CodePointStr);
5362 if (CodePoint < 256)
5363 OS << "\\x" << llvm::format("%02x", CodePoint);
5364 else if (CodePoint <= 0xFFFF)
5365 OS << "\\u" << llvm::format("%04x", CodePoint);
5367 OS << "\\U" << llvm::format("%08x", CodePoint);
5369 Specifier = CodePointStr;
5372 EmitFormatDiagnostic(
5373 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
5374 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
5380 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
5381 const char *startSpec,
5382 unsigned specifierLen) {
5383 EmitFormatDiagnostic(
5384 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
5385 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
5389 CheckFormatHandler::CheckNumArgs(
5390 const analyze_format_string::FormatSpecifier &FS,
5391 const analyze_format_string::ConversionSpecifier &CS,
5392 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
5394 if (argIndex >= NumDataArgs) {
5395 PartialDiagnostic PDiag = FS.usesPositionalArg()
5396 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
5397 << (argIndex+1) << NumDataArgs)
5398 : S.PDiag(diag::warn_printf_insufficient_data_args);
5399 EmitFormatDiagnostic(
5400 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
5401 getSpecifierRange(startSpecifier, specifierLen));
5403 // Since more arguments than conversion tokens are given, by extension
5404 // all arguments are covered, so mark this as so.
5405 UncoveredArg.setAllCovered();
5411 template<typename Range>
5412 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
5414 bool IsStringLocation,
5416 ArrayRef<FixItHint> FixIt) {
5417 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
5418 Loc, IsStringLocation, StringRange, FixIt);
5421 /// \brief If the format string is not within the funcion call, emit a note
5422 /// so that the function call and string are in diagnostic messages.
5424 /// \param InFunctionCall if true, the format string is within the function
5425 /// call and only one diagnostic message will be produced. Otherwise, an
5426 /// extra note will be emitted pointing to location of the format string.
5428 /// \param ArgumentExpr the expression that is passed as the format string
5429 /// argument in the function call. Used for getting locations when two
5430 /// diagnostics are emitted.
5432 /// \param PDiag the callee should already have provided any strings for the
5433 /// diagnostic message. This function only adds locations and fixits
5436 /// \param Loc primary location for diagnostic. If two diagnostics are
5437 /// required, one will be at Loc and a new SourceLocation will be created for
5440 /// \param IsStringLocation if true, Loc points to the format string should be
5441 /// used for the note. Otherwise, Loc points to the argument list and will
5442 /// be used with PDiag.
5444 /// \param StringRange some or all of the string to highlight. This is
5445 /// templated so it can accept either a CharSourceRange or a SourceRange.
5447 /// \param FixIt optional fix it hint for the format string.
5448 template <typename Range>
5449 void CheckFormatHandler::EmitFormatDiagnostic(
5450 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
5451 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
5452 Range StringRange, ArrayRef<FixItHint> FixIt) {
5453 if (InFunctionCall) {
5454 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
5458 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
5459 << ArgumentExpr->getSourceRange();
5461 const Sema::SemaDiagnosticBuilder &Note =
5462 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
5463 diag::note_format_string_defined);
5465 Note << StringRange;
5470 //===--- CHECK: Printf format string checking ------------------------------===//
5473 class CheckPrintfHandler : public CheckFormatHandler {
5475 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
5476 const Expr *origFormatExpr,
5477 const Sema::FormatStringType type, unsigned firstDataArg,
5478 unsigned numDataArgs, bool isObjC, const char *beg,
5479 bool hasVAListArg, ArrayRef<const Expr *> Args,
5480 unsigned formatIdx, bool inFunctionCall,
5481 Sema::VariadicCallType CallType,
5482 llvm::SmallBitVector &CheckedVarArgs,
5483 UncoveredArgHandler &UncoveredArg)
5484 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
5485 numDataArgs, beg, hasVAListArg, Args, formatIdx,
5486 inFunctionCall, CallType, CheckedVarArgs,
5489 bool isObjCContext() const { return FSType == Sema::FST_NSString; }
5491 /// Returns true if '%@' specifiers are allowed in the format string.
5492 bool allowsObjCArg() const {
5493 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
5494 FSType == Sema::FST_OSTrace;
5497 bool HandleInvalidPrintfConversionSpecifier(
5498 const analyze_printf::PrintfSpecifier &FS,
5499 const char *startSpecifier,
5500 unsigned specifierLen) override;
5502 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
5503 const char *startSpecifier,
5504 unsigned specifierLen) override;
5505 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5506 const char *StartSpecifier,
5507 unsigned SpecifierLen,
5510 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
5511 const char *startSpecifier, unsigned specifierLen);
5512 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
5513 const analyze_printf::OptionalAmount &Amt,
5515 const char *startSpecifier, unsigned specifierLen);
5516 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5517 const analyze_printf::OptionalFlag &flag,
5518 const char *startSpecifier, unsigned specifierLen);
5519 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
5520 const analyze_printf::OptionalFlag &ignoredFlag,
5521 const analyze_printf::OptionalFlag &flag,
5522 const char *startSpecifier, unsigned specifierLen);
5523 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
5526 void HandleEmptyObjCModifierFlag(const char *startFlag,
5527 unsigned flagLen) override;
5529 void HandleInvalidObjCModifierFlag(const char *startFlag,
5530 unsigned flagLen) override;
5532 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
5533 const char *flagsEnd,
5534 const char *conversionPosition)
5537 } // end anonymous namespace
5539 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
5540 const analyze_printf::PrintfSpecifier &FS,
5541 const char *startSpecifier,
5542 unsigned specifierLen) {
5543 const analyze_printf::PrintfConversionSpecifier &CS =
5544 FS.getConversionSpecifier();
5546 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5547 getLocationOfByte(CS.getStart()),
5548 startSpecifier, specifierLen,
5549 CS.getStart(), CS.getLength());
5552 bool CheckPrintfHandler::HandleAmount(
5553 const analyze_format_string::OptionalAmount &Amt,
5554 unsigned k, const char *startSpecifier,
5555 unsigned specifierLen) {
5556 if (Amt.hasDataArgument()) {
5557 if (!HasVAListArg) {
5558 unsigned argIndex = Amt.getArgIndex();
5559 if (argIndex >= NumDataArgs) {
5560 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
5562 getLocationOfByte(Amt.getStart()),
5563 /*IsStringLocation*/true,
5564 getSpecifierRange(startSpecifier, specifierLen));
5565 // Don't do any more checking. We will just emit
5570 // Type check the data argument. It should be an 'int'.
5571 // Although not in conformance with C99, we also allow the argument to be
5572 // an 'unsigned int' as that is a reasonably safe case. GCC also
5573 // doesn't emit a warning for that case.
5574 CoveredArgs.set(argIndex);
5575 const Expr *Arg = getDataArg(argIndex);
5579 QualType T = Arg->getType();
5581 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
5582 assert(AT.isValid());
5584 if (!AT.matchesType(S.Context, T)) {
5585 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
5586 << k << AT.getRepresentativeTypeName(S.Context)
5587 << T << Arg->getSourceRange(),
5588 getLocationOfByte(Amt.getStart()),
5589 /*IsStringLocation*/true,
5590 getSpecifierRange(startSpecifier, specifierLen));
5591 // Don't do any more checking. We will just emit
5600 void CheckPrintfHandler::HandleInvalidAmount(
5601 const analyze_printf::PrintfSpecifier &FS,
5602 const analyze_printf::OptionalAmount &Amt,
5604 const char *startSpecifier,
5605 unsigned specifierLen) {
5606 const analyze_printf::PrintfConversionSpecifier &CS =
5607 FS.getConversionSpecifier();
5610 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
5611 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
5612 Amt.getConstantLength()))
5615 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
5616 << type << CS.toString(),
5617 getLocationOfByte(Amt.getStart()),
5618 /*IsStringLocation*/true,
5619 getSpecifierRange(startSpecifier, specifierLen),
5623 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5624 const analyze_printf::OptionalFlag &flag,
5625 const char *startSpecifier,
5626 unsigned specifierLen) {
5627 // Warn about pointless flag with a fixit removal.
5628 const analyze_printf::PrintfConversionSpecifier &CS =
5629 FS.getConversionSpecifier();
5630 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
5631 << flag.toString() << CS.toString(),
5632 getLocationOfByte(flag.getPosition()),
5633 /*IsStringLocation*/true,
5634 getSpecifierRange(startSpecifier, specifierLen),
5635 FixItHint::CreateRemoval(
5636 getSpecifierRange(flag.getPosition(), 1)));
5639 void CheckPrintfHandler::HandleIgnoredFlag(
5640 const analyze_printf::PrintfSpecifier &FS,
5641 const analyze_printf::OptionalFlag &ignoredFlag,
5642 const analyze_printf::OptionalFlag &flag,
5643 const char *startSpecifier,
5644 unsigned specifierLen) {
5645 // Warn about ignored flag with a fixit removal.
5646 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
5647 << ignoredFlag.toString() << flag.toString(),
5648 getLocationOfByte(ignoredFlag.getPosition()),
5649 /*IsStringLocation*/true,
5650 getSpecifierRange(startSpecifier, specifierLen),
5651 FixItHint::CreateRemoval(
5652 getSpecifierRange(ignoredFlag.getPosition(), 1)));
5655 // void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5656 // bool IsStringLocation, Range StringRange,
5657 // ArrayRef<FixItHint> Fixit = None);
5659 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
5661 // Warn about an empty flag.
5662 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
5663 getLocationOfByte(startFlag),
5664 /*IsStringLocation*/true,
5665 getSpecifierRange(startFlag, flagLen));
5668 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
5670 // Warn about an invalid flag.
5671 auto Range = getSpecifierRange(startFlag, flagLen);
5672 StringRef flag(startFlag, flagLen);
5673 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
5674 getLocationOfByte(startFlag),
5675 /*IsStringLocation*/true,
5676 Range, FixItHint::CreateRemoval(Range));
5679 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
5680 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
5681 // Warn about using '[...]' without a '@' conversion.
5682 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
5683 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
5684 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
5685 getLocationOfByte(conversionPosition),
5686 /*IsStringLocation*/true,
5687 Range, FixItHint::CreateRemoval(Range));
5690 // Determines if the specified is a C++ class or struct containing
5691 // a member with the specified name and kind (e.g. a CXXMethodDecl named
5693 template<typename MemberKind>
5694 static llvm::SmallPtrSet<MemberKind*, 1>
5695 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
5696 const RecordType *RT = Ty->getAs<RecordType>();
5697 llvm::SmallPtrSet<MemberKind*, 1> Results;
5701 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
5702 if (!RD || !RD->getDefinition())
5705 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
5706 Sema::LookupMemberName);
5707 R.suppressDiagnostics();
5709 // We just need to include all members of the right kind turned up by the
5710 // filter, at this point.
5711 if (S.LookupQualifiedName(R, RT->getDecl()))
5712 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5713 NamedDecl *decl = (*I)->getUnderlyingDecl();
5714 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
5720 /// Check if we could call '.c_str()' on an object.
5722 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
5723 /// allow the call, or if it would be ambiguous).
5724 bool Sema::hasCStrMethod(const Expr *E) {
5725 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5727 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
5728 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5730 if ((*MI)->getMinRequiredArguments() == 0)
5735 // Check if a (w)string was passed when a (w)char* was needed, and offer a
5736 // better diagnostic if so. AT is assumed to be valid.
5737 // Returns true when a c_str() conversion method is found.
5738 bool CheckPrintfHandler::checkForCStrMembers(
5739 const analyze_printf::ArgType &AT, const Expr *E) {
5740 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5743 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
5745 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5747 const CXXMethodDecl *Method = *MI;
5748 if (Method->getMinRequiredArguments() == 0 &&
5749 AT.matchesType(S.Context, Method->getReturnType())) {
5750 // FIXME: Suggest parens if the expression needs them.
5751 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
5752 S.Diag(E->getLocStart(), diag::note_printf_c_str)
5754 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
5763 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
5765 const char *startSpecifier,
5766 unsigned specifierLen) {
5767 using namespace analyze_format_string;
5768 using namespace analyze_printf;
5769 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
5771 if (FS.consumesDataArgument()) {
5774 usesPositionalArgs = FS.usesPositionalArg();
5776 else if (usesPositionalArgs != FS.usesPositionalArg()) {
5777 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5778 startSpecifier, specifierLen);
5783 // First check if the field width, precision, and conversion specifier
5784 // have matching data arguments.
5785 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
5786 startSpecifier, specifierLen)) {
5790 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
5791 startSpecifier, specifierLen)) {
5795 if (!CS.consumesDataArgument()) {
5796 // FIXME: Technically specifying a precision or field width here
5797 // makes no sense. Worth issuing a warning at some point.
5801 // Consume the argument.
5802 unsigned argIndex = FS.getArgIndex();
5803 if (argIndex < NumDataArgs) {
5804 // The check to see if the argIndex is valid will come later.
5805 // We set the bit here because we may exit early from this
5806 // function if we encounter some other error.
5807 CoveredArgs.set(argIndex);
5810 // FreeBSD kernel extensions.
5811 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
5812 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
5813 // We need at least two arguments.
5814 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
5817 // Claim the second argument.
5818 CoveredArgs.set(argIndex + 1);
5820 // Type check the first argument (int for %b, pointer for %D)
5821 const Expr *Ex = getDataArg(argIndex);
5822 const analyze_printf::ArgType &AT =
5823 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
5824 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
5825 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
5826 EmitFormatDiagnostic(
5827 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5828 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
5829 << false << Ex->getSourceRange(),
5830 Ex->getLocStart(), /*IsStringLocation*/false,
5831 getSpecifierRange(startSpecifier, specifierLen));
5833 // Type check the second argument (char * for both %b and %D)
5834 Ex = getDataArg(argIndex + 1);
5835 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
5836 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
5837 EmitFormatDiagnostic(
5838 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5839 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
5840 << false << Ex->getSourceRange(),
5841 Ex->getLocStart(), /*IsStringLocation*/false,
5842 getSpecifierRange(startSpecifier, specifierLen));
5847 // Check for using an Objective-C specific conversion specifier
5848 // in a non-ObjC literal.
5849 if (!allowsObjCArg() && CS.isObjCArg()) {
5850 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5854 // %P can only be used with os_log.
5855 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
5856 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5860 // %n is not allowed with os_log.
5861 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
5862 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
5863 getLocationOfByte(CS.getStart()),
5864 /*IsStringLocation*/ false,
5865 getSpecifierRange(startSpecifier, specifierLen));
5870 // Only scalars are allowed for os_trace.
5871 if (FSType == Sema::FST_OSTrace &&
5872 (CS.getKind() == ConversionSpecifier::PArg ||
5873 CS.getKind() == ConversionSpecifier::sArg ||
5874 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
5875 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5879 // Check for use of public/private annotation outside of os_log().
5880 if (FSType != Sema::FST_OSLog) {
5881 if (FS.isPublic().isSet()) {
5882 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
5884 getLocationOfByte(FS.isPublic().getPosition()),
5885 /*IsStringLocation*/ false,
5886 getSpecifierRange(startSpecifier, specifierLen));
5888 if (FS.isPrivate().isSet()) {
5889 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
5891 getLocationOfByte(FS.isPrivate().getPosition()),
5892 /*IsStringLocation*/ false,
5893 getSpecifierRange(startSpecifier, specifierLen));
5897 // Check for invalid use of field width
5898 if (!FS.hasValidFieldWidth()) {
5899 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
5900 startSpecifier, specifierLen);
5903 // Check for invalid use of precision
5904 if (!FS.hasValidPrecision()) {
5905 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
5906 startSpecifier, specifierLen);
5909 // Precision is mandatory for %P specifier.
5910 if (CS.getKind() == ConversionSpecifier::PArg &&
5911 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
5912 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
5913 getLocationOfByte(startSpecifier),
5914 /*IsStringLocation*/ false,
5915 getSpecifierRange(startSpecifier, specifierLen));
5918 // Check each flag does not conflict with any other component.
5919 if (!FS.hasValidThousandsGroupingPrefix())
5920 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
5921 if (!FS.hasValidLeadingZeros())
5922 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
5923 if (!FS.hasValidPlusPrefix())
5924 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
5925 if (!FS.hasValidSpacePrefix())
5926 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
5927 if (!FS.hasValidAlternativeForm())
5928 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
5929 if (!FS.hasValidLeftJustified())
5930 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
5932 // Check that flags are not ignored by another flag
5933 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
5934 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
5935 startSpecifier, specifierLen);
5936 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
5937 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
5938 startSpecifier, specifierLen);
5940 // Check the length modifier is valid with the given conversion specifier.
5941 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
5942 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5943 diag::warn_format_nonsensical_length);
5944 else if (!FS.hasStandardLengthModifier())
5945 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
5946 else if (!FS.hasStandardLengthConversionCombination())
5947 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5948 diag::warn_format_non_standard_conversion_spec);
5950 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
5951 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
5953 // The remaining checks depend on the data arguments.
5957 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
5960 const Expr *Arg = getDataArg(argIndex);
5964 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
5967 static bool requiresParensToAddCast(const Expr *E) {
5968 // FIXME: We should have a general way to reason about operator
5969 // precedence and whether parens are actually needed here.
5970 // Take care of a few common cases where they aren't.
5971 const Expr *Inside = E->IgnoreImpCasts();
5972 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
5973 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
5975 switch (Inside->getStmtClass()) {
5976 case Stmt::ArraySubscriptExprClass:
5977 case Stmt::CallExprClass:
5978 case Stmt::CharacterLiteralClass:
5979 case Stmt::CXXBoolLiteralExprClass:
5980 case Stmt::DeclRefExprClass:
5981 case Stmt::FloatingLiteralClass:
5982 case Stmt::IntegerLiteralClass:
5983 case Stmt::MemberExprClass:
5984 case Stmt::ObjCArrayLiteralClass:
5985 case Stmt::ObjCBoolLiteralExprClass:
5986 case Stmt::ObjCBoxedExprClass:
5987 case Stmt::ObjCDictionaryLiteralClass:
5988 case Stmt::ObjCEncodeExprClass:
5989 case Stmt::ObjCIvarRefExprClass:
5990 case Stmt::ObjCMessageExprClass:
5991 case Stmt::ObjCPropertyRefExprClass:
5992 case Stmt::ObjCStringLiteralClass:
5993 case Stmt::ObjCSubscriptRefExprClass:
5994 case Stmt::ParenExprClass:
5995 case Stmt::StringLiteralClass:
5996 case Stmt::UnaryOperatorClass:
6003 static std::pair<QualType, StringRef>
6004 shouldNotPrintDirectly(const ASTContext &Context,
6005 QualType IntendedTy,
6007 // Use a 'while' to peel off layers of typedefs.
6008 QualType TyTy = IntendedTy;
6009 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
6010 StringRef Name = UserTy->getDecl()->getName();
6011 QualType CastTy = llvm::StringSwitch<QualType>(Name)
6012 .Case("CFIndex", Context.LongTy)
6013 .Case("NSInteger", Context.LongTy)
6014 .Case("NSUInteger", Context.UnsignedLongTy)
6015 .Case("SInt32", Context.IntTy)
6016 .Case("UInt32", Context.UnsignedIntTy)
6017 .Default(QualType());
6019 if (!CastTy.isNull())
6020 return std::make_pair(CastTy, Name);
6022 TyTy = UserTy->desugar();
6025 // Strip parens if necessary.
6026 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
6027 return shouldNotPrintDirectly(Context,
6028 PE->getSubExpr()->getType(),
6031 // If this is a conditional expression, then its result type is constructed
6032 // via usual arithmetic conversions and thus there might be no necessary
6033 // typedef sugar there. Recurse to operands to check for NSInteger &
6034 // Co. usage condition.
6035 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6036 QualType TrueTy, FalseTy;
6037 StringRef TrueName, FalseName;
6039 std::tie(TrueTy, TrueName) =
6040 shouldNotPrintDirectly(Context,
6041 CO->getTrueExpr()->getType(),
6043 std::tie(FalseTy, FalseName) =
6044 shouldNotPrintDirectly(Context,
6045 CO->getFalseExpr()->getType(),
6046 CO->getFalseExpr());
6048 if (TrueTy == FalseTy)
6049 return std::make_pair(TrueTy, TrueName);
6050 else if (TrueTy.isNull())
6051 return std::make_pair(FalseTy, FalseName);
6052 else if (FalseTy.isNull())
6053 return std::make_pair(TrueTy, TrueName);
6056 return std::make_pair(QualType(), StringRef());
6060 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
6061 const char *StartSpecifier,
6062 unsigned SpecifierLen,
6064 using namespace analyze_format_string;
6065 using namespace analyze_printf;
6066 // Now type check the data expression that matches the
6067 // format specifier.
6068 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
6072 QualType ExprTy = E->getType();
6073 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
6074 ExprTy = TET->getUnderlyingExpr()->getType();
6077 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
6079 if (match == analyze_printf::ArgType::Match) {
6083 // Look through argument promotions for our error message's reported type.
6084 // This includes the integral and floating promotions, but excludes array
6085 // and function pointer decay; seeing that an argument intended to be a
6086 // string has type 'char [6]' is probably more confusing than 'char *'.
6087 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6088 if (ICE->getCastKind() == CK_IntegralCast ||
6089 ICE->getCastKind() == CK_FloatingCast) {
6090 E = ICE->getSubExpr();
6091 ExprTy = E->getType();
6093 // Check if we didn't match because of an implicit cast from a 'char'
6094 // or 'short' to an 'int'. This is done because printf is a varargs
6096 if (ICE->getType() == S.Context.IntTy ||
6097 ICE->getType() == S.Context.UnsignedIntTy) {
6098 // All further checking is done on the subexpression.
6099 if (AT.matchesType(S.Context, ExprTy))
6103 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
6104 // Special case for 'a', which has type 'int' in C.
6105 // Note, however, that we do /not/ want to treat multibyte constants like
6106 // 'MooV' as characters! This form is deprecated but still exists.
6107 if (ExprTy == S.Context.IntTy)
6108 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
6109 ExprTy = S.Context.CharTy;
6112 // Look through enums to their underlying type.
6113 bool IsEnum = false;
6114 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
6115 ExprTy = EnumTy->getDecl()->getIntegerType();
6119 // %C in an Objective-C context prints a unichar, not a wchar_t.
6120 // If the argument is an integer of some kind, believe the %C and suggest
6121 // a cast instead of changing the conversion specifier.
6122 QualType IntendedTy = ExprTy;
6123 if (isObjCContext() &&
6124 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
6125 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
6126 !ExprTy->isCharType()) {
6127 // 'unichar' is defined as a typedef of unsigned short, but we should
6128 // prefer using the typedef if it is visible.
6129 IntendedTy = S.Context.UnsignedShortTy;
6131 // While we are here, check if the value is an IntegerLiteral that happens
6132 // to be within the valid range.
6133 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
6134 const llvm::APInt &V = IL->getValue();
6135 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
6139 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
6140 Sema::LookupOrdinaryName);
6141 if (S.LookupName(Result, S.getCurScope())) {
6142 NamedDecl *ND = Result.getFoundDecl();
6143 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
6144 if (TD->getUnderlyingType() == IntendedTy)
6145 IntendedTy = S.Context.getTypedefType(TD);
6150 // Special-case some of Darwin's platform-independence types by suggesting
6151 // casts to primitive types that are known to be large enough.
6152 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
6153 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
6155 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
6156 if (!CastTy.isNull()) {
6157 IntendedTy = CastTy;
6158 ShouldNotPrintDirectly = true;
6162 // We may be able to offer a FixItHint if it is a supported type.
6163 PrintfSpecifier fixedFS = FS;
6165 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
6168 // Get the fix string from the fixed format specifier
6169 SmallString<16> buf;
6170 llvm::raw_svector_ostream os(buf);
6171 fixedFS.toString(os);
6173 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
6175 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
6176 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6177 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6178 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6180 // In this case, the specifier is wrong and should be changed to match
6182 EmitFormatDiagnostic(S.PDiag(diag)
6183 << AT.getRepresentativeTypeName(S.Context)
6184 << IntendedTy << IsEnum << E->getSourceRange(),
6186 /*IsStringLocation*/ false, SpecRange,
6187 FixItHint::CreateReplacement(SpecRange, os.str()));
6189 // The canonical type for formatting this value is different from the
6190 // actual type of the expression. (This occurs, for example, with Darwin's
6191 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
6192 // should be printed as 'long' for 64-bit compatibility.)
6193 // Rather than emitting a normal format/argument mismatch, we want to
6194 // add a cast to the recommended type (and correct the format string
6196 SmallString<16> CastBuf;
6197 llvm::raw_svector_ostream CastFix(CastBuf);
6199 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
6202 SmallVector<FixItHint,4> Hints;
6203 if (!AT.matchesType(S.Context, IntendedTy))
6204 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
6206 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
6207 // If there's already a cast present, just replace it.
6208 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
6209 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
6211 } else if (!requiresParensToAddCast(E)) {
6212 // If the expression has high enough precedence,
6213 // just write the C-style cast.
6214 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6217 // Otherwise, add parens around the expression as well as the cast.
6219 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6222 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
6223 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6226 if (ShouldNotPrintDirectly) {
6227 // The expression has a type that should not be printed directly.
6228 // We extract the name from the typedef because we don't want to show
6229 // the underlying type in the diagnostic.
6231 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6232 Name = TypedefTy->getDecl()->getName();
6235 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
6236 << Name << IntendedTy << IsEnum
6237 << E->getSourceRange(),
6238 E->getLocStart(), /*IsStringLocation=*/false,
6241 // In this case, the expression could be printed using a different
6242 // specifier, but we've decided that the specifier is probably correct
6243 // and we should cast instead. Just use the normal warning message.
6244 EmitFormatDiagnostic(
6245 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6246 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
6247 << E->getSourceRange(),
6248 E->getLocStart(), /*IsStringLocation*/false,
6253 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
6255 // Since the warning for passing non-POD types to variadic functions
6256 // was deferred until now, we emit a warning for non-POD
6258 switch (S.isValidVarArgType(ExprTy)) {
6259 case Sema::VAK_Valid:
6260 case Sema::VAK_ValidInCXX11: {
6261 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6262 if (match == analyze_printf::ArgType::NoMatchPedantic) {
6263 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6266 EmitFormatDiagnostic(
6267 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
6268 << IsEnum << CSR << E->getSourceRange(),
6269 E->getLocStart(), /*IsStringLocation*/ false, CSR);
6272 case Sema::VAK_Undefined:
6273 case Sema::VAK_MSVCUndefined:
6274 EmitFormatDiagnostic(
6275 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
6276 << S.getLangOpts().CPlusPlus11
6279 << AT.getRepresentativeTypeName(S.Context)
6281 << E->getSourceRange(),
6282 E->getLocStart(), /*IsStringLocation*/false, CSR);
6283 checkForCStrMembers(AT, E);
6286 case Sema::VAK_Invalid:
6287 if (ExprTy->isObjCObjectType())
6288 EmitFormatDiagnostic(
6289 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
6290 << S.getLangOpts().CPlusPlus11
6293 << AT.getRepresentativeTypeName(S.Context)
6295 << E->getSourceRange(),
6296 E->getLocStart(), /*IsStringLocation*/false, CSR);
6298 // FIXME: If this is an initializer list, suggest removing the braces
6299 // or inserting a cast to the target type.
6300 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
6301 << isa<InitListExpr>(E) << ExprTy << CallType
6302 << AT.getRepresentativeTypeName(S.Context)
6303 << E->getSourceRange();
6307 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
6308 "format string specifier index out of range");
6309 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
6315 //===--- CHECK: Scanf format string checking ------------------------------===//
6318 class CheckScanfHandler : public CheckFormatHandler {
6320 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
6321 const Expr *origFormatExpr, Sema::FormatStringType type,
6322 unsigned firstDataArg, unsigned numDataArgs,
6323 const char *beg, bool hasVAListArg,
6324 ArrayRef<const Expr *> Args, unsigned formatIdx,
6325 bool inFunctionCall, Sema::VariadicCallType CallType,
6326 llvm::SmallBitVector &CheckedVarArgs,
6327 UncoveredArgHandler &UncoveredArg)
6328 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6329 numDataArgs, beg, hasVAListArg, Args, formatIdx,
6330 inFunctionCall, CallType, CheckedVarArgs,
6333 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
6334 const char *startSpecifier,
6335 unsigned specifierLen) override;
6337 bool HandleInvalidScanfConversionSpecifier(
6338 const analyze_scanf::ScanfSpecifier &FS,
6339 const char *startSpecifier,
6340 unsigned specifierLen) override;
6342 void HandleIncompleteScanList(const char *start, const char *end) override;
6344 } // end anonymous namespace
6346 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
6348 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
6349 getLocationOfByte(end), /*IsStringLocation*/true,
6350 getSpecifierRange(start, end - start));
6353 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
6354 const analyze_scanf::ScanfSpecifier &FS,
6355 const char *startSpecifier,
6356 unsigned specifierLen) {
6358 const analyze_scanf::ScanfConversionSpecifier &CS =
6359 FS.getConversionSpecifier();
6361 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6362 getLocationOfByte(CS.getStart()),
6363 startSpecifier, specifierLen,
6364 CS.getStart(), CS.getLength());
6367 bool CheckScanfHandler::HandleScanfSpecifier(
6368 const analyze_scanf::ScanfSpecifier &FS,
6369 const char *startSpecifier,
6370 unsigned specifierLen) {
6371 using namespace analyze_scanf;
6372 using namespace analyze_format_string;
6374 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
6376 // Handle case where '%' and '*' don't consume an argument. These shouldn't
6377 // be used to decide if we are using positional arguments consistently.
6378 if (FS.consumesDataArgument()) {
6381 usesPositionalArgs = FS.usesPositionalArg();
6383 else if (usesPositionalArgs != FS.usesPositionalArg()) {
6384 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6385 startSpecifier, specifierLen);
6390 // Check if the field with is non-zero.
6391 const OptionalAmount &Amt = FS.getFieldWidth();
6392 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
6393 if (Amt.getConstantAmount() == 0) {
6394 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
6395 Amt.getConstantLength());
6396 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
6397 getLocationOfByte(Amt.getStart()),
6398 /*IsStringLocation*/true, R,
6399 FixItHint::CreateRemoval(R));
6403 if (!FS.consumesDataArgument()) {
6404 // FIXME: Technically specifying a precision or field width here
6405 // makes no sense. Worth issuing a warning at some point.
6409 // Consume the argument.
6410 unsigned argIndex = FS.getArgIndex();
6411 if (argIndex < NumDataArgs) {
6412 // The check to see if the argIndex is valid will come later.
6413 // We set the bit here because we may exit early from this
6414 // function if we encounter some other error.
6415 CoveredArgs.set(argIndex);
6418 // Check the length modifier is valid with the given conversion specifier.
6419 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
6420 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6421 diag::warn_format_nonsensical_length);
6422 else if (!FS.hasStandardLengthModifier())
6423 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
6424 else if (!FS.hasStandardLengthConversionCombination())
6425 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6426 diag::warn_format_non_standard_conversion_spec);
6428 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6429 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6431 // The remaining checks depend on the data arguments.
6435 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
6438 // Check that the argument type matches the format specifier.
6439 const Expr *Ex = getDataArg(argIndex);
6443 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
6445 if (!AT.isValid()) {
6449 analyze_format_string::ArgType::MatchKind match =
6450 AT.matchesType(S.Context, Ex->getType());
6451 if (match == analyze_format_string::ArgType::Match) {
6455 ScanfSpecifier fixedFS = FS;
6456 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
6457 S.getLangOpts(), S.Context);
6459 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6460 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6461 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6465 // Get the fix string from the fixed format specifier.
6466 SmallString<128> buf;
6467 llvm::raw_svector_ostream os(buf);
6468 fixedFS.toString(os);
6470 EmitFormatDiagnostic(
6471 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
6472 << Ex->getType() << false << Ex->getSourceRange(),
6474 /*IsStringLocation*/ false,
6475 getSpecifierRange(startSpecifier, specifierLen),
6476 FixItHint::CreateReplacement(
6477 getSpecifierRange(startSpecifier, specifierLen), os.str()));
6479 EmitFormatDiagnostic(S.PDiag(diag)
6480 << AT.getRepresentativeTypeName(S.Context)
6481 << Ex->getType() << false << Ex->getSourceRange(),
6483 /*IsStringLocation*/ false,
6484 getSpecifierRange(startSpecifier, specifierLen));
6490 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
6491 const Expr *OrigFormatExpr,
6492 ArrayRef<const Expr *> Args,
6493 bool HasVAListArg, unsigned format_idx,
6494 unsigned firstDataArg,
6495 Sema::FormatStringType Type,
6496 bool inFunctionCall,
6497 Sema::VariadicCallType CallType,
6498 llvm::SmallBitVector &CheckedVarArgs,
6499 UncoveredArgHandler &UncoveredArg) {
6500 // CHECK: is the format string a wide literal?
6501 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
6502 CheckFormatHandler::EmitFormatDiagnostic(
6503 S, inFunctionCall, Args[format_idx],
6504 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
6505 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
6509 // Str - The format string. NOTE: this is NOT null-terminated!
6510 StringRef StrRef = FExpr->getString();
6511 const char *Str = StrRef.data();
6512 // Account for cases where the string literal is truncated in a declaration.
6513 const ConstantArrayType *T =
6514 S.Context.getAsConstantArrayType(FExpr->getType());
6515 assert(T && "String literal not of constant array type!");
6516 size_t TypeSize = T->getSize().getZExtValue();
6517 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6518 const unsigned numDataArgs = Args.size() - firstDataArg;
6520 // Emit a warning if the string literal is truncated and does not contain an
6521 // embedded null character.
6522 if (TypeSize <= StrRef.size() &&
6523 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
6524 CheckFormatHandler::EmitFormatDiagnostic(
6525 S, inFunctionCall, Args[format_idx],
6526 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
6527 FExpr->getLocStart(),
6528 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
6532 // CHECK: empty format string?
6533 if (StrLen == 0 && numDataArgs > 0) {
6534 CheckFormatHandler::EmitFormatDiagnostic(
6535 S, inFunctionCall, Args[format_idx],
6536 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
6537 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
6541 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
6542 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
6543 Type == Sema::FST_OSTrace) {
6544 CheckPrintfHandler H(
6545 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
6546 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
6547 HasVAListArg, Args, format_idx, inFunctionCall, CallType,
6548 CheckedVarArgs, UncoveredArg);
6550 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
6552 S.Context.getTargetInfo(),
6553 Type == Sema::FST_FreeBSDKPrintf))
6555 } else if (Type == Sema::FST_Scanf) {
6556 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
6557 numDataArgs, Str, HasVAListArg, Args, format_idx,
6558 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
6560 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
6562 S.Context.getTargetInfo()))
6564 } // TODO: handle other formats
6567 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
6568 // Str - The format string. NOTE: this is NOT null-terminated!
6569 StringRef StrRef = FExpr->getString();
6570 const char *Str = StrRef.data();
6571 // Account for cases where the string literal is truncated in a declaration.
6572 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
6573 assert(T && "String literal not of constant array type!");
6574 size_t TypeSize = T->getSize().getZExtValue();
6575 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6576 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
6578 Context.getTargetInfo());
6581 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
6583 // Returns the related absolute value function that is larger, of 0 if one
6585 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
6586 switch (AbsFunction) {
6590 case Builtin::BI__builtin_abs:
6591 return Builtin::BI__builtin_labs;
6592 case Builtin::BI__builtin_labs:
6593 return Builtin::BI__builtin_llabs;
6594 case Builtin::BI__builtin_llabs:
6597 case Builtin::BI__builtin_fabsf:
6598 return Builtin::BI__builtin_fabs;
6599 case Builtin::BI__builtin_fabs:
6600 return Builtin::BI__builtin_fabsl;
6601 case Builtin::BI__builtin_fabsl:
6604 case Builtin::BI__builtin_cabsf:
6605 return Builtin::BI__builtin_cabs;
6606 case Builtin::BI__builtin_cabs:
6607 return Builtin::BI__builtin_cabsl;
6608 case Builtin::BI__builtin_cabsl:
6611 case Builtin::BIabs:
6612 return Builtin::BIlabs;
6613 case Builtin::BIlabs:
6614 return Builtin::BIllabs;
6615 case Builtin::BIllabs:
6618 case Builtin::BIfabsf:
6619 return Builtin::BIfabs;
6620 case Builtin::BIfabs:
6621 return Builtin::BIfabsl;
6622 case Builtin::BIfabsl:
6625 case Builtin::BIcabsf:
6626 return Builtin::BIcabs;
6627 case Builtin::BIcabs:
6628 return Builtin::BIcabsl;
6629 case Builtin::BIcabsl:
6634 // Returns the argument type of the absolute value function.
6635 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
6640 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
6641 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
6642 if (Error != ASTContext::GE_None)
6645 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
6649 if (FT->getNumParams() != 1)
6652 return FT->getParamType(0);
6655 // Returns the best absolute value function, or zero, based on type and
6656 // current absolute value function.
6657 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
6658 unsigned AbsFunctionKind) {
6659 unsigned BestKind = 0;
6660 uint64_t ArgSize = Context.getTypeSize(ArgType);
6661 for (unsigned Kind = AbsFunctionKind; Kind != 0;
6662 Kind = getLargerAbsoluteValueFunction(Kind)) {
6663 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
6664 if (Context.getTypeSize(ParamType) >= ArgSize) {
6667 else if (Context.hasSameType(ParamType, ArgType)) {
6676 enum AbsoluteValueKind {
6682 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
6683 if (T->isIntegralOrEnumerationType())
6685 if (T->isRealFloatingType())
6686 return AVK_Floating;
6687 if (T->isAnyComplexType())
6690 llvm_unreachable("Type not integer, floating, or complex");
6693 // Changes the absolute value function to a different type. Preserves whether
6694 // the function is a builtin.
6695 static unsigned changeAbsFunction(unsigned AbsKind,
6696 AbsoluteValueKind ValueKind) {
6697 switch (ValueKind) {
6702 case Builtin::BI__builtin_fabsf:
6703 case Builtin::BI__builtin_fabs:
6704 case Builtin::BI__builtin_fabsl:
6705 case Builtin::BI__builtin_cabsf:
6706 case Builtin::BI__builtin_cabs:
6707 case Builtin::BI__builtin_cabsl:
6708 return Builtin::BI__builtin_abs;
6709 case Builtin::BIfabsf:
6710 case Builtin::BIfabs:
6711 case Builtin::BIfabsl:
6712 case Builtin::BIcabsf:
6713 case Builtin::BIcabs:
6714 case Builtin::BIcabsl:
6715 return Builtin::BIabs;
6721 case Builtin::BI__builtin_abs:
6722 case Builtin::BI__builtin_labs:
6723 case Builtin::BI__builtin_llabs:
6724 case Builtin::BI__builtin_cabsf:
6725 case Builtin::BI__builtin_cabs:
6726 case Builtin::BI__builtin_cabsl:
6727 return Builtin::BI__builtin_fabsf;
6728 case Builtin::BIabs:
6729 case Builtin::BIlabs:
6730 case Builtin::BIllabs:
6731 case Builtin::BIcabsf:
6732 case Builtin::BIcabs:
6733 case Builtin::BIcabsl:
6734 return Builtin::BIfabsf;
6740 case Builtin::BI__builtin_abs:
6741 case Builtin::BI__builtin_labs:
6742 case Builtin::BI__builtin_llabs:
6743 case Builtin::BI__builtin_fabsf:
6744 case Builtin::BI__builtin_fabs:
6745 case Builtin::BI__builtin_fabsl:
6746 return Builtin::BI__builtin_cabsf;
6747 case Builtin::BIabs:
6748 case Builtin::BIlabs:
6749 case Builtin::BIllabs:
6750 case Builtin::BIfabsf:
6751 case Builtin::BIfabs:
6752 case Builtin::BIfabsl:
6753 return Builtin::BIcabsf;
6756 llvm_unreachable("Unable to convert function");
6759 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
6760 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
6764 switch (FDecl->getBuiltinID()) {
6767 case Builtin::BI__builtin_abs:
6768 case Builtin::BI__builtin_fabs:
6769 case Builtin::BI__builtin_fabsf:
6770 case Builtin::BI__builtin_fabsl:
6771 case Builtin::BI__builtin_labs:
6772 case Builtin::BI__builtin_llabs:
6773 case Builtin::BI__builtin_cabs:
6774 case Builtin::BI__builtin_cabsf:
6775 case Builtin::BI__builtin_cabsl:
6776 case Builtin::BIabs:
6777 case Builtin::BIlabs:
6778 case Builtin::BIllabs:
6779 case Builtin::BIfabs:
6780 case Builtin::BIfabsf:
6781 case Builtin::BIfabsl:
6782 case Builtin::BIcabs:
6783 case Builtin::BIcabsf:
6784 case Builtin::BIcabsl:
6785 return FDecl->getBuiltinID();
6787 llvm_unreachable("Unknown Builtin type");
6790 // If the replacement is valid, emit a note with replacement function.
6791 // Additionally, suggest including the proper header if not already included.
6792 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
6793 unsigned AbsKind, QualType ArgType) {
6794 bool EmitHeaderHint = true;
6795 const char *HeaderName = nullptr;
6796 const char *FunctionName = nullptr;
6797 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
6798 FunctionName = "std::abs";
6799 if (ArgType->isIntegralOrEnumerationType()) {
6800 HeaderName = "cstdlib";
6801 } else if (ArgType->isRealFloatingType()) {
6802 HeaderName = "cmath";
6804 llvm_unreachable("Invalid Type");
6807 // Lookup all std::abs
6808 if (NamespaceDecl *Std = S.getStdNamespace()) {
6809 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
6810 R.suppressDiagnostics();
6811 S.LookupQualifiedName(R, Std);
6813 for (const auto *I : R) {
6814 const FunctionDecl *FDecl = nullptr;
6815 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
6816 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
6818 FDecl = dyn_cast<FunctionDecl>(I);
6823 // Found std::abs(), check that they are the right ones.
6824 if (FDecl->getNumParams() != 1)
6827 // Check that the parameter type can handle the argument.
6828 QualType ParamType = FDecl->getParamDecl(0)->getType();
6829 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
6830 S.Context.getTypeSize(ArgType) <=
6831 S.Context.getTypeSize(ParamType)) {
6832 // Found a function, don't need the header hint.
6833 EmitHeaderHint = false;
6839 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
6840 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
6843 DeclarationName DN(&S.Context.Idents.get(FunctionName));
6844 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
6845 R.suppressDiagnostics();
6846 S.LookupName(R, S.getCurScope());
6848 if (R.isSingleResult()) {
6849 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
6850 if (FD && FD->getBuiltinID() == AbsKind) {
6851 EmitHeaderHint = false;
6855 } else if (!R.empty()) {
6861 S.Diag(Loc, diag::note_replace_abs_function)
6862 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
6867 if (!EmitHeaderHint)
6870 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
6874 template <std::size_t StrLen>
6875 static bool IsStdFunction(const FunctionDecl *FDecl,
6876 const char (&Str)[StrLen]) {
6879 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
6881 if (!FDecl->isInStdNamespace())
6887 // Warn when using the wrong abs() function.
6888 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
6889 const FunctionDecl *FDecl) {
6890 if (Call->getNumArgs() != 1)
6893 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
6894 bool IsStdAbs = IsStdFunction(FDecl, "abs");
6895 if (AbsKind == 0 && !IsStdAbs)
6898 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
6899 QualType ParamType = Call->getArg(0)->getType();
6901 // Unsigned types cannot be negative. Suggest removing the absolute value
6903 if (ArgType->isUnsignedIntegerType()) {
6904 const char *FunctionName =
6905 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
6906 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
6907 Diag(Call->getExprLoc(), diag::note_remove_abs)
6909 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
6913 // Taking the absolute value of a pointer is very suspicious, they probably
6914 // wanted to index into an array, dereference a pointer, call a function, etc.
6915 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
6916 unsigned DiagType = 0;
6917 if (ArgType->isFunctionType())
6919 else if (ArgType->isArrayType())
6922 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
6926 // std::abs has overloads which prevent most of the absolute value problems
6931 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
6932 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
6934 // The argument and parameter are the same kind. Check if they are the right
6936 if (ArgValueKind == ParamValueKind) {
6937 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
6940 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
6941 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
6942 << FDecl << ArgType << ParamType;
6944 if (NewAbsKind == 0)
6947 emitReplacement(*this, Call->getExprLoc(),
6948 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
6952 // ArgValueKind != ParamValueKind
6953 // The wrong type of absolute value function was used. Attempt to find the
6955 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
6956 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
6957 if (NewAbsKind == 0)
6960 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
6961 << FDecl << ParamValueKind << ArgValueKind;
6963 emitReplacement(*this, Call->getExprLoc(),
6964 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
6967 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
6968 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
6969 const FunctionDecl *FDecl) {
6970 if (!Call || !FDecl) return;
6972 // Ignore template specializations and macros.
6973 if (inTemplateInstantiation()) return;
6974 if (Call->getExprLoc().isMacroID()) return;
6976 // Only care about the one template argument, two function parameter std::max
6977 if (Call->getNumArgs() != 2) return;
6978 if (!IsStdFunction(FDecl, "max")) return;
6979 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
6980 if (!ArgList) return;
6981 if (ArgList->size() != 1) return;
6983 // Check that template type argument is unsigned integer.
6984 const auto& TA = ArgList->get(0);
6985 if (TA.getKind() != TemplateArgument::Type) return;
6986 QualType ArgType = TA.getAsType();
6987 if (!ArgType->isUnsignedIntegerType()) return;
6989 // See if either argument is a literal zero.
6990 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
6991 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
6992 if (!MTE) return false;
6993 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
6994 if (!Num) return false;
6995 if (Num->getValue() != 0) return false;
6999 const Expr *FirstArg = Call->getArg(0);
7000 const Expr *SecondArg = Call->getArg(1);
7001 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
7002 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
7004 // Only warn when exactly one argument is zero.
7005 if (IsFirstArgZero == IsSecondArgZero) return;
7007 SourceRange FirstRange = FirstArg->getSourceRange();
7008 SourceRange SecondRange = SecondArg->getSourceRange();
7010 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
7012 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
7013 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
7015 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
7016 SourceRange RemovalRange;
7017 if (IsFirstArgZero) {
7018 RemovalRange = SourceRange(FirstRange.getBegin(),
7019 SecondRange.getBegin().getLocWithOffset(-1));
7021 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
7022 SecondRange.getEnd());
7025 Diag(Call->getExprLoc(), diag::note_remove_max_call)
7026 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
7027 << FixItHint::CreateRemoval(RemovalRange);
7030 //===--- CHECK: Standard memory functions ---------------------------------===//
7032 /// \brief Takes the expression passed to the size_t parameter of functions
7033 /// such as memcmp, strncat, etc and warns if it's a comparison.
7035 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
7036 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
7037 IdentifierInfo *FnName,
7038 SourceLocation FnLoc,
7039 SourceLocation RParenLoc) {
7040 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
7044 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
7045 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
7048 SourceRange SizeRange = Size->getSourceRange();
7049 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
7050 << SizeRange << FnName;
7051 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
7052 << FnName << FixItHint::CreateInsertion(
7053 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
7054 << FixItHint::CreateRemoval(RParenLoc);
7055 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
7056 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
7057 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
7063 /// \brief Determine whether the given type is or contains a dynamic class type
7064 /// (e.g., whether it has a vtable).
7065 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
7066 bool &IsContained) {
7067 // Look through array types while ignoring qualifiers.
7068 const Type *Ty = T->getBaseElementTypeUnsafe();
7069 IsContained = false;
7071 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
7072 RD = RD ? RD->getDefinition() : nullptr;
7073 if (!RD || RD->isInvalidDecl())
7076 if (RD->isDynamicClass())
7079 // Check all the fields. If any bases were dynamic, the class is dynamic.
7080 // It's impossible for a class to transitively contain itself by value, so
7081 // infinite recursion is impossible.
7082 for (auto *FD : RD->fields()) {
7084 if (const CXXRecordDecl *ContainedRD =
7085 getContainedDynamicClass(FD->getType(), SubContained)) {
7094 /// \brief If E is a sizeof expression, returns its argument expression,
7095 /// otherwise returns NULL.
7096 static const Expr *getSizeOfExprArg(const Expr *E) {
7097 if (const UnaryExprOrTypeTraitExpr *SizeOf =
7098 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7099 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
7100 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
7105 /// \brief If E is a sizeof expression, returns its argument type.
7106 static QualType getSizeOfArgType(const Expr *E) {
7107 if (const UnaryExprOrTypeTraitExpr *SizeOf =
7108 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7109 if (SizeOf->getKind() == clang::UETT_SizeOf)
7110 return SizeOf->getTypeOfArgument();
7115 /// \brief Check for dangerous or invalid arguments to memset().
7117 /// This issues warnings on known problematic, dangerous or unspecified
7118 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
7121 /// \param Call The call expression to diagnose.
7122 void Sema::CheckMemaccessArguments(const CallExpr *Call,
7124 IdentifierInfo *FnName) {
7127 // It is possible to have a non-standard definition of memset. Validate
7128 // we have enough arguments, and if not, abort further checking.
7129 unsigned ExpectedNumArgs =
7130 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
7131 if (Call->getNumArgs() < ExpectedNumArgs)
7134 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
7135 BId == Builtin::BIstrndup ? 1 : 2);
7137 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
7138 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
7140 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
7141 Call->getLocStart(), Call->getRParenLoc()))
7144 // We have special checking when the length is a sizeof expression.
7145 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
7146 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
7147 llvm::FoldingSetNodeID SizeOfArgID;
7149 // Although widely used, 'bzero' is not a standard function. Be more strict
7150 // with the argument types before allowing diagnostics and only allow the
7151 // form bzero(ptr, sizeof(...)).
7152 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7153 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
7156 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
7157 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
7158 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
7160 QualType DestTy = Dest->getType();
7162 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
7163 PointeeTy = DestPtrTy->getPointeeType();
7165 // Never warn about void type pointers. This can be used to suppress
7167 if (PointeeTy->isVoidType())
7170 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
7171 // actually comparing the expressions for equality. Because computing the
7172 // expression IDs can be expensive, we only do this if the diagnostic is
7175 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
7176 SizeOfArg->getExprLoc())) {
7177 // We only compute IDs for expressions if the warning is enabled, and
7178 // cache the sizeof arg's ID.
7179 if (SizeOfArgID == llvm::FoldingSetNodeID())
7180 SizeOfArg->Profile(SizeOfArgID, Context, true);
7181 llvm::FoldingSetNodeID DestID;
7182 Dest->Profile(DestID, Context, true);
7183 if (DestID == SizeOfArgID) {
7184 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
7185 // over sizeof(src) as well.
7186 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
7187 StringRef ReadableName = FnName->getName();
7189 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
7190 if (UnaryOp->getOpcode() == UO_AddrOf)
7191 ActionIdx = 1; // If its an address-of operator, just remove it.
7192 if (!PointeeTy->isIncompleteType() &&
7193 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
7194 ActionIdx = 2; // If the pointee's size is sizeof(char),
7195 // suggest an explicit length.
7197 // If the function is defined as a builtin macro, do not show macro
7199 SourceLocation SL = SizeOfArg->getExprLoc();
7200 SourceRange DSR = Dest->getSourceRange();
7201 SourceRange SSR = SizeOfArg->getSourceRange();
7202 SourceManager &SM = getSourceManager();
7204 if (SM.isMacroArgExpansion(SL)) {
7205 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
7206 SL = SM.getSpellingLoc(SL);
7207 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
7208 SM.getSpellingLoc(DSR.getEnd()));
7209 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
7210 SM.getSpellingLoc(SSR.getEnd()));
7213 DiagRuntimeBehavior(SL, SizeOfArg,
7214 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
7220 DiagRuntimeBehavior(SL, SizeOfArg,
7221 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
7229 // Also check for cases where the sizeof argument is the exact same
7230 // type as the memory argument, and where it points to a user-defined
7232 if (SizeOfArgTy != QualType()) {
7233 if (PointeeTy->isRecordType() &&
7234 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
7235 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
7236 PDiag(diag::warn_sizeof_pointer_type_memaccess)
7237 << FnName << SizeOfArgTy << ArgIdx
7238 << PointeeTy << Dest->getSourceRange()
7239 << LenExpr->getSourceRange());
7243 } else if (DestTy->isArrayType()) {
7247 if (PointeeTy == QualType())
7250 // Always complain about dynamic classes.
7252 if (const CXXRecordDecl *ContainedRD =
7253 getContainedDynamicClass(PointeeTy, IsContained)) {
7255 unsigned OperationType = 0;
7256 // "overwritten" if we're warning about the destination for any call
7257 // but memcmp; otherwise a verb appropriate to the call.
7258 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
7259 if (BId == Builtin::BImemcpy)
7261 else if(BId == Builtin::BImemmove)
7263 else if (BId == Builtin::BImemcmp)
7267 DiagRuntimeBehavior(
7268 Dest->getExprLoc(), Dest,
7269 PDiag(diag::warn_dyn_class_memaccess)
7270 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
7271 << FnName << IsContained << ContainedRD << OperationType
7272 << Call->getCallee()->getSourceRange());
7273 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
7274 BId != Builtin::BImemset)
7275 DiagRuntimeBehavior(
7276 Dest->getExprLoc(), Dest,
7277 PDiag(diag::warn_arc_object_memaccess)
7278 << ArgIdx << FnName << PointeeTy
7279 << Call->getCallee()->getSourceRange());
7283 DiagRuntimeBehavior(
7284 Dest->getExprLoc(), Dest,
7285 PDiag(diag::note_bad_memaccess_silence)
7286 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
7291 // A little helper routine: ignore addition and subtraction of integer literals.
7292 // This intentionally does not ignore all integer constant expressions because
7293 // we don't want to remove sizeof().
7294 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
7295 Ex = Ex->IgnoreParenCasts();
7298 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
7299 if (!BO || !BO->isAdditiveOp())
7302 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
7303 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
7305 if (isa<IntegerLiteral>(RHS))
7307 else if (isa<IntegerLiteral>(LHS))
7316 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
7317 ASTContext &Context) {
7318 // Only handle constant-sized or VLAs, but not flexible members.
7319 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
7320 // Only issue the FIXIT for arrays of size > 1.
7321 if (CAT->getSize().getSExtValue() <= 1)
7323 } else if (!Ty->isVariableArrayType()) {
7329 // Warn if the user has made the 'size' argument to strlcpy or strlcat
7330 // be the size of the source, instead of the destination.
7331 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
7332 IdentifierInfo *FnName) {
7334 // Don't crash if the user has the wrong number of arguments
7335 unsigned NumArgs = Call->getNumArgs();
7336 if ((NumArgs != 3) && (NumArgs != 4))
7339 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
7340 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
7341 const Expr *CompareWithSrc = nullptr;
7343 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
7344 Call->getLocStart(), Call->getRParenLoc()))
7347 // Look for 'strlcpy(dst, x, sizeof(x))'
7348 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
7349 CompareWithSrc = Ex;
7351 // Look for 'strlcpy(dst, x, strlen(x))'
7352 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
7353 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
7354 SizeCall->getNumArgs() == 1)
7355 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
7359 if (!CompareWithSrc)
7362 // Determine if the argument to sizeof/strlen is equal to the source
7363 // argument. In principle there's all kinds of things you could do
7364 // here, for instance creating an == expression and evaluating it with
7365 // EvaluateAsBooleanCondition, but this uses a more direct technique:
7366 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
7370 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
7371 if (!CompareWithSrcDRE ||
7372 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
7375 const Expr *OriginalSizeArg = Call->getArg(2);
7376 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
7377 << OriginalSizeArg->getSourceRange() << FnName;
7379 // Output a FIXIT hint if the destination is an array (rather than a
7380 // pointer to an array). This could be enhanced to handle some
7381 // pointers if we know the actual size, like if DstArg is 'array+2'
7382 // we could say 'sizeof(array)-2'.
7383 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
7384 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
7387 SmallString<128> sizeString;
7388 llvm::raw_svector_ostream OS(sizeString);
7390 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7393 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
7394 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
7398 /// Check if two expressions refer to the same declaration.
7399 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
7400 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
7401 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
7402 return D1->getDecl() == D2->getDecl();
7406 static const Expr *getStrlenExprArg(const Expr *E) {
7407 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7408 const FunctionDecl *FD = CE->getDirectCallee();
7409 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
7411 return CE->getArg(0)->IgnoreParenCasts();
7416 // Warn on anti-patterns as the 'size' argument to strncat.
7417 // The correct size argument should look like following:
7418 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
7419 void Sema::CheckStrncatArguments(const CallExpr *CE,
7420 IdentifierInfo *FnName) {
7421 // Don't crash if the user has the wrong number of arguments.
7422 if (CE->getNumArgs() < 3)
7424 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
7425 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
7426 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
7428 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
7429 CE->getRParenLoc()))
7432 // Identify common expressions, which are wrongly used as the size argument
7433 // to strncat and may lead to buffer overflows.
7434 unsigned PatternType = 0;
7435 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
7437 if (referToTheSameDecl(SizeOfArg, DstArg))
7440 else if (referToTheSameDecl(SizeOfArg, SrcArg))
7442 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
7443 if (BE->getOpcode() == BO_Sub) {
7444 const Expr *L = BE->getLHS()->IgnoreParenCasts();
7445 const Expr *R = BE->getRHS()->IgnoreParenCasts();
7446 // - sizeof(dst) - strlen(dst)
7447 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
7448 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
7450 // - sizeof(src) - (anything)
7451 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
7456 if (PatternType == 0)
7459 // Generate the diagnostic.
7460 SourceLocation SL = LenArg->getLocStart();
7461 SourceRange SR = LenArg->getSourceRange();
7462 SourceManager &SM = getSourceManager();
7464 // If the function is defined as a builtin macro, do not show macro expansion.
7465 if (SM.isMacroArgExpansion(SL)) {
7466 SL = SM.getSpellingLoc(SL);
7467 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
7468 SM.getSpellingLoc(SR.getEnd()));
7471 // Check if the destination is an array (rather than a pointer to an array).
7472 QualType DstTy = DstArg->getType();
7473 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
7475 if (!isKnownSizeArray) {
7476 if (PatternType == 1)
7477 Diag(SL, diag::warn_strncat_wrong_size) << SR;
7479 Diag(SL, diag::warn_strncat_src_size) << SR;
7483 if (PatternType == 1)
7484 Diag(SL, diag::warn_strncat_large_size) << SR;
7486 Diag(SL, diag::warn_strncat_src_size) << SR;
7488 SmallString<128> sizeString;
7489 llvm::raw_svector_ostream OS(sizeString);
7491 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7494 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7497 Diag(SL, diag::note_strncat_wrong_size)
7498 << FixItHint::CreateReplacement(SR, OS.str());
7501 //===--- CHECK: Return Address of Stack Variable --------------------------===//
7503 static const Expr *EvalVal(const Expr *E,
7504 SmallVectorImpl<const DeclRefExpr *> &refVars,
7505 const Decl *ParentDecl);
7506 static const Expr *EvalAddr(const Expr *E,
7507 SmallVectorImpl<const DeclRefExpr *> &refVars,
7508 const Decl *ParentDecl);
7510 /// CheckReturnStackAddr - Check if a return statement returns the address
7511 /// of a stack variable.
7513 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
7514 SourceLocation ReturnLoc) {
7516 const Expr *stackE = nullptr;
7517 SmallVector<const DeclRefExpr *, 8> refVars;
7519 // Perform checking for returned stack addresses, local blocks,
7520 // label addresses or references to temporaries.
7521 if (lhsType->isPointerType() ||
7522 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
7523 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
7524 } else if (lhsType->isReferenceType()) {
7525 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
7529 return; // Nothing suspicious was found.
7531 // Parameters are initialized in the calling scope, so taking the address
7532 // of a parameter reference doesn't need a warning.
7533 for (auto *DRE : refVars)
7534 if (isa<ParmVarDecl>(DRE->getDecl()))
7537 SourceLocation diagLoc;
7538 SourceRange diagRange;
7539 if (refVars.empty()) {
7540 diagLoc = stackE->getLocStart();
7541 diagRange = stackE->getSourceRange();
7543 // We followed through a reference variable. 'stackE' contains the
7544 // problematic expression but we will warn at the return statement pointing
7545 // at the reference variable. We will later display the "trail" of
7546 // reference variables using notes.
7547 diagLoc = refVars[0]->getLocStart();
7548 diagRange = refVars[0]->getSourceRange();
7551 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
7552 // address of local var
7553 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
7554 << DR->getDecl()->getDeclName() << diagRange;
7555 } else if (isa<BlockExpr>(stackE)) { // local block.
7556 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
7557 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
7558 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
7559 } else { // local temporary.
7560 // If there is an LValue->RValue conversion, then the value of the
7561 // reference type is used, not the reference.
7562 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
7563 if (ICE->getCastKind() == CK_LValueToRValue) {
7567 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
7568 << lhsType->isReferenceType() << diagRange;
7571 // Display the "trail" of reference variables that we followed until we
7572 // found the problematic expression using notes.
7573 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
7574 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
7575 // If this var binds to another reference var, show the range of the next
7576 // var, otherwise the var binds to the problematic expression, in which case
7577 // show the range of the expression.
7578 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
7579 : stackE->getSourceRange();
7580 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
7581 << VD->getDeclName() << range;
7585 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
7586 /// check if the expression in a return statement evaluates to an address
7587 /// to a location on the stack, a local block, an address of a label, or a
7588 /// reference to local temporary. The recursion is used to traverse the
7589 /// AST of the return expression, with recursion backtracking when we
7590 /// encounter a subexpression that (1) clearly does not lead to one of the
7591 /// above problematic expressions (2) is something we cannot determine leads to
7592 /// a problematic expression based on such local checking.
7594 /// Both EvalAddr and EvalVal follow through reference variables to evaluate
7595 /// the expression that they point to. Such variables are added to the
7596 /// 'refVars' vector so that we know what the reference variable "trail" was.
7598 /// EvalAddr processes expressions that are pointers that are used as
7599 /// references (and not L-values). EvalVal handles all other values.
7600 /// At the base case of the recursion is a check for the above problematic
7603 /// This implementation handles:
7605 /// * pointer-to-pointer casts
7606 /// * implicit conversions from array references to pointers
7607 /// * taking the address of fields
7608 /// * arbitrary interplay between "&" and "*" operators
7609 /// * pointer arithmetic from an address of a stack variable
7610 /// * taking the address of an array element where the array is on the stack
7611 static const Expr *EvalAddr(const Expr *E,
7612 SmallVectorImpl<const DeclRefExpr *> &refVars,
7613 const Decl *ParentDecl) {
7614 if (E->isTypeDependent())
7617 // We should only be called for evaluating pointer expressions.
7618 assert((E->getType()->isAnyPointerType() ||
7619 E->getType()->isBlockPointerType() ||
7620 E->getType()->isObjCQualifiedIdType()) &&
7621 "EvalAddr only works on pointers");
7623 E = E->IgnoreParens();
7625 // Our "symbolic interpreter" is just a dispatch off the currently
7626 // viewed AST node. We then recursively traverse the AST by calling
7627 // EvalAddr and EvalVal appropriately.
7628 switch (E->getStmtClass()) {
7629 case Stmt::DeclRefExprClass: {
7630 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7632 // If we leave the immediate function, the lifetime isn't about to end.
7633 if (DR->refersToEnclosingVariableOrCapture())
7636 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
7637 // If this is a reference variable, follow through to the expression that
7639 if (V->hasLocalStorage() &&
7640 V->getType()->isReferenceType() && V->hasInit()) {
7641 // Add the reference variable to the "trail".
7642 refVars.push_back(DR);
7643 return EvalAddr(V->getInit(), refVars, ParentDecl);
7649 case Stmt::UnaryOperatorClass: {
7650 // The only unary operator that make sense to handle here
7651 // is AddrOf. All others don't make sense as pointers.
7652 const UnaryOperator *U = cast<UnaryOperator>(E);
7654 if (U->getOpcode() == UO_AddrOf)
7655 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
7659 case Stmt::BinaryOperatorClass: {
7660 // Handle pointer arithmetic. All other binary operators are not valid
7662 const BinaryOperator *B = cast<BinaryOperator>(E);
7663 BinaryOperatorKind op = B->getOpcode();
7665 if (op != BO_Add && op != BO_Sub)
7668 const Expr *Base = B->getLHS();
7670 // Determine which argument is the real pointer base. It could be
7671 // the RHS argument instead of the LHS.
7672 if (!Base->getType()->isPointerType())
7675 assert(Base->getType()->isPointerType());
7676 return EvalAddr(Base, refVars, ParentDecl);
7679 // For conditional operators we need to see if either the LHS or RHS are
7680 // valid DeclRefExpr*s. If one of them is valid, we return it.
7681 case Stmt::ConditionalOperatorClass: {
7682 const ConditionalOperator *C = cast<ConditionalOperator>(E);
7684 // Handle the GNU extension for missing LHS.
7685 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
7686 if (const Expr *LHSExpr = C->getLHS()) {
7687 // In C++, we can have a throw-expression, which has 'void' type.
7688 if (!LHSExpr->getType()->isVoidType())
7689 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
7693 // In C++, we can have a throw-expression, which has 'void' type.
7694 if (C->getRHS()->getType()->isVoidType())
7697 return EvalAddr(C->getRHS(), refVars, ParentDecl);
7700 case Stmt::BlockExprClass:
7701 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
7702 return E; // local block.
7705 case Stmt::AddrLabelExprClass:
7706 return E; // address of label.
7708 case Stmt::ExprWithCleanupsClass:
7709 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7712 // For casts, we need to handle conversions from arrays to
7713 // pointer values, and pointer-to-pointer conversions.
7714 case Stmt::ImplicitCastExprClass:
7715 case Stmt::CStyleCastExprClass:
7716 case Stmt::CXXFunctionalCastExprClass:
7717 case Stmt::ObjCBridgedCastExprClass:
7718 case Stmt::CXXStaticCastExprClass:
7719 case Stmt::CXXDynamicCastExprClass:
7720 case Stmt::CXXConstCastExprClass:
7721 case Stmt::CXXReinterpretCastExprClass: {
7722 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
7723 switch (cast<CastExpr>(E)->getCastKind()) {
7724 case CK_LValueToRValue:
7726 case CK_BaseToDerived:
7727 case CK_DerivedToBase:
7728 case CK_UncheckedDerivedToBase:
7730 case CK_CPointerToObjCPointerCast:
7731 case CK_BlockPointerToObjCPointerCast:
7732 case CK_AnyPointerToBlockPointerCast:
7733 return EvalAddr(SubExpr, refVars, ParentDecl);
7735 case CK_ArrayToPointerDecay:
7736 return EvalVal(SubExpr, refVars, ParentDecl);
7739 if (SubExpr->getType()->isAnyPointerType() ||
7740 SubExpr->getType()->isBlockPointerType() ||
7741 SubExpr->getType()->isObjCQualifiedIdType())
7742 return EvalAddr(SubExpr, refVars, ParentDecl);
7751 case Stmt::MaterializeTemporaryExprClass:
7752 if (const Expr *Result =
7753 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7754 refVars, ParentDecl))
7758 // Everything else: we simply don't reason about them.
7764 /// EvalVal - This function is complements EvalAddr in the mutual recursion.
7765 /// See the comments for EvalAddr for more details.
7766 static const Expr *EvalVal(const Expr *E,
7767 SmallVectorImpl<const DeclRefExpr *> &refVars,
7768 const Decl *ParentDecl) {
7770 // We should only be called for evaluating non-pointer expressions, or
7771 // expressions with a pointer type that are not used as references but
7773 // are l-values (e.g., DeclRefExpr with a pointer type).
7775 // Our "symbolic interpreter" is just a dispatch off the currently
7776 // viewed AST node. We then recursively traverse the AST by calling
7777 // EvalAddr and EvalVal appropriately.
7779 E = E->IgnoreParens();
7780 switch (E->getStmtClass()) {
7781 case Stmt::ImplicitCastExprClass: {
7782 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
7783 if (IE->getValueKind() == VK_LValue) {
7784 E = IE->getSubExpr();
7790 case Stmt::ExprWithCleanupsClass:
7791 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7794 case Stmt::DeclRefExprClass: {
7795 // When we hit a DeclRefExpr we are looking at code that refers to a
7796 // variable's name. If it's not a reference variable we check if it has
7797 // local storage within the function, and if so, return the expression.
7798 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7800 // If we leave the immediate function, the lifetime isn't about to end.
7801 if (DR->refersToEnclosingVariableOrCapture())
7804 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
7805 // Check if it refers to itself, e.g. "int& i = i;".
7806 if (V == ParentDecl)
7809 if (V->hasLocalStorage()) {
7810 if (!V->getType()->isReferenceType())
7813 // Reference variable, follow through to the expression that
7816 // Add the reference variable to the "trail".
7817 refVars.push_back(DR);
7818 return EvalVal(V->getInit(), refVars, V);
7826 case Stmt::UnaryOperatorClass: {
7827 // The only unary operator that make sense to handle here
7828 // is Deref. All others don't resolve to a "name." This includes
7829 // handling all sorts of rvalues passed to a unary operator.
7830 const UnaryOperator *U = cast<UnaryOperator>(E);
7832 if (U->getOpcode() == UO_Deref)
7833 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
7838 case Stmt::ArraySubscriptExprClass: {
7839 // Array subscripts are potential references to data on the stack. We
7840 // retrieve the DeclRefExpr* for the array variable if it indeed
7841 // has local storage.
7842 const auto *ASE = cast<ArraySubscriptExpr>(E);
7843 if (ASE->isTypeDependent())
7845 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
7848 case Stmt::OMPArraySectionExprClass: {
7849 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
7853 case Stmt::ConditionalOperatorClass: {
7854 // For conditional operators we need to see if either the LHS or RHS are
7855 // non-NULL Expr's. If one is non-NULL, we return it.
7856 const ConditionalOperator *C = cast<ConditionalOperator>(E);
7858 // Handle the GNU extension for missing LHS.
7859 if (const Expr *LHSExpr = C->getLHS()) {
7860 // In C++, we can have a throw-expression, which has 'void' type.
7861 if (!LHSExpr->getType()->isVoidType())
7862 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
7866 // In C++, we can have a throw-expression, which has 'void' type.
7867 if (C->getRHS()->getType()->isVoidType())
7870 return EvalVal(C->getRHS(), refVars, ParentDecl);
7873 // Accesses to members are potential references to data on the stack.
7874 case Stmt::MemberExprClass: {
7875 const MemberExpr *M = cast<MemberExpr>(E);
7877 // Check for indirect access. We only want direct field accesses.
7881 // Check whether the member type is itself a reference, in which case
7882 // we're not going to refer to the member, but to what the member refers
7884 if (M->getMemberDecl()->getType()->isReferenceType())
7887 return EvalVal(M->getBase(), refVars, ParentDecl);
7890 case Stmt::MaterializeTemporaryExprClass:
7891 if (const Expr *Result =
7892 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7893 refVars, ParentDecl))
7898 // Check that we don't return or take the address of a reference to a
7899 // temporary. This is only useful in C++.
7900 if (!E->isTypeDependent() && E->isRValue())
7903 // Everything else: we simply don't reason about them.
7910 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
7911 SourceLocation ReturnLoc,
7913 const AttrVec *Attrs,
7914 const FunctionDecl *FD) {
7915 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
7917 // Check if the return value is null but should not be.
7918 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
7919 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
7920 CheckNonNullExpr(*this, RetValExp))
7921 Diag(ReturnLoc, diag::warn_null_ret)
7922 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
7924 // C++11 [basic.stc.dynamic.allocation]p4:
7925 // If an allocation function declared with a non-throwing
7926 // exception-specification fails to allocate storage, it shall return
7927 // a null pointer. Any other allocation function that fails to allocate
7928 // storage shall indicate failure only by throwing an exception [...]
7930 OverloadedOperatorKind Op = FD->getOverloadedOperator();
7931 if (Op == OO_New || Op == OO_Array_New) {
7932 const FunctionProtoType *Proto
7933 = FD->getType()->castAs<FunctionProtoType>();
7934 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
7935 CheckNonNullExpr(*this, RetValExp))
7936 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
7937 << FD << getLangOpts().CPlusPlus11;
7942 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
7944 /// Check for comparisons of floating point operands using != and ==.
7945 /// Issue a warning if these are no self-comparisons, as they are not likely
7946 /// to do what the programmer intended.
7947 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
7948 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
7949 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
7951 // Special case: check for x == x (which is OK).
7952 // Do not emit warnings for such cases.
7953 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
7954 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
7955 if (DRL->getDecl() == DRR->getDecl())
7958 // Special case: check for comparisons against literals that can be exactly
7959 // represented by APFloat. In such cases, do not emit a warning. This
7960 // is a heuristic: often comparison against such literals are used to
7961 // detect if a value in a variable has not changed. This clearly can
7962 // lead to false negatives.
7963 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
7967 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
7971 // Check for comparisons with builtin types.
7972 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
7973 if (CL->getBuiltinCallee())
7976 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
7977 if (CR->getBuiltinCallee())
7980 // Emit the diagnostic.
7981 Diag(Loc, diag::warn_floatingpoint_eq)
7982 << LHS->getSourceRange() << RHS->getSourceRange();
7985 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
7986 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
7990 /// Structure recording the 'active' range of an integer-valued
7993 /// The number of bits active in the int.
7996 /// True if the int is known not to have negative values.
7999 IntRange(unsigned Width, bool NonNegative)
8000 : Width(Width), NonNegative(NonNegative)
8003 /// Returns the range of the bool type.
8004 static IntRange forBoolType() {
8005 return IntRange(1, true);
8008 /// Returns the range of an opaque value of the given integral type.
8009 static IntRange forValueOfType(ASTContext &C, QualType T) {
8010 return forValueOfCanonicalType(C,
8011 T->getCanonicalTypeInternal().getTypePtr());
8014 /// Returns the range of an opaque value of a canonical integral type.
8015 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
8016 assert(T->isCanonicalUnqualified());
8018 if (const VectorType *VT = dyn_cast<VectorType>(T))
8019 T = VT->getElementType().getTypePtr();
8020 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8021 T = CT->getElementType().getTypePtr();
8022 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8023 T = AT->getValueType().getTypePtr();
8025 // For enum types, use the known bit width of the enumerators.
8026 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
8027 EnumDecl *Enum = ET->getDecl();
8028 if (!Enum->isCompleteDefinition())
8029 return IntRange(C.getIntWidth(QualType(T, 0)), false);
8031 unsigned NumPositive = Enum->getNumPositiveBits();
8032 unsigned NumNegative = Enum->getNumNegativeBits();
8034 if (NumNegative == 0)
8035 return IntRange(NumPositive, true/*NonNegative*/);
8037 return IntRange(std::max(NumPositive + 1, NumNegative),
8038 false/*NonNegative*/);
8041 const BuiltinType *BT = cast<BuiltinType>(T);
8042 assert(BT->isInteger());
8044 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8047 /// Returns the "target" range of a canonical integral type, i.e.
8048 /// the range of values expressible in the type.
8050 /// This matches forValueOfCanonicalType except that enums have the
8051 /// full range of their type, not the range of their enumerators.
8052 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
8053 assert(T->isCanonicalUnqualified());
8055 if (const VectorType *VT = dyn_cast<VectorType>(T))
8056 T = VT->getElementType().getTypePtr();
8057 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8058 T = CT->getElementType().getTypePtr();
8059 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8060 T = AT->getValueType().getTypePtr();
8061 if (const EnumType *ET = dyn_cast<EnumType>(T))
8062 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
8064 const BuiltinType *BT = cast<BuiltinType>(T);
8065 assert(BT->isInteger());
8067 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8070 /// Returns the supremum of two ranges: i.e. their conservative merge.
8071 static IntRange join(IntRange L, IntRange R) {
8072 return IntRange(std::max(L.Width, R.Width),
8073 L.NonNegative && R.NonNegative);
8076 /// Returns the infinum of two ranges: i.e. their aggressive merge.
8077 static IntRange meet(IntRange L, IntRange R) {
8078 return IntRange(std::min(L.Width, R.Width),
8079 L.NonNegative || R.NonNegative);
8083 IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
8084 if (value.isSigned() && value.isNegative())
8085 return IntRange(value.getMinSignedBits(), false);
8087 if (value.getBitWidth() > MaxWidth)
8088 value = value.trunc(MaxWidth);
8090 // isNonNegative() just checks the sign bit without considering
8092 return IntRange(value.getActiveBits(), true);
8095 IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
8096 unsigned MaxWidth) {
8098 return GetValueRange(C, result.getInt(), MaxWidth);
8100 if (result.isVector()) {
8101 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
8102 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
8103 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
8104 R = IntRange::join(R, El);
8109 if (result.isComplexInt()) {
8110 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
8111 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
8112 return IntRange::join(R, I);
8115 // This can happen with lossless casts to intptr_t of "based" lvalues.
8116 // Assume it might use arbitrary bits.
8117 // FIXME: The only reason we need to pass the type in here is to get
8118 // the sign right on this one case. It would be nice if APValue
8120 assert(result.isLValue() || result.isAddrLabelDiff());
8121 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
8124 QualType GetExprType(const Expr *E) {
8125 QualType Ty = E->getType();
8126 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
8127 Ty = AtomicRHS->getValueType();
8131 /// Pseudo-evaluate the given integer expression, estimating the
8132 /// range of values it might take.
8134 /// \param MaxWidth - the width to which the value will be truncated
8135 IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
8136 E = E->IgnoreParens();
8138 // Try a full evaluation first.
8139 Expr::EvalResult result;
8140 if (E->EvaluateAsRValue(result, C))
8141 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
8143 // I think we only want to look through implicit casts here; if the
8144 // user has an explicit widening cast, we should treat the value as
8145 // being of the new, wider type.
8146 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
8147 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
8148 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
8150 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
8152 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
8153 CE->getCastKind() == CK_BooleanToSignedIntegral;
8155 // Assume that non-integer casts can span the full range of the type.
8157 return OutputTypeRange;
8160 = GetExprRange(C, CE->getSubExpr(),
8161 std::min(MaxWidth, OutputTypeRange.Width));
8163 // Bail out if the subexpr's range is as wide as the cast type.
8164 if (SubRange.Width >= OutputTypeRange.Width)
8165 return OutputTypeRange;
8167 // Otherwise, we take the smaller width, and we're non-negative if
8168 // either the output type or the subexpr is.
8169 return IntRange(SubRange.Width,
8170 SubRange.NonNegative || OutputTypeRange.NonNegative);
8173 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
8174 // If we can fold the condition, just take that operand.
8176 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
8177 return GetExprRange(C, CondResult ? CO->getTrueExpr()
8178 : CO->getFalseExpr(),
8181 // Otherwise, conservatively merge.
8182 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
8183 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
8184 return IntRange::join(L, R);
8187 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
8188 switch (BO->getOpcode()) {
8190 // Boolean-valued operations are single-bit and positive.
8199 return IntRange::forBoolType();
8201 // The type of the assignments is the type of the LHS, so the RHS
8202 // is not necessarily the same type.
8211 return IntRange::forValueOfType(C, GetExprType(E));
8213 // Simple assignments just pass through the RHS, which will have
8214 // been coerced to the LHS type.
8217 return GetExprRange(C, BO->getRHS(), MaxWidth);
8219 // Operations with opaque sources are black-listed.
8222 return IntRange::forValueOfType(C, GetExprType(E));
8224 // Bitwise-and uses the *infinum* of the two source ranges.
8227 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
8228 GetExprRange(C, BO->getRHS(), MaxWidth));
8230 // Left shift gets black-listed based on a judgement call.
8232 // ...except that we want to treat '1 << (blah)' as logically
8233 // positive. It's an important idiom.
8234 if (IntegerLiteral *I
8235 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
8236 if (I->getValue() == 1) {
8237 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
8238 return IntRange(R.Width, /*NonNegative*/ true);
8244 return IntRange::forValueOfType(C, GetExprType(E));
8246 // Right shift by a constant can narrow its left argument.
8248 case BO_ShrAssign: {
8249 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8251 // If the shift amount is a positive constant, drop the width by
8254 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
8255 shift.isNonNegative()) {
8256 unsigned zext = shift.getZExtValue();
8257 if (zext >= L.Width)
8258 L.Width = (L.NonNegative ? 0 : 1);
8266 // Comma acts as its right operand.
8268 return GetExprRange(C, BO->getRHS(), MaxWidth);
8270 // Black-list pointer subtractions.
8272 if (BO->getLHS()->getType()->isPointerType())
8273 return IntRange::forValueOfType(C, GetExprType(E));
8276 // The width of a division result is mostly determined by the size
8279 // Don't 'pre-truncate' the operands.
8280 unsigned opWidth = C.getIntWidth(GetExprType(E));
8281 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8283 // If the divisor is constant, use that.
8284 llvm::APSInt divisor;
8285 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
8286 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
8287 if (log2 >= L.Width)
8288 L.Width = (L.NonNegative ? 0 : 1);
8290 L.Width = std::min(L.Width - log2, MaxWidth);
8294 // Otherwise, just use the LHS's width.
8295 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8296 return IntRange(L.Width, L.NonNegative && R.NonNegative);
8299 // The result of a remainder can't be larger than the result of
8302 // Don't 'pre-truncate' the operands.
8303 unsigned opWidth = C.getIntWidth(GetExprType(E));
8304 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8305 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8307 IntRange meet = IntRange::meet(L, R);
8308 meet.Width = std::min(meet.Width, MaxWidth);
8312 // The default behavior is okay for these.
8320 // The default case is to treat the operation as if it were closed
8321 // on the narrowest type that encompasses both operands.
8322 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8323 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
8324 return IntRange::join(L, R);
8327 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
8328 switch (UO->getOpcode()) {
8329 // Boolean-valued operations are white-listed.
8331 return IntRange::forBoolType();
8333 // Operations with opaque sources are black-listed.
8335 case UO_AddrOf: // should be impossible
8336 return IntRange::forValueOfType(C, GetExprType(E));
8339 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
8343 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
8344 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
8346 if (const auto *BitField = E->getSourceBitField())
8347 return IntRange(BitField->getBitWidthValue(C),
8348 BitField->getType()->isUnsignedIntegerOrEnumerationType());
8350 return IntRange::forValueOfType(C, GetExprType(E));
8353 IntRange GetExprRange(ASTContext &C, const Expr *E) {
8354 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
8357 /// Checks whether the given value, which currently has the given
8358 /// source semantics, has the same value when coerced through the
8359 /// target semantics.
8360 bool IsSameFloatAfterCast(const llvm::APFloat &value,
8361 const llvm::fltSemantics &Src,
8362 const llvm::fltSemantics &Tgt) {
8363 llvm::APFloat truncated = value;
8366 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
8367 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
8369 return truncated.bitwiseIsEqual(value);
8372 /// Checks whether the given value, which currently has the given
8373 /// source semantics, has the same value when coerced through the
8374 /// target semantics.
8376 /// The value might be a vector of floats (or a complex number).
8377 bool IsSameFloatAfterCast(const APValue &value,
8378 const llvm::fltSemantics &Src,
8379 const llvm::fltSemantics &Tgt) {
8380 if (value.isFloat())
8381 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
8383 if (value.isVector()) {
8384 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
8385 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
8390 assert(value.isComplexFloat());
8391 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
8392 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
8395 void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
8397 bool IsZero(Sema &S, Expr *E) {
8398 // Suppress cases where we are comparing against an enum constant.
8399 if (const DeclRefExpr *DR =
8400 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
8401 if (isa<EnumConstantDecl>(DR->getDecl()))
8404 // Suppress cases where the '0' value is expanded from a macro.
8405 if (E->getLocStart().isMacroID())
8409 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
8412 bool HasEnumType(Expr *E) {
8413 // Strip off implicit integral promotions.
8414 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8415 if (ICE->getCastKind() != CK_IntegralCast &&
8416 ICE->getCastKind() != CK_NoOp)
8418 E = ICE->getSubExpr();
8421 return E->getType()->isEnumeralType();
8424 void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
8425 // Disable warning in template instantiations.
8426 if (S.inTemplateInstantiation())
8429 BinaryOperatorKind op = E->getOpcode();
8430 if (E->isValueDependent())
8433 if (op == BO_LT && IsZero(S, E->getRHS())) {
8434 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
8435 << "< 0" << "false" << HasEnumType(E->getLHS())
8436 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8437 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
8438 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
8439 << ">= 0" << "true" << HasEnumType(E->getLHS())
8440 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8441 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
8442 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
8443 << "0 >" << "false" << HasEnumType(E->getRHS())
8444 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8445 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
8446 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
8447 << "0 <=" << "true" << HasEnumType(E->getRHS())
8448 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8452 void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant,
8453 Expr *Other, const llvm::APSInt &Value,
8455 // Disable warning in template instantiations.
8456 if (S.inTemplateInstantiation())
8459 // TODO: Investigate using GetExprRange() to get tighter bounds
8460 // on the bit ranges.
8461 QualType OtherT = Other->getType();
8462 if (const auto *AT = OtherT->getAs<AtomicType>())
8463 OtherT = AT->getValueType();
8464 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
8465 unsigned OtherWidth = OtherRange.Width;
8467 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
8469 // 0 values are handled later by CheckTrivialUnsignedComparison().
8470 if ((Value == 0) && (!OtherIsBooleanType))
8473 BinaryOperatorKind op = E->getOpcode();
8476 // Used for diagnostic printout.
8478 LiteralConstant = 0,
8481 } LiteralOrBoolConstant = LiteralConstant;
8483 if (!OtherIsBooleanType) {
8484 QualType ConstantT = Constant->getType();
8485 QualType CommonT = E->getLHS()->getType();
8487 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
8489 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
8490 "comparison with non-integer type");
8492 bool ConstantSigned = ConstantT->isSignedIntegerType();
8493 bool CommonSigned = CommonT->isSignedIntegerType();
8495 bool EqualityOnly = false;
8498 // The common type is signed, therefore no signed to unsigned conversion.
8499 if (!OtherRange.NonNegative) {
8500 // Check that the constant is representable in type OtherT.
8501 if (ConstantSigned) {
8502 if (OtherWidth >= Value.getMinSignedBits())
8504 } else { // !ConstantSigned
8505 if (OtherWidth >= Value.getActiveBits() + 1)
8508 } else { // !OtherSigned
8509 // Check that the constant is representable in type OtherT.
8510 // Negative values are out of range.
8511 if (ConstantSigned) {
8512 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
8514 } else { // !ConstantSigned
8515 if (OtherWidth >= Value.getActiveBits())
8519 } else { // !CommonSigned
8520 if (OtherRange.NonNegative) {
8521 if (OtherWidth >= Value.getActiveBits())
8523 } else { // OtherSigned
8524 assert(!ConstantSigned &&
8525 "Two signed types converted to unsigned types.");
8526 // Check to see if the constant is representable in OtherT.
8527 if (OtherWidth > Value.getActiveBits())
8529 // Check to see if the constant is equivalent to a negative value
8531 if (S.Context.getIntWidth(ConstantT) ==
8532 S.Context.getIntWidth(CommonT) &&
8533 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
8535 // The constant value rests between values that OtherT can represent
8536 // after conversion. Relational comparison still works, but equality
8537 // comparisons will be tautological.
8538 EqualityOnly = true;
8542 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
8544 if (op == BO_EQ || op == BO_NE) {
8545 IsTrue = op == BO_NE;
8546 } else if (EqualityOnly) {
8548 } else if (RhsConstant) {
8549 if (op == BO_GT || op == BO_GE)
8550 IsTrue = !PositiveConstant;
8551 else // op == BO_LT || op == BO_LE
8552 IsTrue = PositiveConstant;
8554 if (op == BO_LT || op == BO_LE)
8555 IsTrue = !PositiveConstant;
8556 else // op == BO_GT || op == BO_GE
8557 IsTrue = PositiveConstant;
8560 // Other isKnownToHaveBooleanValue
8561 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
8562 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
8563 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
8565 static const struct LinkedConditions {
8566 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
8567 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
8568 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
8569 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
8570 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
8571 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
8574 // Constant on LHS. | Constant on RHS. |
8575 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
8576 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
8577 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
8578 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
8579 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
8580 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
8581 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
8584 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
8586 enum ConstantValue ConstVal = Zero;
8587 if (Value.isUnsigned() || Value.isNonNegative()) {
8589 LiteralOrBoolConstant =
8590 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
8592 } else if (Value == 1) {
8593 LiteralOrBoolConstant =
8594 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
8597 LiteralOrBoolConstant = LiteralConstant;
8604 CompareBoolWithConstantResult CmpRes;
8608 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
8611 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
8614 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
8617 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
8620 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
8623 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
8630 if (CmpRes == AFals) {
8632 } else if (CmpRes == ATrue) {
8639 // If this is a comparison to an enum constant, include that
8640 // constant in the diagnostic.
8641 const EnumConstantDecl *ED = nullptr;
8642 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
8643 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
8645 SmallString<64> PrettySourceValue;
8646 llvm::raw_svector_ostream OS(PrettySourceValue);
8648 OS << '\'' << *ED << "' (" << Value << ")";
8652 S.DiagRuntimeBehavior(
8653 E->getOperatorLoc(), E,
8654 S.PDiag(diag::warn_out_of_range_compare)
8655 << OS.str() << LiteralOrBoolConstant
8656 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
8657 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
8660 /// Analyze the operands of the given comparison. Implements the
8661 /// fallback case from AnalyzeComparison.
8662 void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
8663 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8664 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
8667 /// \brief Implements -Wsign-compare.
8669 /// \param E the binary operator to check for warnings
8670 void AnalyzeComparison(Sema &S, BinaryOperator *E) {
8671 // The type the comparison is being performed in.
8672 QualType T = E->getLHS()->getType();
8674 // Only analyze comparison operators where both sides have been converted to
8676 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
8677 return AnalyzeImpConvsInComparison(S, E);
8679 // Don't analyze value-dependent comparisons directly.
8680 if (E->isValueDependent())
8681 return AnalyzeImpConvsInComparison(S, E);
8683 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
8684 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
8686 bool IsComparisonConstant = false;
8688 // Check whether an integer constant comparison results in a value
8689 // of 'true' or 'false'.
8690 if (T->isIntegralType(S.Context)) {
8691 llvm::APSInt RHSValue;
8692 bool IsRHSIntegralLiteral =
8693 RHS->isIntegerConstantExpr(RHSValue, S.Context);
8694 llvm::APSInt LHSValue;
8695 bool IsLHSIntegralLiteral =
8696 LHS->isIntegerConstantExpr(LHSValue, S.Context);
8697 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
8698 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
8699 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
8700 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
8702 IsComparisonConstant =
8703 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
8704 } else if (!T->hasUnsignedIntegerRepresentation())
8705 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
8707 // We don't do anything special if this isn't an unsigned integral
8708 // comparison: we're only interested in integral comparisons, and
8709 // signed comparisons only happen in cases we don't care to warn about.
8711 // We also don't care about value-dependent expressions or expressions
8712 // whose result is a constant.
8713 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
8714 return AnalyzeImpConvsInComparison(S, E);
8716 // Check to see if one of the (unmodified) operands is of different
8718 Expr *signedOperand, *unsignedOperand;
8719 if (LHS->getType()->hasSignedIntegerRepresentation()) {
8720 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
8721 "unsigned comparison between two signed integer expressions?");
8722 signedOperand = LHS;
8723 unsignedOperand = RHS;
8724 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
8725 signedOperand = RHS;
8726 unsignedOperand = LHS;
8728 CheckTrivialUnsignedComparison(S, E);
8729 return AnalyzeImpConvsInComparison(S, E);
8732 // Otherwise, calculate the effective range of the signed operand.
8733 IntRange signedRange = GetExprRange(S.Context, signedOperand);
8735 // Go ahead and analyze implicit conversions in the operands. Note
8736 // that we skip the implicit conversions on both sides.
8737 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
8738 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
8740 // If the signed range is non-negative, -Wsign-compare won't fire,
8741 // but we should still check for comparisons which are always true
8743 if (signedRange.NonNegative)
8744 return CheckTrivialUnsignedComparison(S, E);
8746 // For (in)equality comparisons, if the unsigned operand is a
8747 // constant which cannot collide with a overflowed signed operand,
8748 // then reinterpreting the signed operand as unsigned will not
8749 // change the result of the comparison.
8750 if (E->isEqualityOp()) {
8751 unsigned comparisonWidth = S.Context.getIntWidth(T);
8752 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
8754 // We should never be unable to prove that the unsigned operand is
8756 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
8758 if (unsignedRange.Width < comparisonWidth)
8762 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
8763 S.PDiag(diag::warn_mixed_sign_comparison)
8764 << LHS->getType() << RHS->getType()
8765 << LHS->getSourceRange() << RHS->getSourceRange());
8768 /// Analyzes an attempt to assign the given value to a bitfield.
8770 /// Returns true if there was something fishy about the attempt.
8771 bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
8772 SourceLocation InitLoc) {
8773 assert(Bitfield->isBitField());
8774 if (Bitfield->isInvalidDecl())
8777 // White-list bool bitfields.
8778 QualType BitfieldType = Bitfield->getType();
8779 if (BitfieldType->isBooleanType())
8782 if (BitfieldType->isEnumeralType()) {
8783 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
8784 // If the underlying enum type was not explicitly specified as an unsigned
8785 // type and the enum contain only positive values, MSVC++ will cause an
8786 // inconsistency by storing this as a signed type.
8787 if (S.getLangOpts().CPlusPlus11 &&
8788 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
8789 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
8790 BitfieldEnumDecl->getNumNegativeBits() == 0) {
8791 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
8792 << BitfieldEnumDecl->getNameAsString();
8796 if (Bitfield->getType()->isBooleanType())
8799 // Ignore value- or type-dependent expressions.
8800 if (Bitfield->getBitWidth()->isValueDependent() ||
8801 Bitfield->getBitWidth()->isTypeDependent() ||
8802 Init->isValueDependent() ||
8803 Init->isTypeDependent())
8806 Expr *OriginalInit = Init->IgnoreParenImpCasts();
8807 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
8810 if (!OriginalInit->EvaluateAsInt(Value, S.Context,
8811 Expr::SE_AllowSideEffects)) {
8812 // The RHS is not constant. If the RHS has an enum type, make sure the
8813 // bitfield is wide enough to hold all the values of the enum without
8815 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
8816 EnumDecl *ED = EnumTy->getDecl();
8817 bool SignedBitfield = BitfieldType->isSignedIntegerType();
8819 // Enum types are implicitly signed on Windows, so check if there are any
8820 // negative enumerators to see if the enum was intended to be signed or
8822 bool SignedEnum = ED->getNumNegativeBits() > 0;
8824 // Check for surprising sign changes when assigning enum values to a
8825 // bitfield of different signedness. If the bitfield is signed and we
8826 // have exactly the right number of bits to store this unsigned enum,
8827 // suggest changing the enum to an unsigned type. This typically happens
8828 // on Windows where unfixed enums always use an underlying type of 'int'.
8829 unsigned DiagID = 0;
8830 if (SignedEnum && !SignedBitfield) {
8831 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
8832 } else if (SignedBitfield && !SignedEnum &&
8833 ED->getNumPositiveBits() == FieldWidth) {
8834 DiagID = diag::warn_signed_bitfield_enum_conversion;
8838 S.Diag(InitLoc, DiagID) << Bitfield << ED;
8839 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
8840 SourceRange TypeRange =
8841 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
8842 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
8843 << SignedEnum << TypeRange;
8846 // Compute the required bitwidth. If the enum has negative values, we need
8847 // one more bit than the normal number of positive bits to represent the
8849 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
8850 ED->getNumNegativeBits())
8851 : ED->getNumPositiveBits();
8853 // Check the bitwidth.
8854 if (BitsNeeded > FieldWidth) {
8855 Expr *WidthExpr = Bitfield->getBitWidth();
8856 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
8858 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
8859 << BitsNeeded << ED << WidthExpr->getSourceRange();
8866 unsigned OriginalWidth = Value.getBitWidth();
8868 if (!Value.isSigned() || Value.isNegative())
8869 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
8870 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
8871 OriginalWidth = Value.getMinSignedBits();
8873 if (OriginalWidth <= FieldWidth)
8876 // Compute the value which the bitfield will contain.
8877 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
8878 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
8880 // Check whether the stored value is equal to the original value.
8881 TruncatedValue = TruncatedValue.extend(OriginalWidth);
8882 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
8885 // Special-case bitfields of width 1: booleans are naturally 0/1, and
8886 // therefore don't strictly fit into a signed bitfield of width 1.
8887 if (FieldWidth == 1 && Value == 1)
8890 std::string PrettyValue = Value.toString(10);
8891 std::string PrettyTrunc = TruncatedValue.toString(10);
8893 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
8894 << PrettyValue << PrettyTrunc << OriginalInit->getType()
8895 << Init->getSourceRange();
8900 /// Analyze the given simple or compound assignment for warning-worthy
8902 void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
8903 // Just recurse on the LHS.
8904 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8906 // We want to recurse on the RHS as normal unless we're assigning to
8908 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
8909 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
8910 E->getOperatorLoc())) {
8911 // Recurse, ignoring any implicit conversions on the RHS.
8912 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
8913 E->getOperatorLoc());
8917 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
8920 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
8921 void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
8922 SourceLocation CContext, unsigned diag,
8923 bool pruneControlFlow = false) {
8924 if (pruneControlFlow) {
8925 S.DiagRuntimeBehavior(E->getExprLoc(), E,
8927 << SourceType << T << E->getSourceRange()
8928 << SourceRange(CContext));
8931 S.Diag(E->getExprLoc(), diag)
8932 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
8935 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
8936 void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
8937 unsigned diag, bool pruneControlFlow = false) {
8938 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
8942 /// Diagnose an implicit cast from a floating point value to an integer value.
8943 void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
8945 SourceLocation CContext) {
8946 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
8947 const bool PruneWarnings = S.inTemplateInstantiation();
8949 Expr *InnerE = E->IgnoreParenImpCasts();
8950 // We also want to warn on, e.g., "int i = -1.234"
8951 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
8952 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
8953 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
8955 const bool IsLiteral =
8956 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
8958 llvm::APFloat Value(0.0);
8960 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
8962 return DiagnoseImpCast(S, E, T, CContext,
8963 diag::warn_impcast_float_integer, PruneWarnings);
8966 bool isExact = false;
8968 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
8969 T->hasUnsignedIntegerRepresentation());
8970 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
8971 &isExact) == llvm::APFloat::opOK &&
8973 if (IsLiteral) return;
8974 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
8978 unsigned DiagID = 0;
8980 // Warn on floating point literal to integer.
8981 DiagID = diag::warn_impcast_literal_float_to_integer;
8982 } else if (IntegerValue == 0) {
8983 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
8984 return DiagnoseImpCast(S, E, T, CContext,
8985 diag::warn_impcast_float_integer, PruneWarnings);
8987 // Warn on non-zero to zero conversion.
8988 DiagID = diag::warn_impcast_float_to_integer_zero;
8990 if (IntegerValue.isUnsigned()) {
8991 if (!IntegerValue.isMaxValue()) {
8992 return DiagnoseImpCast(S, E, T, CContext,
8993 diag::warn_impcast_float_integer, PruneWarnings);
8995 } else { // IntegerValue.isSigned()
8996 if (!IntegerValue.isMaxSignedValue() &&
8997 !IntegerValue.isMinSignedValue()) {
8998 return DiagnoseImpCast(S, E, T, CContext,
8999 diag::warn_impcast_float_integer, PruneWarnings);
9002 // Warn on evaluatable floating point expression to integer conversion.
9003 DiagID = diag::warn_impcast_float_to_integer;
9006 // FIXME: Force the precision of the source value down so we don't print
9007 // digits which are usually useless (we don't really care here if we
9008 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
9009 // would automatically print the shortest representation, but it's a bit
9010 // tricky to implement.
9011 SmallString<16> PrettySourceValue;
9012 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
9013 precision = (precision * 59 + 195) / 196;
9014 Value.toString(PrettySourceValue, precision);
9016 SmallString<16> PrettyTargetValue;
9018 PrettyTargetValue = Value.isZero() ? "false" : "true";
9020 IntegerValue.toString(PrettyTargetValue);
9022 if (PruneWarnings) {
9023 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9025 << E->getType() << T.getUnqualifiedType()
9026 << PrettySourceValue << PrettyTargetValue
9027 << E->getSourceRange() << SourceRange(CContext));
9029 S.Diag(E->getExprLoc(), DiagID)
9030 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
9031 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
9035 std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
9036 if (!Range.Width) return "0";
9038 llvm::APSInt ValueInRange = Value;
9039 ValueInRange.setIsSigned(!Range.NonNegative);
9040 ValueInRange = ValueInRange.trunc(Range.Width);
9041 return ValueInRange.toString(10);
9044 bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
9045 if (!isa<ImplicitCastExpr>(Ex))
9048 Expr *InnerE = Ex->IgnoreParenImpCasts();
9049 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
9050 const Type *Source =
9051 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
9052 if (Target->isDependentType())
9055 const BuiltinType *FloatCandidateBT =
9056 dyn_cast<BuiltinType>(ToBool ? Source : Target);
9057 const Type *BoolCandidateType = ToBool ? Target : Source;
9059 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
9060 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
9063 void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
9064 SourceLocation CC) {
9065 unsigned NumArgs = TheCall->getNumArgs();
9066 for (unsigned i = 0; i < NumArgs; ++i) {
9067 Expr *CurrA = TheCall->getArg(i);
9068 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
9071 bool IsSwapped = ((i > 0) &&
9072 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
9073 IsSwapped |= ((i < (NumArgs - 1)) &&
9074 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
9076 // Warn on this floating-point to bool conversion.
9077 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
9078 CurrA->getType(), CC,
9079 diag::warn_impcast_floating_point_to_bool);
9084 void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
9085 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
9089 // Don't warn on functions which have return type nullptr_t.
9090 if (isa<CallExpr>(E))
9093 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
9094 const Expr::NullPointerConstantKind NullKind =
9095 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
9096 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
9099 // Return if target type is a safe conversion.
9100 if (T->isAnyPointerType() || T->isBlockPointerType() ||
9101 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
9104 SourceLocation Loc = E->getSourceRange().getBegin();
9106 // Venture through the macro stacks to get to the source of macro arguments.
9107 // The new location is a better location than the complete location that was
9109 while (S.SourceMgr.isMacroArgExpansion(Loc))
9110 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
9112 while (S.SourceMgr.isMacroArgExpansion(CC))
9113 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
9115 // __null is usually wrapped in a macro. Go up a macro if that is the case.
9116 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
9117 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
9118 Loc, S.SourceMgr, S.getLangOpts());
9119 if (MacroName == "NULL")
9120 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
9123 // Only warn if the null and context location are in the same macro expansion.
9124 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
9127 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
9128 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
9129 << FixItHint::CreateReplacement(Loc,
9130 S.getFixItZeroLiteralForType(T, Loc));
9133 void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9134 ObjCArrayLiteral *ArrayLiteral);
9135 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9136 ObjCDictionaryLiteral *DictionaryLiteral);
9138 /// Check a single element within a collection literal against the
9139 /// target element type.
9140 void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
9141 Expr *Element, unsigned ElementKind) {
9142 // Skip a bitcast to 'id' or qualified 'id'.
9143 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
9144 if (ICE->getCastKind() == CK_BitCast &&
9145 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
9146 Element = ICE->getSubExpr();
9149 QualType ElementType = Element->getType();
9150 ExprResult ElementResult(Element);
9151 if (ElementType->getAs<ObjCObjectPointerType>() &&
9152 S.CheckSingleAssignmentConstraints(TargetElementType,
9155 != Sema::Compatible) {
9156 S.Diag(Element->getLocStart(),
9157 diag::warn_objc_collection_literal_element)
9158 << ElementType << ElementKind << TargetElementType
9159 << Element->getSourceRange();
9162 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
9163 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
9164 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
9165 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
9168 /// Check an Objective-C array literal being converted to the given
9170 void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9171 ObjCArrayLiteral *ArrayLiteral) {
9175 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9179 if (TargetObjCPtr->isUnspecialized() ||
9180 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9181 != S.NSArrayDecl->getCanonicalDecl())
9184 auto TypeArgs = TargetObjCPtr->getTypeArgs();
9185 if (TypeArgs.size() != 1)
9188 QualType TargetElementType = TypeArgs[0];
9189 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
9190 checkObjCCollectionLiteralElement(S, TargetElementType,
9191 ArrayLiteral->getElement(I),
9196 /// Check an Objective-C dictionary literal being converted to the given
9198 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9199 ObjCDictionaryLiteral *DictionaryLiteral) {
9200 if (!S.NSDictionaryDecl)
9203 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9207 if (TargetObjCPtr->isUnspecialized() ||
9208 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9209 != S.NSDictionaryDecl->getCanonicalDecl())
9212 auto TypeArgs = TargetObjCPtr->getTypeArgs();
9213 if (TypeArgs.size() != 2)
9216 QualType TargetKeyType = TypeArgs[0];
9217 QualType TargetObjectType = TypeArgs[1];
9218 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
9219 auto Element = DictionaryLiteral->getKeyValueElement(I);
9220 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
9221 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
9225 // Helper function to filter out cases for constant width constant conversion.
9226 // Don't warn on char array initialization or for non-decimal values.
9227 bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
9228 SourceLocation CC) {
9229 // If initializing from a constant, and the constant starts with '0',
9230 // then it is a binary, octal, or hexadecimal. Allow these constants
9231 // to fill all the bits, even if there is a sign change.
9232 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
9233 const char FirstLiteralCharacter =
9234 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
9235 if (FirstLiteralCharacter == '0')
9239 // If the CC location points to a '{', and the type is char, then assume
9240 // assume it is an array initialization.
9241 if (CC.isValid() && T->isCharType()) {
9242 const char FirstContextCharacter =
9243 S.getSourceManager().getCharacterData(CC)[0];
9244 if (FirstContextCharacter == '{')
9251 void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
9252 SourceLocation CC, bool *ICContext = nullptr) {
9253 if (E->isTypeDependent() || E->isValueDependent()) return;
9255 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
9256 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
9257 if (Source == Target) return;
9258 if (Target->isDependentType()) return;
9260 // If the conversion context location is invalid don't complain. We also
9261 // don't want to emit a warning if the issue occurs from the expansion of
9262 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
9263 // delay this check as long as possible. Once we detect we are in that
9264 // scenario, we just return.
9268 // Diagnose implicit casts to bool.
9269 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
9270 if (isa<StringLiteral>(E))
9271 // Warn on string literal to bool. Checks for string literals in logical
9272 // and expressions, for instance, assert(0 && "error here"), are
9273 // prevented by a check in AnalyzeImplicitConversions().
9274 return DiagnoseImpCast(S, E, T, CC,
9275 diag::warn_impcast_string_literal_to_bool);
9276 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
9277 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
9278 // This covers the literal expressions that evaluate to Objective-C
9280 return DiagnoseImpCast(S, E, T, CC,
9281 diag::warn_impcast_objective_c_literal_to_bool);
9283 if (Source->isPointerType() || Source->canDecayToPointerType()) {
9284 // Warn on pointer to bool conversion that is always true.
9285 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
9290 // Check implicit casts from Objective-C collection literals to specialized
9291 // collection types, e.g., NSArray<NSString *> *.
9292 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
9293 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
9294 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
9295 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
9297 // Strip vector types.
9298 if (isa<VectorType>(Source)) {
9299 if (!isa<VectorType>(Target)) {
9300 if (S.SourceMgr.isInSystemMacro(CC))
9302 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
9305 // If the vector cast is cast between two vectors of the same size, it is
9306 // a bitcast, not a conversion.
9307 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
9310 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
9311 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
9313 if (auto VecTy = dyn_cast<VectorType>(Target))
9314 Target = VecTy->getElementType().getTypePtr();
9316 // Strip complex types.
9317 if (isa<ComplexType>(Source)) {
9318 if (!isa<ComplexType>(Target)) {
9319 if (S.SourceMgr.isInSystemMacro(CC))
9322 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
9325 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
9326 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
9329 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
9330 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
9332 // If the source is floating point...
9333 if (SourceBT && SourceBT->isFloatingPoint()) {
9334 // ...and the target is floating point...
9335 if (TargetBT && TargetBT->isFloatingPoint()) {
9336 // ...then warn if we're dropping FP rank.
9338 // Builtin FP kinds are ordered by increasing FP rank.
9339 if (SourceBT->getKind() > TargetBT->getKind()) {
9340 // Don't warn about float constants that are precisely
9341 // representable in the target type.
9342 Expr::EvalResult result;
9343 if (E->EvaluateAsRValue(result, S.Context)) {
9344 // Value might be a float, a float vector, or a float complex.
9345 if (IsSameFloatAfterCast(result.Val,
9346 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
9347 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
9351 if (S.SourceMgr.isInSystemMacro(CC))
9354 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
9356 // ... or possibly if we're increasing rank, too
9357 else if (TargetBT->getKind() > SourceBT->getKind()) {
9358 if (S.SourceMgr.isInSystemMacro(CC))
9361 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
9366 // If the target is integral, always warn.
9367 if (TargetBT && TargetBT->isInteger()) {
9368 if (S.SourceMgr.isInSystemMacro(CC))
9371 DiagnoseFloatingImpCast(S, E, T, CC);
9374 // Detect the case where a call result is converted from floating-point to
9375 // to bool, and the final argument to the call is converted from bool, to
9376 // discover this typo:
9378 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
9380 // FIXME: This is an incredibly special case; is there some more general
9381 // way to detect this class of misplaced-parentheses bug?
9382 if (Target->isBooleanType() && isa<CallExpr>(E)) {
9383 // Check last argument of function call to see if it is an
9384 // implicit cast from a type matching the type the result
9385 // is being cast to.
9386 CallExpr *CEx = cast<CallExpr>(E);
9387 if (unsigned NumArgs = CEx->getNumArgs()) {
9388 Expr *LastA = CEx->getArg(NumArgs - 1);
9389 Expr *InnerE = LastA->IgnoreParenImpCasts();
9390 if (isa<ImplicitCastExpr>(LastA) &&
9391 InnerE->getType()->isBooleanType()) {
9392 // Warn on this floating-point to bool conversion
9393 DiagnoseImpCast(S, E, T, CC,
9394 diag::warn_impcast_floating_point_to_bool);
9401 DiagnoseNullConversion(S, E, T, CC);
9403 S.DiscardMisalignedMemberAddress(Target, E);
9405 if (!Source->isIntegerType() || !Target->isIntegerType())
9408 // TODO: remove this early return once the false positives for constant->bool
9409 // in templates, macros, etc, are reduced or removed.
9410 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
9413 IntRange SourceRange = GetExprRange(S.Context, E);
9414 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
9416 if (SourceRange.Width > TargetRange.Width) {
9417 // If the source is a constant, use a default-on diagnostic.
9418 // TODO: this should happen for bitfield stores, too.
9419 llvm::APSInt Value(32);
9420 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
9421 if (S.SourceMgr.isInSystemMacro(CC))
9424 std::string PrettySourceValue = Value.toString(10);
9425 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
9427 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9428 S.PDiag(diag::warn_impcast_integer_precision_constant)
9429 << PrettySourceValue << PrettyTargetValue
9430 << E->getType() << T << E->getSourceRange()
9431 << clang::SourceRange(CC));
9435 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
9436 if (S.SourceMgr.isInSystemMacro(CC))
9439 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
9440 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
9441 /* pruneControlFlow */ true);
9442 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
9445 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
9446 SourceRange.NonNegative && Source->isSignedIntegerType()) {
9447 // Warn when doing a signed to signed conversion, warn if the positive
9448 // source value is exactly the width of the target type, which will
9449 // cause a negative value to be stored.
9452 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
9453 !S.SourceMgr.isInSystemMacro(CC)) {
9454 if (isSameWidthConstantConversion(S, E, T, CC)) {
9455 std::string PrettySourceValue = Value.toString(10);
9456 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
9458 S.DiagRuntimeBehavior(
9460 S.PDiag(diag::warn_impcast_integer_precision_constant)
9461 << PrettySourceValue << PrettyTargetValue << E->getType() << T
9462 << E->getSourceRange() << clang::SourceRange(CC));
9467 // Fall through for non-constants to give a sign conversion warning.
9470 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
9471 (!TargetRange.NonNegative && SourceRange.NonNegative &&
9472 SourceRange.Width == TargetRange.Width)) {
9473 if (S.SourceMgr.isInSystemMacro(CC))
9476 unsigned DiagID = diag::warn_impcast_integer_sign;
9478 // Traditionally, gcc has warned about this under -Wsign-compare.
9479 // We also want to warn about it in -Wconversion.
9480 // So if -Wconversion is off, use a completely identical diagnostic
9481 // in the sign-compare group.
9482 // The conditional-checking code will
9484 DiagID = diag::warn_impcast_integer_sign_conditional;
9488 return DiagnoseImpCast(S, E, T, CC, DiagID);
9491 // Diagnose conversions between different enumeration types.
9492 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
9493 // type, to give us better diagnostics.
9494 QualType SourceType = E->getType();
9495 if (!S.getLangOpts().CPlusPlus) {
9496 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9497 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
9498 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
9499 SourceType = S.Context.getTypeDeclType(Enum);
9500 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
9504 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
9505 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
9506 if (SourceEnum->getDecl()->hasNameForLinkage() &&
9507 TargetEnum->getDecl()->hasNameForLinkage() &&
9508 SourceEnum != TargetEnum) {
9509 if (S.SourceMgr.isInSystemMacro(CC))
9512 return DiagnoseImpCast(S, E, SourceType, T, CC,
9513 diag::warn_impcast_different_enum_types);
9517 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9518 SourceLocation CC, QualType T);
9520 void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
9521 SourceLocation CC, bool &ICContext) {
9522 E = E->IgnoreParenImpCasts();
9524 if (isa<ConditionalOperator>(E))
9525 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
9527 AnalyzeImplicitConversions(S, E, CC);
9528 if (E->getType() != T)
9529 return CheckImplicitConversion(S, E, T, CC, &ICContext);
9532 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9533 SourceLocation CC, QualType T) {
9534 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
9536 bool Suspicious = false;
9537 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
9538 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
9540 // If -Wconversion would have warned about either of the candidates
9541 // for a signedness conversion to the context type...
9542 if (!Suspicious) return;
9544 // ...but it's currently ignored...
9545 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
9548 // ...then check whether it would have warned about either of the
9549 // candidates for a signedness conversion to the condition type.
9550 if (E->getType() == T) return;
9553 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
9554 E->getType(), CC, &Suspicious);
9556 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
9557 E->getType(), CC, &Suspicious);
9560 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9561 /// Input argument E is a logical expression.
9562 void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
9563 if (S.getLangOpts().Bool)
9565 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
9568 /// AnalyzeImplicitConversions - Find and report any interesting
9569 /// implicit conversions in the given expression. There are a couple
9570 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
9571 void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
9572 QualType T = OrigE->getType();
9573 Expr *E = OrigE->IgnoreParenImpCasts();
9575 if (E->isTypeDependent() || E->isValueDependent())
9578 // For conditional operators, we analyze the arguments as if they
9579 // were being fed directly into the output.
9580 if (isa<ConditionalOperator>(E)) {
9581 ConditionalOperator *CO = cast<ConditionalOperator>(E);
9582 CheckConditionalOperator(S, CO, CC, T);
9586 // Check implicit argument conversions for function calls.
9587 if (CallExpr *Call = dyn_cast<CallExpr>(E))
9588 CheckImplicitArgumentConversions(S, Call, CC);
9590 // Go ahead and check any implicit conversions we might have skipped.
9591 // The non-canonical typecheck is just an optimization;
9592 // CheckImplicitConversion will filter out dead implicit conversions.
9593 if (E->getType() != T)
9594 CheckImplicitConversion(S, E, T, CC);
9596 // Now continue drilling into this expression.
9598 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
9599 // The bound subexpressions in a PseudoObjectExpr are not reachable
9600 // as transitive children.
9601 // FIXME: Use a more uniform representation for this.
9602 for (auto *SE : POE->semantics())
9603 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
9604 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
9607 // Skip past explicit casts.
9608 if (isa<ExplicitCastExpr>(E)) {
9609 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
9610 return AnalyzeImplicitConversions(S, E, CC);
9613 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9614 // Do a somewhat different check with comparison operators.
9615 if (BO->isComparisonOp())
9616 return AnalyzeComparison(S, BO);
9618 // And with simple assignments.
9619 if (BO->getOpcode() == BO_Assign)
9620 return AnalyzeAssignment(S, BO);
9623 // These break the otherwise-useful invariant below. Fortunately,
9624 // we don't really need to recurse into them, because any internal
9625 // expressions should have been analyzed already when they were
9626 // built into statements.
9627 if (isa<StmtExpr>(E)) return;
9629 // Don't descend into unevaluated contexts.
9630 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
9632 // Now just recurse over the expression's children.
9633 CC = E->getExprLoc();
9634 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
9635 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
9636 for (Stmt *SubStmt : E->children()) {
9637 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
9641 if (IsLogicalAndOperator &&
9642 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
9643 // Ignore checking string literals that are in logical and operators.
9644 // This is a common pattern for asserts.
9646 AnalyzeImplicitConversions(S, ChildExpr, CC);
9649 if (BO && BO->isLogicalOp()) {
9650 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
9651 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
9652 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
9654 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
9655 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
9656 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
9659 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
9660 if (U->getOpcode() == UO_LNot)
9661 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
9664 } // end anonymous namespace
9666 /// Diagnose integer type and any valid implicit convertion to it.
9667 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
9668 // Taking into account implicit conversions,
9669 // allow any integer.
9670 if (!E->getType()->isIntegerType()) {
9671 S.Diag(E->getLocStart(),
9672 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
9675 // Potentially emit standard warnings for implicit conversions if enabled
9676 // using -Wconversion.
9677 CheckImplicitConversion(S, E, IntT, E->getLocStart());
9681 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
9682 // Returns true when emitting a warning about taking the address of a reference.
9683 static bool CheckForReference(Sema &SemaRef, const Expr *E,
9684 const PartialDiagnostic &PD) {
9685 E = E->IgnoreParenImpCasts();
9687 const FunctionDecl *FD = nullptr;
9689 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9690 if (!DRE->getDecl()->getType()->isReferenceType())
9692 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9693 if (!M->getMemberDecl()->getType()->isReferenceType())
9695 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
9696 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
9698 FD = Call->getDirectCallee();
9703 SemaRef.Diag(E->getExprLoc(), PD);
9705 // If possible, point to location of function.
9707 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
9713 // Returns true if the SourceLocation is expanded from any macro body.
9714 // Returns false if the SourceLocation is invalid, is from not in a macro
9715 // expansion, or is from expanded from a top-level macro argument.
9716 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
9717 if (Loc.isInvalid())
9720 while (Loc.isMacroID()) {
9721 if (SM.isMacroBodyExpansion(Loc))
9723 Loc = SM.getImmediateMacroCallerLoc(Loc);
9729 /// \brief Diagnose pointers that are always non-null.
9730 /// \param E the expression containing the pointer
9731 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
9732 /// compared to a null pointer
9733 /// \param IsEqual True when the comparison is equal to a null pointer
9734 /// \param Range Extra SourceRange to highlight in the diagnostic
9735 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
9736 Expr::NullPointerConstantKind NullKind,
9737 bool IsEqual, SourceRange Range) {
9741 // Don't warn inside macros.
9742 if (E->getExprLoc().isMacroID()) {
9743 const SourceManager &SM = getSourceManager();
9744 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
9745 IsInAnyMacroBody(SM, Range.getBegin()))
9748 E = E->IgnoreImpCasts();
9750 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
9752 if (isa<CXXThisExpr>(E)) {
9753 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
9754 : diag::warn_this_bool_conversion;
9755 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
9759 bool IsAddressOf = false;
9761 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9762 if (UO->getOpcode() != UO_AddrOf)
9765 E = UO->getSubExpr();
9769 unsigned DiagID = IsCompare
9770 ? diag::warn_address_of_reference_null_compare
9771 : diag::warn_address_of_reference_bool_conversion;
9772 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
9774 if (CheckForReference(*this, E, PD)) {
9779 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
9780 bool IsParam = isa<NonNullAttr>(NonnullAttr);
9782 llvm::raw_string_ostream S(Str);
9783 E->printPretty(S, nullptr, getPrintingPolicy());
9784 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
9785 : diag::warn_cast_nonnull_to_bool;
9786 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
9787 << E->getSourceRange() << Range << IsEqual;
9788 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
9791 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
9792 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
9793 if (auto *Callee = Call->getDirectCallee()) {
9794 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
9795 ComplainAboutNonnullParamOrCall(A);
9801 // Expect to find a single Decl. Skip anything more complicated.
9802 ValueDecl *D = nullptr;
9803 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
9805 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9806 D = M->getMemberDecl();
9809 // Weak Decls can be null.
9810 if (!D || D->isWeak())
9813 // Check for parameter decl with nonnull attribute
9814 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
9815 if (getCurFunction() &&
9816 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
9817 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
9818 ComplainAboutNonnullParamOrCall(A);
9822 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
9823 auto ParamIter = llvm::find(FD->parameters(), PV);
9824 assert(ParamIter != FD->param_end());
9825 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
9827 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
9828 if (!NonNull->args_size()) {
9829 ComplainAboutNonnullParamOrCall(NonNull);
9833 for (unsigned ArgNo : NonNull->args()) {
9834 if (ArgNo == ParamNo) {
9835 ComplainAboutNonnullParamOrCall(NonNull);
9844 QualType T = D->getType();
9845 const bool IsArray = T->isArrayType();
9846 const bool IsFunction = T->isFunctionType();
9848 // Address of function is used to silence the function warning.
9849 if (IsAddressOf && IsFunction) {
9854 if (!IsAddressOf && !IsFunction && !IsArray)
9857 // Pretty print the expression for the diagnostic.
9859 llvm::raw_string_ostream S(Str);
9860 E->printPretty(S, nullptr, getPrintingPolicy());
9862 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
9863 : diag::warn_impcast_pointer_to_bool;
9870 DiagType = AddressOf;
9871 else if (IsFunction)
9872 DiagType = FunctionPointer;
9874 DiagType = ArrayPointer;
9876 llvm_unreachable("Could not determine diagnostic.");
9877 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
9878 << Range << IsEqual;
9883 // Suggest '&' to silence the function warning.
9884 Diag(E->getExprLoc(), diag::note_function_warning_silence)
9885 << FixItHint::CreateInsertion(E->getLocStart(), "&");
9887 // Check to see if '()' fixit should be emitted.
9888 QualType ReturnType;
9889 UnresolvedSet<4> NonTemplateOverloads;
9890 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
9891 if (ReturnType.isNull())
9895 // There are two cases here. If there is null constant, the only suggest
9896 // for a pointer return type. If the null is 0, then suggest if the return
9897 // type is a pointer or an integer type.
9898 if (!ReturnType->isPointerType()) {
9899 if (NullKind == Expr::NPCK_ZeroExpression ||
9900 NullKind == Expr::NPCK_ZeroLiteral) {
9901 if (!ReturnType->isIntegerType())
9907 } else { // !IsCompare
9908 // For function to bool, only suggest if the function pointer has bool
9910 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
9913 Diag(E->getExprLoc(), diag::note_function_to_function_call)
9914 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
9917 /// Diagnoses "dangerous" implicit conversions within the given
9918 /// expression (which is a full expression). Implements -Wconversion
9919 /// and -Wsign-compare.
9921 /// \param CC the "context" location of the implicit conversion, i.e.
9922 /// the most location of the syntactic entity requiring the implicit
9924 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
9925 // Don't diagnose in unevaluated contexts.
9926 if (isUnevaluatedContext())
9929 // Don't diagnose for value- or type-dependent expressions.
9930 if (E->isTypeDependent() || E->isValueDependent())
9933 // Check for array bounds violations in cases where the check isn't triggered
9934 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
9935 // ArraySubscriptExpr is on the RHS of a variable initialization.
9936 CheckArrayAccess(E);
9938 // This is not the right CC for (e.g.) a variable initialization.
9939 AnalyzeImplicitConversions(*this, E, CC);
9942 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9943 /// Input argument E is a logical expression.
9944 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
9945 ::CheckBoolLikeConversion(*this, E, CC);
9948 /// Diagnose when expression is an integer constant expression and its evaluation
9949 /// results in integer overflow
9950 void Sema::CheckForIntOverflow (Expr *E) {
9951 // Use a work list to deal with nested struct initializers.
9952 SmallVector<Expr *, 2> Exprs(1, E);
9955 Expr *E = Exprs.pop_back_val();
9957 if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
9958 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
9962 if (auto InitList = dyn_cast<InitListExpr>(E))
9963 Exprs.append(InitList->inits().begin(), InitList->inits().end());
9965 if (isa<ObjCBoxedExpr>(E))
9966 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
9967 } while (!Exprs.empty());
9971 /// \brief Visitor for expressions which looks for unsequenced operations on the
9973 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
9974 typedef EvaluatedExprVisitor<SequenceChecker> Base;
9976 /// \brief A tree of sequenced regions within an expression. Two regions are
9977 /// unsequenced if one is an ancestor or a descendent of the other. When we
9978 /// finish processing an expression with sequencing, such as a comma
9979 /// expression, we fold its tree nodes into its parent, since they are
9980 /// unsequenced with respect to nodes we will visit later.
9981 class SequenceTree {
9983 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
9984 unsigned Parent : 31;
9985 unsigned Merged : 1;
9987 SmallVector<Value, 8> Values;
9990 /// \brief A region within an expression which may be sequenced with respect
9991 /// to some other region.
9993 explicit Seq(unsigned N) : Index(N) {}
9995 friend class SequenceTree;
10000 SequenceTree() { Values.push_back(Value(0)); }
10001 Seq root() const { return Seq(0); }
10003 /// \brief Create a new sequence of operations, which is an unsequenced
10004 /// subset of \p Parent. This sequence of operations is sequenced with
10005 /// respect to other children of \p Parent.
10006 Seq allocate(Seq Parent) {
10007 Values.push_back(Value(Parent.Index));
10008 return Seq(Values.size() - 1);
10011 /// \brief Merge a sequence of operations into its parent.
10012 void merge(Seq S) {
10013 Values[S.Index].Merged = true;
10016 /// \brief Determine whether two operations are unsequenced. This operation
10017 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
10018 /// should have been merged into its parent as appropriate.
10019 bool isUnsequenced(Seq Cur, Seq Old) {
10020 unsigned C = representative(Cur.Index);
10021 unsigned Target = representative(Old.Index);
10022 while (C >= Target) {
10025 C = Values[C].Parent;
10031 /// \brief Pick a representative for a sequence.
10032 unsigned representative(unsigned K) {
10033 if (Values[K].Merged)
10034 // Perform path compression as we go.
10035 return Values[K].Parent = representative(Values[K].Parent);
10040 /// An object for which we can track unsequenced uses.
10041 typedef NamedDecl *Object;
10043 /// Different flavors of object usage which we track. We only track the
10044 /// least-sequenced usage of each kind.
10046 /// A read of an object. Multiple unsequenced reads are OK.
10048 /// A modification of an object which is sequenced before the value
10049 /// computation of the expression, such as ++n in C++.
10051 /// A modification of an object which is not sequenced before the value
10052 /// computation of the expression, such as n++.
10053 UK_ModAsSideEffect,
10055 UK_Count = UK_ModAsSideEffect + 1
10059 Usage() : Use(nullptr), Seq() {}
10061 SequenceTree::Seq Seq;
10065 UsageInfo() : Diagnosed(false) {}
10066 Usage Uses[UK_Count];
10067 /// Have we issued a diagnostic for this variable already?
10070 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
10073 /// Sequenced regions within the expression.
10075 /// Declaration modifications and references which we have seen.
10076 UsageInfoMap UsageMap;
10077 /// The region we are currently within.
10078 SequenceTree::Seq Region;
10079 /// Filled in with declarations which were modified as a side-effect
10080 /// (that is, post-increment operations).
10081 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
10082 /// Expressions to check later. We defer checking these to reduce
10084 SmallVectorImpl<Expr *> &WorkList;
10086 /// RAII object wrapping the visitation of a sequenced subexpression of an
10087 /// expression. At the end of this process, the side-effects of the evaluation
10088 /// become sequenced with respect to the value computation of the result, so
10089 /// we downgrade any UK_ModAsSideEffect within the evaluation to
10091 struct SequencedSubexpression {
10092 SequencedSubexpression(SequenceChecker &Self)
10093 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
10094 Self.ModAsSideEffect = &ModAsSideEffect;
10096 ~SequencedSubexpression() {
10097 for (auto &M : llvm::reverse(ModAsSideEffect)) {
10098 UsageInfo &U = Self.UsageMap[M.first];
10099 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
10100 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
10101 SideEffectUsage = M.second;
10103 Self.ModAsSideEffect = OldModAsSideEffect;
10106 SequenceChecker &Self;
10107 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
10108 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
10111 /// RAII object wrapping the visitation of a subexpression which we might
10112 /// choose to evaluate as a constant. If any subexpression is evaluated and
10113 /// found to be non-constant, this allows us to suppress the evaluation of
10114 /// the outer expression.
10115 class EvaluationTracker {
10117 EvaluationTracker(SequenceChecker &Self)
10118 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
10119 Self.EvalTracker = this;
10121 ~EvaluationTracker() {
10122 Self.EvalTracker = Prev;
10124 Prev->EvalOK &= EvalOK;
10127 bool evaluate(const Expr *E, bool &Result) {
10128 if (!EvalOK || E->isValueDependent())
10130 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
10135 SequenceChecker &Self;
10136 EvaluationTracker *Prev;
10140 /// \brief Find the object which is produced by the specified expression,
10142 Object getObject(Expr *E, bool Mod) const {
10143 E = E->IgnoreParenCasts();
10144 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10145 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
10146 return getObject(UO->getSubExpr(), Mod);
10147 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10148 if (BO->getOpcode() == BO_Comma)
10149 return getObject(BO->getRHS(), Mod);
10150 if (Mod && BO->isAssignmentOp())
10151 return getObject(BO->getLHS(), Mod);
10152 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10153 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
10154 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
10155 return ME->getMemberDecl();
10156 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10157 // FIXME: If this is a reference, map through to its value.
10158 return DRE->getDecl();
10162 /// \brief Note that an object was modified or used by an expression.
10163 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
10164 Usage &U = UI.Uses[UK];
10165 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
10166 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
10167 ModAsSideEffect->push_back(std::make_pair(O, U));
10172 /// \brief Check whether a modification or use conflicts with a prior usage.
10173 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
10178 const Usage &U = UI.Uses[OtherKind];
10179 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
10183 Expr *ModOrUse = Ref;
10184 if (OtherKind == UK_Use)
10185 std::swap(Mod, ModOrUse);
10187 SemaRef.Diag(Mod->getExprLoc(),
10188 IsModMod ? diag::warn_unsequenced_mod_mod
10189 : diag::warn_unsequenced_mod_use)
10190 << O << SourceRange(ModOrUse->getExprLoc());
10191 UI.Diagnosed = true;
10194 void notePreUse(Object O, Expr *Use) {
10195 UsageInfo &U = UsageMap[O];
10196 // Uses conflict with other modifications.
10197 checkUsage(O, U, Use, UK_ModAsValue, false);
10199 void notePostUse(Object O, Expr *Use) {
10200 UsageInfo &U = UsageMap[O];
10201 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
10202 addUsage(U, O, Use, UK_Use);
10205 void notePreMod(Object O, Expr *Mod) {
10206 UsageInfo &U = UsageMap[O];
10207 // Modifications conflict with other modifications and with uses.
10208 checkUsage(O, U, Mod, UK_ModAsValue, true);
10209 checkUsage(O, U, Mod, UK_Use, false);
10211 void notePostMod(Object O, Expr *Use, UsageKind UK) {
10212 UsageInfo &U = UsageMap[O];
10213 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
10214 addUsage(U, O, Use, UK);
10218 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
10219 : Base(S.Context), SemaRef(S), Region(Tree.root()),
10220 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
10224 void VisitStmt(Stmt *S) {
10225 // Skip all statements which aren't expressions for now.
10228 void VisitExpr(Expr *E) {
10229 // By default, just recurse to evaluated subexpressions.
10230 Base::VisitStmt(E);
10233 void VisitCastExpr(CastExpr *E) {
10234 Object O = Object();
10235 if (E->getCastKind() == CK_LValueToRValue)
10236 O = getObject(E->getSubExpr(), false);
10245 void VisitBinComma(BinaryOperator *BO) {
10246 // C++11 [expr.comma]p1:
10247 // Every value computation and side effect associated with the left
10248 // expression is sequenced before every value computation and side
10249 // effect associated with the right expression.
10250 SequenceTree::Seq LHS = Tree.allocate(Region);
10251 SequenceTree::Seq RHS = Tree.allocate(Region);
10252 SequenceTree::Seq OldRegion = Region;
10255 SequencedSubexpression SeqLHS(*this);
10257 Visit(BO->getLHS());
10261 Visit(BO->getRHS());
10263 Region = OldRegion;
10265 // Forget that LHS and RHS are sequenced. They are both unsequenced
10266 // with respect to other stuff.
10271 void VisitBinAssign(BinaryOperator *BO) {
10272 // The modification is sequenced after the value computation of the LHS
10273 // and RHS, so check it before inspecting the operands and update the
10275 Object O = getObject(BO->getLHS(), true);
10277 return VisitExpr(BO);
10281 // C++11 [expr.ass]p7:
10282 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
10285 // Therefore, for a compound assignment operator, O is considered used
10286 // everywhere except within the evaluation of E1 itself.
10287 if (isa<CompoundAssignOperator>(BO))
10290 Visit(BO->getLHS());
10292 if (isa<CompoundAssignOperator>(BO))
10293 notePostUse(O, BO);
10295 Visit(BO->getRHS());
10297 // C++11 [expr.ass]p1:
10298 // the assignment is sequenced [...] before the value computation of the
10299 // assignment expression.
10300 // C11 6.5.16/3 has no such rule.
10301 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10302 : UK_ModAsSideEffect);
10305 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
10306 VisitBinAssign(CAO);
10309 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10310 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10311 void VisitUnaryPreIncDec(UnaryOperator *UO) {
10312 Object O = getObject(UO->getSubExpr(), true);
10314 return VisitExpr(UO);
10317 Visit(UO->getSubExpr());
10318 // C++11 [expr.pre.incr]p1:
10319 // the expression ++x is equivalent to x+=1
10320 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10321 : UK_ModAsSideEffect);
10324 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10325 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10326 void VisitUnaryPostIncDec(UnaryOperator *UO) {
10327 Object O = getObject(UO->getSubExpr(), true);
10329 return VisitExpr(UO);
10332 Visit(UO->getSubExpr());
10333 notePostMod(O, UO, UK_ModAsSideEffect);
10336 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
10337 void VisitBinLOr(BinaryOperator *BO) {
10338 // The side-effects of the LHS of an '&&' are sequenced before the
10339 // value computation of the RHS, and hence before the value computation
10340 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
10341 // as if they were unconditionally sequenced.
10342 EvaluationTracker Eval(*this);
10344 SequencedSubexpression Sequenced(*this);
10345 Visit(BO->getLHS());
10349 if (Eval.evaluate(BO->getLHS(), Result)) {
10351 Visit(BO->getRHS());
10353 // Check for unsequenced operations in the RHS, treating it as an
10354 // entirely separate evaluation.
10356 // FIXME: If there are operations in the RHS which are unsequenced
10357 // with respect to operations outside the RHS, and those operations
10358 // are unconditionally evaluated, diagnose them.
10359 WorkList.push_back(BO->getRHS());
10362 void VisitBinLAnd(BinaryOperator *BO) {
10363 EvaluationTracker Eval(*this);
10365 SequencedSubexpression Sequenced(*this);
10366 Visit(BO->getLHS());
10370 if (Eval.evaluate(BO->getLHS(), Result)) {
10372 Visit(BO->getRHS());
10374 WorkList.push_back(BO->getRHS());
10378 // Only visit the condition, unless we can be sure which subexpression will
10380 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
10381 EvaluationTracker Eval(*this);
10383 SequencedSubexpression Sequenced(*this);
10384 Visit(CO->getCond());
10388 if (Eval.evaluate(CO->getCond(), Result))
10389 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
10391 WorkList.push_back(CO->getTrueExpr());
10392 WorkList.push_back(CO->getFalseExpr());
10396 void VisitCallExpr(CallExpr *CE) {
10397 // C++11 [intro.execution]p15:
10398 // When calling a function [...], every value computation and side effect
10399 // associated with any argument expression, or with the postfix expression
10400 // designating the called function, is sequenced before execution of every
10401 // expression or statement in the body of the function [and thus before
10402 // the value computation of its result].
10403 SequencedSubexpression Sequenced(*this);
10404 Base::VisitCallExpr(CE);
10406 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
10409 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
10410 // This is a call, so all subexpressions are sequenced before the result.
10411 SequencedSubexpression Sequenced(*this);
10413 if (!CCE->isListInitialization())
10414 return VisitExpr(CCE);
10416 // In C++11, list initializations are sequenced.
10417 SmallVector<SequenceTree::Seq, 32> Elts;
10418 SequenceTree::Seq Parent = Region;
10419 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
10420 E = CCE->arg_end();
10422 Region = Tree.allocate(Parent);
10423 Elts.push_back(Region);
10427 // Forget that the initializers are sequenced.
10429 for (unsigned I = 0; I < Elts.size(); ++I)
10430 Tree.merge(Elts[I]);
10433 void VisitInitListExpr(InitListExpr *ILE) {
10434 if (!SemaRef.getLangOpts().CPlusPlus11)
10435 return VisitExpr(ILE);
10437 // In C++11, list initializations are sequenced.
10438 SmallVector<SequenceTree::Seq, 32> Elts;
10439 SequenceTree::Seq Parent = Region;
10440 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
10441 Expr *E = ILE->getInit(I);
10443 Region = Tree.allocate(Parent);
10444 Elts.push_back(Region);
10448 // Forget that the initializers are sequenced.
10450 for (unsigned I = 0; I < Elts.size(); ++I)
10451 Tree.merge(Elts[I]);
10454 } // end anonymous namespace
10456 void Sema::CheckUnsequencedOperations(Expr *E) {
10457 SmallVector<Expr *, 8> WorkList;
10458 WorkList.push_back(E);
10459 while (!WorkList.empty()) {
10460 Expr *Item = WorkList.pop_back_val();
10461 SequenceChecker(*this, Item, WorkList);
10465 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
10466 bool IsConstexpr) {
10467 CheckImplicitConversions(E, CheckLoc);
10468 if (!E->isInstantiationDependent())
10469 CheckUnsequencedOperations(E);
10470 if (!IsConstexpr && !E->isValueDependent())
10471 CheckForIntOverflow(E);
10472 DiagnoseMisalignedMembers();
10475 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
10476 FieldDecl *BitField,
10478 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
10481 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
10482 SourceLocation Loc) {
10483 if (!PType->isVariablyModifiedType())
10485 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
10486 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
10489 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
10490 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
10493 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
10494 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
10498 const ArrayType *AT = S.Context.getAsArrayType(PType);
10502 if (AT->getSizeModifier() != ArrayType::Star) {
10503 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
10507 S.Diag(Loc, diag::err_array_star_in_function_definition);
10510 /// CheckParmsForFunctionDef - Check that the parameters of the given
10511 /// function are appropriate for the definition of a function. This
10512 /// takes care of any checks that cannot be performed on the
10513 /// declaration itself, e.g., that the types of each of the function
10514 /// parameters are complete.
10515 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
10516 bool CheckParameterNames) {
10517 bool HasInvalidParm = false;
10518 for (ParmVarDecl *Param : Parameters) {
10519 // C99 6.7.5.3p4: the parameters in a parameter type list in a
10520 // function declarator that is part of a function definition of
10521 // that function shall not have incomplete type.
10523 // This is also C++ [dcl.fct]p6.
10524 if (!Param->isInvalidDecl() &&
10525 RequireCompleteType(Param->getLocation(), Param->getType(),
10526 diag::err_typecheck_decl_incomplete_type)) {
10527 Param->setInvalidDecl();
10528 HasInvalidParm = true;
10531 // C99 6.9.1p5: If the declarator includes a parameter type list, the
10532 // declaration of each parameter shall include an identifier.
10533 if (CheckParameterNames &&
10534 Param->getIdentifier() == nullptr &&
10535 !Param->isImplicit() &&
10536 !getLangOpts().CPlusPlus)
10537 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
10540 // If the function declarator is not part of a definition of that
10541 // function, parameters may have incomplete type and may use the [*]
10542 // notation in their sequences of declarator specifiers to specify
10543 // variable length array types.
10544 QualType PType = Param->getOriginalType();
10545 // FIXME: This diagnostic should point the '[*]' if source-location
10546 // information is added for it.
10547 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
10549 // MSVC destroys objects passed by value in the callee. Therefore a
10550 // function definition which takes such a parameter must be able to call the
10551 // object's destructor. However, we don't perform any direct access check
10553 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
10555 .areArgsDestroyedLeftToRightInCallee()) {
10556 if (!Param->isInvalidDecl()) {
10557 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
10558 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
10559 if (!ClassDecl->isInvalidDecl() &&
10560 !ClassDecl->hasIrrelevantDestructor() &&
10561 !ClassDecl->isDependentContext()) {
10562 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10563 MarkFunctionReferenced(Param->getLocation(), Destructor);
10564 DiagnoseUseOfDecl(Destructor, Param->getLocation());
10570 // Parameters with the pass_object_size attribute only need to be marked
10571 // constant at function definitions. Because we lack information about
10572 // whether we're on a declaration or definition when we're instantiating the
10573 // attribute, we need to check for constness here.
10574 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
10575 if (!Param->getType().isConstQualified())
10576 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
10577 << Attr->getSpelling() << 1;
10580 return HasInvalidParm;
10583 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr
10585 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
10586 ASTContext &Context) {
10587 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
10588 return Context.getDeclAlign(DRE->getDecl());
10590 if (const auto *ME = dyn_cast<MemberExpr>(E))
10591 return Context.getDeclAlign(ME->getMemberDecl());
10596 /// CheckCastAlign - Implements -Wcast-align, which warns when a
10597 /// pointer cast increases the alignment requirements.
10598 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
10599 // This is actually a lot of work to potentially be doing on every
10600 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
10601 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
10604 // Ignore dependent types.
10605 if (T->isDependentType() || Op->getType()->isDependentType())
10608 // Require that the destination be a pointer type.
10609 const PointerType *DestPtr = T->getAs<PointerType>();
10610 if (!DestPtr) return;
10612 // If the destination has alignment 1, we're done.
10613 QualType DestPointee = DestPtr->getPointeeType();
10614 if (DestPointee->isIncompleteType()) return;
10615 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
10616 if (DestAlign.isOne()) return;
10618 // Require that the source be a pointer type.
10619 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
10620 if (!SrcPtr) return;
10621 QualType SrcPointee = SrcPtr->getPointeeType();
10623 // Whitelist casts from cv void*. We already implicitly
10624 // whitelisted casts to cv void*, since they have alignment 1.
10625 // Also whitelist casts involving incomplete types, which implicitly
10626 // includes 'void'.
10627 if (SrcPointee->isIncompleteType()) return;
10629 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
10631 if (auto *CE = dyn_cast<CastExpr>(Op)) {
10632 if (CE->getCastKind() == CK_ArrayToPointerDecay)
10633 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
10634 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
10635 if (UO->getOpcode() == UO_AddrOf)
10636 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
10639 if (SrcAlign >= DestAlign) return;
10641 Diag(TRange.getBegin(), diag::warn_cast_align)
10642 << Op->getType() << T
10643 << static_cast<unsigned>(SrcAlign.getQuantity())
10644 << static_cast<unsigned>(DestAlign.getQuantity())
10645 << TRange << Op->getSourceRange();
10648 /// \brief Check whether this array fits the idiom of a size-one tail padded
10649 /// array member of a struct.
10651 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
10652 /// commonly used to emulate flexible arrays in C89 code.
10653 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
10654 const NamedDecl *ND) {
10655 if (Size != 1 || !ND) return false;
10657 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
10658 if (!FD) return false;
10660 // Don't consider sizes resulting from macro expansions or template argument
10661 // substitution to form C89 tail-padded arrays.
10663 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
10665 TypeLoc TL = TInfo->getTypeLoc();
10666 // Look through typedefs.
10667 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
10668 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
10669 TInfo = TDL->getTypeSourceInfo();
10672 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
10673 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
10674 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
10680 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
10681 if (!RD) return false;
10682 if (RD->isUnion()) return false;
10683 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10684 if (!CRD->isStandardLayout()) return false;
10687 // See if this is the last field decl in the record.
10688 const Decl *D = FD;
10689 while ((D = D->getNextDeclInContext()))
10690 if (isa<FieldDecl>(D))
10695 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
10696 const ArraySubscriptExpr *ASE,
10697 bool AllowOnePastEnd, bool IndexNegated) {
10698 IndexExpr = IndexExpr->IgnoreParenImpCasts();
10699 if (IndexExpr->isValueDependent())
10702 const Type *EffectiveType =
10703 BaseExpr->getType()->getPointeeOrArrayElementType();
10704 BaseExpr = BaseExpr->IgnoreParenCasts();
10705 const ConstantArrayType *ArrayTy =
10706 Context.getAsConstantArrayType(BaseExpr->getType());
10710 llvm::APSInt index;
10711 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
10716 const NamedDecl *ND = nullptr;
10717 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10718 ND = dyn_cast<NamedDecl>(DRE->getDecl());
10719 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
10720 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
10722 if (index.isUnsigned() || !index.isNegative()) {
10723 llvm::APInt size = ArrayTy->getSize();
10724 if (!size.isStrictlyPositive())
10727 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
10728 if (BaseType != EffectiveType) {
10729 // Make sure we're comparing apples to apples when comparing index to size
10730 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
10731 uint64_t array_typesize = Context.getTypeSize(BaseType);
10732 // Handle ptrarith_typesize being zero, such as when casting to void*
10733 if (!ptrarith_typesize) ptrarith_typesize = 1;
10734 if (ptrarith_typesize != array_typesize) {
10735 // There's a cast to a different size type involved
10736 uint64_t ratio = array_typesize / ptrarith_typesize;
10737 // TODO: Be smarter about handling cases where array_typesize is not a
10738 // multiple of ptrarith_typesize
10739 if (ptrarith_typesize * ratio == array_typesize)
10740 size *= llvm::APInt(size.getBitWidth(), ratio);
10744 if (size.getBitWidth() > index.getBitWidth())
10745 index = index.zext(size.getBitWidth());
10746 else if (size.getBitWidth() < index.getBitWidth())
10747 size = size.zext(index.getBitWidth());
10749 // For array subscripting the index must be less than size, but for pointer
10750 // arithmetic also allow the index (offset) to be equal to size since
10751 // computing the next address after the end of the array is legal and
10752 // commonly done e.g. in C++ iterators and range-based for loops.
10753 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
10756 // Also don't warn for arrays of size 1 which are members of some
10757 // structure. These are often used to approximate flexible arrays in C89
10759 if (IsTailPaddedMemberArray(*this, size, ND))
10762 // Suppress the warning if the subscript expression (as identified by the
10763 // ']' location) and the index expression are both from macro expansions
10764 // within a system header.
10766 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
10767 ASE->getRBracketLoc());
10768 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
10769 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
10770 IndexExpr->getLocStart());
10771 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
10776 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
10778 DiagID = diag::warn_array_index_exceeds_bounds;
10780 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10781 PDiag(DiagID) << index.toString(10, true)
10782 << size.toString(10, true)
10783 << (unsigned)size.getLimitedValue(~0U)
10784 << IndexExpr->getSourceRange());
10786 unsigned DiagID = diag::warn_array_index_precedes_bounds;
10788 DiagID = diag::warn_ptr_arith_precedes_bounds;
10789 if (index.isNegative()) index = -index;
10792 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10793 PDiag(DiagID) << index.toString(10, true)
10794 << IndexExpr->getSourceRange());
10798 // Try harder to find a NamedDecl to point at in the note.
10799 while (const ArraySubscriptExpr *ASE =
10800 dyn_cast<ArraySubscriptExpr>(BaseExpr))
10801 BaseExpr = ASE->getBase()->IgnoreParenCasts();
10802 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10803 ND = dyn_cast<NamedDecl>(DRE->getDecl());
10804 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
10805 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
10809 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
10810 PDiag(diag::note_array_index_out_of_bounds)
10811 << ND->getDeclName());
10814 void Sema::CheckArrayAccess(const Expr *expr) {
10815 int AllowOnePastEnd = 0;
10817 expr = expr->IgnoreParenImpCasts();
10818 switch (expr->getStmtClass()) {
10819 case Stmt::ArraySubscriptExprClass: {
10820 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
10821 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
10822 AllowOnePastEnd > 0);
10825 case Stmt::OMPArraySectionExprClass: {
10826 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
10827 if (ASE->getLowerBound())
10828 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
10829 /*ASE=*/nullptr, AllowOnePastEnd > 0);
10832 case Stmt::UnaryOperatorClass: {
10833 // Only unwrap the * and & unary operators
10834 const UnaryOperator *UO = cast<UnaryOperator>(expr);
10835 expr = UO->getSubExpr();
10836 switch (UO->getOpcode()) {
10848 case Stmt::ConditionalOperatorClass: {
10849 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
10850 if (const Expr *lhs = cond->getLHS())
10851 CheckArrayAccess(lhs);
10852 if (const Expr *rhs = cond->getRHS())
10853 CheckArrayAccess(rhs);
10856 case Stmt::CXXOperatorCallExprClass: {
10857 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
10858 for (const auto *Arg : OCE->arguments())
10859 CheckArrayAccess(Arg);
10868 //===--- CHECK: Objective-C retain cycles ----------------------------------//
10871 struct RetainCycleOwner {
10872 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
10875 SourceLocation Loc;
10878 void setLocsFrom(Expr *e) {
10879 Loc = e->getExprLoc();
10880 Range = e->getSourceRange();
10883 } // end anonymous namespace
10885 /// Consider whether capturing the given variable can possibly lead to
10886 /// a retain cycle.
10887 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
10888 // In ARC, it's captured strongly iff the variable has __strong
10889 // lifetime. In MRR, it's captured strongly if the variable is
10890 // __block and has an appropriate type.
10891 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10894 owner.Variable = var;
10896 owner.setLocsFrom(ref);
10900 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
10902 e = e->IgnoreParens();
10903 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
10904 switch (cast->getCastKind()) {
10906 case CK_LValueBitCast:
10907 case CK_LValueToRValue:
10908 case CK_ARCReclaimReturnedObject:
10909 e = cast->getSubExpr();
10917 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
10918 ObjCIvarDecl *ivar = ref->getDecl();
10919 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10922 // Try to find a retain cycle in the base.
10923 if (!findRetainCycleOwner(S, ref->getBase(), owner))
10926 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
10927 owner.Indirect = true;
10931 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
10932 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
10933 if (!var) return false;
10934 return considerVariable(var, ref, owner);
10937 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
10938 if (member->isArrow()) return false;
10940 // Don't count this as an indirect ownership.
10941 e = member->getBase();
10945 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
10946 // Only pay attention to pseudo-objects on property references.
10947 ObjCPropertyRefExpr *pre
10948 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
10950 if (!pre) return false;
10951 if (pre->isImplicitProperty()) return false;
10952 ObjCPropertyDecl *property = pre->getExplicitProperty();
10953 if (!property->isRetaining() &&
10954 !(property->getPropertyIvarDecl() &&
10955 property->getPropertyIvarDecl()->getType()
10956 .getObjCLifetime() == Qualifiers::OCL_Strong))
10959 owner.Indirect = true;
10960 if (pre->isSuperReceiver()) {
10961 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
10962 if (!owner.Variable)
10964 owner.Loc = pre->getLocation();
10965 owner.Range = pre->getSourceRange();
10968 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
10969 ->getSourceExpr());
10980 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
10981 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
10982 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
10983 Context(Context), Variable(variable), Capturer(nullptr),
10984 VarWillBeReased(false) {}
10985 ASTContext &Context;
10988 bool VarWillBeReased;
10990 void VisitDeclRefExpr(DeclRefExpr *ref) {
10991 if (ref->getDecl() == Variable && !Capturer)
10995 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
10996 if (Capturer) return;
10997 Visit(ref->getBase());
10998 if (Capturer && ref->isFreeIvar())
11002 void VisitBlockExpr(BlockExpr *block) {
11003 // Look inside nested blocks
11004 if (block->getBlockDecl()->capturesVariable(Variable))
11005 Visit(block->getBlockDecl()->getBody());
11008 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
11009 if (Capturer) return;
11010 if (OVE->getSourceExpr())
11011 Visit(OVE->getSourceExpr());
11013 void VisitBinaryOperator(BinaryOperator *BinOp) {
11014 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
11016 Expr *LHS = BinOp->getLHS();
11017 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
11018 if (DRE->getDecl() != Variable)
11020 if (Expr *RHS = BinOp->getRHS()) {
11021 RHS = RHS->IgnoreParenCasts();
11022 llvm::APSInt Value;
11024 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
11029 } // end anonymous namespace
11031 /// Check whether the given argument is a block which captures a
11033 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
11034 assert(owner.Variable && owner.Loc.isValid());
11036 e = e->IgnoreParenCasts();
11038 // Look through [^{...} copy] and Block_copy(^{...}).
11039 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
11040 Selector Cmd = ME->getSelector();
11041 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
11042 e = ME->getInstanceReceiver();
11045 e = e->IgnoreParenCasts();
11047 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
11048 if (CE->getNumArgs() == 1) {
11049 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
11051 const IdentifierInfo *FnI = Fn->getIdentifier();
11052 if (FnI && FnI->isStr("_Block_copy")) {
11053 e = CE->getArg(0)->IgnoreParenCasts();
11059 BlockExpr *block = dyn_cast<BlockExpr>(e);
11060 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
11063 FindCaptureVisitor visitor(S.Context, owner.Variable);
11064 visitor.Visit(block->getBlockDecl()->getBody());
11065 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
11068 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
11069 RetainCycleOwner &owner) {
11071 assert(owner.Variable && owner.Loc.isValid());
11073 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
11074 << owner.Variable << capturer->getSourceRange();
11075 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
11076 << owner.Indirect << owner.Range;
11079 /// Check for a keyword selector that starts with the word 'add' or
11081 static bool isSetterLikeSelector(Selector sel) {
11082 if (sel.isUnarySelector()) return false;
11084 StringRef str = sel.getNameForSlot(0);
11085 while (!str.empty() && str.front() == '_') str = str.substr(1);
11086 if (str.startswith("set"))
11087 str = str.substr(3);
11088 else if (str.startswith("add")) {
11089 // Specially whitelist 'addOperationWithBlock:'.
11090 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
11092 str = str.substr(3);
11097 if (str.empty()) return true;
11098 return !isLowercase(str.front());
11101 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
11102 ObjCMessageExpr *Message) {
11103 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
11104 Message->getReceiverInterface(),
11105 NSAPI::ClassId_NSMutableArray);
11106 if (!IsMutableArray) {
11110 Selector Sel = Message->getSelector();
11112 Optional<NSAPI::NSArrayMethodKind> MKOpt =
11113 S.NSAPIObj->getNSArrayMethodKind(Sel);
11118 NSAPI::NSArrayMethodKind MK = *MKOpt;
11121 case NSAPI::NSMutableArr_addObject:
11122 case NSAPI::NSMutableArr_insertObjectAtIndex:
11123 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
11125 case NSAPI::NSMutableArr_replaceObjectAtIndex:
11136 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
11137 ObjCMessageExpr *Message) {
11138 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
11139 Message->getReceiverInterface(),
11140 NSAPI::ClassId_NSMutableDictionary);
11141 if (!IsMutableDictionary) {
11145 Selector Sel = Message->getSelector();
11147 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
11148 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
11153 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
11156 case NSAPI::NSMutableDict_setObjectForKey:
11157 case NSAPI::NSMutableDict_setValueForKey:
11158 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
11168 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
11169 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
11170 Message->getReceiverInterface(),
11171 NSAPI::ClassId_NSMutableSet);
11173 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
11174 Message->getReceiverInterface(),
11175 NSAPI::ClassId_NSMutableOrderedSet);
11176 if (!IsMutableSet && !IsMutableOrderedSet) {
11180 Selector Sel = Message->getSelector();
11182 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
11187 NSAPI::NSSetMethodKind MK = *MKOpt;
11190 case NSAPI::NSMutableSet_addObject:
11191 case NSAPI::NSOrderedSet_setObjectAtIndex:
11192 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
11193 case NSAPI::NSOrderedSet_insertObjectAtIndex:
11195 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
11202 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
11203 if (!Message->isInstanceMessage()) {
11207 Optional<int> ArgOpt;
11209 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
11210 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
11211 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
11215 int ArgIndex = *ArgOpt;
11217 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
11218 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
11219 Arg = OE->getSourceExpr()->IgnoreImpCasts();
11222 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
11223 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
11224 if (ArgRE->isObjCSelfExpr()) {
11225 Diag(Message->getSourceRange().getBegin(),
11226 diag::warn_objc_circular_container)
11227 << ArgRE->getDecl()->getName() << StringRef("super");
11231 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
11233 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
11234 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
11237 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
11238 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
11239 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
11240 ValueDecl *Decl = ReceiverRE->getDecl();
11241 Diag(Message->getSourceRange().getBegin(),
11242 diag::warn_objc_circular_container)
11243 << Decl->getName() << Decl->getName();
11244 if (!ArgRE->isObjCSelfExpr()) {
11245 Diag(Decl->getLocation(),
11246 diag::note_objc_circular_container_declared_here)
11247 << Decl->getName();
11251 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
11252 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
11253 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
11254 ObjCIvarDecl *Decl = IvarRE->getDecl();
11255 Diag(Message->getSourceRange().getBegin(),
11256 diag::warn_objc_circular_container)
11257 << Decl->getName() << Decl->getName();
11258 Diag(Decl->getLocation(),
11259 diag::note_objc_circular_container_declared_here)
11260 << Decl->getName();
11267 /// Check a message send to see if it's likely to cause a retain cycle.
11268 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
11269 // Only check instance methods whose selector looks like a setter.
11270 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
11273 // Try to find a variable that the receiver is strongly owned by.
11274 RetainCycleOwner owner;
11275 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
11276 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
11279 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
11280 owner.Variable = getCurMethodDecl()->getSelfDecl();
11281 owner.Loc = msg->getSuperLoc();
11282 owner.Range = msg->getSuperLoc();
11285 // Check whether the receiver is captured by any of the arguments.
11286 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
11287 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
11288 return diagnoseRetainCycle(*this, capturer, owner);
11291 /// Check a property assign to see if it's likely to cause a retain cycle.
11292 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
11293 RetainCycleOwner owner;
11294 if (!findRetainCycleOwner(*this, receiver, owner))
11297 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
11298 diagnoseRetainCycle(*this, capturer, owner);
11301 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
11302 RetainCycleOwner Owner;
11303 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
11306 // Because we don't have an expression for the variable, we have to set the
11307 // location explicitly here.
11308 Owner.Loc = Var->getLocation();
11309 Owner.Range = Var->getSourceRange();
11311 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
11312 diagnoseRetainCycle(*this, Capturer, Owner);
11315 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
11316 Expr *RHS, bool isProperty) {
11317 // Check if RHS is an Objective-C object literal, which also can get
11318 // immediately zapped in a weak reference. Note that we explicitly
11319 // allow ObjCStringLiterals, since those are designed to never really die.
11320 RHS = RHS->IgnoreParenImpCasts();
11322 // This enum needs to match with the 'select' in
11323 // warn_objc_arc_literal_assign (off-by-1).
11324 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
11325 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
11328 S.Diag(Loc, diag::warn_arc_literal_assign)
11330 << (isProperty ? 0 : 1)
11331 << RHS->getSourceRange();
11336 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
11337 Qualifiers::ObjCLifetime LT,
11338 Expr *RHS, bool isProperty) {
11339 // Strip off any implicit cast added to get to the one ARC-specific.
11340 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11341 if (cast->getCastKind() == CK_ARCConsumeObject) {
11342 S.Diag(Loc, diag::warn_arc_retained_assign)
11343 << (LT == Qualifiers::OCL_ExplicitNone)
11344 << (isProperty ? 0 : 1)
11345 << RHS->getSourceRange();
11348 RHS = cast->getSubExpr();
11351 if (LT == Qualifiers::OCL_Weak &&
11352 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
11358 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
11359 QualType LHS, Expr *RHS) {
11360 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
11362 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
11365 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
11371 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
11372 Expr *LHS, Expr *RHS) {
11374 // PropertyRef on LHS type need be directly obtained from
11375 // its declaration as it has a PseudoType.
11376 ObjCPropertyRefExpr *PRE
11377 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
11378 if (PRE && !PRE->isImplicitProperty()) {
11379 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11381 LHSType = PD->getType();
11384 if (LHSType.isNull())
11385 LHSType = LHS->getType();
11387 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
11389 if (LT == Qualifiers::OCL_Weak) {
11390 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
11391 getCurFunction()->markSafeWeakUse(LHS);
11394 if (checkUnsafeAssigns(Loc, LHSType, RHS))
11397 // FIXME. Check for other life times.
11398 if (LT != Qualifiers::OCL_None)
11402 if (PRE->isImplicitProperty())
11404 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11408 unsigned Attributes = PD->getPropertyAttributes();
11409 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
11410 // when 'assign' attribute was not explicitly specified
11411 // by user, ignore it and rely on property type itself
11412 // for lifetime info.
11413 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
11414 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
11415 LHSType->isObjCRetainableType())
11418 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11419 if (cast->getCastKind() == CK_ARCConsumeObject) {
11420 Diag(Loc, diag::warn_arc_retained_property_assign)
11421 << RHS->getSourceRange();
11424 RHS = cast->getSubExpr();
11427 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
11428 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
11434 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
11437 bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
11438 SourceLocation StmtLoc,
11439 const NullStmt *Body) {
11440 // Do not warn if the body is a macro that expands to nothing, e.g:
11446 if (Body->hasLeadingEmptyMacro())
11449 // Get line numbers of statement and body.
11450 bool StmtLineInvalid;
11451 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
11453 if (StmtLineInvalid)
11456 bool BodyLineInvalid;
11457 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
11459 if (BodyLineInvalid)
11462 // Warn if null statement and body are on the same line.
11463 if (StmtLine != BodyLine)
11468 } // end anonymous namespace
11470 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
11473 // Since this is a syntactic check, don't emit diagnostic for template
11474 // instantiations, this just adds noise.
11475 if (CurrentInstantiationScope)
11478 // The body should be a null statement.
11479 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11483 // Do the usual checks.
11484 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11487 Diag(NBody->getSemiLoc(), DiagID);
11488 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11491 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
11492 const Stmt *PossibleBody) {
11493 assert(!CurrentInstantiationScope); // Ensured by caller
11495 SourceLocation StmtLoc;
11498 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
11499 StmtLoc = FS->getRParenLoc();
11500 Body = FS->getBody();
11501 DiagID = diag::warn_empty_for_body;
11502 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
11503 StmtLoc = WS->getCond()->getSourceRange().getEnd();
11504 Body = WS->getBody();
11505 DiagID = diag::warn_empty_while_body;
11507 return; // Neither `for' nor `while'.
11509 // The body should be a null statement.
11510 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11514 // Skip expensive checks if diagnostic is disabled.
11515 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
11518 // Do the usual checks.
11519 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11522 // `for(...);' and `while(...);' are popular idioms, so in order to keep
11523 // noise level low, emit diagnostics only if for/while is followed by a
11524 // CompoundStmt, e.g.:
11525 // for (int i = 0; i < n; i++);
11529 // or if for/while is followed by a statement with more indentation
11530 // than for/while itself:
11531 // for (int i = 0; i < n; i++);
11533 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
11534 if (!ProbableTypo) {
11535 bool BodyColInvalid;
11536 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
11537 PossibleBody->getLocStart(),
11539 if (BodyColInvalid)
11542 bool StmtColInvalid;
11543 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
11546 if (StmtColInvalid)
11549 if (BodyCol > StmtCol)
11550 ProbableTypo = true;
11553 if (ProbableTypo) {
11554 Diag(NBody->getSemiLoc(), DiagID);
11555 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11559 //===--- CHECK: Warn on self move with std::move. -------------------------===//
11561 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
11562 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
11563 SourceLocation OpLoc) {
11564 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
11567 if (inTemplateInstantiation())
11570 // Strip parens and casts away.
11571 LHSExpr = LHSExpr->IgnoreParenImpCasts();
11572 RHSExpr = RHSExpr->IgnoreParenImpCasts();
11574 // Check for a call expression
11575 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
11576 if (!CE || CE->getNumArgs() != 1)
11579 // Check for a call to std::move
11580 const FunctionDecl *FD = CE->getDirectCallee();
11581 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
11582 !FD->getIdentifier()->isStr("move"))
11585 // Get argument from std::move
11586 RHSExpr = CE->getArg(0);
11588 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11589 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11591 // Two DeclRefExpr's, check that the decls are the same.
11592 if (LHSDeclRef && RHSDeclRef) {
11593 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11595 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11596 RHSDeclRef->getDecl()->getCanonicalDecl())
11599 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11600 << LHSExpr->getSourceRange()
11601 << RHSExpr->getSourceRange();
11605 // Member variables require a different approach to check for self moves.
11606 // MemberExpr's are the same if every nested MemberExpr refers to the same
11607 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
11608 // the base Expr's are CXXThisExpr's.
11609 const Expr *LHSBase = LHSExpr;
11610 const Expr *RHSBase = RHSExpr;
11611 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
11612 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
11613 if (!LHSME || !RHSME)
11616 while (LHSME && RHSME) {
11617 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
11618 RHSME->getMemberDecl()->getCanonicalDecl())
11621 LHSBase = LHSME->getBase();
11622 RHSBase = RHSME->getBase();
11623 LHSME = dyn_cast<MemberExpr>(LHSBase);
11624 RHSME = dyn_cast<MemberExpr>(RHSBase);
11627 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
11628 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
11629 if (LHSDeclRef && RHSDeclRef) {
11630 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11632 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11633 RHSDeclRef->getDecl()->getCanonicalDecl())
11636 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11637 << LHSExpr->getSourceRange()
11638 << RHSExpr->getSourceRange();
11642 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
11643 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11644 << LHSExpr->getSourceRange()
11645 << RHSExpr->getSourceRange();
11648 //===--- Layout compatibility ----------------------------------------------//
11652 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
11654 /// \brief Check if two enumeration types are layout-compatible.
11655 bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
11656 // C++11 [dcl.enum] p8:
11657 // Two enumeration types are layout-compatible if they have the same
11658 // underlying type.
11659 return ED1->isComplete() && ED2->isComplete() &&
11660 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
11663 /// \brief Check if two fields are layout-compatible.
11664 bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
11665 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
11668 if (Field1->isBitField() != Field2->isBitField())
11671 if (Field1->isBitField()) {
11672 // Make sure that the bit-fields are the same length.
11673 unsigned Bits1 = Field1->getBitWidthValue(C);
11674 unsigned Bits2 = Field2->getBitWidthValue(C);
11676 if (Bits1 != Bits2)
11683 /// \brief Check if two standard-layout structs are layout-compatible.
11684 /// (C++11 [class.mem] p17)
11685 bool isLayoutCompatibleStruct(ASTContext &C,
11688 // If both records are C++ classes, check that base classes match.
11689 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
11690 // If one of records is a CXXRecordDecl we are in C++ mode,
11691 // thus the other one is a CXXRecordDecl, too.
11692 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
11693 // Check number of base classes.
11694 if (D1CXX->getNumBases() != D2CXX->getNumBases())
11697 // Check the base classes.
11698 for (CXXRecordDecl::base_class_const_iterator
11699 Base1 = D1CXX->bases_begin(),
11700 BaseEnd1 = D1CXX->bases_end(),
11701 Base2 = D2CXX->bases_begin();
11703 ++Base1, ++Base2) {
11704 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
11707 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
11708 // If only RD2 is a C++ class, it should have zero base classes.
11709 if (D2CXX->getNumBases() > 0)
11713 // Check the fields.
11714 RecordDecl::field_iterator Field2 = RD2->field_begin(),
11715 Field2End = RD2->field_end(),
11716 Field1 = RD1->field_begin(),
11717 Field1End = RD1->field_end();
11718 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
11719 if (!isLayoutCompatible(C, *Field1, *Field2))
11722 if (Field1 != Field1End || Field2 != Field2End)
11728 /// \brief Check if two standard-layout unions are layout-compatible.
11729 /// (C++11 [class.mem] p18)
11730 bool isLayoutCompatibleUnion(ASTContext &C,
11733 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
11734 for (auto *Field2 : RD2->fields())
11735 UnmatchedFields.insert(Field2);
11737 for (auto *Field1 : RD1->fields()) {
11738 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
11739 I = UnmatchedFields.begin(),
11740 E = UnmatchedFields.end();
11742 for ( ; I != E; ++I) {
11743 if (isLayoutCompatible(C, Field1, *I)) {
11744 bool Result = UnmatchedFields.erase(*I);
11754 return UnmatchedFields.empty();
11757 bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
11758 if (RD1->isUnion() != RD2->isUnion())
11761 if (RD1->isUnion())
11762 return isLayoutCompatibleUnion(C, RD1, RD2);
11764 return isLayoutCompatibleStruct(C, RD1, RD2);
11767 /// \brief Check if two types are layout-compatible in C++11 sense.
11768 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
11769 if (T1.isNull() || T2.isNull())
11772 // C++11 [basic.types] p11:
11773 // If two types T1 and T2 are the same type, then T1 and T2 are
11774 // layout-compatible types.
11775 if (C.hasSameType(T1, T2))
11778 T1 = T1.getCanonicalType().getUnqualifiedType();
11779 T2 = T2.getCanonicalType().getUnqualifiedType();
11781 const Type::TypeClass TC1 = T1->getTypeClass();
11782 const Type::TypeClass TC2 = T2->getTypeClass();
11787 if (TC1 == Type::Enum) {
11788 return isLayoutCompatible(C,
11789 cast<EnumType>(T1)->getDecl(),
11790 cast<EnumType>(T2)->getDecl());
11791 } else if (TC1 == Type::Record) {
11792 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
11795 return isLayoutCompatible(C,
11796 cast<RecordType>(T1)->getDecl(),
11797 cast<RecordType>(T2)->getDecl());
11802 } // end anonymous namespace
11804 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
11807 /// \brief Given a type tag expression find the type tag itself.
11809 /// \param TypeExpr Type tag expression, as it appears in user's code.
11811 /// \param VD Declaration of an identifier that appears in a type tag.
11813 /// \param MagicValue Type tag magic value.
11814 bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
11815 const ValueDecl **VD, uint64_t *MagicValue) {
11820 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
11822 switch (TypeExpr->getStmtClass()) {
11823 case Stmt::UnaryOperatorClass: {
11824 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
11825 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
11826 TypeExpr = UO->getSubExpr();
11832 case Stmt::DeclRefExprClass: {
11833 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
11834 *VD = DRE->getDecl();
11838 case Stmt::IntegerLiteralClass: {
11839 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
11840 llvm::APInt MagicValueAPInt = IL->getValue();
11841 if (MagicValueAPInt.getActiveBits() <= 64) {
11842 *MagicValue = MagicValueAPInt.getZExtValue();
11848 case Stmt::BinaryConditionalOperatorClass:
11849 case Stmt::ConditionalOperatorClass: {
11850 const AbstractConditionalOperator *ACO =
11851 cast<AbstractConditionalOperator>(TypeExpr);
11853 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
11855 TypeExpr = ACO->getTrueExpr();
11857 TypeExpr = ACO->getFalseExpr();
11863 case Stmt::BinaryOperatorClass: {
11864 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
11865 if (BO->getOpcode() == BO_Comma) {
11866 TypeExpr = BO->getRHS();
11878 /// \brief Retrieve the C type corresponding to type tag TypeExpr.
11880 /// \param TypeExpr Expression that specifies a type tag.
11882 /// \param MagicValues Registered magic values.
11884 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
11887 /// \param TypeInfo Information about the corresponding C type.
11889 /// \returns true if the corresponding C type was found.
11890 bool GetMatchingCType(
11891 const IdentifierInfo *ArgumentKind,
11892 const Expr *TypeExpr, const ASTContext &Ctx,
11893 const llvm::DenseMap<Sema::TypeTagMagicValue,
11894 Sema::TypeTagData> *MagicValues,
11895 bool &FoundWrongKind,
11896 Sema::TypeTagData &TypeInfo) {
11897 FoundWrongKind = false;
11899 // Variable declaration that has type_tag_for_datatype attribute.
11900 const ValueDecl *VD = nullptr;
11902 uint64_t MagicValue;
11904 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
11908 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
11909 if (I->getArgumentKind() != ArgumentKind) {
11910 FoundWrongKind = true;
11913 TypeInfo.Type = I->getMatchingCType();
11914 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
11915 TypeInfo.MustBeNull = I->getMustBeNull();
11924 llvm::DenseMap<Sema::TypeTagMagicValue,
11925 Sema::TypeTagData>::const_iterator I =
11926 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
11927 if (I == MagicValues->end())
11930 TypeInfo = I->second;
11933 } // end anonymous namespace
11935 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
11936 uint64_t MagicValue, QualType Type,
11937 bool LayoutCompatible,
11939 if (!TypeTagForDatatypeMagicValues)
11940 TypeTagForDatatypeMagicValues.reset(
11941 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
11943 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
11944 (*TypeTagForDatatypeMagicValues)[Magic] =
11945 TypeTagData(Type, LayoutCompatible, MustBeNull);
11949 bool IsSameCharType(QualType T1, QualType T2) {
11950 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
11954 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
11958 BuiltinType::Kind T1Kind = BT1->getKind();
11959 BuiltinType::Kind T2Kind = BT2->getKind();
11961 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
11962 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
11963 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
11964 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
11966 } // end anonymous namespace
11968 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
11969 const Expr * const *ExprArgs) {
11970 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
11971 bool IsPointerAttr = Attr->getIsPointer();
11973 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
11974 bool FoundWrongKind;
11975 TypeTagData TypeInfo;
11976 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
11977 TypeTagForDatatypeMagicValues.get(),
11978 FoundWrongKind, TypeInfo)) {
11979 if (FoundWrongKind)
11980 Diag(TypeTagExpr->getExprLoc(),
11981 diag::warn_type_tag_for_datatype_wrong_kind)
11982 << TypeTagExpr->getSourceRange();
11986 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
11987 if (IsPointerAttr) {
11988 // Skip implicit cast of pointer to `void *' (as a function argument).
11989 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
11990 if (ICE->getType()->isVoidPointerType() &&
11991 ICE->getCastKind() == CK_BitCast)
11992 ArgumentExpr = ICE->getSubExpr();
11994 QualType ArgumentType = ArgumentExpr->getType();
11996 // Passing a `void*' pointer shouldn't trigger a warning.
11997 if (IsPointerAttr && ArgumentType->isVoidPointerType())
12000 if (TypeInfo.MustBeNull) {
12001 // Type tag with matching void type requires a null pointer.
12002 if (!ArgumentExpr->isNullPointerConstant(Context,
12003 Expr::NPC_ValueDependentIsNotNull)) {
12004 Diag(ArgumentExpr->getExprLoc(),
12005 diag::warn_type_safety_null_pointer_required)
12006 << ArgumentKind->getName()
12007 << ArgumentExpr->getSourceRange()
12008 << TypeTagExpr->getSourceRange();
12013 QualType RequiredType = TypeInfo.Type;
12015 RequiredType = Context.getPointerType(RequiredType);
12017 bool mismatch = false;
12018 if (!TypeInfo.LayoutCompatible) {
12019 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
12021 // C++11 [basic.fundamental] p1:
12022 // Plain char, signed char, and unsigned char are three distinct types.
12024 // But we treat plain `char' as equivalent to `signed char' or `unsigned
12025 // char' depending on the current char signedness mode.
12027 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
12028 RequiredType->getPointeeType())) ||
12029 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
12033 mismatch = !isLayoutCompatible(Context,
12034 ArgumentType->getPointeeType(),
12035 RequiredType->getPointeeType());
12037 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
12040 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
12041 << ArgumentType << ArgumentKind
12042 << TypeInfo.LayoutCompatible << RequiredType
12043 << ArgumentExpr->getSourceRange()
12044 << TypeTagExpr->getSourceRange();
12047 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
12048 CharUnits Alignment) {
12049 MisalignedMembers.emplace_back(E, RD, MD, Alignment);
12052 void Sema::DiagnoseMisalignedMembers() {
12053 for (MisalignedMember &m : MisalignedMembers) {
12054 const NamedDecl *ND = m.RD;
12055 if (ND->getName().empty()) {
12056 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
12059 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
12060 << m.MD << ND << m.E->getSourceRange();
12062 MisalignedMembers.clear();
12065 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
12066 E = E->IgnoreParens();
12067 if (!T->isPointerType() && !T->isIntegerType())
12069 if (isa<UnaryOperator>(E) &&
12070 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
12071 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
12072 if (isa<MemberExpr>(Op)) {
12073 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
12074 MisalignedMember(Op));
12075 if (MA != MisalignedMembers.end() &&
12076 (T->isIntegerType() ||
12077 (T->isPointerType() &&
12078 Context.getTypeAlignInChars(T->getPointeeType()) <= MA->Alignment)))
12079 MisalignedMembers.erase(MA);
12084 void Sema::RefersToMemberWithReducedAlignment(
12086 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
12088 const auto *ME = dyn_cast<MemberExpr>(E);
12092 // No need to check expressions with an __unaligned-qualified type.
12093 if (E->getType().getQualifiers().hasUnaligned())
12096 // For a chain of MemberExpr like "a.b.c.d" this list
12097 // will keep FieldDecl's like [d, c, b].
12098 SmallVector<FieldDecl *, 4> ReverseMemberChain;
12099 const MemberExpr *TopME = nullptr;
12100 bool AnyIsPacked = false;
12102 QualType BaseType = ME->getBase()->getType();
12104 BaseType = BaseType->getPointeeType();
12105 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
12106 if (RD->isInvalidDecl())
12109 ValueDecl *MD = ME->getMemberDecl();
12110 auto *FD = dyn_cast<FieldDecl>(MD);
12111 // We do not care about non-data members.
12112 if (!FD || FD->isInvalidDecl())
12116 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
12117 ReverseMemberChain.push_back(FD);
12120 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
12122 assert(TopME && "We did not compute a topmost MemberExpr!");
12124 // Not the scope of this diagnostic.
12128 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
12129 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
12130 // TODO: The innermost base of the member expression may be too complicated.
12131 // For now, just disregard these cases. This is left for future
12133 if (!DRE && !isa<CXXThisExpr>(TopBase))
12136 // Alignment expected by the whole expression.
12137 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
12139 // No need to do anything else with this case.
12140 if (ExpectedAlignment.isOne())
12143 // Synthesize offset of the whole access.
12145 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
12147 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
12150 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
12151 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
12152 ReverseMemberChain.back()->getParent()->getTypeForDecl());
12154 // The base expression of the innermost MemberExpr may give
12155 // stronger guarantees than the class containing the member.
12156 if (DRE && !TopME->isArrow()) {
12157 const ValueDecl *VD = DRE->getDecl();
12158 if (!VD->getType()->isReferenceType())
12159 CompleteObjectAlignment =
12160 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
12163 // Check if the synthesized offset fulfills the alignment.
12164 if (Offset % ExpectedAlignment != 0 ||
12165 // It may fulfill the offset it but the effective alignment may still be
12166 // lower than the expected expression alignment.
12167 CompleteObjectAlignment < ExpectedAlignment) {
12168 // If this happens, we want to determine a sensible culprit of this.
12169 // Intuitively, watching the chain of member expressions from right to
12170 // left, we start with the required alignment (as required by the field
12171 // type) but some packed attribute in that chain has reduced the alignment.
12172 // It may happen that another packed structure increases it again. But if
12173 // we are here such increase has not been enough. So pointing the first
12174 // FieldDecl that either is packed or else its RecordDecl is,
12175 // seems reasonable.
12176 FieldDecl *FD = nullptr;
12177 CharUnits Alignment;
12178 for (FieldDecl *FDI : ReverseMemberChain) {
12179 if (FDI->hasAttr<PackedAttr>() ||
12180 FDI->getParent()->hasAttr<PackedAttr>()) {
12182 Alignment = std::min(
12183 Context.getTypeAlignInChars(FD->getType()),
12184 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
12188 assert(FD && "We did not find a packed FieldDecl!");
12189 Action(E, FD->getParent(), FD, Alignment);
12193 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
12194 using namespace std::placeholders;
12195 RefersToMemberWithReducedAlignment(
12196 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,