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_enqueue_kernel_expected_type) << "block";
315 return checkOpenCLBlockArgs(S, BlockArg);
318 /// Diagnose integer type and any valid implicit conversion to it.
319 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
320 const QualType &IntType);
322 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
323 unsigned Start, unsigned End) {
324 bool IllegalParams = false;
325 for (unsigned I = Start; I <= End; ++I)
326 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
327 S.Context.getSizeType());
328 return IllegalParams;
331 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
332 /// 'local void*' parameter of passed block.
333 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
335 unsigned NumNonVarArgs) {
336 const BlockPointerType *BPT =
337 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
338 unsigned NumBlockParams =
339 BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
340 unsigned TotalNumArgs = TheCall->getNumArgs();
342 // For each argument passed to the block, a corresponding uint needs to
343 // be passed to describe the size of the local memory.
344 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
345 S.Diag(TheCall->getLocStart(),
346 diag::err_opencl_enqueue_kernel_local_size_args);
350 // Check that the sizes of the local memory are specified by integers.
351 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
355 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
356 /// overload formats specified in Table 6.13.17.1.
357 /// int enqueue_kernel(queue_t queue,
358 /// kernel_enqueue_flags_t flags,
359 /// const ndrange_t ndrange,
360 /// void (^block)(void))
361 /// int enqueue_kernel(queue_t queue,
362 /// kernel_enqueue_flags_t flags,
363 /// const ndrange_t ndrange,
364 /// uint num_events_in_wait_list,
365 /// clk_event_t *event_wait_list,
366 /// clk_event_t *event_ret,
367 /// void (^block)(void))
368 /// int enqueue_kernel(queue_t queue,
369 /// kernel_enqueue_flags_t flags,
370 /// const ndrange_t ndrange,
371 /// void (^block)(local void*, ...),
373 /// int enqueue_kernel(queue_t queue,
374 /// kernel_enqueue_flags_t flags,
375 /// const ndrange_t ndrange,
376 /// uint num_events_in_wait_list,
377 /// clk_event_t *event_wait_list,
378 /// clk_event_t *event_ret,
379 /// void (^block)(local void*, ...),
381 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
382 unsigned NumArgs = TheCall->getNumArgs();
385 S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args);
389 Expr *Arg0 = TheCall->getArg(0);
390 Expr *Arg1 = TheCall->getArg(1);
391 Expr *Arg2 = TheCall->getArg(2);
392 Expr *Arg3 = TheCall->getArg(3);
394 // First argument always needs to be a queue_t type.
395 if (!Arg0->getType()->isQueueT()) {
396 S.Diag(TheCall->getArg(0)->getLocStart(),
397 diag::err_opencl_enqueue_kernel_expected_type)
398 << S.Context.OCLQueueTy;
402 // Second argument always needs to be a kernel_enqueue_flags_t enum value.
403 if (!Arg1->getType()->isIntegerType()) {
404 S.Diag(TheCall->getArg(1)->getLocStart(),
405 diag::err_opencl_enqueue_kernel_expected_type)
406 << "'kernel_enqueue_flags_t' (i.e. uint)";
410 // Third argument is always an ndrange_t type.
411 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
412 S.Diag(TheCall->getArg(2)->getLocStart(),
413 diag::err_opencl_enqueue_kernel_expected_type)
418 // With four arguments, there is only one form that the function could be
419 // called in: no events and no variable arguments.
421 // check that the last argument is the right block type.
422 if (!isBlockPointer(Arg3)) {
423 S.Diag(Arg3->getLocStart(), diag::err_opencl_enqueue_kernel_expected_type)
427 // we have a block type, check the prototype
428 const BlockPointerType *BPT =
429 cast<BlockPointerType>(Arg3->getType().getCanonicalType());
430 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
431 S.Diag(Arg3->getLocStart(),
432 diag::err_opencl_enqueue_kernel_blocks_no_args);
437 // we can have block + varargs.
438 if (isBlockPointer(Arg3))
439 return (checkOpenCLBlockArgs(S, Arg3) ||
440 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
441 // last two cases with either exactly 7 args or 7 args and varargs.
443 // check common block argument.
444 Expr *Arg6 = TheCall->getArg(6);
445 if (!isBlockPointer(Arg6)) {
446 S.Diag(Arg6->getLocStart(), diag::err_opencl_enqueue_kernel_expected_type)
450 if (checkOpenCLBlockArgs(S, Arg6))
453 // Forth argument has to be any integer type.
454 if (!Arg3->getType()->isIntegerType()) {
455 S.Diag(TheCall->getArg(3)->getLocStart(),
456 diag::err_opencl_enqueue_kernel_expected_type)
460 // check remaining common arguments.
461 Expr *Arg4 = TheCall->getArg(4);
462 Expr *Arg5 = TheCall->getArg(5);
464 // Fifth argument is always passed as a pointer to clk_event_t.
465 if (!Arg4->isNullPointerConstant(S.Context,
466 Expr::NPC_ValueDependentIsNotNull) &&
467 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
468 S.Diag(TheCall->getArg(4)->getLocStart(),
469 diag::err_opencl_enqueue_kernel_expected_type)
470 << S.Context.getPointerType(S.Context.OCLClkEventTy);
474 // Sixth argument is always passed as a pointer to clk_event_t.
475 if (!Arg5->isNullPointerConstant(S.Context,
476 Expr::NPC_ValueDependentIsNotNull) &&
477 !(Arg5->getType()->isPointerType() &&
478 Arg5->getType()->getPointeeType()->isClkEventT())) {
479 S.Diag(TheCall->getArg(5)->getLocStart(),
480 diag::err_opencl_enqueue_kernel_expected_type)
481 << S.Context.getPointerType(S.Context.OCLClkEventTy);
488 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
491 // None of the specific case has been detected, give generic error
492 S.Diag(TheCall->getLocStart(),
493 diag::err_opencl_enqueue_kernel_incorrect_args);
497 /// Returns OpenCL access qual.
498 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
499 return D->getAttr<OpenCLAccessAttr>();
502 /// Returns true if pipe element type is different from the pointer.
503 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
504 const Expr *Arg0 = Call->getArg(0);
505 // First argument type should always be pipe.
506 if (!Arg0->getType()->isPipeType()) {
507 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
508 << Call->getDirectCallee() << Arg0->getSourceRange();
511 OpenCLAccessAttr *AccessQual =
512 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
513 // Validates the access qualifier is compatible with the call.
514 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
515 // read_only and write_only, and assumed to be read_only if no qualifier is
517 switch (Call->getDirectCallee()->getBuiltinID()) {
518 case Builtin::BIread_pipe:
519 case Builtin::BIreserve_read_pipe:
520 case Builtin::BIcommit_read_pipe:
521 case Builtin::BIwork_group_reserve_read_pipe:
522 case Builtin::BIsub_group_reserve_read_pipe:
523 case Builtin::BIwork_group_commit_read_pipe:
524 case Builtin::BIsub_group_commit_read_pipe:
525 if (!(!AccessQual || AccessQual->isReadOnly())) {
526 S.Diag(Arg0->getLocStart(),
527 diag::err_opencl_builtin_pipe_invalid_access_modifier)
528 << "read_only" << Arg0->getSourceRange();
532 case Builtin::BIwrite_pipe:
533 case Builtin::BIreserve_write_pipe:
534 case Builtin::BIcommit_write_pipe:
535 case Builtin::BIwork_group_reserve_write_pipe:
536 case Builtin::BIsub_group_reserve_write_pipe:
537 case Builtin::BIwork_group_commit_write_pipe:
538 case Builtin::BIsub_group_commit_write_pipe:
539 if (!(AccessQual && AccessQual->isWriteOnly())) {
540 S.Diag(Arg0->getLocStart(),
541 diag::err_opencl_builtin_pipe_invalid_access_modifier)
542 << "write_only" << Arg0->getSourceRange();
552 /// Returns true if pipe element type is different from the pointer.
553 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
554 const Expr *Arg0 = Call->getArg(0);
555 const Expr *ArgIdx = Call->getArg(Idx);
556 const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
557 const QualType EltTy = PipeTy->getElementType();
558 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
559 // The Idx argument should be a pointer and the type of the pointer and
560 // the type of pipe element should also be the same.
562 !S.Context.hasSameType(
563 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
564 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
565 << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
566 << ArgIdx->getType() << ArgIdx->getSourceRange();
572 // \brief Performs semantic analysis for the read/write_pipe call.
573 // \param S Reference to the semantic analyzer.
574 // \param Call A pointer to the builtin call.
575 // \return True if a semantic error has been found, false otherwise.
576 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
577 // OpenCL v2.0 s6.13.16.2 - The built-in read/write
578 // functions have two forms.
579 switch (Call->getNumArgs()) {
581 if (checkOpenCLPipeArg(S, Call))
583 // The call with 2 arguments should be
584 // read/write_pipe(pipe T, T*).
585 // Check packet type T.
586 if (checkOpenCLPipePacketType(S, Call, 1))
591 if (checkOpenCLPipeArg(S, Call))
593 // The call with 4 arguments should be
594 // read/write_pipe(pipe T, reserve_id_t, uint, T*).
595 // Check reserve_id_t.
596 if (!Call->getArg(1)->getType()->isReserveIDT()) {
597 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
598 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
599 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
604 const Expr *Arg2 = Call->getArg(2);
605 if (!Arg2->getType()->isIntegerType() &&
606 !Arg2->getType()->isUnsignedIntegerType()) {
607 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
608 << Call->getDirectCallee() << S.Context.UnsignedIntTy
609 << Arg2->getType() << Arg2->getSourceRange();
613 // Check packet type T.
614 if (checkOpenCLPipePacketType(S, Call, 3))
618 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
619 << Call->getDirectCallee() << Call->getSourceRange();
626 // \brief Performs a semantic analysis on the {work_group_/sub_group_
627 // /_}reserve_{read/write}_pipe
628 // \param S Reference to the semantic analyzer.
629 // \param Call The call to the builtin function to be analyzed.
630 // \return True if a semantic error was found, false otherwise.
631 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
632 if (checkArgCount(S, Call, 2))
635 if (checkOpenCLPipeArg(S, Call))
638 // Check the reserve size.
639 if (!Call->getArg(1)->getType()->isIntegerType() &&
640 !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
641 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
642 << Call->getDirectCallee() << S.Context.UnsignedIntTy
643 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
650 // \brief Performs a semantic analysis on {work_group_/sub_group_
651 // /_}commit_{read/write}_pipe
652 // \param S Reference to the semantic analyzer.
653 // \param Call The call to the builtin function to be analyzed.
654 // \return True if a semantic error was found, false otherwise.
655 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
656 if (checkArgCount(S, Call, 2))
659 if (checkOpenCLPipeArg(S, Call))
662 // Check reserve_id_t.
663 if (!Call->getArg(1)->getType()->isReserveIDT()) {
664 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
665 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
666 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
673 // \brief Performs a semantic analysis on the call to built-in Pipe
675 // \param S Reference to the semantic analyzer.
676 // \param Call The call to the builtin function to be analyzed.
677 // \return True if a semantic error was found, false otherwise.
678 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
679 if (checkArgCount(S, Call, 1))
682 if (!Call->getArg(0)->getType()->isPipeType()) {
683 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
684 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
690 // \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions.
691 // \brief Performs semantic analysis for the to_global/local/private call.
692 // \param S Reference to the semantic analyzer.
693 // \param BuiltinID ID of the builtin function.
694 // \param Call A pointer to the builtin call.
695 // \return True if a semantic error has been found, false otherwise.
696 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
698 if (Call->getNumArgs() != 1) {
699 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num)
700 << Call->getDirectCallee() << Call->getSourceRange();
704 auto RT = Call->getArg(0)->getType();
705 if (!RT->isPointerType() || RT->getPointeeType()
706 .getAddressSpace() == LangAS::opencl_constant) {
707 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
708 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
712 RT = RT->getPointeeType();
713 auto Qual = RT.getQualifiers();
715 case Builtin::BIto_global:
716 Qual.setAddressSpace(LangAS::opencl_global);
718 case Builtin::BIto_local:
719 Qual.setAddressSpace(LangAS::opencl_local);
722 Qual.removeAddressSpace();
724 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
725 RT.getUnqualifiedType(), Qual)));
731 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
733 ExprResult TheCallResult(TheCall);
735 // Find out if any arguments are required to be integer constant expressions.
736 unsigned ICEArguments = 0;
737 ASTContext::GetBuiltinTypeError Error;
738 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
739 if (Error != ASTContext::GE_None)
740 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
742 // If any arguments are required to be ICE's, check and diagnose.
743 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
744 // Skip arguments not required to be ICE's.
745 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
748 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
750 ICEArguments &= ~(1 << ArgNo);
754 case Builtin::BI__builtin___CFStringMakeConstantString:
755 assert(TheCall->getNumArgs() == 1 &&
756 "Wrong # arguments to builtin CFStringMakeConstantString");
757 if (CheckObjCString(TheCall->getArg(0)))
760 case Builtin::BI__builtin_stdarg_start:
761 case Builtin::BI__builtin_va_start:
762 if (SemaBuiltinVAStart(TheCall))
765 case Builtin::BI__va_start: {
766 switch (Context.getTargetInfo().getTriple().getArch()) {
767 case llvm::Triple::arm:
768 case llvm::Triple::thumb:
769 if (SemaBuiltinVAStartARM(TheCall))
773 if (SemaBuiltinVAStart(TheCall))
779 case Builtin::BI__builtin_isgreater:
780 case Builtin::BI__builtin_isgreaterequal:
781 case Builtin::BI__builtin_isless:
782 case Builtin::BI__builtin_islessequal:
783 case Builtin::BI__builtin_islessgreater:
784 case Builtin::BI__builtin_isunordered:
785 if (SemaBuiltinUnorderedCompare(TheCall))
788 case Builtin::BI__builtin_fpclassify:
789 if (SemaBuiltinFPClassification(TheCall, 6))
792 case Builtin::BI__builtin_isfinite:
793 case Builtin::BI__builtin_isinf:
794 case Builtin::BI__builtin_isinf_sign:
795 case Builtin::BI__builtin_isnan:
796 case Builtin::BI__builtin_isnormal:
797 if (SemaBuiltinFPClassification(TheCall, 1))
800 case Builtin::BI__builtin_shufflevector:
801 return SemaBuiltinShuffleVector(TheCall);
802 // TheCall will be freed by the smart pointer here, but that's fine, since
803 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
804 case Builtin::BI__builtin_prefetch:
805 if (SemaBuiltinPrefetch(TheCall))
808 case Builtin::BI__builtin_alloca_with_align:
809 if (SemaBuiltinAllocaWithAlign(TheCall))
812 case Builtin::BI__assume:
813 case Builtin::BI__builtin_assume:
814 if (SemaBuiltinAssume(TheCall))
817 case Builtin::BI__builtin_assume_aligned:
818 if (SemaBuiltinAssumeAligned(TheCall))
821 case Builtin::BI__builtin_object_size:
822 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
825 case Builtin::BI__builtin_longjmp:
826 if (SemaBuiltinLongjmp(TheCall))
829 case Builtin::BI__builtin_setjmp:
830 if (SemaBuiltinSetjmp(TheCall))
833 case Builtin::BI_setjmp:
834 case Builtin::BI_setjmpex:
835 if (checkArgCount(*this, TheCall, 1))
839 case Builtin::BI__builtin_classify_type:
840 if (checkArgCount(*this, TheCall, 1)) return true;
841 TheCall->setType(Context.IntTy);
843 case Builtin::BI__builtin_constant_p:
844 if (checkArgCount(*this, TheCall, 1)) return true;
845 TheCall->setType(Context.IntTy);
847 case Builtin::BI__sync_fetch_and_add:
848 case Builtin::BI__sync_fetch_and_add_1:
849 case Builtin::BI__sync_fetch_and_add_2:
850 case Builtin::BI__sync_fetch_and_add_4:
851 case Builtin::BI__sync_fetch_and_add_8:
852 case Builtin::BI__sync_fetch_and_add_16:
853 case Builtin::BI__sync_fetch_and_sub:
854 case Builtin::BI__sync_fetch_and_sub_1:
855 case Builtin::BI__sync_fetch_and_sub_2:
856 case Builtin::BI__sync_fetch_and_sub_4:
857 case Builtin::BI__sync_fetch_and_sub_8:
858 case Builtin::BI__sync_fetch_and_sub_16:
859 case Builtin::BI__sync_fetch_and_or:
860 case Builtin::BI__sync_fetch_and_or_1:
861 case Builtin::BI__sync_fetch_and_or_2:
862 case Builtin::BI__sync_fetch_and_or_4:
863 case Builtin::BI__sync_fetch_and_or_8:
864 case Builtin::BI__sync_fetch_and_or_16:
865 case Builtin::BI__sync_fetch_and_and:
866 case Builtin::BI__sync_fetch_and_and_1:
867 case Builtin::BI__sync_fetch_and_and_2:
868 case Builtin::BI__sync_fetch_and_and_4:
869 case Builtin::BI__sync_fetch_and_and_8:
870 case Builtin::BI__sync_fetch_and_and_16:
871 case Builtin::BI__sync_fetch_and_xor:
872 case Builtin::BI__sync_fetch_and_xor_1:
873 case Builtin::BI__sync_fetch_and_xor_2:
874 case Builtin::BI__sync_fetch_and_xor_4:
875 case Builtin::BI__sync_fetch_and_xor_8:
876 case Builtin::BI__sync_fetch_and_xor_16:
877 case Builtin::BI__sync_fetch_and_nand:
878 case Builtin::BI__sync_fetch_and_nand_1:
879 case Builtin::BI__sync_fetch_and_nand_2:
880 case Builtin::BI__sync_fetch_and_nand_4:
881 case Builtin::BI__sync_fetch_and_nand_8:
882 case Builtin::BI__sync_fetch_and_nand_16:
883 case Builtin::BI__sync_add_and_fetch:
884 case Builtin::BI__sync_add_and_fetch_1:
885 case Builtin::BI__sync_add_and_fetch_2:
886 case Builtin::BI__sync_add_and_fetch_4:
887 case Builtin::BI__sync_add_and_fetch_8:
888 case Builtin::BI__sync_add_and_fetch_16:
889 case Builtin::BI__sync_sub_and_fetch:
890 case Builtin::BI__sync_sub_and_fetch_1:
891 case Builtin::BI__sync_sub_and_fetch_2:
892 case Builtin::BI__sync_sub_and_fetch_4:
893 case Builtin::BI__sync_sub_and_fetch_8:
894 case Builtin::BI__sync_sub_and_fetch_16:
895 case Builtin::BI__sync_and_and_fetch:
896 case Builtin::BI__sync_and_and_fetch_1:
897 case Builtin::BI__sync_and_and_fetch_2:
898 case Builtin::BI__sync_and_and_fetch_4:
899 case Builtin::BI__sync_and_and_fetch_8:
900 case Builtin::BI__sync_and_and_fetch_16:
901 case Builtin::BI__sync_or_and_fetch:
902 case Builtin::BI__sync_or_and_fetch_1:
903 case Builtin::BI__sync_or_and_fetch_2:
904 case Builtin::BI__sync_or_and_fetch_4:
905 case Builtin::BI__sync_or_and_fetch_8:
906 case Builtin::BI__sync_or_and_fetch_16:
907 case Builtin::BI__sync_xor_and_fetch:
908 case Builtin::BI__sync_xor_and_fetch_1:
909 case Builtin::BI__sync_xor_and_fetch_2:
910 case Builtin::BI__sync_xor_and_fetch_4:
911 case Builtin::BI__sync_xor_and_fetch_8:
912 case Builtin::BI__sync_xor_and_fetch_16:
913 case Builtin::BI__sync_nand_and_fetch:
914 case Builtin::BI__sync_nand_and_fetch_1:
915 case Builtin::BI__sync_nand_and_fetch_2:
916 case Builtin::BI__sync_nand_and_fetch_4:
917 case Builtin::BI__sync_nand_and_fetch_8:
918 case Builtin::BI__sync_nand_and_fetch_16:
919 case Builtin::BI__sync_val_compare_and_swap:
920 case Builtin::BI__sync_val_compare_and_swap_1:
921 case Builtin::BI__sync_val_compare_and_swap_2:
922 case Builtin::BI__sync_val_compare_and_swap_4:
923 case Builtin::BI__sync_val_compare_and_swap_8:
924 case Builtin::BI__sync_val_compare_and_swap_16:
925 case Builtin::BI__sync_bool_compare_and_swap:
926 case Builtin::BI__sync_bool_compare_and_swap_1:
927 case Builtin::BI__sync_bool_compare_and_swap_2:
928 case Builtin::BI__sync_bool_compare_and_swap_4:
929 case Builtin::BI__sync_bool_compare_and_swap_8:
930 case Builtin::BI__sync_bool_compare_and_swap_16:
931 case Builtin::BI__sync_lock_test_and_set:
932 case Builtin::BI__sync_lock_test_and_set_1:
933 case Builtin::BI__sync_lock_test_and_set_2:
934 case Builtin::BI__sync_lock_test_and_set_4:
935 case Builtin::BI__sync_lock_test_and_set_8:
936 case Builtin::BI__sync_lock_test_and_set_16:
937 case Builtin::BI__sync_lock_release:
938 case Builtin::BI__sync_lock_release_1:
939 case Builtin::BI__sync_lock_release_2:
940 case Builtin::BI__sync_lock_release_4:
941 case Builtin::BI__sync_lock_release_8:
942 case Builtin::BI__sync_lock_release_16:
943 case Builtin::BI__sync_swap:
944 case Builtin::BI__sync_swap_1:
945 case Builtin::BI__sync_swap_2:
946 case Builtin::BI__sync_swap_4:
947 case Builtin::BI__sync_swap_8:
948 case Builtin::BI__sync_swap_16:
949 return SemaBuiltinAtomicOverloaded(TheCallResult);
950 case Builtin::BI__builtin_nontemporal_load:
951 case Builtin::BI__builtin_nontemporal_store:
952 return SemaBuiltinNontemporalOverloaded(TheCallResult);
953 #define BUILTIN(ID, TYPE, ATTRS)
954 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
955 case Builtin::BI##ID: \
956 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
957 #include "clang/Basic/Builtins.def"
958 case Builtin::BI__builtin_annotation:
959 if (SemaBuiltinAnnotation(*this, TheCall))
962 case Builtin::BI__builtin_addressof:
963 if (SemaBuiltinAddressof(*this, TheCall))
966 case Builtin::BI__builtin_add_overflow:
967 case Builtin::BI__builtin_sub_overflow:
968 case Builtin::BI__builtin_mul_overflow:
969 if (SemaBuiltinOverflow(*this, TheCall))
972 case Builtin::BI__builtin_operator_new:
973 case Builtin::BI__builtin_operator_delete:
974 if (!getLangOpts().CPlusPlus) {
975 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
976 << (BuiltinID == Builtin::BI__builtin_operator_new
977 ? "__builtin_operator_new"
978 : "__builtin_operator_delete")
982 // CodeGen assumes it can find the global new and delete to call,
983 // so ensure that they are declared.
984 DeclareGlobalNewDelete();
987 // check secure string manipulation functions where overflows
988 // are detectable at compile time
989 case Builtin::BI__builtin___memcpy_chk:
990 case Builtin::BI__builtin___memmove_chk:
991 case Builtin::BI__builtin___memset_chk:
992 case Builtin::BI__builtin___strlcat_chk:
993 case Builtin::BI__builtin___strlcpy_chk:
994 case Builtin::BI__builtin___strncat_chk:
995 case Builtin::BI__builtin___strncpy_chk:
996 case Builtin::BI__builtin___stpncpy_chk:
997 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
999 case Builtin::BI__builtin___memccpy_chk:
1000 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
1002 case Builtin::BI__builtin___snprintf_chk:
1003 case Builtin::BI__builtin___vsnprintf_chk:
1004 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
1006 case Builtin::BI__builtin_call_with_static_chain:
1007 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1010 case Builtin::BI__exception_code:
1011 case Builtin::BI_exception_code:
1012 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1013 diag::err_seh___except_block))
1016 case Builtin::BI__exception_info:
1017 case Builtin::BI_exception_info:
1018 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1019 diag::err_seh___except_filter))
1022 case Builtin::BI__GetExceptionInfo:
1023 if (checkArgCount(*this, TheCall, 1))
1026 if (CheckCXXThrowOperand(
1027 TheCall->getLocStart(),
1028 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1032 TheCall->setType(Context.VoidPtrTy);
1034 // OpenCL v2.0, s6.13.16 - Pipe functions
1035 case Builtin::BIread_pipe:
1036 case Builtin::BIwrite_pipe:
1037 // Since those two functions are declared with var args, we need a semantic
1038 // check for the argument.
1039 if (SemaBuiltinRWPipe(*this, TheCall))
1041 TheCall->setType(Context.IntTy);
1043 case Builtin::BIreserve_read_pipe:
1044 case Builtin::BIreserve_write_pipe:
1045 case Builtin::BIwork_group_reserve_read_pipe:
1046 case Builtin::BIwork_group_reserve_write_pipe:
1047 case Builtin::BIsub_group_reserve_read_pipe:
1048 case Builtin::BIsub_group_reserve_write_pipe:
1049 if (SemaBuiltinReserveRWPipe(*this, TheCall))
1051 // Since return type of reserve_read/write_pipe built-in function is
1052 // reserve_id_t, which is not defined in the builtin def file , we used int
1053 // as return type and need to override the return type of these functions.
1054 TheCall->setType(Context.OCLReserveIDTy);
1056 case Builtin::BIcommit_read_pipe:
1057 case Builtin::BIcommit_write_pipe:
1058 case Builtin::BIwork_group_commit_read_pipe:
1059 case Builtin::BIwork_group_commit_write_pipe:
1060 case Builtin::BIsub_group_commit_read_pipe:
1061 case Builtin::BIsub_group_commit_write_pipe:
1062 if (SemaBuiltinCommitRWPipe(*this, TheCall))
1065 case Builtin::BIget_pipe_num_packets:
1066 case Builtin::BIget_pipe_max_packets:
1067 if (SemaBuiltinPipePackets(*this, TheCall))
1069 TheCall->setType(Context.UnsignedIntTy);
1071 case Builtin::BIto_global:
1072 case Builtin::BIto_local:
1073 case Builtin::BIto_private:
1074 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1077 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1078 case Builtin::BIenqueue_kernel:
1079 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1082 case Builtin::BIget_kernel_work_group_size:
1083 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1084 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1087 case Builtin::BI__builtin_os_log_format:
1088 case Builtin::BI__builtin_os_log_format_buffer_size:
1089 if (SemaBuiltinOSLogFormat(TheCall)) {
1095 // Since the target specific builtins for each arch overlap, only check those
1096 // of the arch we are compiling for.
1097 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1098 switch (Context.getTargetInfo().getTriple().getArch()) {
1099 case llvm::Triple::arm:
1100 case llvm::Triple::armeb:
1101 case llvm::Triple::thumb:
1102 case llvm::Triple::thumbeb:
1103 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1106 case llvm::Triple::aarch64:
1107 case llvm::Triple::aarch64_be:
1108 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
1111 case llvm::Triple::mips:
1112 case llvm::Triple::mipsel:
1113 case llvm::Triple::mips64:
1114 case llvm::Triple::mips64el:
1115 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1118 case llvm::Triple::systemz:
1119 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1122 case llvm::Triple::x86:
1123 case llvm::Triple::x86_64:
1124 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1127 case llvm::Triple::ppc:
1128 case llvm::Triple::ppc64:
1129 case llvm::Triple::ppc64le:
1130 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1138 return TheCallResult;
1141 // Get the valid immediate range for the specified NEON type code.
1142 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1143 NeonTypeFlags Type(t);
1144 int IsQuad = ForceQuad ? true : Type.isQuad();
1145 switch (Type.getEltType()) {
1146 case NeonTypeFlags::Int8:
1147 case NeonTypeFlags::Poly8:
1148 return shift ? 7 : (8 << IsQuad) - 1;
1149 case NeonTypeFlags::Int16:
1150 case NeonTypeFlags::Poly16:
1151 return shift ? 15 : (4 << IsQuad) - 1;
1152 case NeonTypeFlags::Int32:
1153 return shift ? 31 : (2 << IsQuad) - 1;
1154 case NeonTypeFlags::Int64:
1155 case NeonTypeFlags::Poly64:
1156 return shift ? 63 : (1 << IsQuad) - 1;
1157 case NeonTypeFlags::Poly128:
1158 return shift ? 127 : (1 << IsQuad) - 1;
1159 case NeonTypeFlags::Float16:
1160 assert(!shift && "cannot shift float types!");
1161 return (4 << IsQuad) - 1;
1162 case NeonTypeFlags::Float32:
1163 assert(!shift && "cannot shift float types!");
1164 return (2 << IsQuad) - 1;
1165 case NeonTypeFlags::Float64:
1166 assert(!shift && "cannot shift float types!");
1167 return (1 << IsQuad) - 1;
1169 llvm_unreachable("Invalid NeonTypeFlag!");
1172 /// getNeonEltType - Return the QualType corresponding to the elements of
1173 /// the vector type specified by the NeonTypeFlags. This is used to check
1174 /// the pointer arguments for Neon load/store intrinsics.
1175 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
1176 bool IsPolyUnsigned, bool IsInt64Long) {
1177 switch (Flags.getEltType()) {
1178 case NeonTypeFlags::Int8:
1179 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1180 case NeonTypeFlags::Int16:
1181 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1182 case NeonTypeFlags::Int32:
1183 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1184 case NeonTypeFlags::Int64:
1186 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1188 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1189 : Context.LongLongTy;
1190 case NeonTypeFlags::Poly8:
1191 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
1192 case NeonTypeFlags::Poly16:
1193 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
1194 case NeonTypeFlags::Poly64:
1196 return Context.UnsignedLongTy;
1198 return Context.UnsignedLongLongTy;
1199 case NeonTypeFlags::Poly128:
1201 case NeonTypeFlags::Float16:
1202 return Context.HalfTy;
1203 case NeonTypeFlags::Float32:
1204 return Context.FloatTy;
1205 case NeonTypeFlags::Float64:
1206 return Context.DoubleTy;
1208 llvm_unreachable("Invalid NeonTypeFlag!");
1211 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1212 llvm::APSInt Result;
1216 bool HasConstPtr = false;
1217 switch (BuiltinID) {
1218 #define GET_NEON_OVERLOAD_CHECK
1219 #include "clang/Basic/arm_neon.inc"
1220 #undef GET_NEON_OVERLOAD_CHECK
1223 // For NEON intrinsics which are overloaded on vector element type, validate
1224 // the immediate which specifies which variant to emit.
1225 unsigned ImmArg = TheCall->getNumArgs()-1;
1227 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1230 TV = Result.getLimitedValue(64);
1231 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1232 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
1233 << TheCall->getArg(ImmArg)->getSourceRange();
1236 if (PtrArgNum >= 0) {
1237 // Check that pointer arguments have the specified type.
1238 Expr *Arg = TheCall->getArg(PtrArgNum);
1239 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1240 Arg = ICE->getSubExpr();
1241 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1242 QualType RHSTy = RHS.get()->getType();
1244 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
1245 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1246 Arch == llvm::Triple::aarch64_be;
1248 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1250 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
1252 EltTy = EltTy.withConst();
1253 QualType LHSTy = Context.getPointerType(EltTy);
1254 AssignConvertType ConvTy;
1255 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1256 if (RHS.isInvalid())
1258 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1259 RHS.get(), AA_Assigning))
1263 // For NEON intrinsics which take an immediate value as part of the
1264 // instruction, range check them here.
1265 unsigned i = 0, l = 0, u = 0;
1266 switch (BuiltinID) {
1269 #define GET_NEON_IMMEDIATE_CHECK
1270 #include "clang/Basic/arm_neon.inc"
1271 #undef GET_NEON_IMMEDIATE_CHECK
1274 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1277 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1278 unsigned MaxWidth) {
1279 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
1280 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1281 BuiltinID == ARM::BI__builtin_arm_strex ||
1282 BuiltinID == ARM::BI__builtin_arm_stlex ||
1283 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1284 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1285 BuiltinID == AArch64::BI__builtin_arm_strex ||
1286 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
1287 "unexpected ARM builtin");
1288 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
1289 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1290 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1291 BuiltinID == AArch64::BI__builtin_arm_ldaex;
1293 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1295 // Ensure that we have the proper number of arguments.
1296 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1299 // Inspect the pointer argument of the atomic builtin. This should always be
1300 // a pointer type, whose element is an integral scalar or pointer type.
1301 // Because it is a pointer type, we don't have to worry about any implicit
1303 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1304 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1305 if (PointerArgRes.isInvalid())
1307 PointerArg = PointerArgRes.get();
1309 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1311 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1312 << PointerArg->getType() << PointerArg->getSourceRange();
1316 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1317 // task is to insert the appropriate casts into the AST. First work out just
1318 // what the appropriate type is.
1319 QualType ValType = pointerType->getPointeeType();
1320 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1322 AddrType.addConst();
1324 // Issue a warning if the cast is dodgy.
1325 CastKind CastNeeded = CK_NoOp;
1326 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1327 CastNeeded = CK_BitCast;
1328 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1329 << PointerArg->getType()
1330 << Context.getPointerType(AddrType)
1331 << AA_Passing << PointerArg->getSourceRange();
1334 // Finally, do the cast and replace the argument with the corrected version.
1335 AddrType = Context.getPointerType(AddrType);
1336 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1337 if (PointerArgRes.isInvalid())
1339 PointerArg = PointerArgRes.get();
1341 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1343 // In general, we allow ints, floats and pointers to be loaded and stored.
1344 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1345 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1346 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1347 << PointerArg->getType() << PointerArg->getSourceRange();
1351 // But ARM doesn't have instructions to deal with 128-bit versions.
1352 if (Context.getTypeSize(ValType) > MaxWidth) {
1353 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
1354 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1355 << PointerArg->getType() << PointerArg->getSourceRange();
1359 switch (ValType.getObjCLifetime()) {
1360 case Qualifiers::OCL_None:
1361 case Qualifiers::OCL_ExplicitNone:
1365 case Qualifiers::OCL_Weak:
1366 case Qualifiers::OCL_Strong:
1367 case Qualifiers::OCL_Autoreleasing:
1368 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1369 << ValType << PointerArg->getSourceRange();
1374 TheCall->setType(ValType);
1378 // Initialize the argument to be stored.
1379 ExprResult ValArg = TheCall->getArg(0);
1380 InitializedEntity Entity = InitializedEntity::InitializeParameter(
1381 Context, ValType, /*consume*/ false);
1382 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1383 if (ValArg.isInvalid())
1385 TheCall->setArg(0, ValArg.get());
1387 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1388 // but the custom checker bypasses all default analysis.
1389 TheCall->setType(Context.IntTy);
1393 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1394 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
1395 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1396 BuiltinID == ARM::BI__builtin_arm_strex ||
1397 BuiltinID == ARM::BI__builtin_arm_stlex) {
1398 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
1401 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1402 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1403 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1406 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1407 BuiltinID == ARM::BI__builtin_arm_wsr64)
1408 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1410 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1411 BuiltinID == ARM::BI__builtin_arm_rsrp ||
1412 BuiltinID == ARM::BI__builtin_arm_wsr ||
1413 BuiltinID == ARM::BI__builtin_arm_wsrp)
1414 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1416 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1419 // For intrinsics which take an immediate value as part of the instruction,
1420 // range check them here.
1421 unsigned i = 0, l = 0, u = 0;
1422 switch (BuiltinID) {
1423 default: return false;
1424 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
1425 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
1426 case ARM::BI__builtin_arm_vcvtr_f:
1427 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
1428 case ARM::BI__builtin_arm_dmb:
1429 case ARM::BI__builtin_arm_dsb:
1430 case ARM::BI__builtin_arm_isb:
1431 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
1434 // FIXME: VFP Intrinsics should error if VFP not present.
1435 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1438 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
1439 CallExpr *TheCall) {
1440 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1441 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1442 BuiltinID == AArch64::BI__builtin_arm_strex ||
1443 BuiltinID == AArch64::BI__builtin_arm_stlex) {
1444 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1447 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1448 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1449 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1450 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1451 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1454 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1455 BuiltinID == AArch64::BI__builtin_arm_wsr64)
1456 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1458 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1459 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1460 BuiltinID == AArch64::BI__builtin_arm_wsr ||
1461 BuiltinID == AArch64::BI__builtin_arm_wsrp)
1462 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1464 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1467 // For intrinsics which take an immediate value as part of the instruction,
1468 // range check them here.
1469 unsigned i = 0, l = 0, u = 0;
1470 switch (BuiltinID) {
1471 default: return false;
1472 case AArch64::BI__builtin_arm_dmb:
1473 case AArch64::BI__builtin_arm_dsb:
1474 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1477 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1480 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
1481 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
1482 // ordering for DSP is unspecified. MSA is ordered by the data format used
1483 // by the underlying instruction i.e., df/m, df/n and then by size.
1485 // FIXME: The size tests here should instead be tablegen'd along with the
1486 // definitions from include/clang/Basic/BuiltinsMips.def.
1487 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
1489 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1490 unsigned i = 0, l = 0, u = 0, m = 0;
1491 switch (BuiltinID) {
1492 default: return false;
1493 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1494 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
1495 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1496 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1497 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1498 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1499 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
1500 // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
1502 // These intrinsics take an unsigned 3 bit immediate.
1503 case Mips::BI__builtin_msa_bclri_b:
1504 case Mips::BI__builtin_msa_bnegi_b:
1505 case Mips::BI__builtin_msa_bseti_b:
1506 case Mips::BI__builtin_msa_sat_s_b:
1507 case Mips::BI__builtin_msa_sat_u_b:
1508 case Mips::BI__builtin_msa_slli_b:
1509 case Mips::BI__builtin_msa_srai_b:
1510 case Mips::BI__builtin_msa_srari_b:
1511 case Mips::BI__builtin_msa_srli_b:
1512 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
1513 case Mips::BI__builtin_msa_binsli_b:
1514 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
1515 // These intrinsics take an unsigned 4 bit immediate.
1516 case Mips::BI__builtin_msa_bclri_h:
1517 case Mips::BI__builtin_msa_bnegi_h:
1518 case Mips::BI__builtin_msa_bseti_h:
1519 case Mips::BI__builtin_msa_sat_s_h:
1520 case Mips::BI__builtin_msa_sat_u_h:
1521 case Mips::BI__builtin_msa_slli_h:
1522 case Mips::BI__builtin_msa_srai_h:
1523 case Mips::BI__builtin_msa_srari_h:
1524 case Mips::BI__builtin_msa_srli_h:
1525 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
1526 case Mips::BI__builtin_msa_binsli_h:
1527 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
1528 // These intrinsics take an unsigned 5 bit immedate.
1529 // The first block of intrinsics actually have an unsigned 5 bit field,
1530 // not a df/n field.
1531 case Mips::BI__builtin_msa_clei_u_b:
1532 case Mips::BI__builtin_msa_clei_u_h:
1533 case Mips::BI__builtin_msa_clei_u_w:
1534 case Mips::BI__builtin_msa_clei_u_d:
1535 case Mips::BI__builtin_msa_clti_u_b:
1536 case Mips::BI__builtin_msa_clti_u_h:
1537 case Mips::BI__builtin_msa_clti_u_w:
1538 case Mips::BI__builtin_msa_clti_u_d:
1539 case Mips::BI__builtin_msa_maxi_u_b:
1540 case Mips::BI__builtin_msa_maxi_u_h:
1541 case Mips::BI__builtin_msa_maxi_u_w:
1542 case Mips::BI__builtin_msa_maxi_u_d:
1543 case Mips::BI__builtin_msa_mini_u_b:
1544 case Mips::BI__builtin_msa_mini_u_h:
1545 case Mips::BI__builtin_msa_mini_u_w:
1546 case Mips::BI__builtin_msa_mini_u_d:
1547 case Mips::BI__builtin_msa_addvi_b:
1548 case Mips::BI__builtin_msa_addvi_h:
1549 case Mips::BI__builtin_msa_addvi_w:
1550 case Mips::BI__builtin_msa_addvi_d:
1551 case Mips::BI__builtin_msa_bclri_w:
1552 case Mips::BI__builtin_msa_bnegi_w:
1553 case Mips::BI__builtin_msa_bseti_w:
1554 case Mips::BI__builtin_msa_sat_s_w:
1555 case Mips::BI__builtin_msa_sat_u_w:
1556 case Mips::BI__builtin_msa_slli_w:
1557 case Mips::BI__builtin_msa_srai_w:
1558 case Mips::BI__builtin_msa_srari_w:
1559 case Mips::BI__builtin_msa_srli_w:
1560 case Mips::BI__builtin_msa_srlri_w:
1561 case Mips::BI__builtin_msa_subvi_b:
1562 case Mips::BI__builtin_msa_subvi_h:
1563 case Mips::BI__builtin_msa_subvi_w:
1564 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
1565 case Mips::BI__builtin_msa_binsli_w:
1566 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
1567 // These intrinsics take an unsigned 6 bit immediate.
1568 case Mips::BI__builtin_msa_bclri_d:
1569 case Mips::BI__builtin_msa_bnegi_d:
1570 case Mips::BI__builtin_msa_bseti_d:
1571 case Mips::BI__builtin_msa_sat_s_d:
1572 case Mips::BI__builtin_msa_sat_u_d:
1573 case Mips::BI__builtin_msa_slli_d:
1574 case Mips::BI__builtin_msa_srai_d:
1575 case Mips::BI__builtin_msa_srari_d:
1576 case Mips::BI__builtin_msa_srli_d:
1577 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
1578 case Mips::BI__builtin_msa_binsli_d:
1579 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
1580 // These intrinsics take a signed 5 bit immediate.
1581 case Mips::BI__builtin_msa_ceqi_b:
1582 case Mips::BI__builtin_msa_ceqi_h:
1583 case Mips::BI__builtin_msa_ceqi_w:
1584 case Mips::BI__builtin_msa_ceqi_d:
1585 case Mips::BI__builtin_msa_clti_s_b:
1586 case Mips::BI__builtin_msa_clti_s_h:
1587 case Mips::BI__builtin_msa_clti_s_w:
1588 case Mips::BI__builtin_msa_clti_s_d:
1589 case Mips::BI__builtin_msa_clei_s_b:
1590 case Mips::BI__builtin_msa_clei_s_h:
1591 case Mips::BI__builtin_msa_clei_s_w:
1592 case Mips::BI__builtin_msa_clei_s_d:
1593 case Mips::BI__builtin_msa_maxi_s_b:
1594 case Mips::BI__builtin_msa_maxi_s_h:
1595 case Mips::BI__builtin_msa_maxi_s_w:
1596 case Mips::BI__builtin_msa_maxi_s_d:
1597 case Mips::BI__builtin_msa_mini_s_b:
1598 case Mips::BI__builtin_msa_mini_s_h:
1599 case Mips::BI__builtin_msa_mini_s_w:
1600 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
1601 // These intrinsics take an unsigned 8 bit immediate.
1602 case Mips::BI__builtin_msa_andi_b:
1603 case Mips::BI__builtin_msa_nori_b:
1604 case Mips::BI__builtin_msa_ori_b:
1605 case Mips::BI__builtin_msa_shf_b:
1606 case Mips::BI__builtin_msa_shf_h:
1607 case Mips::BI__builtin_msa_shf_w:
1608 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
1609 case Mips::BI__builtin_msa_bseli_b:
1610 case Mips::BI__builtin_msa_bmnzi_b:
1611 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
1613 // These intrinsics take an unsigned 4 bit immediate.
1614 case Mips::BI__builtin_msa_copy_s_b:
1615 case Mips::BI__builtin_msa_copy_u_b:
1616 case Mips::BI__builtin_msa_insve_b:
1617 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
1618 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
1619 // These intrinsics take an unsigned 3 bit immediate.
1620 case Mips::BI__builtin_msa_copy_s_h:
1621 case Mips::BI__builtin_msa_copy_u_h:
1622 case Mips::BI__builtin_msa_insve_h:
1623 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
1624 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
1625 // These intrinsics take an unsigned 2 bit immediate.
1626 case Mips::BI__builtin_msa_copy_s_w:
1627 case Mips::BI__builtin_msa_copy_u_w:
1628 case Mips::BI__builtin_msa_insve_w:
1629 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
1630 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
1631 // These intrinsics take an unsigned 1 bit immediate.
1632 case Mips::BI__builtin_msa_copy_s_d:
1633 case Mips::BI__builtin_msa_copy_u_d:
1634 case Mips::BI__builtin_msa_insve_d:
1635 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
1636 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
1637 // Memory offsets and immediate loads.
1638 // These intrinsics take a signed 10 bit immediate.
1639 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
1640 case Mips::BI__builtin_msa_ldi_h:
1641 case Mips::BI__builtin_msa_ldi_w:
1642 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
1643 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
1644 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
1645 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
1646 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
1647 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
1648 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
1649 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
1650 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
1654 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1656 return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
1657 SemaBuiltinConstantArgMultiple(TheCall, i, m);
1660 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1661 unsigned i = 0, l = 0, u = 0;
1662 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1663 BuiltinID == PPC::BI__builtin_divdeu ||
1664 BuiltinID == PPC::BI__builtin_bpermd;
1665 bool IsTarget64Bit = Context.getTargetInfo()
1666 .getTypeWidth(Context
1668 .getIntPtrType()) == 64;
1669 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1670 BuiltinID == PPC::BI__builtin_divweu ||
1671 BuiltinID == PPC::BI__builtin_divde ||
1672 BuiltinID == PPC::BI__builtin_divdeu;
1674 if (Is64BitBltin && !IsTarget64Bit)
1675 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1676 << TheCall->getSourceRange();
1678 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1679 (BuiltinID == PPC::BI__builtin_bpermd &&
1680 !Context.getTargetInfo().hasFeature("bpermd")))
1681 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1682 << TheCall->getSourceRange();
1684 switch (BuiltinID) {
1685 default: return false;
1686 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1687 case PPC::BI__builtin_altivec_crypto_vshasigmad:
1688 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1689 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1690 case PPC::BI__builtin_tbegin:
1691 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1692 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1693 case PPC::BI__builtin_tabortwc:
1694 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1695 case PPC::BI__builtin_tabortwci:
1696 case PPC::BI__builtin_tabortdci:
1697 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1698 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
1700 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1703 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1704 CallExpr *TheCall) {
1705 if (BuiltinID == SystemZ::BI__builtin_tabort) {
1706 Expr *Arg = TheCall->getArg(0);
1707 llvm::APSInt AbortCode(32);
1708 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1709 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1710 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1711 << Arg->getSourceRange();
1714 // For intrinsics which take an immediate value as part of the instruction,
1715 // range check them here.
1716 unsigned i = 0, l = 0, u = 0;
1717 switch (BuiltinID) {
1718 default: return false;
1719 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1720 case SystemZ::BI__builtin_s390_verimb:
1721 case SystemZ::BI__builtin_s390_verimh:
1722 case SystemZ::BI__builtin_s390_verimf:
1723 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1724 case SystemZ::BI__builtin_s390_vfaeb:
1725 case SystemZ::BI__builtin_s390_vfaeh:
1726 case SystemZ::BI__builtin_s390_vfaef:
1727 case SystemZ::BI__builtin_s390_vfaebs:
1728 case SystemZ::BI__builtin_s390_vfaehs:
1729 case SystemZ::BI__builtin_s390_vfaefs:
1730 case SystemZ::BI__builtin_s390_vfaezb:
1731 case SystemZ::BI__builtin_s390_vfaezh:
1732 case SystemZ::BI__builtin_s390_vfaezf:
1733 case SystemZ::BI__builtin_s390_vfaezbs:
1734 case SystemZ::BI__builtin_s390_vfaezhs:
1735 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1736 case SystemZ::BI__builtin_s390_vfidb:
1737 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1738 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1739 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1740 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1741 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1742 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1743 case SystemZ::BI__builtin_s390_vstrcb:
1744 case SystemZ::BI__builtin_s390_vstrch:
1745 case SystemZ::BI__builtin_s390_vstrcf:
1746 case SystemZ::BI__builtin_s390_vstrczb:
1747 case SystemZ::BI__builtin_s390_vstrczh:
1748 case SystemZ::BI__builtin_s390_vstrczf:
1749 case SystemZ::BI__builtin_s390_vstrcbs:
1750 case SystemZ::BI__builtin_s390_vstrchs:
1751 case SystemZ::BI__builtin_s390_vstrcfs:
1752 case SystemZ::BI__builtin_s390_vstrczbs:
1753 case SystemZ::BI__builtin_s390_vstrczhs:
1754 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1756 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1759 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1760 /// This checks that the target supports __builtin_cpu_supports and
1761 /// that the string argument is constant and valid.
1762 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1763 Expr *Arg = TheCall->getArg(0);
1765 // Check if the argument is a string literal.
1766 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1767 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1768 << Arg->getSourceRange();
1770 // Check the contents of the string.
1772 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1773 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1774 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1775 << Arg->getSourceRange();
1779 // Check if the rounding mode is legal.
1780 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
1781 // Indicates if this instruction has rounding control or just SAE.
1784 unsigned ArgNum = 0;
1785 switch (BuiltinID) {
1788 case X86::BI__builtin_ia32_vcvttsd2si32:
1789 case X86::BI__builtin_ia32_vcvttsd2si64:
1790 case X86::BI__builtin_ia32_vcvttsd2usi32:
1791 case X86::BI__builtin_ia32_vcvttsd2usi64:
1792 case X86::BI__builtin_ia32_vcvttss2si32:
1793 case X86::BI__builtin_ia32_vcvttss2si64:
1794 case X86::BI__builtin_ia32_vcvttss2usi32:
1795 case X86::BI__builtin_ia32_vcvttss2usi64:
1798 case X86::BI__builtin_ia32_cvtps2pd512_mask:
1799 case X86::BI__builtin_ia32_cvttpd2dq512_mask:
1800 case X86::BI__builtin_ia32_cvttpd2qq512_mask:
1801 case X86::BI__builtin_ia32_cvttpd2udq512_mask:
1802 case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
1803 case X86::BI__builtin_ia32_cvttps2dq512_mask:
1804 case X86::BI__builtin_ia32_cvttps2qq512_mask:
1805 case X86::BI__builtin_ia32_cvttps2udq512_mask:
1806 case X86::BI__builtin_ia32_cvttps2uqq512_mask:
1807 case X86::BI__builtin_ia32_exp2pd_mask:
1808 case X86::BI__builtin_ia32_exp2ps_mask:
1809 case X86::BI__builtin_ia32_getexppd512_mask:
1810 case X86::BI__builtin_ia32_getexpps512_mask:
1811 case X86::BI__builtin_ia32_rcp28pd_mask:
1812 case X86::BI__builtin_ia32_rcp28ps_mask:
1813 case X86::BI__builtin_ia32_rsqrt28pd_mask:
1814 case X86::BI__builtin_ia32_rsqrt28ps_mask:
1815 case X86::BI__builtin_ia32_vcomisd:
1816 case X86::BI__builtin_ia32_vcomiss:
1817 case X86::BI__builtin_ia32_vcvtph2ps512_mask:
1820 case X86::BI__builtin_ia32_cmppd512_mask:
1821 case X86::BI__builtin_ia32_cmpps512_mask:
1822 case X86::BI__builtin_ia32_cmpsd_mask:
1823 case X86::BI__builtin_ia32_cmpss_mask:
1824 case X86::BI__builtin_ia32_cvtss2sd_round_mask:
1825 case X86::BI__builtin_ia32_getexpsd128_round_mask:
1826 case X86::BI__builtin_ia32_getexpss128_round_mask:
1827 case X86::BI__builtin_ia32_maxpd512_mask:
1828 case X86::BI__builtin_ia32_maxps512_mask:
1829 case X86::BI__builtin_ia32_maxsd_round_mask:
1830 case X86::BI__builtin_ia32_maxss_round_mask:
1831 case X86::BI__builtin_ia32_minpd512_mask:
1832 case X86::BI__builtin_ia32_minps512_mask:
1833 case X86::BI__builtin_ia32_minsd_round_mask:
1834 case X86::BI__builtin_ia32_minss_round_mask:
1835 case X86::BI__builtin_ia32_rcp28sd_round_mask:
1836 case X86::BI__builtin_ia32_rcp28ss_round_mask:
1837 case X86::BI__builtin_ia32_reducepd512_mask:
1838 case X86::BI__builtin_ia32_reduceps512_mask:
1839 case X86::BI__builtin_ia32_rndscalepd_mask:
1840 case X86::BI__builtin_ia32_rndscaleps_mask:
1841 case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
1842 case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
1845 case X86::BI__builtin_ia32_fixupimmpd512_mask:
1846 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
1847 case X86::BI__builtin_ia32_fixupimmps512_mask:
1848 case X86::BI__builtin_ia32_fixupimmps512_maskz:
1849 case X86::BI__builtin_ia32_fixupimmsd_mask:
1850 case X86::BI__builtin_ia32_fixupimmsd_maskz:
1851 case X86::BI__builtin_ia32_fixupimmss_mask:
1852 case X86::BI__builtin_ia32_fixupimmss_maskz:
1853 case X86::BI__builtin_ia32_rangepd512_mask:
1854 case X86::BI__builtin_ia32_rangeps512_mask:
1855 case X86::BI__builtin_ia32_rangesd128_round_mask:
1856 case X86::BI__builtin_ia32_rangess128_round_mask:
1857 case X86::BI__builtin_ia32_reducesd_mask:
1858 case X86::BI__builtin_ia32_reducess_mask:
1859 case X86::BI__builtin_ia32_rndscalesd_round_mask:
1860 case X86::BI__builtin_ia32_rndscaless_round_mask:
1863 case X86::BI__builtin_ia32_vcvtsd2si64:
1864 case X86::BI__builtin_ia32_vcvtsd2si32:
1865 case X86::BI__builtin_ia32_vcvtsd2usi32:
1866 case X86::BI__builtin_ia32_vcvtsd2usi64:
1867 case X86::BI__builtin_ia32_vcvtss2si32:
1868 case X86::BI__builtin_ia32_vcvtss2si64:
1869 case X86::BI__builtin_ia32_vcvtss2usi32:
1870 case X86::BI__builtin_ia32_vcvtss2usi64:
1874 case X86::BI__builtin_ia32_cvtsi2sd64:
1875 case X86::BI__builtin_ia32_cvtsi2ss32:
1876 case X86::BI__builtin_ia32_cvtsi2ss64:
1877 case X86::BI__builtin_ia32_cvtusi2sd64:
1878 case X86::BI__builtin_ia32_cvtusi2ss32:
1879 case X86::BI__builtin_ia32_cvtusi2ss64:
1883 case X86::BI__builtin_ia32_cvtdq2ps512_mask:
1884 case X86::BI__builtin_ia32_cvtudq2ps512_mask:
1885 case X86::BI__builtin_ia32_cvtpd2ps512_mask:
1886 case X86::BI__builtin_ia32_cvtpd2qq512_mask:
1887 case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
1888 case X86::BI__builtin_ia32_cvtps2qq512_mask:
1889 case X86::BI__builtin_ia32_cvtps2uqq512_mask:
1890 case X86::BI__builtin_ia32_cvtqq2pd512_mask:
1891 case X86::BI__builtin_ia32_cvtqq2ps512_mask:
1892 case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
1893 case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
1894 case X86::BI__builtin_ia32_sqrtpd512_mask:
1895 case X86::BI__builtin_ia32_sqrtps512_mask:
1899 case X86::BI__builtin_ia32_addpd512_mask:
1900 case X86::BI__builtin_ia32_addps512_mask:
1901 case X86::BI__builtin_ia32_divpd512_mask:
1902 case X86::BI__builtin_ia32_divps512_mask:
1903 case X86::BI__builtin_ia32_mulpd512_mask:
1904 case X86::BI__builtin_ia32_mulps512_mask:
1905 case X86::BI__builtin_ia32_subpd512_mask:
1906 case X86::BI__builtin_ia32_subps512_mask:
1907 case X86::BI__builtin_ia32_addss_round_mask:
1908 case X86::BI__builtin_ia32_addsd_round_mask:
1909 case X86::BI__builtin_ia32_divss_round_mask:
1910 case X86::BI__builtin_ia32_divsd_round_mask:
1911 case X86::BI__builtin_ia32_mulss_round_mask:
1912 case X86::BI__builtin_ia32_mulsd_round_mask:
1913 case X86::BI__builtin_ia32_subss_round_mask:
1914 case X86::BI__builtin_ia32_subsd_round_mask:
1915 case X86::BI__builtin_ia32_scalefpd512_mask:
1916 case X86::BI__builtin_ia32_scalefps512_mask:
1917 case X86::BI__builtin_ia32_scalefsd_round_mask:
1918 case X86::BI__builtin_ia32_scalefss_round_mask:
1919 case X86::BI__builtin_ia32_getmantpd512_mask:
1920 case X86::BI__builtin_ia32_getmantps512_mask:
1921 case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
1922 case X86::BI__builtin_ia32_sqrtsd_round_mask:
1923 case X86::BI__builtin_ia32_sqrtss_round_mask:
1924 case X86::BI__builtin_ia32_vfmaddpd512_mask:
1925 case X86::BI__builtin_ia32_vfmaddpd512_mask3:
1926 case X86::BI__builtin_ia32_vfmaddpd512_maskz:
1927 case X86::BI__builtin_ia32_vfmaddps512_mask:
1928 case X86::BI__builtin_ia32_vfmaddps512_mask3:
1929 case X86::BI__builtin_ia32_vfmaddps512_maskz:
1930 case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
1931 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
1932 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
1933 case X86::BI__builtin_ia32_vfmaddsubps512_mask:
1934 case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
1935 case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
1936 case X86::BI__builtin_ia32_vfmsubpd512_mask3:
1937 case X86::BI__builtin_ia32_vfmsubps512_mask3:
1938 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
1939 case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
1940 case X86::BI__builtin_ia32_vfnmaddpd512_mask:
1941 case X86::BI__builtin_ia32_vfnmaddps512_mask:
1942 case X86::BI__builtin_ia32_vfnmsubpd512_mask:
1943 case X86::BI__builtin_ia32_vfnmsubpd512_mask3:
1944 case X86::BI__builtin_ia32_vfnmsubps512_mask:
1945 case X86::BI__builtin_ia32_vfnmsubps512_mask3:
1946 case X86::BI__builtin_ia32_vfmaddsd3_mask:
1947 case X86::BI__builtin_ia32_vfmaddsd3_maskz:
1948 case X86::BI__builtin_ia32_vfmaddsd3_mask3:
1949 case X86::BI__builtin_ia32_vfmaddss3_mask:
1950 case X86::BI__builtin_ia32_vfmaddss3_maskz:
1951 case X86::BI__builtin_ia32_vfmaddss3_mask3:
1955 case X86::BI__builtin_ia32_getmantsd_round_mask:
1956 case X86::BI__builtin_ia32_getmantss_round_mask:
1962 llvm::APSInt Result;
1964 // We can't check the value of a dependent argument.
1965 Expr *Arg = TheCall->getArg(ArgNum);
1966 if (Arg->isTypeDependent() || Arg->isValueDependent())
1969 // Check constant-ness first.
1970 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
1973 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
1974 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
1975 // combined with ROUND_NO_EXC.
1976 if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
1977 Result == 8/*ROUND_NO_EXC*/ ||
1978 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
1981 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
1982 << Arg->getSourceRange();
1985 // Check if the gather/scatter scale is legal.
1986 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
1987 CallExpr *TheCall) {
1988 unsigned ArgNum = 0;
1989 switch (BuiltinID) {
1992 case X86::BI__builtin_ia32_gatherpfdpd:
1993 case X86::BI__builtin_ia32_gatherpfdps:
1994 case X86::BI__builtin_ia32_gatherpfqpd:
1995 case X86::BI__builtin_ia32_gatherpfqps:
1996 case X86::BI__builtin_ia32_scatterpfdpd:
1997 case X86::BI__builtin_ia32_scatterpfdps:
1998 case X86::BI__builtin_ia32_scatterpfqpd:
1999 case X86::BI__builtin_ia32_scatterpfqps:
2002 case X86::BI__builtin_ia32_gatherd_pd:
2003 case X86::BI__builtin_ia32_gatherd_pd256:
2004 case X86::BI__builtin_ia32_gatherq_pd:
2005 case X86::BI__builtin_ia32_gatherq_pd256:
2006 case X86::BI__builtin_ia32_gatherd_ps:
2007 case X86::BI__builtin_ia32_gatherd_ps256:
2008 case X86::BI__builtin_ia32_gatherq_ps:
2009 case X86::BI__builtin_ia32_gatherq_ps256:
2010 case X86::BI__builtin_ia32_gatherd_q:
2011 case X86::BI__builtin_ia32_gatherd_q256:
2012 case X86::BI__builtin_ia32_gatherq_q:
2013 case X86::BI__builtin_ia32_gatherq_q256:
2014 case X86::BI__builtin_ia32_gatherd_d:
2015 case X86::BI__builtin_ia32_gatherd_d256:
2016 case X86::BI__builtin_ia32_gatherq_d:
2017 case X86::BI__builtin_ia32_gatherq_d256:
2018 case X86::BI__builtin_ia32_gather3div2df:
2019 case X86::BI__builtin_ia32_gather3div2di:
2020 case X86::BI__builtin_ia32_gather3div4df:
2021 case X86::BI__builtin_ia32_gather3div4di:
2022 case X86::BI__builtin_ia32_gather3div4sf:
2023 case X86::BI__builtin_ia32_gather3div4si:
2024 case X86::BI__builtin_ia32_gather3div8sf:
2025 case X86::BI__builtin_ia32_gather3div8si:
2026 case X86::BI__builtin_ia32_gather3siv2df:
2027 case X86::BI__builtin_ia32_gather3siv2di:
2028 case X86::BI__builtin_ia32_gather3siv4df:
2029 case X86::BI__builtin_ia32_gather3siv4di:
2030 case X86::BI__builtin_ia32_gather3siv4sf:
2031 case X86::BI__builtin_ia32_gather3siv4si:
2032 case X86::BI__builtin_ia32_gather3siv8sf:
2033 case X86::BI__builtin_ia32_gather3siv8si:
2034 case X86::BI__builtin_ia32_gathersiv8df:
2035 case X86::BI__builtin_ia32_gathersiv16sf:
2036 case X86::BI__builtin_ia32_gatherdiv8df:
2037 case X86::BI__builtin_ia32_gatherdiv16sf:
2038 case X86::BI__builtin_ia32_gathersiv8di:
2039 case X86::BI__builtin_ia32_gathersiv16si:
2040 case X86::BI__builtin_ia32_gatherdiv8di:
2041 case X86::BI__builtin_ia32_gatherdiv16si:
2042 case X86::BI__builtin_ia32_scatterdiv2df:
2043 case X86::BI__builtin_ia32_scatterdiv2di:
2044 case X86::BI__builtin_ia32_scatterdiv4df:
2045 case X86::BI__builtin_ia32_scatterdiv4di:
2046 case X86::BI__builtin_ia32_scatterdiv4sf:
2047 case X86::BI__builtin_ia32_scatterdiv4si:
2048 case X86::BI__builtin_ia32_scatterdiv8sf:
2049 case X86::BI__builtin_ia32_scatterdiv8si:
2050 case X86::BI__builtin_ia32_scattersiv2df:
2051 case X86::BI__builtin_ia32_scattersiv2di:
2052 case X86::BI__builtin_ia32_scattersiv4df:
2053 case X86::BI__builtin_ia32_scattersiv4di:
2054 case X86::BI__builtin_ia32_scattersiv4sf:
2055 case X86::BI__builtin_ia32_scattersiv4si:
2056 case X86::BI__builtin_ia32_scattersiv8sf:
2057 case X86::BI__builtin_ia32_scattersiv8si:
2058 case X86::BI__builtin_ia32_scattersiv8df:
2059 case X86::BI__builtin_ia32_scattersiv16sf:
2060 case X86::BI__builtin_ia32_scatterdiv8df:
2061 case X86::BI__builtin_ia32_scatterdiv16sf:
2062 case X86::BI__builtin_ia32_scattersiv8di:
2063 case X86::BI__builtin_ia32_scattersiv16si:
2064 case X86::BI__builtin_ia32_scatterdiv8di:
2065 case X86::BI__builtin_ia32_scatterdiv16si:
2070 llvm::APSInt Result;
2072 // We can't check the value of a dependent argument.
2073 Expr *Arg = TheCall->getArg(ArgNum);
2074 if (Arg->isTypeDependent() || Arg->isValueDependent())
2077 // Check constant-ness first.
2078 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2081 if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
2084 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale)
2085 << Arg->getSourceRange();
2088 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2089 if (BuiltinID == X86::BI__builtin_cpu_supports)
2090 return SemaBuiltinCpuSupports(*this, TheCall);
2092 if (BuiltinID == X86::BI__builtin_ms_va_start)
2093 return SemaBuiltinMSVAStart(TheCall);
2095 // If the intrinsic has rounding or SAE make sure its valid.
2096 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
2099 // If the intrinsic has a gather/scatter scale immediate make sure its valid.
2100 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
2103 // For intrinsics which take an immediate value as part of the instruction,
2104 // range check them here.
2105 int i = 0, l = 0, u = 0;
2106 switch (BuiltinID) {
2109 case X86::BI_mm_prefetch:
2110 i = 1; l = 0; u = 3;
2112 case X86::BI__builtin_ia32_sha1rnds4:
2113 case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
2114 case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
2115 case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
2116 case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
2117 i = 2; l = 0; u = 3;
2119 case X86::BI__builtin_ia32_vpermil2pd:
2120 case X86::BI__builtin_ia32_vpermil2pd256:
2121 case X86::BI__builtin_ia32_vpermil2ps:
2122 case X86::BI__builtin_ia32_vpermil2ps256:
2123 i = 3; l = 0; u = 3;
2125 case X86::BI__builtin_ia32_cmpb128_mask:
2126 case X86::BI__builtin_ia32_cmpw128_mask:
2127 case X86::BI__builtin_ia32_cmpd128_mask:
2128 case X86::BI__builtin_ia32_cmpq128_mask:
2129 case X86::BI__builtin_ia32_cmpb256_mask:
2130 case X86::BI__builtin_ia32_cmpw256_mask:
2131 case X86::BI__builtin_ia32_cmpd256_mask:
2132 case X86::BI__builtin_ia32_cmpq256_mask:
2133 case X86::BI__builtin_ia32_cmpb512_mask:
2134 case X86::BI__builtin_ia32_cmpw512_mask:
2135 case X86::BI__builtin_ia32_cmpd512_mask:
2136 case X86::BI__builtin_ia32_cmpq512_mask:
2137 case X86::BI__builtin_ia32_ucmpb128_mask:
2138 case X86::BI__builtin_ia32_ucmpw128_mask:
2139 case X86::BI__builtin_ia32_ucmpd128_mask:
2140 case X86::BI__builtin_ia32_ucmpq128_mask:
2141 case X86::BI__builtin_ia32_ucmpb256_mask:
2142 case X86::BI__builtin_ia32_ucmpw256_mask:
2143 case X86::BI__builtin_ia32_ucmpd256_mask:
2144 case X86::BI__builtin_ia32_ucmpq256_mask:
2145 case X86::BI__builtin_ia32_ucmpb512_mask:
2146 case X86::BI__builtin_ia32_ucmpw512_mask:
2147 case X86::BI__builtin_ia32_ucmpd512_mask:
2148 case X86::BI__builtin_ia32_ucmpq512_mask:
2149 case X86::BI__builtin_ia32_vpcomub:
2150 case X86::BI__builtin_ia32_vpcomuw:
2151 case X86::BI__builtin_ia32_vpcomud:
2152 case X86::BI__builtin_ia32_vpcomuq:
2153 case X86::BI__builtin_ia32_vpcomb:
2154 case X86::BI__builtin_ia32_vpcomw:
2155 case X86::BI__builtin_ia32_vpcomd:
2156 case X86::BI__builtin_ia32_vpcomq:
2157 i = 2; l = 0; u = 7;
2159 case X86::BI__builtin_ia32_roundps:
2160 case X86::BI__builtin_ia32_roundpd:
2161 case X86::BI__builtin_ia32_roundps256:
2162 case X86::BI__builtin_ia32_roundpd256:
2163 i = 1; l = 0; u = 15;
2165 case X86::BI__builtin_ia32_roundss:
2166 case X86::BI__builtin_ia32_roundsd:
2167 case X86::BI__builtin_ia32_rangepd128_mask:
2168 case X86::BI__builtin_ia32_rangepd256_mask:
2169 case X86::BI__builtin_ia32_rangepd512_mask:
2170 case X86::BI__builtin_ia32_rangeps128_mask:
2171 case X86::BI__builtin_ia32_rangeps256_mask:
2172 case X86::BI__builtin_ia32_rangeps512_mask:
2173 case X86::BI__builtin_ia32_getmantsd_round_mask:
2174 case X86::BI__builtin_ia32_getmantss_round_mask:
2175 i = 2; l = 0; u = 15;
2177 case X86::BI__builtin_ia32_cmpps:
2178 case X86::BI__builtin_ia32_cmpss:
2179 case X86::BI__builtin_ia32_cmppd:
2180 case X86::BI__builtin_ia32_cmpsd:
2181 case X86::BI__builtin_ia32_cmpps256:
2182 case X86::BI__builtin_ia32_cmppd256:
2183 case X86::BI__builtin_ia32_cmpps128_mask:
2184 case X86::BI__builtin_ia32_cmppd128_mask:
2185 case X86::BI__builtin_ia32_cmpps256_mask:
2186 case X86::BI__builtin_ia32_cmppd256_mask:
2187 case X86::BI__builtin_ia32_cmpps512_mask:
2188 case X86::BI__builtin_ia32_cmppd512_mask:
2189 case X86::BI__builtin_ia32_cmpsd_mask:
2190 case X86::BI__builtin_ia32_cmpss_mask:
2191 i = 2; l = 0; u = 31;
2193 case X86::BI__builtin_ia32_xabort:
2194 i = 0; l = -128; u = 255;
2196 case X86::BI__builtin_ia32_pshufw:
2197 case X86::BI__builtin_ia32_aeskeygenassist128:
2198 i = 1; l = -128; u = 255;
2200 case X86::BI__builtin_ia32_vcvtps2ph:
2201 case X86::BI__builtin_ia32_vcvtps2ph256:
2202 case X86::BI__builtin_ia32_rndscaleps_128_mask:
2203 case X86::BI__builtin_ia32_rndscalepd_128_mask:
2204 case X86::BI__builtin_ia32_rndscaleps_256_mask:
2205 case X86::BI__builtin_ia32_rndscalepd_256_mask:
2206 case X86::BI__builtin_ia32_rndscaleps_mask:
2207 case X86::BI__builtin_ia32_rndscalepd_mask:
2208 case X86::BI__builtin_ia32_reducepd128_mask:
2209 case X86::BI__builtin_ia32_reducepd256_mask:
2210 case X86::BI__builtin_ia32_reducepd512_mask:
2211 case X86::BI__builtin_ia32_reduceps128_mask:
2212 case X86::BI__builtin_ia32_reduceps256_mask:
2213 case X86::BI__builtin_ia32_reduceps512_mask:
2214 case X86::BI__builtin_ia32_prold512_mask:
2215 case X86::BI__builtin_ia32_prolq512_mask:
2216 case X86::BI__builtin_ia32_prold128_mask:
2217 case X86::BI__builtin_ia32_prold256_mask:
2218 case X86::BI__builtin_ia32_prolq128_mask:
2219 case X86::BI__builtin_ia32_prolq256_mask:
2220 case X86::BI__builtin_ia32_prord128_mask:
2221 case X86::BI__builtin_ia32_prord256_mask:
2222 case X86::BI__builtin_ia32_prorq128_mask:
2223 case X86::BI__builtin_ia32_prorq256_mask:
2224 case X86::BI__builtin_ia32_fpclasspd128_mask:
2225 case X86::BI__builtin_ia32_fpclasspd256_mask:
2226 case X86::BI__builtin_ia32_fpclassps128_mask:
2227 case X86::BI__builtin_ia32_fpclassps256_mask:
2228 case X86::BI__builtin_ia32_fpclassps512_mask:
2229 case X86::BI__builtin_ia32_fpclasspd512_mask:
2230 case X86::BI__builtin_ia32_fpclasssd_mask:
2231 case X86::BI__builtin_ia32_fpclassss_mask:
2232 i = 1; l = 0; u = 255;
2234 case X86::BI__builtin_ia32_palignr:
2235 case X86::BI__builtin_ia32_insertps128:
2236 case X86::BI__builtin_ia32_dpps:
2237 case X86::BI__builtin_ia32_dppd:
2238 case X86::BI__builtin_ia32_dpps256:
2239 case X86::BI__builtin_ia32_mpsadbw128:
2240 case X86::BI__builtin_ia32_mpsadbw256:
2241 case X86::BI__builtin_ia32_pcmpistrm128:
2242 case X86::BI__builtin_ia32_pcmpistri128:
2243 case X86::BI__builtin_ia32_pcmpistria128:
2244 case X86::BI__builtin_ia32_pcmpistric128:
2245 case X86::BI__builtin_ia32_pcmpistrio128:
2246 case X86::BI__builtin_ia32_pcmpistris128:
2247 case X86::BI__builtin_ia32_pcmpistriz128:
2248 case X86::BI__builtin_ia32_pclmulqdq128:
2249 case X86::BI__builtin_ia32_vperm2f128_pd256:
2250 case X86::BI__builtin_ia32_vperm2f128_ps256:
2251 case X86::BI__builtin_ia32_vperm2f128_si256:
2252 case X86::BI__builtin_ia32_permti256:
2253 i = 2; l = -128; u = 255;
2255 case X86::BI__builtin_ia32_palignr128:
2256 case X86::BI__builtin_ia32_palignr256:
2257 case X86::BI__builtin_ia32_palignr512_mask:
2258 case X86::BI__builtin_ia32_vcomisd:
2259 case X86::BI__builtin_ia32_vcomiss:
2260 case X86::BI__builtin_ia32_shuf_f32x4_mask:
2261 case X86::BI__builtin_ia32_shuf_f64x2_mask:
2262 case X86::BI__builtin_ia32_shuf_i32x4_mask:
2263 case X86::BI__builtin_ia32_shuf_i64x2_mask:
2264 case X86::BI__builtin_ia32_dbpsadbw128_mask:
2265 case X86::BI__builtin_ia32_dbpsadbw256_mask:
2266 case X86::BI__builtin_ia32_dbpsadbw512_mask:
2267 i = 2; l = 0; u = 255;
2269 case X86::BI__builtin_ia32_fixupimmpd512_mask:
2270 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2271 case X86::BI__builtin_ia32_fixupimmps512_mask:
2272 case X86::BI__builtin_ia32_fixupimmps512_maskz:
2273 case X86::BI__builtin_ia32_fixupimmsd_mask:
2274 case X86::BI__builtin_ia32_fixupimmsd_maskz:
2275 case X86::BI__builtin_ia32_fixupimmss_mask:
2276 case X86::BI__builtin_ia32_fixupimmss_maskz:
2277 case X86::BI__builtin_ia32_fixupimmpd128_mask:
2278 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2279 case X86::BI__builtin_ia32_fixupimmpd256_mask:
2280 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2281 case X86::BI__builtin_ia32_fixupimmps128_mask:
2282 case X86::BI__builtin_ia32_fixupimmps128_maskz:
2283 case X86::BI__builtin_ia32_fixupimmps256_mask:
2284 case X86::BI__builtin_ia32_fixupimmps256_maskz:
2285 case X86::BI__builtin_ia32_pternlogd512_mask:
2286 case X86::BI__builtin_ia32_pternlogd512_maskz:
2287 case X86::BI__builtin_ia32_pternlogq512_mask:
2288 case X86::BI__builtin_ia32_pternlogq512_maskz:
2289 case X86::BI__builtin_ia32_pternlogd128_mask:
2290 case X86::BI__builtin_ia32_pternlogd128_maskz:
2291 case X86::BI__builtin_ia32_pternlogd256_mask:
2292 case X86::BI__builtin_ia32_pternlogd256_maskz:
2293 case X86::BI__builtin_ia32_pternlogq128_mask:
2294 case X86::BI__builtin_ia32_pternlogq128_maskz:
2295 case X86::BI__builtin_ia32_pternlogq256_mask:
2296 case X86::BI__builtin_ia32_pternlogq256_maskz:
2297 i = 3; l = 0; u = 255;
2299 case X86::BI__builtin_ia32_gatherpfdpd:
2300 case X86::BI__builtin_ia32_gatherpfdps:
2301 case X86::BI__builtin_ia32_gatherpfqpd:
2302 case X86::BI__builtin_ia32_gatherpfqps:
2303 case X86::BI__builtin_ia32_scatterpfdpd:
2304 case X86::BI__builtin_ia32_scatterpfdps:
2305 case X86::BI__builtin_ia32_scatterpfqpd:
2306 case X86::BI__builtin_ia32_scatterpfqps:
2307 i = 4; l = 2; u = 3;
2309 case X86::BI__builtin_ia32_pcmpestrm128:
2310 case X86::BI__builtin_ia32_pcmpestri128:
2311 case X86::BI__builtin_ia32_pcmpestria128:
2312 case X86::BI__builtin_ia32_pcmpestric128:
2313 case X86::BI__builtin_ia32_pcmpestrio128:
2314 case X86::BI__builtin_ia32_pcmpestris128:
2315 case X86::BI__builtin_ia32_pcmpestriz128:
2316 i = 4; l = -128; u = 255;
2318 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2319 case X86::BI__builtin_ia32_rndscaless_round_mask:
2320 i = 4; l = 0; u = 255;
2323 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2326 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2327 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
2328 /// Returns true when the format fits the function and the FormatStringInfo has
2330 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2331 FormatStringInfo *FSI) {
2332 FSI->HasVAListArg = Format->getFirstArg() == 0;
2333 FSI->FormatIdx = Format->getFormatIdx() - 1;
2334 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
2336 // The way the format attribute works in GCC, the implicit this argument
2337 // of member functions is counted. However, it doesn't appear in our own
2338 // lists, so decrement format_idx in that case.
2340 if(FSI->FormatIdx == 0)
2343 if (FSI->FirstDataArg != 0)
2344 --FSI->FirstDataArg;
2349 /// Checks if a the given expression evaluates to null.
2351 /// \brief Returns true if the value evaluates to null.
2352 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
2353 // If the expression has non-null type, it doesn't evaluate to null.
2354 if (auto nullability
2355 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2356 if (*nullability == NullabilityKind::NonNull)
2360 // As a special case, transparent unions initialized with zero are
2361 // considered null for the purposes of the nonnull attribute.
2362 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
2363 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2364 if (const CompoundLiteralExpr *CLE =
2365 dyn_cast<CompoundLiteralExpr>(Expr))
2366 if (const InitListExpr *ILE =
2367 dyn_cast<InitListExpr>(CLE->getInitializer()))
2368 Expr = ILE->getInit(0);
2372 return (!Expr->isValueDependent() &&
2373 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2377 static void CheckNonNullArgument(Sema &S,
2378 const Expr *ArgExpr,
2379 SourceLocation CallSiteLoc) {
2380 if (CheckNonNullExpr(S, ArgExpr))
2381 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2382 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
2385 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2386 FormatStringInfo FSI;
2387 if ((GetFormatStringType(Format) == FST_NSString) &&
2388 getFormatStringInfo(Format, false, &FSI)) {
2389 Idx = FSI.FormatIdx;
2394 /// \brief Diagnose use of %s directive in an NSString which is being passed
2395 /// as formatting string to formatting method.
2397 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
2398 const NamedDecl *FDecl,
2402 bool Format = false;
2403 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2404 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
2409 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2410 if (S.GetFormatNSStringIdx(I, Idx)) {
2415 if (!Format || NumArgs <= Idx)
2417 const Expr *FormatExpr = Args[Idx];
2418 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2419 FormatExpr = CSCE->getSubExpr();
2420 const StringLiteral *FormatString;
2421 if (const ObjCStringLiteral *OSL =
2422 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2423 FormatString = OSL->getString();
2425 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2428 if (S.FormatStringHasSArg(FormatString)) {
2429 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2431 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2432 << FDecl->getDeclName();
2436 /// Determine whether the given type has a non-null nullability annotation.
2437 static bool isNonNullType(ASTContext &ctx, QualType type) {
2438 if (auto nullability = type->getNullability(ctx))
2439 return *nullability == NullabilityKind::NonNull;
2444 static void CheckNonNullArguments(Sema &S,
2445 const NamedDecl *FDecl,
2446 const FunctionProtoType *Proto,
2447 ArrayRef<const Expr *> Args,
2448 SourceLocation CallSiteLoc) {
2449 assert((FDecl || Proto) && "Need a function declaration or prototype");
2451 // Check the attributes attached to the method/function itself.
2452 llvm::SmallBitVector NonNullArgs;
2454 // Handle the nonnull attribute on the function/method declaration itself.
2455 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2456 if (!NonNull->args_size()) {
2457 // Easy case: all pointer arguments are nonnull.
2458 for (const auto *Arg : Args)
2459 if (S.isValidPointerAttrType(Arg->getType()))
2460 CheckNonNullArgument(S, Arg, CallSiteLoc);
2464 for (unsigned Val : NonNull->args()) {
2465 if (Val >= Args.size())
2467 if (NonNullArgs.empty())
2468 NonNullArgs.resize(Args.size());
2469 NonNullArgs.set(Val);
2474 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2475 // Handle the nonnull attribute on the parameters of the
2477 ArrayRef<ParmVarDecl*> parms;
2478 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2479 parms = FD->parameters();
2481 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2483 unsigned ParamIndex = 0;
2484 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2485 I != E; ++I, ++ParamIndex) {
2486 const ParmVarDecl *PVD = *I;
2487 if (PVD->hasAttr<NonNullAttr>() ||
2488 isNonNullType(S.Context, PVD->getType())) {
2489 if (NonNullArgs.empty())
2490 NonNullArgs.resize(Args.size());
2492 NonNullArgs.set(ParamIndex);
2496 // If we have a non-function, non-method declaration but no
2497 // function prototype, try to dig out the function prototype.
2499 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2500 QualType type = VD->getType().getNonReferenceType();
2501 if (auto pointerType = type->getAs<PointerType>())
2502 type = pointerType->getPointeeType();
2503 else if (auto blockType = type->getAs<BlockPointerType>())
2504 type = blockType->getPointeeType();
2505 // FIXME: data member pointers?
2507 // Dig out the function prototype, if there is one.
2508 Proto = type->getAs<FunctionProtoType>();
2512 // Fill in non-null argument information from the nullability
2513 // information on the parameter types (if we have them).
2516 for (auto paramType : Proto->getParamTypes()) {
2517 if (isNonNullType(S.Context, paramType)) {
2518 if (NonNullArgs.empty())
2519 NonNullArgs.resize(Args.size());
2521 NonNullArgs.set(Index);
2529 // Check for non-null arguments.
2530 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2531 ArgIndex != ArgIndexEnd; ++ArgIndex) {
2532 if (NonNullArgs[ArgIndex])
2533 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
2537 /// Handles the checks for format strings, non-POD arguments to vararg
2538 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
2540 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
2541 const Expr *ThisArg, ArrayRef<const Expr *> Args,
2542 bool IsMemberFunction, SourceLocation Loc,
2543 SourceRange Range, VariadicCallType CallType) {
2544 // FIXME: We should check as much as we can in the template definition.
2545 if (CurContext->isDependentContext())
2548 // Printf and scanf checking.
2549 llvm::SmallBitVector CheckedVarArgs;
2551 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2552 // Only create vector if there are format attributes.
2553 CheckedVarArgs.resize(Args.size());
2555 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
2560 // Refuse POD arguments that weren't caught by the format string
2562 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
2563 if (CallType != VariadicDoesNotApply &&
2564 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
2565 unsigned NumParams = Proto ? Proto->getNumParams()
2566 : FDecl && isa<FunctionDecl>(FDecl)
2567 ? cast<FunctionDecl>(FDecl)->getNumParams()
2568 : FDecl && isa<ObjCMethodDecl>(FDecl)
2569 ? cast<ObjCMethodDecl>(FDecl)->param_size()
2572 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
2573 // Args[ArgIdx] can be null in malformed code.
2574 if (const Expr *Arg = Args[ArgIdx]) {
2575 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
2576 checkVariadicArgument(Arg, CallType);
2581 if (FDecl || Proto) {
2582 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
2584 // Type safety checking.
2586 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
2587 CheckArgumentWithTypeTag(I, Args.data());
2592 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
2595 /// CheckConstructorCall - Check a constructor call for correctness and safety
2596 /// properties not enforced by the C type system.
2597 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
2598 ArrayRef<const Expr *> Args,
2599 const FunctionProtoType *Proto,
2600 SourceLocation Loc) {
2601 VariadicCallType CallType =
2602 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
2603 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
2604 Loc, SourceRange(), CallType);
2607 /// CheckFunctionCall - Check a direct function call for various correctness
2608 /// and safety properties not strictly enforced by the C type system.
2609 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2610 const FunctionProtoType *Proto) {
2611 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2612 isa<CXXMethodDecl>(FDecl);
2613 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2614 IsMemberOperatorCall;
2615 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2616 TheCall->getCallee());
2617 Expr** Args = TheCall->getArgs();
2618 unsigned NumArgs = TheCall->getNumArgs();
2620 Expr *ImplicitThis = nullptr;
2621 if (IsMemberOperatorCall) {
2622 // If this is a call to a member operator, hide the first argument
2624 // FIXME: Our choice of AST representation here is less than ideal.
2625 ImplicitThis = Args[0];
2628 } else if (IsMemberFunction)
2630 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
2632 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
2633 IsMemberFunction, TheCall->getRParenLoc(),
2634 TheCall->getCallee()->getSourceRange(), CallType);
2636 IdentifierInfo *FnInfo = FDecl->getIdentifier();
2637 // None of the checks below are needed for functions that don't have
2638 // simple names (e.g., C++ conversion functions).
2642 CheckAbsoluteValueFunction(TheCall, FDecl);
2643 CheckMaxUnsignedZero(TheCall, FDecl);
2645 if (getLangOpts().ObjC1)
2646 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
2648 unsigned CMId = FDecl->getMemoryFunctionKind();
2652 // Handle memory setting and copying functions.
2653 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
2654 CheckStrlcpycatArguments(TheCall, FnInfo);
2655 else if (CMId == Builtin::BIstrncat)
2656 CheckStrncatArguments(TheCall, FnInfo);
2658 CheckMemaccessArguments(TheCall, CMId, FnInfo);
2663 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
2664 ArrayRef<const Expr *> Args) {
2665 VariadicCallType CallType =
2666 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
2668 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
2669 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
2675 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2676 const FunctionProtoType *Proto) {
2678 if (const auto *V = dyn_cast<VarDecl>(NDecl))
2679 Ty = V->getType().getNonReferenceType();
2680 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
2681 Ty = F->getType().getNonReferenceType();
2685 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2686 !Ty->isFunctionProtoType())
2689 VariadicCallType CallType;
2690 if (!Proto || !Proto->isVariadic()) {
2691 CallType = VariadicDoesNotApply;
2692 } else if (Ty->isBlockPointerType()) {
2693 CallType = VariadicBlock;
2694 } else { // Ty->isFunctionPointerType()
2695 CallType = VariadicFunction;
2698 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
2699 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2700 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
2701 TheCall->getCallee()->getSourceRange(), CallType);
2706 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2707 /// such as function pointers returned from functions.
2708 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
2709 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
2710 TheCall->getCallee());
2711 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
2712 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2713 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
2714 TheCall->getCallee()->getSourceRange(), CallType);
2719 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
2720 if (!llvm::isValidAtomicOrderingCABI(Ordering))
2723 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
2725 case AtomicExpr::AO__c11_atomic_init:
2726 llvm_unreachable("There is no ordering argument for an init");
2728 case AtomicExpr::AO__c11_atomic_load:
2729 case AtomicExpr::AO__atomic_load_n:
2730 case AtomicExpr::AO__atomic_load:
2731 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2732 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2734 case AtomicExpr::AO__c11_atomic_store:
2735 case AtomicExpr::AO__atomic_store:
2736 case AtomicExpr::AO__atomic_store_n:
2737 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2738 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2739 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2746 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2747 AtomicExpr::AtomicOp Op) {
2748 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2749 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2751 // All these operations take one of the following forms:
2753 // C __c11_atomic_init(A *, C)
2755 // C __c11_atomic_load(A *, int)
2757 // void __atomic_load(A *, CP, int)
2759 // void __atomic_store(A *, CP, int)
2761 // C __c11_atomic_add(A *, M, int)
2763 // C __atomic_exchange_n(A *, CP, int)
2765 // void __atomic_exchange(A *, C *, CP, int)
2767 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
2769 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
2772 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2773 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
2775 // C is an appropriate type,
2776 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
2777 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
2778 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
2779 // the int parameters are for orderings.
2781 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
2782 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
2783 AtomicExpr::AO__atomic_load,
2784 "need to update code for modified C11 atomics");
2785 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
2786 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
2787 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
2788 Op == AtomicExpr::AO__atomic_store_n ||
2789 Op == AtomicExpr::AO__atomic_exchange_n ||
2790 Op == AtomicExpr::AO__atomic_compare_exchange_n;
2791 bool IsAddSub = false;
2794 case AtomicExpr::AO__c11_atomic_init:
2798 case AtomicExpr::AO__c11_atomic_load:
2799 case AtomicExpr::AO__atomic_load_n:
2803 case AtomicExpr::AO__atomic_load:
2807 case AtomicExpr::AO__c11_atomic_store:
2808 case AtomicExpr::AO__atomic_store:
2809 case AtomicExpr::AO__atomic_store_n:
2813 case AtomicExpr::AO__c11_atomic_fetch_add:
2814 case AtomicExpr::AO__c11_atomic_fetch_sub:
2815 case AtomicExpr::AO__atomic_fetch_add:
2816 case AtomicExpr::AO__atomic_fetch_sub:
2817 case AtomicExpr::AO__atomic_add_fetch:
2818 case AtomicExpr::AO__atomic_sub_fetch:
2821 case AtomicExpr::AO__c11_atomic_fetch_and:
2822 case AtomicExpr::AO__c11_atomic_fetch_or:
2823 case AtomicExpr::AO__c11_atomic_fetch_xor:
2824 case AtomicExpr::AO__atomic_fetch_and:
2825 case AtomicExpr::AO__atomic_fetch_or:
2826 case AtomicExpr::AO__atomic_fetch_xor:
2827 case AtomicExpr::AO__atomic_fetch_nand:
2828 case AtomicExpr::AO__atomic_and_fetch:
2829 case AtomicExpr::AO__atomic_or_fetch:
2830 case AtomicExpr::AO__atomic_xor_fetch:
2831 case AtomicExpr::AO__atomic_nand_fetch:
2835 case AtomicExpr::AO__c11_atomic_exchange:
2836 case AtomicExpr::AO__atomic_exchange_n:
2840 case AtomicExpr::AO__atomic_exchange:
2844 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
2845 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
2849 case AtomicExpr::AO__atomic_compare_exchange:
2850 case AtomicExpr::AO__atomic_compare_exchange_n:
2855 // Check we have the right number of arguments.
2856 if (TheCall->getNumArgs() < NumArgs[Form]) {
2857 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
2858 << 0 << NumArgs[Form] << TheCall->getNumArgs()
2859 << TheCall->getCallee()->getSourceRange();
2861 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
2862 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
2863 diag::err_typecheck_call_too_many_args)
2864 << 0 << NumArgs[Form] << TheCall->getNumArgs()
2865 << TheCall->getCallee()->getSourceRange();
2869 // Inspect the first argument of the atomic operation.
2870 Expr *Ptr = TheCall->getArg(0);
2871 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
2872 if (ConvertedPtr.isInvalid())
2875 Ptr = ConvertedPtr.get();
2876 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
2878 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
2879 << Ptr->getType() << Ptr->getSourceRange();
2883 // For a __c11 builtin, this should be a pointer to an _Atomic type.
2884 QualType AtomTy = pointerType->getPointeeType(); // 'A'
2885 QualType ValType = AtomTy; // 'C'
2887 if (!AtomTy->isAtomicType()) {
2888 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
2889 << Ptr->getType() << Ptr->getSourceRange();
2892 if (AtomTy.isConstQualified()) {
2893 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
2894 << Ptr->getType() << Ptr->getSourceRange();
2897 ValType = AtomTy->getAs<AtomicType>()->getValueType();
2898 } else if (Form != Load && Form != LoadCopy) {
2899 if (ValType.isConstQualified()) {
2900 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
2901 << Ptr->getType() << Ptr->getSourceRange();
2906 // For an arithmetic operation, the implied arithmetic must be well-formed.
2907 if (Form == Arithmetic) {
2908 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
2909 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
2910 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
2911 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2914 if (!IsAddSub && !ValType->isIntegerType()) {
2915 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
2916 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2919 if (IsC11 && ValType->isPointerType() &&
2920 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
2921 diag::err_incomplete_type)) {
2924 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
2925 // For __atomic_*_n operations, the value type must be a scalar integral or
2926 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
2927 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
2928 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2932 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
2933 !AtomTy->isScalarType()) {
2934 // For GNU atomics, require a trivially-copyable type. This is not part of
2935 // the GNU atomics specification, but we enforce it for sanity.
2936 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
2937 << Ptr->getType() << Ptr->getSourceRange();
2941 switch (ValType.getObjCLifetime()) {
2942 case Qualifiers::OCL_None:
2943 case Qualifiers::OCL_ExplicitNone:
2947 case Qualifiers::OCL_Weak:
2948 case Qualifiers::OCL_Strong:
2949 case Qualifiers::OCL_Autoreleasing:
2950 // FIXME: Can this happen? By this point, ValType should be known
2951 // to be trivially copyable.
2952 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
2953 << ValType << Ptr->getSourceRange();
2957 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
2958 // volatile-ness of the pointee-type inject itself into the result or the
2959 // other operands. Similarly atomic_load can take a pointer to a const 'A'.
2960 ValType.removeLocalVolatile();
2961 ValType.removeLocalConst();
2962 QualType ResultType = ValType;
2963 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init)
2964 ResultType = Context.VoidTy;
2965 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
2966 ResultType = Context.BoolTy;
2968 // The type of a parameter passed 'by value'. In the GNU atomics, such
2969 // arguments are actually passed as pointers.
2970 QualType ByValType = ValType; // 'CP'
2972 ByValType = Ptr->getType();
2974 // The first argument --- the pointer --- has a fixed type; we
2975 // deduce the types of the rest of the arguments accordingly. Walk
2976 // the remaining arguments, converting them to the deduced value type.
2977 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
2979 if (i < NumVals[Form] + 1) {
2982 // The second argument is the non-atomic operand. For arithmetic, this
2983 // is always passed by value, and for a compare_exchange it is always
2984 // passed by address. For the rest, GNU uses by-address and C11 uses
2986 assert(Form != Load);
2987 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
2989 else if (Form == Copy || Form == Xchg)
2991 else if (Form == Arithmetic)
2992 Ty = Context.getPointerDiffType();
2994 Expr *ValArg = TheCall->getArg(i);
2995 // Treat this argument as _Nonnull as we want to show a warning if
2996 // NULL is passed into it.
2997 CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
2999 // Keep address space of non-atomic pointer type.
3000 if (const PointerType *PtrTy =
3001 ValArg->getType()->getAs<PointerType>()) {
3002 AS = PtrTy->getPointeeType().getAddressSpace();
3004 Ty = Context.getPointerType(
3005 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
3009 // The third argument to compare_exchange / GNU exchange is a
3010 // (pointer to a) desired value.
3014 // The fourth argument to GNU compare_exchange is a 'weak' flag.
3015 Ty = Context.BoolTy;
3019 // The order(s) are always converted to int.
3023 InitializedEntity Entity =
3024 InitializedEntity::InitializeParameter(Context, Ty, false);
3025 ExprResult Arg = TheCall->getArg(i);
3026 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3027 if (Arg.isInvalid())
3029 TheCall->setArg(i, Arg.get());
3032 // Permute the arguments into a 'consistent' order.
3033 SmallVector<Expr*, 5> SubExprs;
3034 SubExprs.push_back(Ptr);
3037 // Note, AtomicExpr::getVal1() has a special case for this atomic.
3038 SubExprs.push_back(TheCall->getArg(1)); // Val1
3041 SubExprs.push_back(TheCall->getArg(1)); // Order
3047 SubExprs.push_back(TheCall->getArg(2)); // Order
3048 SubExprs.push_back(TheCall->getArg(1)); // Val1
3051 // Note, AtomicExpr::getVal2() has a special case for this atomic.
3052 SubExprs.push_back(TheCall->getArg(3)); // Order
3053 SubExprs.push_back(TheCall->getArg(1)); // Val1
3054 SubExprs.push_back(TheCall->getArg(2)); // Val2
3057 SubExprs.push_back(TheCall->getArg(3)); // Order
3058 SubExprs.push_back(TheCall->getArg(1)); // Val1
3059 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
3060 SubExprs.push_back(TheCall->getArg(2)); // Val2
3063 SubExprs.push_back(TheCall->getArg(4)); // Order
3064 SubExprs.push_back(TheCall->getArg(1)); // Val1
3065 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
3066 SubExprs.push_back(TheCall->getArg(2)); // Val2
3067 SubExprs.push_back(TheCall->getArg(3)); // Weak
3071 if (SubExprs.size() >= 2 && Form != Init) {
3072 llvm::APSInt Result(32);
3073 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
3074 !isValidOrderingForOp(Result.getSExtValue(), Op))
3075 Diag(SubExprs[1]->getLocStart(),
3076 diag::warn_atomic_op_has_invalid_memory_order)
3077 << SubExprs[1]->getSourceRange();
3080 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
3081 SubExprs, ResultType, Op,
3082 TheCall->getRParenLoc());
3084 if ((Op == AtomicExpr::AO__c11_atomic_load ||
3085 (Op == AtomicExpr::AO__c11_atomic_store)) &&
3086 Context.AtomicUsesUnsupportedLibcall(AE))
3087 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
3088 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
3093 /// checkBuiltinArgument - Given a call to a builtin function, perform
3094 /// normal type-checking on the given argument, updating the call in
3095 /// place. This is useful when a builtin function requires custom
3096 /// type-checking for some of its arguments but not necessarily all of
3099 /// Returns true on error.
3100 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
3101 FunctionDecl *Fn = E->getDirectCallee();
3102 assert(Fn && "builtin call without direct callee!");
3104 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
3105 InitializedEntity Entity =
3106 InitializedEntity::InitializeParameter(S.Context, Param);
3108 ExprResult Arg = E->getArg(0);
3109 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
3110 if (Arg.isInvalid())
3113 E->setArg(ArgIndex, Arg.get());
3117 /// SemaBuiltinAtomicOverloaded - We have a call to a function like
3118 /// __sync_fetch_and_add, which is an overloaded function based on the pointer
3119 /// type of its first argument. The main ActOnCallExpr routines have already
3120 /// promoted the types of arguments because all of these calls are prototyped as
3123 /// This function goes through and does final semantic checking for these
3126 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
3127 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3128 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3129 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3131 // Ensure that we have at least one argument to do type inference from.
3132 if (TheCall->getNumArgs() < 1) {
3133 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3134 << 0 << 1 << TheCall->getNumArgs()
3135 << TheCall->getCallee()->getSourceRange();
3139 // Inspect the first argument of the atomic builtin. This should always be
3140 // a pointer type, whose element is an integral scalar or pointer type.
3141 // Because it is a pointer type, we don't have to worry about any implicit
3143 // FIXME: We don't allow floating point scalars as input.
3144 Expr *FirstArg = TheCall->getArg(0);
3145 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3146 if (FirstArgResult.isInvalid())
3148 FirstArg = FirstArgResult.get();
3149 TheCall->setArg(0, FirstArg);
3151 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3153 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3154 << FirstArg->getType() << FirstArg->getSourceRange();
3158 QualType ValType = pointerType->getPointeeType();
3159 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3160 !ValType->isBlockPointerType()) {
3161 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3162 << FirstArg->getType() << FirstArg->getSourceRange();
3166 switch (ValType.getObjCLifetime()) {
3167 case Qualifiers::OCL_None:
3168 case Qualifiers::OCL_ExplicitNone:
3172 case Qualifiers::OCL_Weak:
3173 case Qualifiers::OCL_Strong:
3174 case Qualifiers::OCL_Autoreleasing:
3175 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3176 << ValType << FirstArg->getSourceRange();
3180 // Strip any qualifiers off ValType.
3181 ValType = ValType.getUnqualifiedType();
3183 // The majority of builtins return a value, but a few have special return
3184 // types, so allow them to override appropriately below.
3185 QualType ResultType = ValType;
3187 // We need to figure out which concrete builtin this maps onto. For example,
3188 // __sync_fetch_and_add with a 2 byte object turns into
3189 // __sync_fetch_and_add_2.
3190 #define BUILTIN_ROW(x) \
3191 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3192 Builtin::BI##x##_8, Builtin::BI##x##_16 }
3194 static const unsigned BuiltinIndices[][5] = {
3195 BUILTIN_ROW(__sync_fetch_and_add),
3196 BUILTIN_ROW(__sync_fetch_and_sub),
3197 BUILTIN_ROW(__sync_fetch_and_or),
3198 BUILTIN_ROW(__sync_fetch_and_and),
3199 BUILTIN_ROW(__sync_fetch_and_xor),
3200 BUILTIN_ROW(__sync_fetch_and_nand),
3202 BUILTIN_ROW(__sync_add_and_fetch),
3203 BUILTIN_ROW(__sync_sub_and_fetch),
3204 BUILTIN_ROW(__sync_and_and_fetch),
3205 BUILTIN_ROW(__sync_or_and_fetch),
3206 BUILTIN_ROW(__sync_xor_and_fetch),
3207 BUILTIN_ROW(__sync_nand_and_fetch),
3209 BUILTIN_ROW(__sync_val_compare_and_swap),
3210 BUILTIN_ROW(__sync_bool_compare_and_swap),
3211 BUILTIN_ROW(__sync_lock_test_and_set),
3212 BUILTIN_ROW(__sync_lock_release),
3213 BUILTIN_ROW(__sync_swap)
3217 // Determine the index of the size.
3219 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
3220 case 1: SizeIndex = 0; break;
3221 case 2: SizeIndex = 1; break;
3222 case 4: SizeIndex = 2; break;
3223 case 8: SizeIndex = 3; break;
3224 case 16: SizeIndex = 4; break;
3226 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3227 << FirstArg->getType() << FirstArg->getSourceRange();
3231 // Each of these builtins has one pointer argument, followed by some number of
3232 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3233 // that we ignore. Find out which row of BuiltinIndices to read from as well
3234 // as the number of fixed args.
3235 unsigned BuiltinID = FDecl->getBuiltinID();
3236 unsigned BuiltinIndex, NumFixed = 1;
3237 bool WarnAboutSemanticsChange = false;
3238 switch (BuiltinID) {
3239 default: llvm_unreachable("Unknown overloaded atomic builtin!");
3240 case Builtin::BI__sync_fetch_and_add:
3241 case Builtin::BI__sync_fetch_and_add_1:
3242 case Builtin::BI__sync_fetch_and_add_2:
3243 case Builtin::BI__sync_fetch_and_add_4:
3244 case Builtin::BI__sync_fetch_and_add_8:
3245 case Builtin::BI__sync_fetch_and_add_16:
3249 case Builtin::BI__sync_fetch_and_sub:
3250 case Builtin::BI__sync_fetch_and_sub_1:
3251 case Builtin::BI__sync_fetch_and_sub_2:
3252 case Builtin::BI__sync_fetch_and_sub_4:
3253 case Builtin::BI__sync_fetch_and_sub_8:
3254 case Builtin::BI__sync_fetch_and_sub_16:
3258 case Builtin::BI__sync_fetch_and_or:
3259 case Builtin::BI__sync_fetch_and_or_1:
3260 case Builtin::BI__sync_fetch_and_or_2:
3261 case Builtin::BI__sync_fetch_and_or_4:
3262 case Builtin::BI__sync_fetch_and_or_8:
3263 case Builtin::BI__sync_fetch_and_or_16:
3267 case Builtin::BI__sync_fetch_and_and:
3268 case Builtin::BI__sync_fetch_and_and_1:
3269 case Builtin::BI__sync_fetch_and_and_2:
3270 case Builtin::BI__sync_fetch_and_and_4:
3271 case Builtin::BI__sync_fetch_and_and_8:
3272 case Builtin::BI__sync_fetch_and_and_16:
3276 case Builtin::BI__sync_fetch_and_xor:
3277 case Builtin::BI__sync_fetch_and_xor_1:
3278 case Builtin::BI__sync_fetch_and_xor_2:
3279 case Builtin::BI__sync_fetch_and_xor_4:
3280 case Builtin::BI__sync_fetch_and_xor_8:
3281 case Builtin::BI__sync_fetch_and_xor_16:
3285 case Builtin::BI__sync_fetch_and_nand:
3286 case Builtin::BI__sync_fetch_and_nand_1:
3287 case Builtin::BI__sync_fetch_and_nand_2:
3288 case Builtin::BI__sync_fetch_and_nand_4:
3289 case Builtin::BI__sync_fetch_and_nand_8:
3290 case Builtin::BI__sync_fetch_and_nand_16:
3292 WarnAboutSemanticsChange = true;
3295 case Builtin::BI__sync_add_and_fetch:
3296 case Builtin::BI__sync_add_and_fetch_1:
3297 case Builtin::BI__sync_add_and_fetch_2:
3298 case Builtin::BI__sync_add_and_fetch_4:
3299 case Builtin::BI__sync_add_and_fetch_8:
3300 case Builtin::BI__sync_add_and_fetch_16:
3304 case Builtin::BI__sync_sub_and_fetch:
3305 case Builtin::BI__sync_sub_and_fetch_1:
3306 case Builtin::BI__sync_sub_and_fetch_2:
3307 case Builtin::BI__sync_sub_and_fetch_4:
3308 case Builtin::BI__sync_sub_and_fetch_8:
3309 case Builtin::BI__sync_sub_and_fetch_16:
3313 case Builtin::BI__sync_and_and_fetch:
3314 case Builtin::BI__sync_and_and_fetch_1:
3315 case Builtin::BI__sync_and_and_fetch_2:
3316 case Builtin::BI__sync_and_and_fetch_4:
3317 case Builtin::BI__sync_and_and_fetch_8:
3318 case Builtin::BI__sync_and_and_fetch_16:
3322 case Builtin::BI__sync_or_and_fetch:
3323 case Builtin::BI__sync_or_and_fetch_1:
3324 case Builtin::BI__sync_or_and_fetch_2:
3325 case Builtin::BI__sync_or_and_fetch_4:
3326 case Builtin::BI__sync_or_and_fetch_8:
3327 case Builtin::BI__sync_or_and_fetch_16:
3331 case Builtin::BI__sync_xor_and_fetch:
3332 case Builtin::BI__sync_xor_and_fetch_1:
3333 case Builtin::BI__sync_xor_and_fetch_2:
3334 case Builtin::BI__sync_xor_and_fetch_4:
3335 case Builtin::BI__sync_xor_and_fetch_8:
3336 case Builtin::BI__sync_xor_and_fetch_16:
3340 case Builtin::BI__sync_nand_and_fetch:
3341 case Builtin::BI__sync_nand_and_fetch_1:
3342 case Builtin::BI__sync_nand_and_fetch_2:
3343 case Builtin::BI__sync_nand_and_fetch_4:
3344 case Builtin::BI__sync_nand_and_fetch_8:
3345 case Builtin::BI__sync_nand_and_fetch_16:
3347 WarnAboutSemanticsChange = true;
3350 case Builtin::BI__sync_val_compare_and_swap:
3351 case Builtin::BI__sync_val_compare_and_swap_1:
3352 case Builtin::BI__sync_val_compare_and_swap_2:
3353 case Builtin::BI__sync_val_compare_and_swap_4:
3354 case Builtin::BI__sync_val_compare_and_swap_8:
3355 case Builtin::BI__sync_val_compare_and_swap_16:
3360 case Builtin::BI__sync_bool_compare_and_swap:
3361 case Builtin::BI__sync_bool_compare_and_swap_1:
3362 case Builtin::BI__sync_bool_compare_and_swap_2:
3363 case Builtin::BI__sync_bool_compare_and_swap_4:
3364 case Builtin::BI__sync_bool_compare_and_swap_8:
3365 case Builtin::BI__sync_bool_compare_and_swap_16:
3368 ResultType = Context.BoolTy;
3371 case Builtin::BI__sync_lock_test_and_set:
3372 case Builtin::BI__sync_lock_test_and_set_1:
3373 case Builtin::BI__sync_lock_test_and_set_2:
3374 case Builtin::BI__sync_lock_test_and_set_4:
3375 case Builtin::BI__sync_lock_test_and_set_8:
3376 case Builtin::BI__sync_lock_test_and_set_16:
3380 case Builtin::BI__sync_lock_release:
3381 case Builtin::BI__sync_lock_release_1:
3382 case Builtin::BI__sync_lock_release_2:
3383 case Builtin::BI__sync_lock_release_4:
3384 case Builtin::BI__sync_lock_release_8:
3385 case Builtin::BI__sync_lock_release_16:
3388 ResultType = Context.VoidTy;
3391 case Builtin::BI__sync_swap:
3392 case Builtin::BI__sync_swap_1:
3393 case Builtin::BI__sync_swap_2:
3394 case Builtin::BI__sync_swap_4:
3395 case Builtin::BI__sync_swap_8:
3396 case Builtin::BI__sync_swap_16:
3401 // Now that we know how many fixed arguments we expect, first check that we
3402 // have at least that many.
3403 if (TheCall->getNumArgs() < 1+NumFixed) {
3404 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3405 << 0 << 1+NumFixed << TheCall->getNumArgs()
3406 << TheCall->getCallee()->getSourceRange();
3410 if (WarnAboutSemanticsChange) {
3411 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
3412 << TheCall->getCallee()->getSourceRange();
3415 // Get the decl for the concrete builtin from this, we can tell what the
3416 // concrete integer type we should convert to is.
3417 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
3418 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
3419 FunctionDecl *NewBuiltinDecl;
3420 if (NewBuiltinID == BuiltinID)
3421 NewBuiltinDecl = FDecl;
3423 // Perform builtin lookup to avoid redeclaring it.
3424 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
3425 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
3426 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
3427 assert(Res.getFoundDecl());
3428 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
3429 if (!NewBuiltinDecl)
3433 // The first argument --- the pointer --- has a fixed type; we
3434 // deduce the types of the rest of the arguments accordingly. Walk
3435 // the remaining arguments, converting them to the deduced value type.
3436 for (unsigned i = 0; i != NumFixed; ++i) {
3437 ExprResult Arg = TheCall->getArg(i+1);
3439 // GCC does an implicit conversion to the pointer or integer ValType. This
3440 // can fail in some cases (1i -> int**), check for this error case now.
3441 // Initialize the argument.
3442 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3443 ValType, /*consume*/ false);
3444 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3445 if (Arg.isInvalid())
3448 // Okay, we have something that *can* be converted to the right type. Check
3449 // to see if there is a potentially weird extension going on here. This can
3450 // happen when you do an atomic operation on something like an char* and
3451 // pass in 42. The 42 gets converted to char. This is even more strange
3452 // for things like 45.123 -> char, etc.
3453 // FIXME: Do this check.
3454 TheCall->setArg(i+1, Arg.get());
3457 ASTContext& Context = this->getASTContext();
3459 // Create a new DeclRefExpr to refer to the new decl.
3460 DeclRefExpr* NewDRE = DeclRefExpr::Create(
3462 DRE->getQualifierLoc(),
3465 /*enclosing*/ false,
3467 Context.BuiltinFnTy,
3468 DRE->getValueKind());
3470 // Set the callee in the CallExpr.
3471 // FIXME: This loses syntactic information.
3472 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
3473 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
3474 CK_BuiltinFnToFnPtr);
3475 TheCall->setCallee(PromotedCall.get());
3477 // Change the result type of the call to match the original value type. This
3478 // is arbitrary, but the codegen for these builtins ins design to handle it
3480 TheCall->setType(ResultType);
3482 return TheCallResult;
3485 /// SemaBuiltinNontemporalOverloaded - We have a call to
3486 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3487 /// overloaded function based on the pointer type of its last argument.
3489 /// This function goes through and does final semantic checking for these
3491 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
3492 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3494 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3495 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3496 unsigned BuiltinID = FDecl->getBuiltinID();
3497 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
3498 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
3499 "Unexpected nontemporal load/store builtin!");
3500 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3501 unsigned numArgs = isStore ? 2 : 1;
3503 // Ensure that we have the proper number of arguments.
3504 if (checkArgCount(*this, TheCall, numArgs))
3507 // Inspect the last argument of the nontemporal builtin. This should always
3508 // be a pointer type, from which we imply the type of the memory access.
3509 // Because it is a pointer type, we don't have to worry about any implicit
3511 Expr *PointerArg = TheCall->getArg(numArgs - 1);
3512 ExprResult PointerArgResult =
3513 DefaultFunctionArrayLvalueConversion(PointerArg);
3515 if (PointerArgResult.isInvalid())
3517 PointerArg = PointerArgResult.get();
3518 TheCall->setArg(numArgs - 1, PointerArg);
3520 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3522 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3523 << PointerArg->getType() << PointerArg->getSourceRange();
3527 QualType ValType = pointerType->getPointeeType();
3529 // Strip any qualifiers off ValType.
3530 ValType = ValType.getUnqualifiedType();
3531 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3532 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
3533 !ValType->isVectorType()) {
3534 Diag(DRE->getLocStart(),
3535 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3536 << PointerArg->getType() << PointerArg->getSourceRange();
3541 TheCall->setType(ValType);
3542 return TheCallResult;
3545 ExprResult ValArg = TheCall->getArg(0);
3546 InitializedEntity Entity = InitializedEntity::InitializeParameter(
3547 Context, ValType, /*consume*/ false);
3548 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3549 if (ValArg.isInvalid())
3552 TheCall->setArg(0, ValArg.get());
3553 TheCall->setType(Context.VoidTy);
3554 return TheCallResult;
3557 /// CheckObjCString - Checks that the argument to the builtin
3558 /// CFString constructor is correct
3559 /// Note: It might also make sense to do the UTF-16 conversion here (would
3560 /// simplify the backend).
3561 bool Sema::CheckObjCString(Expr *Arg) {
3562 Arg = Arg->IgnoreParenCasts();
3563 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
3565 if (!Literal || !Literal->isAscii()) {
3566 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
3567 << Arg->getSourceRange();
3571 if (Literal->containsNonAsciiOrNull()) {
3572 StringRef String = Literal->getString();
3573 unsigned NumBytes = String.size();
3574 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
3575 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3576 llvm::UTF16 *ToPtr = &ToBuf[0];
3578 llvm::ConversionResult Result =
3579 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3580 ToPtr + NumBytes, llvm::strictConversion);
3581 // Check for conversion failure.
3582 if (Result != llvm::conversionOK)
3583 Diag(Arg->getLocStart(),
3584 diag::warn_cfstring_truncated) << Arg->getSourceRange();
3589 /// CheckObjCString - Checks that the format string argument to the os_log()
3590 /// and os_trace() functions is correct, and converts it to const char *.
3591 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
3592 Arg = Arg->IgnoreParenCasts();
3593 auto *Literal = dyn_cast<StringLiteral>(Arg);
3595 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
3596 Literal = ObjcLiteral->getString();
3600 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
3602 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
3603 << Arg->getSourceRange());
3606 ExprResult Result(Literal);
3607 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
3608 InitializedEntity Entity =
3609 InitializedEntity::InitializeParameter(Context, ResultTy, false);
3610 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
3614 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
3615 /// for validity. Emit an error and return true on failure; return false
3617 bool Sema::SemaBuiltinVAStartImpl(CallExpr *TheCall) {
3618 Expr *Fn = TheCall->getCallee();
3619 if (TheCall->getNumArgs() > 2) {
3620 Diag(TheCall->getArg(2)->getLocStart(),
3621 diag::err_typecheck_call_too_many_args)
3622 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3623 << Fn->getSourceRange()
3624 << SourceRange(TheCall->getArg(2)->getLocStart(),
3625 (*(TheCall->arg_end()-1))->getLocEnd());
3629 if (TheCall->getNumArgs() < 2) {
3630 return Diag(TheCall->getLocEnd(),
3631 diag::err_typecheck_call_too_few_args_at_least)
3632 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
3635 // Type-check the first argument normally.
3636 if (checkBuiltinArgument(*this, TheCall, 0))
3639 // Determine whether the current function is variadic or not.
3640 BlockScopeInfo *CurBlock = getCurBlock();
3643 isVariadic = CurBlock->TheDecl->isVariadic();
3644 else if (FunctionDecl *FD = getCurFunctionDecl())
3645 isVariadic = FD->isVariadic();
3647 isVariadic = getCurMethodDecl()->isVariadic();
3650 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3654 // Verify that the second argument to the builtin is the last argument of the
3655 // current function or method.
3656 bool SecondArgIsLastNamedArgument = false;
3657 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
3659 // These are valid if SecondArgIsLastNamedArgument is false after the next
3662 SourceLocation ParamLoc;
3663 bool IsCRegister = false;
3665 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
3666 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
3667 // FIXME: This isn't correct for methods (results in bogus warning).
3668 // Get the last formal in the current function.
3669 const ParmVarDecl *LastArg;
3671 LastArg = CurBlock->TheDecl->parameters().back();
3672 else if (FunctionDecl *FD = getCurFunctionDecl())
3673 LastArg = FD->parameters().back();
3675 LastArg = getCurMethodDecl()->parameters().back();
3676 SecondArgIsLastNamedArgument = PV == LastArg;
3678 Type = PV->getType();
3679 ParamLoc = PV->getLocation();
3681 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
3685 if (!SecondArgIsLastNamedArgument)
3686 Diag(TheCall->getArg(1)->getLocStart(),
3687 diag::warn_second_arg_of_va_start_not_last_named_param);
3688 else if (IsCRegister || Type->isReferenceType() ||
3689 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
3690 // Promotable integers are UB, but enumerations need a bit of
3691 // extra checking to see what their promotable type actually is.
3692 if (!Type->isPromotableIntegerType())
3694 if (!Type->isEnumeralType())
3696 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3698 Context.typesAreCompatible(ED->getPromotionType(), Type));
3700 unsigned Reason = 0;
3701 if (Type->isReferenceType()) Reason = 1;
3702 else if (IsCRegister) Reason = 2;
3703 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
3704 Diag(ParamLoc, diag::note_parameter_type) << Type;
3707 TheCall->setType(Context.VoidTy);
3711 /// Check the arguments to '__builtin_va_start' for validity, and that
3712 /// it was called from a function of the native ABI.
3713 /// Emit an error and return true on failure; return false on success.
3714 bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
3715 // On x86-64 Unix, don't allow this in Win64 ABI functions.
3716 // On x64 Windows, don't allow this in System V ABI functions.
3717 // (Yes, that means there's no corresponding way to support variadic
3718 // System V ABI functions on Windows.)
3719 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) {
3720 unsigned OS = Context.getTargetInfo().getTriple().getOS();
3721 clang::CallingConv CC = CC_C;
3722 if (const FunctionDecl *FD = getCurFunctionDecl())
3723 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3724 if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) ||
3725 (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64))
3726 return Diag(TheCall->getCallee()->getLocStart(),
3727 diag::err_va_start_used_in_wrong_abi_function)
3728 << (OS != llvm::Triple::Win32);
3730 return SemaBuiltinVAStartImpl(TheCall);
3733 /// Check the arguments to '__builtin_ms_va_start' for validity, and that
3734 /// it was called from a Win64 ABI function.
3735 /// Emit an error and return true on failure; return false on success.
3736 bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) {
3737 // This only makes sense for x86-64.
3738 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3739 Expr *Callee = TheCall->getCallee();
3740 if (TT.getArch() != llvm::Triple::x86_64)
3741 return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt);
3742 // Don't allow this in System V ABI functions.
3743 clang::CallingConv CC = CC_C;
3744 if (const FunctionDecl *FD = getCurFunctionDecl())
3745 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3746 if (CC == CC_X86_64SysV ||
3747 (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64))
3748 return Diag(Callee->getLocStart(),
3749 diag::err_ms_va_start_used_in_sysv_function);
3750 return SemaBuiltinVAStartImpl(TheCall);
3753 bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
3754 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
3755 // const char *named_addr);
3757 Expr *Func = Call->getCallee();
3759 if (Call->getNumArgs() < 3)
3760 return Diag(Call->getLocEnd(),
3761 diag::err_typecheck_call_too_few_args_at_least)
3762 << 0 /*function call*/ << 3 << Call->getNumArgs();
3764 // Determine whether the current function is variadic or not.
3766 if (BlockScopeInfo *CurBlock = getCurBlock())
3767 IsVariadic = CurBlock->TheDecl->isVariadic();
3768 else if (FunctionDecl *FD = getCurFunctionDecl())
3769 IsVariadic = FD->isVariadic();
3770 else if (ObjCMethodDecl *MD = getCurMethodDecl())
3771 IsVariadic = MD->isVariadic();
3773 llvm_unreachable("unexpected statement type");
3776 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3780 // Type-check the first argument normally.
3781 if (checkBuiltinArgument(*this, Call, 0))
3787 } ArgumentTypes[] = {
3788 { 1, Context.getPointerType(Context.CharTy.withConst()) },
3789 { 2, Context.getSizeType() },
3792 for (const auto &AT : ArgumentTypes) {
3793 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
3794 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
3796 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
3797 << Arg->getType() << AT.Type << 1 /* different class */
3798 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
3799 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
3805 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
3806 /// friends. This is declared to take (...), so we have to check everything.
3807 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
3808 if (TheCall->getNumArgs() < 2)
3809 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
3810 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
3811 if (TheCall->getNumArgs() > 2)
3812 return Diag(TheCall->getArg(2)->getLocStart(),
3813 diag::err_typecheck_call_too_many_args)
3814 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3815 << SourceRange(TheCall->getArg(2)->getLocStart(),
3816 (*(TheCall->arg_end()-1))->getLocEnd());
3818 ExprResult OrigArg0 = TheCall->getArg(0);
3819 ExprResult OrigArg1 = TheCall->getArg(1);
3821 // Do standard promotions between the two arguments, returning their common
3823 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
3824 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
3827 // Make sure any conversions are pushed back into the call; this is
3828 // type safe since unordered compare builtins are declared as "_Bool
3830 TheCall->setArg(0, OrigArg0.get());
3831 TheCall->setArg(1, OrigArg1.get());
3833 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
3836 // If the common type isn't a real floating type, then the arguments were
3837 // invalid for this operation.
3838 if (Res.isNull() || !Res->isRealFloatingType())
3839 return Diag(OrigArg0.get()->getLocStart(),
3840 diag::err_typecheck_call_invalid_ordered_compare)
3841 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
3842 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
3847 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
3848 /// __builtin_isnan and friends. This is declared to take (...), so we have
3849 /// to check everything. We expect the last argument to be a floating point
3851 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
3852 if (TheCall->getNumArgs() < NumArgs)
3853 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
3854 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
3855 if (TheCall->getNumArgs() > NumArgs)
3856 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
3857 diag::err_typecheck_call_too_many_args)
3858 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
3859 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
3860 (*(TheCall->arg_end()-1))->getLocEnd());
3862 Expr *OrigArg = TheCall->getArg(NumArgs-1);
3864 if (OrigArg->isTypeDependent())
3867 // This operation requires a non-_Complex floating-point number.
3868 if (!OrigArg->getType()->isRealFloatingType())
3869 return Diag(OrigArg->getLocStart(),
3870 diag::err_typecheck_call_invalid_unary_fp)
3871 << OrigArg->getType() << OrigArg->getSourceRange();
3873 // If this is an implicit conversion from float -> float or double, remove it.
3874 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
3875 // Only remove standard FloatCasts, leaving other casts inplace
3876 if (Cast->getCastKind() == CK_FloatingCast) {
3877 Expr *CastArg = Cast->getSubExpr();
3878 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
3879 assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
3880 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) &&
3881 "promotion from float to either float or double is the only expected cast here");
3882 Cast->setSubExpr(nullptr);
3883 TheCall->setArg(NumArgs-1, CastArg);
3891 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
3892 // This is declared to take (...), so we have to check everything.
3893 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
3894 if (TheCall->getNumArgs() < 2)
3895 return ExprError(Diag(TheCall->getLocEnd(),
3896 diag::err_typecheck_call_too_few_args_at_least)
3897 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3898 << TheCall->getSourceRange());
3900 // Determine which of the following types of shufflevector we're checking:
3901 // 1) unary, vector mask: (lhs, mask)
3902 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
3903 QualType resType = TheCall->getArg(0)->getType();
3904 unsigned numElements = 0;
3906 if (!TheCall->getArg(0)->isTypeDependent() &&
3907 !TheCall->getArg(1)->isTypeDependent()) {
3908 QualType LHSType = TheCall->getArg(0)->getType();
3909 QualType RHSType = TheCall->getArg(1)->getType();
3911 if (!LHSType->isVectorType() || !RHSType->isVectorType())
3912 return ExprError(Diag(TheCall->getLocStart(),
3913 diag::err_shufflevector_non_vector)
3914 << SourceRange(TheCall->getArg(0)->getLocStart(),
3915 TheCall->getArg(1)->getLocEnd()));
3917 numElements = LHSType->getAs<VectorType>()->getNumElements();
3918 unsigned numResElements = TheCall->getNumArgs() - 2;
3920 // Check to see if we have a call with 2 vector arguments, the unary shuffle
3921 // with mask. If so, verify that RHS is an integer vector type with the
3922 // same number of elts as lhs.
3923 if (TheCall->getNumArgs() == 2) {
3924 if (!RHSType->hasIntegerRepresentation() ||
3925 RHSType->getAs<VectorType>()->getNumElements() != numElements)
3926 return ExprError(Diag(TheCall->getLocStart(),
3927 diag::err_shufflevector_incompatible_vector)
3928 << SourceRange(TheCall->getArg(1)->getLocStart(),
3929 TheCall->getArg(1)->getLocEnd()));
3930 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
3931 return ExprError(Diag(TheCall->getLocStart(),
3932 diag::err_shufflevector_incompatible_vector)
3933 << SourceRange(TheCall->getArg(0)->getLocStart(),
3934 TheCall->getArg(1)->getLocEnd()));
3935 } else if (numElements != numResElements) {
3936 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
3937 resType = Context.getVectorType(eltType, numResElements,
3938 VectorType::GenericVector);
3942 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
3943 if (TheCall->getArg(i)->isTypeDependent() ||
3944 TheCall->getArg(i)->isValueDependent())
3947 llvm::APSInt Result(32);
3948 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
3949 return ExprError(Diag(TheCall->getLocStart(),
3950 diag::err_shufflevector_nonconstant_argument)
3951 << TheCall->getArg(i)->getSourceRange());
3953 // Allow -1 which will be translated to undef in the IR.
3954 if (Result.isSigned() && Result.isAllOnesValue())
3957 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
3958 return ExprError(Diag(TheCall->getLocStart(),
3959 diag::err_shufflevector_argument_too_large)
3960 << TheCall->getArg(i)->getSourceRange());
3963 SmallVector<Expr*, 32> exprs;
3965 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
3966 exprs.push_back(TheCall->getArg(i));
3967 TheCall->setArg(i, nullptr);
3970 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
3971 TheCall->getCallee()->getLocStart(),
3972 TheCall->getRParenLoc());
3975 /// SemaConvertVectorExpr - Handle __builtin_convertvector
3976 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
3977 SourceLocation BuiltinLoc,
3978 SourceLocation RParenLoc) {
3979 ExprValueKind VK = VK_RValue;
3980 ExprObjectKind OK = OK_Ordinary;
3981 QualType DstTy = TInfo->getType();
3982 QualType SrcTy = E->getType();
3984 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
3985 return ExprError(Diag(BuiltinLoc,
3986 diag::err_convertvector_non_vector)
3987 << E->getSourceRange());
3988 if (!DstTy->isVectorType() && !DstTy->isDependentType())
3989 return ExprError(Diag(BuiltinLoc,
3990 diag::err_convertvector_non_vector_type));
3992 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
3993 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
3994 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
3995 if (SrcElts != DstElts)
3996 return ExprError(Diag(BuiltinLoc,
3997 diag::err_convertvector_incompatible_vector)
3998 << E->getSourceRange());
4001 return new (Context)
4002 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
4005 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
4006 // This is declared to take (const void*, ...) and can take two
4007 // optional constant int args.
4008 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
4009 unsigned NumArgs = TheCall->getNumArgs();
4012 return Diag(TheCall->getLocEnd(),
4013 diag::err_typecheck_call_too_many_args_at_most)
4014 << 0 /*function call*/ << 3 << NumArgs
4015 << TheCall->getSourceRange();
4017 // Argument 0 is checked for us and the remaining arguments must be
4018 // constant integers.
4019 for (unsigned i = 1; i != NumArgs; ++i)
4020 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
4026 /// SemaBuiltinAssume - Handle __assume (MS Extension).
4027 // __assume does not evaluate its arguments, and should warn if its argument
4028 // has side effects.
4029 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
4030 Expr *Arg = TheCall->getArg(0);
4031 if (Arg->isInstantiationDependent()) return false;
4033 if (Arg->HasSideEffects(Context))
4034 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
4035 << Arg->getSourceRange()
4036 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
4041 /// Handle __builtin_alloca_with_align. This is declared
4042 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
4044 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
4045 // The alignment must be a constant integer.
4046 Expr *Arg = TheCall->getArg(1);
4048 // We can't check the value of a dependent argument.
4049 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4050 if (const auto *UE =
4051 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
4052 if (UE->getKind() == UETT_AlignOf)
4053 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
4054 << Arg->getSourceRange();
4056 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
4058 if (!Result.isPowerOf2())
4059 return Diag(TheCall->getLocStart(),
4060 diag::err_alignment_not_power_of_two)
4061 << Arg->getSourceRange();
4063 if (Result < Context.getCharWidth())
4064 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
4065 << (unsigned)Context.getCharWidth()
4066 << Arg->getSourceRange();
4068 if (Result > INT32_MAX)
4069 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
4071 << Arg->getSourceRange();
4077 /// Handle __builtin_assume_aligned. This is declared
4078 /// as (const void*, size_t, ...) and can take one optional constant int arg.
4079 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
4080 unsigned NumArgs = TheCall->getNumArgs();
4083 return Diag(TheCall->getLocEnd(),
4084 diag::err_typecheck_call_too_many_args_at_most)
4085 << 0 /*function call*/ << 3 << NumArgs
4086 << TheCall->getSourceRange();
4088 // The alignment must be a constant integer.
4089 Expr *Arg = TheCall->getArg(1);
4091 // We can't check the value of a dependent argument.
4092 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4093 llvm::APSInt Result;
4094 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4097 if (!Result.isPowerOf2())
4098 return Diag(TheCall->getLocStart(),
4099 diag::err_alignment_not_power_of_two)
4100 << Arg->getSourceRange();
4104 ExprResult Arg(TheCall->getArg(2));
4105 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
4106 Context.getSizeType(), false);
4107 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4108 if (Arg.isInvalid()) return true;
4109 TheCall->setArg(2, Arg.get());
4115 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
4116 unsigned BuiltinID =
4117 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
4118 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
4120 unsigned NumArgs = TheCall->getNumArgs();
4121 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
4122 if (NumArgs < NumRequiredArgs) {
4123 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4124 << 0 /* function call */ << NumRequiredArgs << NumArgs
4125 << TheCall->getSourceRange();
4127 if (NumArgs >= NumRequiredArgs + 0x100) {
4128 return Diag(TheCall->getLocEnd(),
4129 diag::err_typecheck_call_too_many_args_at_most)
4130 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
4131 << TheCall->getSourceRange();
4135 // For formatting call, check buffer arg.
4137 ExprResult Arg(TheCall->getArg(i));
4138 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4139 Context, Context.VoidPtrTy, false);
4140 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4141 if (Arg.isInvalid())
4143 TheCall->setArg(i, Arg.get());
4147 // Check string literal arg.
4148 unsigned FormatIdx = i;
4150 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4151 if (Arg.isInvalid())
4153 TheCall->setArg(i, Arg.get());
4157 // Make sure variadic args are scalar.
4158 unsigned FirstDataArg = i;
4159 while (i < NumArgs) {
4160 ExprResult Arg = DefaultVariadicArgumentPromotion(
4161 TheCall->getArg(i), VariadicFunction, nullptr);
4162 if (Arg.isInvalid())
4164 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4165 if (ArgSize.getQuantity() >= 0x100) {
4166 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4167 << i << (int)ArgSize.getQuantity() << 0xff
4168 << TheCall->getSourceRange();
4170 TheCall->setArg(i, Arg.get());
4174 // Check formatting specifiers. NOTE: We're only doing this for the non-size
4175 // call to avoid duplicate diagnostics.
4177 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4178 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4179 bool Success = CheckFormatArguments(
4180 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4181 VariadicFunction, TheCall->getLocStart(), SourceRange(),
4188 TheCall->setType(Context.getSizeType());
4190 TheCall->setType(Context.VoidPtrTy);
4195 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4196 /// TheCall is a constant expression.
4197 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4198 llvm::APSInt &Result) {
4199 Expr *Arg = TheCall->getArg(ArgNum);
4200 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4201 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4203 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
4205 if (!Arg->isIntegerConstantExpr(Result, Context))
4206 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
4207 << FDecl->getDeclName() << Arg->getSourceRange();
4212 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
4213 /// TheCall is a constant expression in the range [Low, High].
4214 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
4215 int Low, int High) {
4216 llvm::APSInt Result;
4218 // We can't check the value of a dependent argument.
4219 Expr *Arg = TheCall->getArg(ArgNum);
4220 if (Arg->isTypeDependent() || Arg->isValueDependent())
4223 // Check constant-ness first.
4224 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4227 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
4228 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
4229 << Low << High << Arg->getSourceRange();
4234 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
4235 /// TheCall is a constant expression is a multiple of Num..
4236 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
4238 llvm::APSInt Result;
4240 // We can't check the value of a dependent argument.
4241 Expr *Arg = TheCall->getArg(ArgNum);
4242 if (Arg->isTypeDependent() || Arg->isValueDependent())
4245 // Check constant-ness first.
4246 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4249 if (Result.getSExtValue() % Num != 0)
4250 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
4251 << Num << Arg->getSourceRange();
4256 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
4257 /// TheCall is an ARM/AArch64 special register string literal.
4258 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
4259 int ArgNum, unsigned ExpectedFieldNum,
4261 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
4262 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
4263 BuiltinID == ARM::BI__builtin_arm_rsr ||
4264 BuiltinID == ARM::BI__builtin_arm_rsrp ||
4265 BuiltinID == ARM::BI__builtin_arm_wsr ||
4266 BuiltinID == ARM::BI__builtin_arm_wsrp;
4267 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
4268 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
4269 BuiltinID == AArch64::BI__builtin_arm_rsr ||
4270 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
4271 BuiltinID == AArch64::BI__builtin_arm_wsr ||
4272 BuiltinID == AArch64::BI__builtin_arm_wsrp;
4273 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
4275 // We can't check the value of a dependent argument.
4276 Expr *Arg = TheCall->getArg(ArgNum);
4277 if (Arg->isTypeDependent() || Arg->isValueDependent())
4280 // Check if the argument is a string literal.
4281 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4282 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
4283 << Arg->getSourceRange();
4285 // Check the type of special register given.
4286 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4287 SmallVector<StringRef, 6> Fields;
4288 Reg.split(Fields, ":");
4290 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
4291 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4292 << Arg->getSourceRange();
4294 // If the string is the name of a register then we cannot check that it is
4295 // valid here but if the string is of one the forms described in ACLE then we
4296 // can check that the supplied fields are integers and within the valid
4298 if (Fields.size() > 1) {
4299 bool FiveFields = Fields.size() == 5;
4301 bool ValidString = true;
4303 ValidString &= Fields[0].startswith_lower("cp") ||
4304 Fields[0].startswith_lower("p");
4307 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
4309 ValidString &= Fields[2].startswith_lower("c");
4311 Fields[2] = Fields[2].drop_front(1);
4314 ValidString &= Fields[3].startswith_lower("c");
4316 Fields[3] = Fields[3].drop_front(1);
4320 SmallVector<int, 5> Ranges;
4322 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
4324 Ranges.append({15, 7, 15});
4326 for (unsigned i=0; i<Fields.size(); ++i) {
4328 ValidString &= !Fields[i].getAsInteger(10, IntField);
4329 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
4333 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4334 << Arg->getSourceRange();
4336 } else if (IsAArch64Builtin && Fields.size() == 1) {
4337 // If the register name is one of those that appear in the condition below
4338 // and the special register builtin being used is one of the write builtins,
4339 // then we require that the argument provided for writing to the register
4340 // is an integer constant expression. This is because it will be lowered to
4341 // an MSR (immediate) instruction, so we need to know the immediate at
4343 if (TheCall->getNumArgs() != 2)
4346 std::string RegLower = Reg.lower();
4347 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
4348 RegLower != "pan" && RegLower != "uao")
4351 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4357 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
4358 /// This checks that the target supports __builtin_longjmp and
4359 /// that val is a constant 1.
4360 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
4361 if (!Context.getTargetInfo().hasSjLjLowering())
4362 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
4363 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4365 Expr *Arg = TheCall->getArg(1);
4366 llvm::APSInt Result;
4368 // TODO: This is less than ideal. Overload this to take a value.
4369 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4373 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
4374 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
4379 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
4380 /// This checks that the target supports __builtin_setjmp.
4381 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
4382 if (!Context.getTargetInfo().hasSjLjLowering())
4383 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
4384 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4389 class UncoveredArgHandler {
4390 enum { Unknown = -1, AllCovered = -2 };
4391 signed FirstUncoveredArg;
4392 SmallVector<const Expr *, 4> DiagnosticExprs;
4395 UncoveredArgHandler() : FirstUncoveredArg(Unknown) { }
4397 bool hasUncoveredArg() const {
4398 return (FirstUncoveredArg >= 0);
4401 unsigned getUncoveredArg() const {
4402 assert(hasUncoveredArg() && "no uncovered argument");
4403 return FirstUncoveredArg;
4406 void setAllCovered() {
4407 // A string has been found with all arguments covered, so clear out
4409 DiagnosticExprs.clear();
4410 FirstUncoveredArg = AllCovered;
4413 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
4414 assert(NewFirstUncoveredArg >= 0 && "Outside range");
4416 // Don't update if a previous string covers all arguments.
4417 if (FirstUncoveredArg == AllCovered)
4420 // UncoveredArgHandler tracks the highest uncovered argument index
4421 // and with it all the strings that match this index.
4422 if (NewFirstUncoveredArg == FirstUncoveredArg)
4423 DiagnosticExprs.push_back(StrExpr);
4424 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
4425 DiagnosticExprs.clear();
4426 DiagnosticExprs.push_back(StrExpr);
4427 FirstUncoveredArg = NewFirstUncoveredArg;
4431 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
4434 enum StringLiteralCheckType {
4436 SLCT_UncheckedLiteral,
4439 } // end anonymous namespace
4441 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
4442 BinaryOperatorKind BinOpKind,
4443 bool AddendIsRight) {
4444 unsigned BitWidth = Offset.getBitWidth();
4445 unsigned AddendBitWidth = Addend.getBitWidth();
4446 // There might be negative interim results.
4447 if (Addend.isUnsigned()) {
4448 Addend = Addend.zext(++AddendBitWidth);
4449 Addend.setIsSigned(true);
4451 // Adjust the bit width of the APSInts.
4452 if (AddendBitWidth > BitWidth) {
4453 Offset = Offset.sext(AddendBitWidth);
4454 BitWidth = AddendBitWidth;
4455 } else if (BitWidth > AddendBitWidth) {
4456 Addend = Addend.sext(BitWidth);
4460 llvm::APSInt ResOffset = Offset;
4461 if (BinOpKind == BO_Add)
4462 ResOffset = Offset.sadd_ov(Addend, Ov);
4464 assert(AddendIsRight && BinOpKind == BO_Sub &&
4465 "operator must be add or sub with addend on the right");
4466 ResOffset = Offset.ssub_ov(Addend, Ov);
4469 // We add an offset to a pointer here so we should support an offset as big as
4472 assert(BitWidth <= UINT_MAX / 2 && "index (intermediate) result too big");
4473 Offset = Offset.sext(2 * BitWidth);
4474 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
4482 // This is a wrapper class around StringLiteral to support offsetted string
4483 // literals as format strings. It takes the offset into account when returning
4484 // the string and its length or the source locations to display notes correctly.
4485 class FormatStringLiteral {
4486 const StringLiteral *FExpr;
4490 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
4491 : FExpr(fexpr), Offset(Offset) {}
4493 StringRef getString() const {
4494 return FExpr->getString().drop_front(Offset);
4497 unsigned getByteLength() const {
4498 return FExpr->getByteLength() - getCharByteWidth() * Offset;
4500 unsigned getLength() const { return FExpr->getLength() - Offset; }
4501 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
4503 StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
4505 QualType getType() const { return FExpr->getType(); }
4507 bool isAscii() const { return FExpr->isAscii(); }
4508 bool isWide() const { return FExpr->isWide(); }
4509 bool isUTF8() const { return FExpr->isUTF8(); }
4510 bool isUTF16() const { return FExpr->isUTF16(); }
4511 bool isUTF32() const { return FExpr->isUTF32(); }
4512 bool isPascal() const { return FExpr->isPascal(); }
4514 SourceLocation getLocationOfByte(
4515 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
4516 const TargetInfo &Target, unsigned *StartToken = nullptr,
4517 unsigned *StartTokenByteOffset = nullptr) const {
4518 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
4519 StartToken, StartTokenByteOffset);
4522 SourceLocation getLocStart() const LLVM_READONLY {
4523 return FExpr->getLocStart().getLocWithOffset(Offset);
4525 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
4527 } // end anonymous namespace
4529 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
4530 const Expr *OrigFormatExpr,
4531 ArrayRef<const Expr *> Args,
4532 bool HasVAListArg, unsigned format_idx,
4533 unsigned firstDataArg,
4534 Sema::FormatStringType Type,
4535 bool inFunctionCall,
4536 Sema::VariadicCallType CallType,
4537 llvm::SmallBitVector &CheckedVarArgs,
4538 UncoveredArgHandler &UncoveredArg);
4540 // Determine if an expression is a string literal or constant string.
4541 // If this function returns false on the arguments to a function expecting a
4542 // format string, we will usually need to emit a warning.
4543 // True string literals are then checked by CheckFormatString.
4544 static StringLiteralCheckType
4545 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
4546 bool HasVAListArg, unsigned format_idx,
4547 unsigned firstDataArg, Sema::FormatStringType Type,
4548 Sema::VariadicCallType CallType, bool InFunctionCall,
4549 llvm::SmallBitVector &CheckedVarArgs,
4550 UncoveredArgHandler &UncoveredArg,
4551 llvm::APSInt Offset) {
4553 assert(Offset.isSigned() && "invalid offset");
4555 if (E->isTypeDependent() || E->isValueDependent())
4556 return SLCT_NotALiteral;
4558 E = E->IgnoreParenCasts();
4560 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
4561 // Technically -Wformat-nonliteral does not warn about this case.
4562 // The behavior of printf and friends in this case is implementation
4563 // dependent. Ideally if the format string cannot be null then
4564 // it should have a 'nonnull' attribute in the function prototype.
4565 return SLCT_UncheckedLiteral;
4567 switch (E->getStmtClass()) {
4568 case Stmt::BinaryConditionalOperatorClass:
4569 case Stmt::ConditionalOperatorClass: {
4570 // The expression is a literal if both sub-expressions were, and it was
4571 // completely checked only if both sub-expressions were checked.
4572 const AbstractConditionalOperator *C =
4573 cast<AbstractConditionalOperator>(E);
4575 // Determine whether it is necessary to check both sub-expressions, for
4576 // example, because the condition expression is a constant that can be
4577 // evaluated at compile time.
4578 bool CheckLeft = true, CheckRight = true;
4581 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
4588 // We need to maintain the offsets for the right and the left hand side
4589 // separately to check if every possible indexed expression is a valid
4590 // string literal. They might have different offsets for different string
4591 // literals in the end.
4592 StringLiteralCheckType Left;
4594 Left = SLCT_UncheckedLiteral;
4596 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
4597 HasVAListArg, format_idx, firstDataArg,
4598 Type, CallType, InFunctionCall,
4599 CheckedVarArgs, UncoveredArg, Offset);
4600 if (Left == SLCT_NotALiteral || !CheckRight) {
4605 StringLiteralCheckType Right =
4606 checkFormatStringExpr(S, C->getFalseExpr(), Args,
4607 HasVAListArg, format_idx, firstDataArg,
4608 Type, CallType, InFunctionCall, CheckedVarArgs,
4609 UncoveredArg, Offset);
4611 return (CheckLeft && Left < Right) ? Left : Right;
4614 case Stmt::ImplicitCastExprClass: {
4615 E = cast<ImplicitCastExpr>(E)->getSubExpr();
4619 case Stmt::OpaqueValueExprClass:
4620 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
4624 return SLCT_NotALiteral;
4626 case Stmt::PredefinedExprClass:
4627 // While __func__, etc., are technically not string literals, they
4628 // cannot contain format specifiers and thus are not a security
4630 return SLCT_UncheckedLiteral;
4632 case Stmt::DeclRefExprClass: {
4633 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
4635 // As an exception, do not flag errors for variables binding to
4636 // const string literals.
4637 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
4638 bool isConstant = false;
4639 QualType T = DR->getType();
4641 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
4642 isConstant = AT->getElementType().isConstant(S.Context);
4643 } else if (const PointerType *PT = T->getAs<PointerType>()) {
4644 isConstant = T.isConstant(S.Context) &&
4645 PT->getPointeeType().isConstant(S.Context);
4646 } else if (T->isObjCObjectPointerType()) {
4647 // In ObjC, there is usually no "const ObjectPointer" type,
4648 // so don't check if the pointee type is constant.
4649 isConstant = T.isConstant(S.Context);
4653 if (const Expr *Init = VD->getAnyInitializer()) {
4654 // Look through initializers like const char c[] = { "foo" }
4655 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4656 if (InitList->isStringLiteralInit())
4657 Init = InitList->getInit(0)->IgnoreParenImpCasts();
4659 return checkFormatStringExpr(S, Init, Args,
4660 HasVAListArg, format_idx,
4661 firstDataArg, Type, CallType,
4662 /*InFunctionCall*/ false, CheckedVarArgs,
4663 UncoveredArg, Offset);
4667 // For vprintf* functions (i.e., HasVAListArg==true), we add a
4668 // special check to see if the format string is a function parameter
4669 // of the function calling the printf function. If the function
4670 // has an attribute indicating it is a printf-like function, then we
4671 // should suppress warnings concerning non-literals being used in a call
4672 // to a vprintf function. For example:
4675 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
4677 // va_start(ap, fmt);
4678 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
4682 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
4683 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
4684 int PVIndex = PV->getFunctionScopeIndex() + 1;
4685 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
4686 // adjust for implicit parameter
4687 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4688 if (MD->isInstance())
4690 // We also check if the formats are compatible.
4691 // We can't pass a 'scanf' string to a 'printf' function.
4692 if (PVIndex == PVFormat->getFormatIdx() &&
4693 Type == S.GetFormatStringType(PVFormat))
4694 return SLCT_UncheckedLiteral;
4701 return SLCT_NotALiteral;
4704 case Stmt::CallExprClass:
4705 case Stmt::CXXMemberCallExprClass: {
4706 const CallExpr *CE = cast<CallExpr>(E);
4707 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
4708 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
4709 unsigned ArgIndex = FA->getFormatIdx();
4710 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4711 if (MD->isInstance())
4713 const Expr *Arg = CE->getArg(ArgIndex - 1);
4715 return checkFormatStringExpr(S, Arg, Args,
4716 HasVAListArg, format_idx, firstDataArg,
4717 Type, CallType, InFunctionCall,
4718 CheckedVarArgs, UncoveredArg, Offset);
4719 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4720 unsigned BuiltinID = FD->getBuiltinID();
4721 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
4722 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
4723 const Expr *Arg = CE->getArg(0);
4724 return checkFormatStringExpr(S, Arg, Args,
4725 HasVAListArg, format_idx,
4726 firstDataArg, Type, CallType,
4727 InFunctionCall, CheckedVarArgs,
4728 UncoveredArg, Offset);
4733 return SLCT_NotALiteral;
4735 case Stmt::ObjCMessageExprClass: {
4736 const auto *ME = cast<ObjCMessageExpr>(E);
4737 if (const auto *ND = ME->getMethodDecl()) {
4738 if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
4739 unsigned ArgIndex = FA->getFormatIdx();
4740 const Expr *Arg = ME->getArg(ArgIndex - 1);
4741 return checkFormatStringExpr(
4742 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
4743 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
4747 return SLCT_NotALiteral;
4749 case Stmt::ObjCStringLiteralClass:
4750 case Stmt::StringLiteralClass: {
4751 const StringLiteral *StrE = nullptr;
4753 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
4754 StrE = ObjCFExpr->getString();
4756 StrE = cast<StringLiteral>(E);
4759 if (Offset.isNegative() || Offset > StrE->getLength()) {
4760 // TODO: It would be better to have an explicit warning for out of
4762 return SLCT_NotALiteral;
4764 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
4765 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
4766 firstDataArg, Type, InFunctionCall, CallType,
4767 CheckedVarArgs, UncoveredArg);
4768 return SLCT_CheckedLiteral;
4771 return SLCT_NotALiteral;
4773 case Stmt::BinaryOperatorClass: {
4774 llvm::APSInt LResult;
4775 llvm::APSInt RResult;
4777 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
4779 // A string literal + an int offset is still a string literal.
4780 if (BinOp->isAdditiveOp()) {
4781 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
4782 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
4784 if (LIsInt != RIsInt) {
4785 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
4788 if (BinOpKind == BO_Add) {
4789 sumOffsets(Offset, LResult, BinOpKind, RIsInt);
4790 E = BinOp->getRHS();
4794 sumOffsets(Offset, RResult, BinOpKind, RIsInt);
4795 E = BinOp->getLHS();
4801 return SLCT_NotALiteral;
4803 case Stmt::UnaryOperatorClass: {
4804 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
4805 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
4806 if (UnaOp->getOpcode() == clang::UO_AddrOf && ASE) {
4807 llvm::APSInt IndexResult;
4808 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
4809 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
4815 return SLCT_NotALiteral;
4819 return SLCT_NotALiteral;
4823 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
4824 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
4825 .Case("scanf", FST_Scanf)
4826 .Cases("printf", "printf0", FST_Printf)
4827 .Cases("NSString", "CFString", FST_NSString)
4828 .Case("strftime", FST_Strftime)
4829 .Case("strfmon", FST_Strfmon)
4830 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
4831 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
4832 .Case("os_trace", FST_OSLog)
4833 .Case("os_log", FST_OSLog)
4834 .Default(FST_Unknown);
4837 /// CheckFormatArguments - Check calls to printf and scanf (and similar
4838 /// functions) for correct use of format strings.
4839 /// Returns true if a format string has been fully checked.
4840 bool Sema::CheckFormatArguments(const FormatAttr *Format,
4841 ArrayRef<const Expr *> Args,
4843 VariadicCallType CallType,
4844 SourceLocation Loc, SourceRange Range,
4845 llvm::SmallBitVector &CheckedVarArgs) {
4846 FormatStringInfo FSI;
4847 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
4848 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
4849 FSI.FirstDataArg, GetFormatStringType(Format),
4850 CallType, Loc, Range, CheckedVarArgs);
4854 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
4855 bool HasVAListArg, unsigned format_idx,
4856 unsigned firstDataArg, FormatStringType Type,
4857 VariadicCallType CallType,
4858 SourceLocation Loc, SourceRange Range,
4859 llvm::SmallBitVector &CheckedVarArgs) {
4860 // CHECK: printf/scanf-like function is called with no format string.
4861 if (format_idx >= Args.size()) {
4862 Diag(Loc, diag::warn_missing_format_string) << Range;
4866 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
4868 // CHECK: format string is not a string literal.
4870 // Dynamically generated format strings are difficult to
4871 // automatically vet at compile time. Requiring that format strings
4872 // are string literals: (1) permits the checking of format strings by
4873 // the compiler and thereby (2) can practically remove the source of
4874 // many format string exploits.
4876 // Format string can be either ObjC string (e.g. @"%d") or
4877 // C string (e.g. "%d")
4878 // ObjC string uses the same format specifiers as C string, so we can use
4879 // the same format string checking logic for both ObjC and C strings.
4880 UncoveredArgHandler UncoveredArg;
4881 StringLiteralCheckType CT =
4882 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
4883 format_idx, firstDataArg, Type, CallType,
4884 /*IsFunctionCall*/ true, CheckedVarArgs,
4886 /*no string offset*/ llvm::APSInt(64, false) = 0);
4888 // Generate a diagnostic where an uncovered argument is detected.
4889 if (UncoveredArg.hasUncoveredArg()) {
4890 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
4891 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
4892 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
4895 if (CT != SLCT_NotALiteral)
4896 // Literal format string found, check done!
4897 return CT == SLCT_CheckedLiteral;
4899 // Strftime is particular as it always uses a single 'time' argument,
4900 // so it is safe to pass a non-literal string.
4901 if (Type == FST_Strftime)
4904 // Do not emit diag when the string param is a macro expansion and the
4905 // format is either NSString or CFString. This is a hack to prevent
4906 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
4907 // which are usually used in place of NS and CF string literals.
4908 SourceLocation FormatLoc = Args[format_idx]->getLocStart();
4909 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
4912 // If there are no arguments specified, warn with -Wformat-security, otherwise
4913 // warn only with -Wformat-nonliteral.
4914 if (Args.size() == firstDataArg) {
4915 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
4916 << OrigFormatExpr->getSourceRange();
4921 case FST_FreeBSDKPrintf:
4923 Diag(FormatLoc, diag::note_format_security_fixit)
4924 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
4927 Diag(FormatLoc, diag::note_format_security_fixit)
4928 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
4932 Diag(FormatLoc, diag::warn_format_nonliteral)
4933 << OrigFormatExpr->getSourceRange();
4939 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
4942 const FormatStringLiteral *FExpr;
4943 const Expr *OrigFormatExpr;
4944 const Sema::FormatStringType FSType;
4945 const unsigned FirstDataArg;
4946 const unsigned NumDataArgs;
4947 const char *Beg; // Start of format string.
4948 const bool HasVAListArg;
4949 ArrayRef<const Expr *> Args;
4951 llvm::SmallBitVector CoveredArgs;
4952 bool usesPositionalArgs;
4954 bool inFunctionCall;
4955 Sema::VariadicCallType CallType;
4956 llvm::SmallBitVector &CheckedVarArgs;
4957 UncoveredArgHandler &UncoveredArg;
4960 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
4961 const Expr *origFormatExpr,
4962 const Sema::FormatStringType type, unsigned firstDataArg,
4963 unsigned numDataArgs, const char *beg, bool hasVAListArg,
4964 ArrayRef<const Expr *> Args, unsigned formatIdx,
4965 bool inFunctionCall, Sema::VariadicCallType callType,
4966 llvm::SmallBitVector &CheckedVarArgs,
4967 UncoveredArgHandler &UncoveredArg)
4968 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
4969 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
4970 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
4971 usesPositionalArgs(false), atFirstArg(true),
4972 inFunctionCall(inFunctionCall), CallType(callType),
4973 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
4974 CoveredArgs.resize(numDataArgs);
4975 CoveredArgs.reset();
4978 void DoneProcessing();
4980 void HandleIncompleteSpecifier(const char *startSpecifier,
4981 unsigned specifierLen) override;
4983 void HandleInvalidLengthModifier(
4984 const analyze_format_string::FormatSpecifier &FS,
4985 const analyze_format_string::ConversionSpecifier &CS,
4986 const char *startSpecifier, unsigned specifierLen,
4989 void HandleNonStandardLengthModifier(
4990 const analyze_format_string::FormatSpecifier &FS,
4991 const char *startSpecifier, unsigned specifierLen);
4993 void HandleNonStandardConversionSpecifier(
4994 const analyze_format_string::ConversionSpecifier &CS,
4995 const char *startSpecifier, unsigned specifierLen);
4997 void HandlePosition(const char *startPos, unsigned posLen) override;
4999 void HandleInvalidPosition(const char *startSpecifier,
5000 unsigned specifierLen,
5001 analyze_format_string::PositionContext p) override;
5003 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
5005 void HandleNullChar(const char *nullCharacter) override;
5007 template <typename Range>
5009 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
5010 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
5011 bool IsStringLocation, Range StringRange,
5012 ArrayRef<FixItHint> Fixit = None);
5015 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
5016 const char *startSpec,
5017 unsigned specifierLen,
5018 const char *csStart, unsigned csLen);
5020 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
5021 const char *startSpec,
5022 unsigned specifierLen);
5024 SourceRange getFormatStringRange();
5025 CharSourceRange getSpecifierRange(const char *startSpecifier,
5026 unsigned specifierLen);
5027 SourceLocation getLocationOfByte(const char *x);
5029 const Expr *getDataArg(unsigned i) const;
5031 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
5032 const analyze_format_string::ConversionSpecifier &CS,
5033 const char *startSpecifier, unsigned specifierLen,
5036 template <typename Range>
5037 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5038 bool IsStringLocation, Range StringRange,
5039 ArrayRef<FixItHint> Fixit = None);
5041 } // end anonymous namespace
5043 SourceRange CheckFormatHandler::getFormatStringRange() {
5044 return OrigFormatExpr->getSourceRange();
5047 CharSourceRange CheckFormatHandler::
5048 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
5049 SourceLocation Start = getLocationOfByte(startSpecifier);
5050 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
5052 // Advance the end SourceLocation by one due to half-open ranges.
5053 End = End.getLocWithOffset(1);
5055 return CharSourceRange::getCharRange(Start, End);
5058 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
5059 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
5060 S.getLangOpts(), S.Context.getTargetInfo());
5063 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
5064 unsigned specifierLen){
5065 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
5066 getLocationOfByte(startSpecifier),
5067 /*IsStringLocation*/true,
5068 getSpecifierRange(startSpecifier, specifierLen));
5071 void CheckFormatHandler::HandleInvalidLengthModifier(
5072 const analyze_format_string::FormatSpecifier &FS,
5073 const analyze_format_string::ConversionSpecifier &CS,
5074 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
5075 using namespace analyze_format_string;
5077 const LengthModifier &LM = FS.getLengthModifier();
5078 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5080 // See if we know how to fix this length modifier.
5081 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
5083 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
5084 getLocationOfByte(LM.getStart()),
5085 /*IsStringLocation*/true,
5086 getSpecifierRange(startSpecifier, specifierLen));
5088 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5089 << FixedLM->toString()
5090 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5094 if (DiagID == diag::warn_format_nonsensical_length)
5095 Hint = FixItHint::CreateRemoval(LMRange);
5097 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
5098 getLocationOfByte(LM.getStart()),
5099 /*IsStringLocation*/true,
5100 getSpecifierRange(startSpecifier, specifierLen),
5105 void CheckFormatHandler::HandleNonStandardLengthModifier(
5106 const analyze_format_string::FormatSpecifier &FS,
5107 const char *startSpecifier, unsigned specifierLen) {
5108 using namespace analyze_format_string;
5110 const LengthModifier &LM = FS.getLengthModifier();
5111 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5113 // See if we know how to fix this length modifier.
5114 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
5116 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5117 << LM.toString() << 0,
5118 getLocationOfByte(LM.getStart()),
5119 /*IsStringLocation*/true,
5120 getSpecifierRange(startSpecifier, specifierLen));
5122 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5123 << FixedLM->toString()
5124 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5127 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5128 << LM.toString() << 0,
5129 getLocationOfByte(LM.getStart()),
5130 /*IsStringLocation*/true,
5131 getSpecifierRange(startSpecifier, specifierLen));
5135 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5136 const analyze_format_string::ConversionSpecifier &CS,
5137 const char *startSpecifier, unsigned specifierLen) {
5138 using namespace analyze_format_string;
5140 // See if we know how to fix this conversion specifier.
5141 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
5143 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5144 << CS.toString() << /*conversion specifier*/1,
5145 getLocationOfByte(CS.getStart()),
5146 /*IsStringLocation*/true,
5147 getSpecifierRange(startSpecifier, specifierLen));
5149 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5150 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5151 << FixedCS->toString()
5152 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5154 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5155 << CS.toString() << /*conversion specifier*/1,
5156 getLocationOfByte(CS.getStart()),
5157 /*IsStringLocation*/true,
5158 getSpecifierRange(startSpecifier, specifierLen));
5162 void CheckFormatHandler::HandlePosition(const char *startPos,
5164 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5165 getLocationOfByte(startPos),
5166 /*IsStringLocation*/true,
5167 getSpecifierRange(startPos, posLen));
5171 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5172 analyze_format_string::PositionContext p) {
5173 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5175 getLocationOfByte(startPos), /*IsStringLocation*/true,
5176 getSpecifierRange(startPos, posLen));
5179 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
5181 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5182 getLocationOfByte(startPos),
5183 /*IsStringLocation*/true,
5184 getSpecifierRange(startPos, posLen));
5187 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
5188 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
5189 // The presence of a null character is likely an error.
5190 EmitFormatDiagnostic(
5191 S.PDiag(diag::warn_printf_format_string_contains_null_char),
5192 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
5193 getFormatStringRange());
5197 // Note that this may return NULL if there was an error parsing or building
5198 // one of the argument expressions.
5199 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
5200 return Args[FirstDataArg + i];
5203 void CheckFormatHandler::DoneProcessing() {
5204 // Does the number of data arguments exceed the number of
5205 // format conversions in the format string?
5206 if (!HasVAListArg) {
5207 // Find any arguments that weren't covered.
5209 signed notCoveredArg = CoveredArgs.find_first();
5210 if (notCoveredArg >= 0) {
5211 assert((unsigned)notCoveredArg < NumDataArgs);
5212 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
5214 UncoveredArg.setAllCovered();
5219 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
5220 const Expr *ArgExpr) {
5221 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
5227 SourceLocation Loc = ArgExpr->getLocStart();
5229 if (S.getSourceManager().isInSystemMacro(Loc))
5232 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
5233 for (auto E : DiagnosticExprs)
5234 PDiag << E->getSourceRange();
5236 CheckFormatHandler::EmitFormatDiagnostic(
5237 S, IsFunctionCall, DiagnosticExprs[0],
5238 PDiag, Loc, /*IsStringLocation*/false,
5239 DiagnosticExprs[0]->getSourceRange());
5243 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
5245 const char *startSpec,
5246 unsigned specifierLen,
5247 const char *csStart,
5249 bool keepGoing = true;
5250 if (argIndex < NumDataArgs) {
5251 // Consider the argument coverered, even though the specifier doesn't
5253 CoveredArgs.set(argIndex);
5256 // If argIndex exceeds the number of data arguments we
5257 // don't issue a warning because that is just a cascade of warnings (and
5258 // they may have intended '%%' anyway). We don't want to continue processing
5259 // the format string after this point, however, as we will like just get
5260 // gibberish when trying to match arguments.
5264 StringRef Specifier(csStart, csLen);
5266 // If the specifier in non-printable, it could be the first byte of a UTF-8
5267 // sequence. In that case, print the UTF-8 code point. If not, print the byte
5269 std::string CodePointStr;
5270 if (!llvm::sys::locale::isPrint(*csStart)) {
5271 llvm::UTF32 CodePoint;
5272 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
5273 const llvm::UTF8 *E =
5274 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
5275 llvm::ConversionResult Result =
5276 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
5278 if (Result != llvm::conversionOK) {
5279 unsigned char FirstChar = *csStart;
5280 CodePoint = (llvm::UTF32)FirstChar;
5283 llvm::raw_string_ostream OS(CodePointStr);
5284 if (CodePoint < 256)
5285 OS << "\\x" << llvm::format("%02x", CodePoint);
5286 else if (CodePoint <= 0xFFFF)
5287 OS << "\\u" << llvm::format("%04x", CodePoint);
5289 OS << "\\U" << llvm::format("%08x", CodePoint);
5291 Specifier = CodePointStr;
5294 EmitFormatDiagnostic(
5295 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
5296 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
5302 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
5303 const char *startSpec,
5304 unsigned specifierLen) {
5305 EmitFormatDiagnostic(
5306 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
5307 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
5311 CheckFormatHandler::CheckNumArgs(
5312 const analyze_format_string::FormatSpecifier &FS,
5313 const analyze_format_string::ConversionSpecifier &CS,
5314 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
5316 if (argIndex >= NumDataArgs) {
5317 PartialDiagnostic PDiag = FS.usesPositionalArg()
5318 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
5319 << (argIndex+1) << NumDataArgs)
5320 : S.PDiag(diag::warn_printf_insufficient_data_args);
5321 EmitFormatDiagnostic(
5322 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
5323 getSpecifierRange(startSpecifier, specifierLen));
5325 // Since more arguments than conversion tokens are given, by extension
5326 // all arguments are covered, so mark this as so.
5327 UncoveredArg.setAllCovered();
5333 template<typename Range>
5334 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
5336 bool IsStringLocation,
5338 ArrayRef<FixItHint> FixIt) {
5339 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
5340 Loc, IsStringLocation, StringRange, FixIt);
5343 /// \brief If the format string is not within the funcion call, emit a note
5344 /// so that the function call and string are in diagnostic messages.
5346 /// \param InFunctionCall if true, the format string is within the function
5347 /// call and only one diagnostic message will be produced. Otherwise, an
5348 /// extra note will be emitted pointing to location of the format string.
5350 /// \param ArgumentExpr the expression that is passed as the format string
5351 /// argument in the function call. Used for getting locations when two
5352 /// diagnostics are emitted.
5354 /// \param PDiag the callee should already have provided any strings for the
5355 /// diagnostic message. This function only adds locations and fixits
5358 /// \param Loc primary location for diagnostic. If two diagnostics are
5359 /// required, one will be at Loc and a new SourceLocation will be created for
5362 /// \param IsStringLocation if true, Loc points to the format string should be
5363 /// used for the note. Otherwise, Loc points to the argument list and will
5364 /// be used with PDiag.
5366 /// \param StringRange some or all of the string to highlight. This is
5367 /// templated so it can accept either a CharSourceRange or a SourceRange.
5369 /// \param FixIt optional fix it hint for the format string.
5370 template <typename Range>
5371 void CheckFormatHandler::EmitFormatDiagnostic(
5372 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
5373 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
5374 Range StringRange, ArrayRef<FixItHint> FixIt) {
5375 if (InFunctionCall) {
5376 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
5380 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
5381 << ArgumentExpr->getSourceRange();
5383 const Sema::SemaDiagnosticBuilder &Note =
5384 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
5385 diag::note_format_string_defined);
5387 Note << StringRange;
5392 //===--- CHECK: Printf format string checking ------------------------------===//
5395 class CheckPrintfHandler : public CheckFormatHandler {
5397 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
5398 const Expr *origFormatExpr,
5399 const Sema::FormatStringType type, unsigned firstDataArg,
5400 unsigned numDataArgs, bool isObjC, const char *beg,
5401 bool hasVAListArg, ArrayRef<const Expr *> Args,
5402 unsigned formatIdx, bool inFunctionCall,
5403 Sema::VariadicCallType CallType,
5404 llvm::SmallBitVector &CheckedVarArgs,
5405 UncoveredArgHandler &UncoveredArg)
5406 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
5407 numDataArgs, beg, hasVAListArg, Args, formatIdx,
5408 inFunctionCall, CallType, CheckedVarArgs,
5411 bool isObjCContext() const { return FSType == Sema::FST_NSString; }
5413 /// Returns true if '%@' specifiers are allowed in the format string.
5414 bool allowsObjCArg() const {
5415 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
5416 FSType == Sema::FST_OSTrace;
5419 bool HandleInvalidPrintfConversionSpecifier(
5420 const analyze_printf::PrintfSpecifier &FS,
5421 const char *startSpecifier,
5422 unsigned specifierLen) override;
5424 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
5425 const char *startSpecifier,
5426 unsigned specifierLen) override;
5427 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5428 const char *StartSpecifier,
5429 unsigned SpecifierLen,
5432 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
5433 const char *startSpecifier, unsigned specifierLen);
5434 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
5435 const analyze_printf::OptionalAmount &Amt,
5437 const char *startSpecifier, unsigned specifierLen);
5438 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5439 const analyze_printf::OptionalFlag &flag,
5440 const char *startSpecifier, unsigned specifierLen);
5441 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
5442 const analyze_printf::OptionalFlag &ignoredFlag,
5443 const analyze_printf::OptionalFlag &flag,
5444 const char *startSpecifier, unsigned specifierLen);
5445 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
5448 void HandleEmptyObjCModifierFlag(const char *startFlag,
5449 unsigned flagLen) override;
5451 void HandleInvalidObjCModifierFlag(const char *startFlag,
5452 unsigned flagLen) override;
5454 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
5455 const char *flagsEnd,
5456 const char *conversionPosition)
5459 } // end anonymous namespace
5461 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
5462 const analyze_printf::PrintfSpecifier &FS,
5463 const char *startSpecifier,
5464 unsigned specifierLen) {
5465 const analyze_printf::PrintfConversionSpecifier &CS =
5466 FS.getConversionSpecifier();
5468 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5469 getLocationOfByte(CS.getStart()),
5470 startSpecifier, specifierLen,
5471 CS.getStart(), CS.getLength());
5474 bool CheckPrintfHandler::HandleAmount(
5475 const analyze_format_string::OptionalAmount &Amt,
5476 unsigned k, const char *startSpecifier,
5477 unsigned specifierLen) {
5478 if (Amt.hasDataArgument()) {
5479 if (!HasVAListArg) {
5480 unsigned argIndex = Amt.getArgIndex();
5481 if (argIndex >= NumDataArgs) {
5482 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
5484 getLocationOfByte(Amt.getStart()),
5485 /*IsStringLocation*/true,
5486 getSpecifierRange(startSpecifier, specifierLen));
5487 // Don't do any more checking. We will just emit
5492 // Type check the data argument. It should be an 'int'.
5493 // Although not in conformance with C99, we also allow the argument to be
5494 // an 'unsigned int' as that is a reasonably safe case. GCC also
5495 // doesn't emit a warning for that case.
5496 CoveredArgs.set(argIndex);
5497 const Expr *Arg = getDataArg(argIndex);
5501 QualType T = Arg->getType();
5503 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
5504 assert(AT.isValid());
5506 if (!AT.matchesType(S.Context, T)) {
5507 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
5508 << k << AT.getRepresentativeTypeName(S.Context)
5509 << T << Arg->getSourceRange(),
5510 getLocationOfByte(Amt.getStart()),
5511 /*IsStringLocation*/true,
5512 getSpecifierRange(startSpecifier, specifierLen));
5513 // Don't do any more checking. We will just emit
5522 void CheckPrintfHandler::HandleInvalidAmount(
5523 const analyze_printf::PrintfSpecifier &FS,
5524 const analyze_printf::OptionalAmount &Amt,
5526 const char *startSpecifier,
5527 unsigned specifierLen) {
5528 const analyze_printf::PrintfConversionSpecifier &CS =
5529 FS.getConversionSpecifier();
5532 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
5533 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
5534 Amt.getConstantLength()))
5537 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
5538 << type << CS.toString(),
5539 getLocationOfByte(Amt.getStart()),
5540 /*IsStringLocation*/true,
5541 getSpecifierRange(startSpecifier, specifierLen),
5545 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5546 const analyze_printf::OptionalFlag &flag,
5547 const char *startSpecifier,
5548 unsigned specifierLen) {
5549 // Warn about pointless flag with a fixit removal.
5550 const analyze_printf::PrintfConversionSpecifier &CS =
5551 FS.getConversionSpecifier();
5552 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
5553 << flag.toString() << CS.toString(),
5554 getLocationOfByte(flag.getPosition()),
5555 /*IsStringLocation*/true,
5556 getSpecifierRange(startSpecifier, specifierLen),
5557 FixItHint::CreateRemoval(
5558 getSpecifierRange(flag.getPosition(), 1)));
5561 void CheckPrintfHandler::HandleIgnoredFlag(
5562 const analyze_printf::PrintfSpecifier &FS,
5563 const analyze_printf::OptionalFlag &ignoredFlag,
5564 const analyze_printf::OptionalFlag &flag,
5565 const char *startSpecifier,
5566 unsigned specifierLen) {
5567 // Warn about ignored flag with a fixit removal.
5568 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
5569 << ignoredFlag.toString() << flag.toString(),
5570 getLocationOfByte(ignoredFlag.getPosition()),
5571 /*IsStringLocation*/true,
5572 getSpecifierRange(startSpecifier, specifierLen),
5573 FixItHint::CreateRemoval(
5574 getSpecifierRange(ignoredFlag.getPosition(), 1)));
5577 // void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5578 // bool IsStringLocation, Range StringRange,
5579 // ArrayRef<FixItHint> Fixit = None);
5581 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
5583 // Warn about an empty flag.
5584 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
5585 getLocationOfByte(startFlag),
5586 /*IsStringLocation*/true,
5587 getSpecifierRange(startFlag, flagLen));
5590 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
5592 // Warn about an invalid flag.
5593 auto Range = getSpecifierRange(startFlag, flagLen);
5594 StringRef flag(startFlag, flagLen);
5595 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
5596 getLocationOfByte(startFlag),
5597 /*IsStringLocation*/true,
5598 Range, FixItHint::CreateRemoval(Range));
5601 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
5602 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
5603 // Warn about using '[...]' without a '@' conversion.
5604 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
5605 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
5606 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
5607 getLocationOfByte(conversionPosition),
5608 /*IsStringLocation*/true,
5609 Range, FixItHint::CreateRemoval(Range));
5612 // Determines if the specified is a C++ class or struct containing
5613 // a member with the specified name and kind (e.g. a CXXMethodDecl named
5615 template<typename MemberKind>
5616 static llvm::SmallPtrSet<MemberKind*, 1>
5617 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
5618 const RecordType *RT = Ty->getAs<RecordType>();
5619 llvm::SmallPtrSet<MemberKind*, 1> Results;
5623 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
5624 if (!RD || !RD->getDefinition())
5627 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
5628 Sema::LookupMemberName);
5629 R.suppressDiagnostics();
5631 // We just need to include all members of the right kind turned up by the
5632 // filter, at this point.
5633 if (S.LookupQualifiedName(R, RT->getDecl()))
5634 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5635 NamedDecl *decl = (*I)->getUnderlyingDecl();
5636 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
5642 /// Check if we could call '.c_str()' on an object.
5644 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
5645 /// allow the call, or if it would be ambiguous).
5646 bool Sema::hasCStrMethod(const Expr *E) {
5647 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5649 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
5650 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5652 if ((*MI)->getMinRequiredArguments() == 0)
5657 // Check if a (w)string was passed when a (w)char* was needed, and offer a
5658 // better diagnostic if so. AT is assumed to be valid.
5659 // Returns true when a c_str() conversion method is found.
5660 bool CheckPrintfHandler::checkForCStrMembers(
5661 const analyze_printf::ArgType &AT, const Expr *E) {
5662 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5665 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
5667 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5669 const CXXMethodDecl *Method = *MI;
5670 if (Method->getMinRequiredArguments() == 0 &&
5671 AT.matchesType(S.Context, Method->getReturnType())) {
5672 // FIXME: Suggest parens if the expression needs them.
5673 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
5674 S.Diag(E->getLocStart(), diag::note_printf_c_str)
5676 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
5685 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
5687 const char *startSpecifier,
5688 unsigned specifierLen) {
5689 using namespace analyze_format_string;
5690 using namespace analyze_printf;
5691 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
5693 if (FS.consumesDataArgument()) {
5696 usesPositionalArgs = FS.usesPositionalArg();
5698 else if (usesPositionalArgs != FS.usesPositionalArg()) {
5699 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5700 startSpecifier, specifierLen);
5705 // First check if the field width, precision, and conversion specifier
5706 // have matching data arguments.
5707 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
5708 startSpecifier, specifierLen)) {
5712 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
5713 startSpecifier, specifierLen)) {
5717 if (!CS.consumesDataArgument()) {
5718 // FIXME: Technically specifying a precision or field width here
5719 // makes no sense. Worth issuing a warning at some point.
5723 // Consume the argument.
5724 unsigned argIndex = FS.getArgIndex();
5725 if (argIndex < NumDataArgs) {
5726 // The check to see if the argIndex is valid will come later.
5727 // We set the bit here because we may exit early from this
5728 // function if we encounter some other error.
5729 CoveredArgs.set(argIndex);
5732 // FreeBSD kernel extensions.
5733 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
5734 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
5735 // We need at least two arguments.
5736 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
5739 // Claim the second argument.
5740 CoveredArgs.set(argIndex + 1);
5742 // Type check the first argument (int for %b, pointer for %D)
5743 const Expr *Ex = getDataArg(argIndex);
5744 const analyze_printf::ArgType &AT =
5745 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
5746 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
5747 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
5748 EmitFormatDiagnostic(
5749 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5750 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
5751 << false << Ex->getSourceRange(),
5752 Ex->getLocStart(), /*IsStringLocation*/false,
5753 getSpecifierRange(startSpecifier, specifierLen));
5755 // Type check the second argument (char * for both %b and %D)
5756 Ex = getDataArg(argIndex + 1);
5757 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
5758 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
5759 EmitFormatDiagnostic(
5760 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5761 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
5762 << false << Ex->getSourceRange(),
5763 Ex->getLocStart(), /*IsStringLocation*/false,
5764 getSpecifierRange(startSpecifier, specifierLen));
5769 // Check for using an Objective-C specific conversion specifier
5770 // in a non-ObjC literal.
5771 if (!allowsObjCArg() && CS.isObjCArg()) {
5772 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5776 // %P can only be used with os_log.
5777 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
5778 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5782 // %n is not allowed with os_log.
5783 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
5784 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
5785 getLocationOfByte(CS.getStart()),
5786 /*IsStringLocation*/ false,
5787 getSpecifierRange(startSpecifier, specifierLen));
5792 // Only scalars are allowed for os_trace.
5793 if (FSType == Sema::FST_OSTrace &&
5794 (CS.getKind() == ConversionSpecifier::PArg ||
5795 CS.getKind() == ConversionSpecifier::sArg ||
5796 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
5797 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5801 // Check for use of public/private annotation outside of os_log().
5802 if (FSType != Sema::FST_OSLog) {
5803 if (FS.isPublic().isSet()) {
5804 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
5806 getLocationOfByte(FS.isPublic().getPosition()),
5807 /*IsStringLocation*/ false,
5808 getSpecifierRange(startSpecifier, specifierLen));
5810 if (FS.isPrivate().isSet()) {
5811 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
5813 getLocationOfByte(FS.isPrivate().getPosition()),
5814 /*IsStringLocation*/ false,
5815 getSpecifierRange(startSpecifier, specifierLen));
5819 // Check for invalid use of field width
5820 if (!FS.hasValidFieldWidth()) {
5821 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
5822 startSpecifier, specifierLen);
5825 // Check for invalid use of precision
5826 if (!FS.hasValidPrecision()) {
5827 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
5828 startSpecifier, specifierLen);
5831 // Precision is mandatory for %P specifier.
5832 if (CS.getKind() == ConversionSpecifier::PArg &&
5833 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
5834 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
5835 getLocationOfByte(startSpecifier),
5836 /*IsStringLocation*/ false,
5837 getSpecifierRange(startSpecifier, specifierLen));
5840 // Check each flag does not conflict with any other component.
5841 if (!FS.hasValidThousandsGroupingPrefix())
5842 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
5843 if (!FS.hasValidLeadingZeros())
5844 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
5845 if (!FS.hasValidPlusPrefix())
5846 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
5847 if (!FS.hasValidSpacePrefix())
5848 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
5849 if (!FS.hasValidAlternativeForm())
5850 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
5851 if (!FS.hasValidLeftJustified())
5852 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
5854 // Check that flags are not ignored by another flag
5855 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
5856 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
5857 startSpecifier, specifierLen);
5858 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
5859 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
5860 startSpecifier, specifierLen);
5862 // Check the length modifier is valid with the given conversion specifier.
5863 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
5864 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5865 diag::warn_format_nonsensical_length);
5866 else if (!FS.hasStandardLengthModifier())
5867 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
5868 else if (!FS.hasStandardLengthConversionCombination())
5869 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5870 diag::warn_format_non_standard_conversion_spec);
5872 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
5873 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
5875 // The remaining checks depend on the data arguments.
5879 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
5882 const Expr *Arg = getDataArg(argIndex);
5886 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
5889 static bool requiresParensToAddCast(const Expr *E) {
5890 // FIXME: We should have a general way to reason about operator
5891 // precedence and whether parens are actually needed here.
5892 // Take care of a few common cases where they aren't.
5893 const Expr *Inside = E->IgnoreImpCasts();
5894 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
5895 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
5897 switch (Inside->getStmtClass()) {
5898 case Stmt::ArraySubscriptExprClass:
5899 case Stmt::CallExprClass:
5900 case Stmt::CharacterLiteralClass:
5901 case Stmt::CXXBoolLiteralExprClass:
5902 case Stmt::DeclRefExprClass:
5903 case Stmt::FloatingLiteralClass:
5904 case Stmt::IntegerLiteralClass:
5905 case Stmt::MemberExprClass:
5906 case Stmt::ObjCArrayLiteralClass:
5907 case Stmt::ObjCBoolLiteralExprClass:
5908 case Stmt::ObjCBoxedExprClass:
5909 case Stmt::ObjCDictionaryLiteralClass:
5910 case Stmt::ObjCEncodeExprClass:
5911 case Stmt::ObjCIvarRefExprClass:
5912 case Stmt::ObjCMessageExprClass:
5913 case Stmt::ObjCPropertyRefExprClass:
5914 case Stmt::ObjCStringLiteralClass:
5915 case Stmt::ObjCSubscriptRefExprClass:
5916 case Stmt::ParenExprClass:
5917 case Stmt::StringLiteralClass:
5918 case Stmt::UnaryOperatorClass:
5925 static std::pair<QualType, StringRef>
5926 shouldNotPrintDirectly(const ASTContext &Context,
5927 QualType IntendedTy,
5929 // Use a 'while' to peel off layers of typedefs.
5930 QualType TyTy = IntendedTy;
5931 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
5932 StringRef Name = UserTy->getDecl()->getName();
5933 QualType CastTy = llvm::StringSwitch<QualType>(Name)
5934 .Case("NSInteger", Context.LongTy)
5935 .Case("NSUInteger", Context.UnsignedLongTy)
5936 .Case("SInt32", Context.IntTy)
5937 .Case("UInt32", Context.UnsignedIntTy)
5938 .Default(QualType());
5940 if (!CastTy.isNull())
5941 return std::make_pair(CastTy, Name);
5943 TyTy = UserTy->desugar();
5946 // Strip parens if necessary.
5947 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
5948 return shouldNotPrintDirectly(Context,
5949 PE->getSubExpr()->getType(),
5952 // If this is a conditional expression, then its result type is constructed
5953 // via usual arithmetic conversions and thus there might be no necessary
5954 // typedef sugar there. Recurse to operands to check for NSInteger &
5955 // Co. usage condition.
5956 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5957 QualType TrueTy, FalseTy;
5958 StringRef TrueName, FalseName;
5960 std::tie(TrueTy, TrueName) =
5961 shouldNotPrintDirectly(Context,
5962 CO->getTrueExpr()->getType(),
5964 std::tie(FalseTy, FalseName) =
5965 shouldNotPrintDirectly(Context,
5966 CO->getFalseExpr()->getType(),
5967 CO->getFalseExpr());
5969 if (TrueTy == FalseTy)
5970 return std::make_pair(TrueTy, TrueName);
5971 else if (TrueTy.isNull())
5972 return std::make_pair(FalseTy, FalseName);
5973 else if (FalseTy.isNull())
5974 return std::make_pair(TrueTy, TrueName);
5977 return std::make_pair(QualType(), StringRef());
5981 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5982 const char *StartSpecifier,
5983 unsigned SpecifierLen,
5985 using namespace analyze_format_string;
5986 using namespace analyze_printf;
5987 // Now type check the data expression that matches the
5988 // format specifier.
5989 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
5993 QualType ExprTy = E->getType();
5994 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
5995 ExprTy = TET->getUnderlyingExpr()->getType();
5998 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
6000 if (match == analyze_printf::ArgType::Match) {
6004 // Look through argument promotions for our error message's reported type.
6005 // This includes the integral and floating promotions, but excludes array
6006 // and function pointer decay; seeing that an argument intended to be a
6007 // string has type 'char [6]' is probably more confusing than 'char *'.
6008 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6009 if (ICE->getCastKind() == CK_IntegralCast ||
6010 ICE->getCastKind() == CK_FloatingCast) {
6011 E = ICE->getSubExpr();
6012 ExprTy = E->getType();
6014 // Check if we didn't match because of an implicit cast from a 'char'
6015 // or 'short' to an 'int'. This is done because printf is a varargs
6017 if (ICE->getType() == S.Context.IntTy ||
6018 ICE->getType() == S.Context.UnsignedIntTy) {
6019 // All further checking is done on the subexpression.
6020 if (AT.matchesType(S.Context, ExprTy))
6024 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
6025 // Special case for 'a', which has type 'int' in C.
6026 // Note, however, that we do /not/ want to treat multibyte constants like
6027 // 'MooV' as characters! This form is deprecated but still exists.
6028 if (ExprTy == S.Context.IntTy)
6029 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
6030 ExprTy = S.Context.CharTy;
6033 // Look through enums to their underlying type.
6034 bool IsEnum = false;
6035 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
6036 ExprTy = EnumTy->getDecl()->getIntegerType();
6040 // %C in an Objective-C context prints a unichar, not a wchar_t.
6041 // If the argument is an integer of some kind, believe the %C and suggest
6042 // a cast instead of changing the conversion specifier.
6043 QualType IntendedTy = ExprTy;
6044 if (isObjCContext() &&
6045 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
6046 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
6047 !ExprTy->isCharType()) {
6048 // 'unichar' is defined as a typedef of unsigned short, but we should
6049 // prefer using the typedef if it is visible.
6050 IntendedTy = S.Context.UnsignedShortTy;
6052 // While we are here, check if the value is an IntegerLiteral that happens
6053 // to be within the valid range.
6054 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
6055 const llvm::APInt &V = IL->getValue();
6056 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
6060 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
6061 Sema::LookupOrdinaryName);
6062 if (S.LookupName(Result, S.getCurScope())) {
6063 NamedDecl *ND = Result.getFoundDecl();
6064 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
6065 if (TD->getUnderlyingType() == IntendedTy)
6066 IntendedTy = S.Context.getTypedefType(TD);
6071 // Special-case some of Darwin's platform-independence types by suggesting
6072 // casts to primitive types that are known to be large enough.
6073 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
6074 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
6076 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
6077 if (!CastTy.isNull()) {
6078 IntendedTy = CastTy;
6079 ShouldNotPrintDirectly = true;
6083 // We may be able to offer a FixItHint if it is a supported type.
6084 PrintfSpecifier fixedFS = FS;
6086 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
6089 // Get the fix string from the fixed format specifier
6090 SmallString<16> buf;
6091 llvm::raw_svector_ostream os(buf);
6092 fixedFS.toString(os);
6094 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
6096 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
6097 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6098 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6099 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6101 // In this case, the specifier is wrong and should be changed to match
6103 EmitFormatDiagnostic(S.PDiag(diag)
6104 << AT.getRepresentativeTypeName(S.Context)
6105 << IntendedTy << IsEnum << E->getSourceRange(),
6107 /*IsStringLocation*/ false, SpecRange,
6108 FixItHint::CreateReplacement(SpecRange, os.str()));
6110 // The canonical type for formatting this value is different from the
6111 // actual type of the expression. (This occurs, for example, with Darwin's
6112 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
6113 // should be printed as 'long' for 64-bit compatibility.)
6114 // Rather than emitting a normal format/argument mismatch, we want to
6115 // add a cast to the recommended type (and correct the format string
6117 SmallString<16> CastBuf;
6118 llvm::raw_svector_ostream CastFix(CastBuf);
6120 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
6123 SmallVector<FixItHint,4> Hints;
6124 if (!AT.matchesType(S.Context, IntendedTy))
6125 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
6127 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
6128 // If there's already a cast present, just replace it.
6129 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
6130 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
6132 } else if (!requiresParensToAddCast(E)) {
6133 // If the expression has high enough precedence,
6134 // just write the C-style cast.
6135 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6138 // Otherwise, add parens around the expression as well as the cast.
6140 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6143 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
6144 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6147 if (ShouldNotPrintDirectly) {
6148 // The expression has a type that should not be printed directly.
6149 // We extract the name from the typedef because we don't want to show
6150 // the underlying type in the diagnostic.
6152 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6153 Name = TypedefTy->getDecl()->getName();
6156 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
6157 << Name << IntendedTy << IsEnum
6158 << E->getSourceRange(),
6159 E->getLocStart(), /*IsStringLocation=*/false,
6162 // In this case, the expression could be printed using a different
6163 // specifier, but we've decided that the specifier is probably correct
6164 // and we should cast instead. Just use the normal warning message.
6165 EmitFormatDiagnostic(
6166 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6167 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
6168 << E->getSourceRange(),
6169 E->getLocStart(), /*IsStringLocation*/false,
6174 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
6176 // Since the warning for passing non-POD types to variadic functions
6177 // was deferred until now, we emit a warning for non-POD
6179 switch (S.isValidVarArgType(ExprTy)) {
6180 case Sema::VAK_Valid:
6181 case Sema::VAK_ValidInCXX11: {
6182 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6183 if (match == analyze_printf::ArgType::NoMatchPedantic) {
6184 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6187 EmitFormatDiagnostic(
6188 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
6189 << IsEnum << CSR << E->getSourceRange(),
6190 E->getLocStart(), /*IsStringLocation*/ false, CSR);
6193 case Sema::VAK_Undefined:
6194 case Sema::VAK_MSVCUndefined:
6195 EmitFormatDiagnostic(
6196 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
6197 << S.getLangOpts().CPlusPlus11
6200 << AT.getRepresentativeTypeName(S.Context)
6202 << E->getSourceRange(),
6203 E->getLocStart(), /*IsStringLocation*/false, CSR);
6204 checkForCStrMembers(AT, E);
6207 case Sema::VAK_Invalid:
6208 if (ExprTy->isObjCObjectType())
6209 EmitFormatDiagnostic(
6210 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
6211 << S.getLangOpts().CPlusPlus11
6214 << AT.getRepresentativeTypeName(S.Context)
6216 << E->getSourceRange(),
6217 E->getLocStart(), /*IsStringLocation*/false, CSR);
6219 // FIXME: If this is an initializer list, suggest removing the braces
6220 // or inserting a cast to the target type.
6221 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
6222 << isa<InitListExpr>(E) << ExprTy << CallType
6223 << AT.getRepresentativeTypeName(S.Context)
6224 << E->getSourceRange();
6228 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
6229 "format string specifier index out of range");
6230 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
6236 //===--- CHECK: Scanf format string checking ------------------------------===//
6239 class CheckScanfHandler : public CheckFormatHandler {
6241 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
6242 const Expr *origFormatExpr, Sema::FormatStringType type,
6243 unsigned firstDataArg, unsigned numDataArgs,
6244 const char *beg, bool hasVAListArg,
6245 ArrayRef<const Expr *> Args, unsigned formatIdx,
6246 bool inFunctionCall, Sema::VariadicCallType CallType,
6247 llvm::SmallBitVector &CheckedVarArgs,
6248 UncoveredArgHandler &UncoveredArg)
6249 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6250 numDataArgs, beg, hasVAListArg, Args, formatIdx,
6251 inFunctionCall, CallType, CheckedVarArgs,
6254 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
6255 const char *startSpecifier,
6256 unsigned specifierLen) override;
6258 bool HandleInvalidScanfConversionSpecifier(
6259 const analyze_scanf::ScanfSpecifier &FS,
6260 const char *startSpecifier,
6261 unsigned specifierLen) override;
6263 void HandleIncompleteScanList(const char *start, const char *end) override;
6265 } // end anonymous namespace
6267 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
6269 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
6270 getLocationOfByte(end), /*IsStringLocation*/true,
6271 getSpecifierRange(start, end - start));
6274 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
6275 const analyze_scanf::ScanfSpecifier &FS,
6276 const char *startSpecifier,
6277 unsigned specifierLen) {
6279 const analyze_scanf::ScanfConversionSpecifier &CS =
6280 FS.getConversionSpecifier();
6282 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6283 getLocationOfByte(CS.getStart()),
6284 startSpecifier, specifierLen,
6285 CS.getStart(), CS.getLength());
6288 bool CheckScanfHandler::HandleScanfSpecifier(
6289 const analyze_scanf::ScanfSpecifier &FS,
6290 const char *startSpecifier,
6291 unsigned specifierLen) {
6292 using namespace analyze_scanf;
6293 using namespace analyze_format_string;
6295 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
6297 // Handle case where '%' and '*' don't consume an argument. These shouldn't
6298 // be used to decide if we are using positional arguments consistently.
6299 if (FS.consumesDataArgument()) {
6302 usesPositionalArgs = FS.usesPositionalArg();
6304 else if (usesPositionalArgs != FS.usesPositionalArg()) {
6305 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6306 startSpecifier, specifierLen);
6311 // Check if the field with is non-zero.
6312 const OptionalAmount &Amt = FS.getFieldWidth();
6313 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
6314 if (Amt.getConstantAmount() == 0) {
6315 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
6316 Amt.getConstantLength());
6317 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
6318 getLocationOfByte(Amt.getStart()),
6319 /*IsStringLocation*/true, R,
6320 FixItHint::CreateRemoval(R));
6324 if (!FS.consumesDataArgument()) {
6325 // FIXME: Technically specifying a precision or field width here
6326 // makes no sense. Worth issuing a warning at some point.
6330 // Consume the argument.
6331 unsigned argIndex = FS.getArgIndex();
6332 if (argIndex < NumDataArgs) {
6333 // The check to see if the argIndex is valid will come later.
6334 // We set the bit here because we may exit early from this
6335 // function if we encounter some other error.
6336 CoveredArgs.set(argIndex);
6339 // Check the length modifier is valid with the given conversion specifier.
6340 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
6341 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6342 diag::warn_format_nonsensical_length);
6343 else if (!FS.hasStandardLengthModifier())
6344 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
6345 else if (!FS.hasStandardLengthConversionCombination())
6346 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6347 diag::warn_format_non_standard_conversion_spec);
6349 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6350 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6352 // The remaining checks depend on the data arguments.
6356 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
6359 // Check that the argument type matches the format specifier.
6360 const Expr *Ex = getDataArg(argIndex);
6364 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
6366 if (!AT.isValid()) {
6370 analyze_format_string::ArgType::MatchKind match =
6371 AT.matchesType(S.Context, Ex->getType());
6372 if (match == analyze_format_string::ArgType::Match) {
6376 ScanfSpecifier fixedFS = FS;
6377 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
6378 S.getLangOpts(), S.Context);
6380 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6381 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6382 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6386 // Get the fix string from the fixed format specifier.
6387 SmallString<128> buf;
6388 llvm::raw_svector_ostream os(buf);
6389 fixedFS.toString(os);
6391 EmitFormatDiagnostic(
6392 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
6393 << Ex->getType() << false << Ex->getSourceRange(),
6395 /*IsStringLocation*/ false,
6396 getSpecifierRange(startSpecifier, specifierLen),
6397 FixItHint::CreateReplacement(
6398 getSpecifierRange(startSpecifier, specifierLen), os.str()));
6400 EmitFormatDiagnostic(S.PDiag(diag)
6401 << AT.getRepresentativeTypeName(S.Context)
6402 << Ex->getType() << false << Ex->getSourceRange(),
6404 /*IsStringLocation*/ false,
6405 getSpecifierRange(startSpecifier, specifierLen));
6411 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
6412 const Expr *OrigFormatExpr,
6413 ArrayRef<const Expr *> Args,
6414 bool HasVAListArg, unsigned format_idx,
6415 unsigned firstDataArg,
6416 Sema::FormatStringType Type,
6417 bool inFunctionCall,
6418 Sema::VariadicCallType CallType,
6419 llvm::SmallBitVector &CheckedVarArgs,
6420 UncoveredArgHandler &UncoveredArg) {
6421 // CHECK: is the format string a wide literal?
6422 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
6423 CheckFormatHandler::EmitFormatDiagnostic(
6424 S, inFunctionCall, Args[format_idx],
6425 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
6426 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
6430 // Str - The format string. NOTE: this is NOT null-terminated!
6431 StringRef StrRef = FExpr->getString();
6432 const char *Str = StrRef.data();
6433 // Account for cases where the string literal is truncated in a declaration.
6434 const ConstantArrayType *T =
6435 S.Context.getAsConstantArrayType(FExpr->getType());
6436 assert(T && "String literal not of constant array type!");
6437 size_t TypeSize = T->getSize().getZExtValue();
6438 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6439 const unsigned numDataArgs = Args.size() - firstDataArg;
6441 // Emit a warning if the string literal is truncated and does not contain an
6442 // embedded null character.
6443 if (TypeSize <= StrRef.size() &&
6444 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
6445 CheckFormatHandler::EmitFormatDiagnostic(
6446 S, inFunctionCall, Args[format_idx],
6447 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
6448 FExpr->getLocStart(),
6449 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
6453 // CHECK: empty format string?
6454 if (StrLen == 0 && numDataArgs > 0) {
6455 CheckFormatHandler::EmitFormatDiagnostic(
6456 S, inFunctionCall, Args[format_idx],
6457 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
6458 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
6462 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
6463 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
6464 Type == Sema::FST_OSTrace) {
6465 CheckPrintfHandler H(
6466 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
6467 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
6468 HasVAListArg, Args, format_idx, inFunctionCall, CallType,
6469 CheckedVarArgs, UncoveredArg);
6471 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
6473 S.Context.getTargetInfo(),
6474 Type == Sema::FST_FreeBSDKPrintf))
6476 } else if (Type == Sema::FST_Scanf) {
6477 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
6478 numDataArgs, Str, HasVAListArg, Args, format_idx,
6479 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
6481 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
6483 S.Context.getTargetInfo()))
6485 } // TODO: handle other formats
6488 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
6489 // Str - The format string. NOTE: this is NOT null-terminated!
6490 StringRef StrRef = FExpr->getString();
6491 const char *Str = StrRef.data();
6492 // Account for cases where the string literal is truncated in a declaration.
6493 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
6494 assert(T && "String literal not of constant array type!");
6495 size_t TypeSize = T->getSize().getZExtValue();
6496 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6497 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
6499 Context.getTargetInfo());
6502 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
6504 // Returns the related absolute value function that is larger, of 0 if one
6506 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
6507 switch (AbsFunction) {
6511 case Builtin::BI__builtin_abs:
6512 return Builtin::BI__builtin_labs;
6513 case Builtin::BI__builtin_labs:
6514 return Builtin::BI__builtin_llabs;
6515 case Builtin::BI__builtin_llabs:
6518 case Builtin::BI__builtin_fabsf:
6519 return Builtin::BI__builtin_fabs;
6520 case Builtin::BI__builtin_fabs:
6521 return Builtin::BI__builtin_fabsl;
6522 case Builtin::BI__builtin_fabsl:
6525 case Builtin::BI__builtin_cabsf:
6526 return Builtin::BI__builtin_cabs;
6527 case Builtin::BI__builtin_cabs:
6528 return Builtin::BI__builtin_cabsl;
6529 case Builtin::BI__builtin_cabsl:
6532 case Builtin::BIabs:
6533 return Builtin::BIlabs;
6534 case Builtin::BIlabs:
6535 return Builtin::BIllabs;
6536 case Builtin::BIllabs:
6539 case Builtin::BIfabsf:
6540 return Builtin::BIfabs;
6541 case Builtin::BIfabs:
6542 return Builtin::BIfabsl;
6543 case Builtin::BIfabsl:
6546 case Builtin::BIcabsf:
6547 return Builtin::BIcabs;
6548 case Builtin::BIcabs:
6549 return Builtin::BIcabsl;
6550 case Builtin::BIcabsl:
6555 // Returns the argument type of the absolute value function.
6556 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
6561 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
6562 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
6563 if (Error != ASTContext::GE_None)
6566 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
6570 if (FT->getNumParams() != 1)
6573 return FT->getParamType(0);
6576 // Returns the best absolute value function, or zero, based on type and
6577 // current absolute value function.
6578 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
6579 unsigned AbsFunctionKind) {
6580 unsigned BestKind = 0;
6581 uint64_t ArgSize = Context.getTypeSize(ArgType);
6582 for (unsigned Kind = AbsFunctionKind; Kind != 0;
6583 Kind = getLargerAbsoluteValueFunction(Kind)) {
6584 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
6585 if (Context.getTypeSize(ParamType) >= ArgSize) {
6588 else if (Context.hasSameType(ParamType, ArgType)) {
6597 enum AbsoluteValueKind {
6603 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
6604 if (T->isIntegralOrEnumerationType())
6606 if (T->isRealFloatingType())
6607 return AVK_Floating;
6608 if (T->isAnyComplexType())
6611 llvm_unreachable("Type not integer, floating, or complex");
6614 // Changes the absolute value function to a different type. Preserves whether
6615 // the function is a builtin.
6616 static unsigned changeAbsFunction(unsigned AbsKind,
6617 AbsoluteValueKind ValueKind) {
6618 switch (ValueKind) {
6623 case Builtin::BI__builtin_fabsf:
6624 case Builtin::BI__builtin_fabs:
6625 case Builtin::BI__builtin_fabsl:
6626 case Builtin::BI__builtin_cabsf:
6627 case Builtin::BI__builtin_cabs:
6628 case Builtin::BI__builtin_cabsl:
6629 return Builtin::BI__builtin_abs;
6630 case Builtin::BIfabsf:
6631 case Builtin::BIfabs:
6632 case Builtin::BIfabsl:
6633 case Builtin::BIcabsf:
6634 case Builtin::BIcabs:
6635 case Builtin::BIcabsl:
6636 return Builtin::BIabs;
6642 case Builtin::BI__builtin_abs:
6643 case Builtin::BI__builtin_labs:
6644 case Builtin::BI__builtin_llabs:
6645 case Builtin::BI__builtin_cabsf:
6646 case Builtin::BI__builtin_cabs:
6647 case Builtin::BI__builtin_cabsl:
6648 return Builtin::BI__builtin_fabsf;
6649 case Builtin::BIabs:
6650 case Builtin::BIlabs:
6651 case Builtin::BIllabs:
6652 case Builtin::BIcabsf:
6653 case Builtin::BIcabs:
6654 case Builtin::BIcabsl:
6655 return Builtin::BIfabsf;
6661 case Builtin::BI__builtin_abs:
6662 case Builtin::BI__builtin_labs:
6663 case Builtin::BI__builtin_llabs:
6664 case Builtin::BI__builtin_fabsf:
6665 case Builtin::BI__builtin_fabs:
6666 case Builtin::BI__builtin_fabsl:
6667 return Builtin::BI__builtin_cabsf;
6668 case Builtin::BIabs:
6669 case Builtin::BIlabs:
6670 case Builtin::BIllabs:
6671 case Builtin::BIfabsf:
6672 case Builtin::BIfabs:
6673 case Builtin::BIfabsl:
6674 return Builtin::BIcabsf;
6677 llvm_unreachable("Unable to convert function");
6680 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
6681 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
6685 switch (FDecl->getBuiltinID()) {
6688 case Builtin::BI__builtin_abs:
6689 case Builtin::BI__builtin_fabs:
6690 case Builtin::BI__builtin_fabsf:
6691 case Builtin::BI__builtin_fabsl:
6692 case Builtin::BI__builtin_labs:
6693 case Builtin::BI__builtin_llabs:
6694 case Builtin::BI__builtin_cabs:
6695 case Builtin::BI__builtin_cabsf:
6696 case Builtin::BI__builtin_cabsl:
6697 case Builtin::BIabs:
6698 case Builtin::BIlabs:
6699 case Builtin::BIllabs:
6700 case Builtin::BIfabs:
6701 case Builtin::BIfabsf:
6702 case Builtin::BIfabsl:
6703 case Builtin::BIcabs:
6704 case Builtin::BIcabsf:
6705 case Builtin::BIcabsl:
6706 return FDecl->getBuiltinID();
6708 llvm_unreachable("Unknown Builtin type");
6711 // If the replacement is valid, emit a note with replacement function.
6712 // Additionally, suggest including the proper header if not already included.
6713 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
6714 unsigned AbsKind, QualType ArgType) {
6715 bool EmitHeaderHint = true;
6716 const char *HeaderName = nullptr;
6717 const char *FunctionName = nullptr;
6718 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
6719 FunctionName = "std::abs";
6720 if (ArgType->isIntegralOrEnumerationType()) {
6721 HeaderName = "cstdlib";
6722 } else if (ArgType->isRealFloatingType()) {
6723 HeaderName = "cmath";
6725 llvm_unreachable("Invalid Type");
6728 // Lookup all std::abs
6729 if (NamespaceDecl *Std = S.getStdNamespace()) {
6730 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
6731 R.suppressDiagnostics();
6732 S.LookupQualifiedName(R, Std);
6734 for (const auto *I : R) {
6735 const FunctionDecl *FDecl = nullptr;
6736 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
6737 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
6739 FDecl = dyn_cast<FunctionDecl>(I);
6744 // Found std::abs(), check that they are the right ones.
6745 if (FDecl->getNumParams() != 1)
6748 // Check that the parameter type can handle the argument.
6749 QualType ParamType = FDecl->getParamDecl(0)->getType();
6750 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
6751 S.Context.getTypeSize(ArgType) <=
6752 S.Context.getTypeSize(ParamType)) {
6753 // Found a function, don't need the header hint.
6754 EmitHeaderHint = false;
6760 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
6761 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
6764 DeclarationName DN(&S.Context.Idents.get(FunctionName));
6765 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
6766 R.suppressDiagnostics();
6767 S.LookupName(R, S.getCurScope());
6769 if (R.isSingleResult()) {
6770 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
6771 if (FD && FD->getBuiltinID() == AbsKind) {
6772 EmitHeaderHint = false;
6776 } else if (!R.empty()) {
6782 S.Diag(Loc, diag::note_replace_abs_function)
6783 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
6788 if (!EmitHeaderHint)
6791 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
6795 template <std::size_t StrLen>
6796 static bool IsStdFunction(const FunctionDecl *FDecl,
6797 const char (&Str)[StrLen]) {
6800 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
6802 if (!FDecl->isInStdNamespace())
6808 // Warn when using the wrong abs() function.
6809 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
6810 const FunctionDecl *FDecl) {
6811 if (Call->getNumArgs() != 1)
6814 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
6815 bool IsStdAbs = IsStdFunction(FDecl, "abs");
6816 if (AbsKind == 0 && !IsStdAbs)
6819 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
6820 QualType ParamType = Call->getArg(0)->getType();
6822 // Unsigned types cannot be negative. Suggest removing the absolute value
6824 if (ArgType->isUnsignedIntegerType()) {
6825 const char *FunctionName =
6826 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
6827 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
6828 Diag(Call->getExprLoc(), diag::note_remove_abs)
6830 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
6834 // Taking the absolute value of a pointer is very suspicious, they probably
6835 // wanted to index into an array, dereference a pointer, call a function, etc.
6836 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
6837 unsigned DiagType = 0;
6838 if (ArgType->isFunctionType())
6840 else if (ArgType->isArrayType())
6843 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
6847 // std::abs has overloads which prevent most of the absolute value problems
6852 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
6853 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
6855 // The argument and parameter are the same kind. Check if they are the right
6857 if (ArgValueKind == ParamValueKind) {
6858 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
6861 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
6862 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
6863 << FDecl << ArgType << ParamType;
6865 if (NewAbsKind == 0)
6868 emitReplacement(*this, Call->getExprLoc(),
6869 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
6873 // ArgValueKind != ParamValueKind
6874 // The wrong type of absolute value function was used. Attempt to find the
6876 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
6877 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
6878 if (NewAbsKind == 0)
6881 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
6882 << FDecl << ParamValueKind << ArgValueKind;
6884 emitReplacement(*this, Call->getExprLoc(),
6885 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
6888 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
6889 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
6890 const FunctionDecl *FDecl) {
6891 if (!Call || !FDecl) return;
6893 // Ignore template specializations and macros.
6894 if (inTemplateInstantiation()) return;
6895 if (Call->getExprLoc().isMacroID()) return;
6897 // Only care about the one template argument, two function parameter std::max
6898 if (Call->getNumArgs() != 2) return;
6899 if (!IsStdFunction(FDecl, "max")) return;
6900 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
6901 if (!ArgList) return;
6902 if (ArgList->size() != 1) return;
6904 // Check that template type argument is unsigned integer.
6905 const auto& TA = ArgList->get(0);
6906 if (TA.getKind() != TemplateArgument::Type) return;
6907 QualType ArgType = TA.getAsType();
6908 if (!ArgType->isUnsignedIntegerType()) return;
6910 // See if either argument is a literal zero.
6911 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
6912 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
6913 if (!MTE) return false;
6914 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
6915 if (!Num) return false;
6916 if (Num->getValue() != 0) return false;
6920 const Expr *FirstArg = Call->getArg(0);
6921 const Expr *SecondArg = Call->getArg(1);
6922 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
6923 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
6925 // Only warn when exactly one argument is zero.
6926 if (IsFirstArgZero == IsSecondArgZero) return;
6928 SourceRange FirstRange = FirstArg->getSourceRange();
6929 SourceRange SecondRange = SecondArg->getSourceRange();
6931 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
6933 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
6934 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
6936 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
6937 SourceRange RemovalRange;
6938 if (IsFirstArgZero) {
6939 RemovalRange = SourceRange(FirstRange.getBegin(),
6940 SecondRange.getBegin().getLocWithOffset(-1));
6942 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
6943 SecondRange.getEnd());
6946 Diag(Call->getExprLoc(), diag::note_remove_max_call)
6947 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
6948 << FixItHint::CreateRemoval(RemovalRange);
6951 //===--- CHECK: Standard memory functions ---------------------------------===//
6953 /// \brief Takes the expression passed to the size_t parameter of functions
6954 /// such as memcmp, strncat, etc and warns if it's a comparison.
6956 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
6957 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
6958 IdentifierInfo *FnName,
6959 SourceLocation FnLoc,
6960 SourceLocation RParenLoc) {
6961 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
6965 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
6966 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
6969 SourceRange SizeRange = Size->getSourceRange();
6970 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
6971 << SizeRange << FnName;
6972 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
6973 << FnName << FixItHint::CreateInsertion(
6974 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
6975 << FixItHint::CreateRemoval(RParenLoc);
6976 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
6977 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
6978 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
6984 /// \brief Determine whether the given type is or contains a dynamic class type
6985 /// (e.g., whether it has a vtable).
6986 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
6987 bool &IsContained) {
6988 // Look through array types while ignoring qualifiers.
6989 const Type *Ty = T->getBaseElementTypeUnsafe();
6990 IsContained = false;
6992 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
6993 RD = RD ? RD->getDefinition() : nullptr;
6994 if (!RD || RD->isInvalidDecl())
6997 if (RD->isDynamicClass())
7000 // Check all the fields. If any bases were dynamic, the class is dynamic.
7001 // It's impossible for a class to transitively contain itself by value, so
7002 // infinite recursion is impossible.
7003 for (auto *FD : RD->fields()) {
7005 if (const CXXRecordDecl *ContainedRD =
7006 getContainedDynamicClass(FD->getType(), SubContained)) {
7015 /// \brief If E is a sizeof expression, returns its argument expression,
7016 /// otherwise returns NULL.
7017 static const Expr *getSizeOfExprArg(const Expr *E) {
7018 if (const UnaryExprOrTypeTraitExpr *SizeOf =
7019 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7020 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
7021 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
7026 /// \brief If E is a sizeof expression, returns its argument type.
7027 static QualType getSizeOfArgType(const Expr *E) {
7028 if (const UnaryExprOrTypeTraitExpr *SizeOf =
7029 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7030 if (SizeOf->getKind() == clang::UETT_SizeOf)
7031 return SizeOf->getTypeOfArgument();
7036 /// \brief Check for dangerous or invalid arguments to memset().
7038 /// This issues warnings on known problematic, dangerous or unspecified
7039 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
7042 /// \param Call The call expression to diagnose.
7043 void Sema::CheckMemaccessArguments(const CallExpr *Call,
7045 IdentifierInfo *FnName) {
7048 // It is possible to have a non-standard definition of memset. Validate
7049 // we have enough arguments, and if not, abort further checking.
7050 unsigned ExpectedNumArgs =
7051 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
7052 if (Call->getNumArgs() < ExpectedNumArgs)
7055 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
7056 BId == Builtin::BIstrndup ? 1 : 2);
7058 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
7059 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
7061 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
7062 Call->getLocStart(), Call->getRParenLoc()))
7065 // We have special checking when the length is a sizeof expression.
7066 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
7067 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
7068 llvm::FoldingSetNodeID SizeOfArgID;
7070 // Although widely used, 'bzero' is not a standard function. Be more strict
7071 // with the argument types before allowing diagnostics and only allow the
7072 // form bzero(ptr, sizeof(...)).
7073 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7074 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
7077 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
7078 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
7079 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
7081 QualType DestTy = Dest->getType();
7083 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
7084 PointeeTy = DestPtrTy->getPointeeType();
7086 // Never warn about void type pointers. This can be used to suppress
7088 if (PointeeTy->isVoidType())
7091 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
7092 // actually comparing the expressions for equality. Because computing the
7093 // expression IDs can be expensive, we only do this if the diagnostic is
7096 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
7097 SizeOfArg->getExprLoc())) {
7098 // We only compute IDs for expressions if the warning is enabled, and
7099 // cache the sizeof arg's ID.
7100 if (SizeOfArgID == llvm::FoldingSetNodeID())
7101 SizeOfArg->Profile(SizeOfArgID, Context, true);
7102 llvm::FoldingSetNodeID DestID;
7103 Dest->Profile(DestID, Context, true);
7104 if (DestID == SizeOfArgID) {
7105 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
7106 // over sizeof(src) as well.
7107 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
7108 StringRef ReadableName = FnName->getName();
7110 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
7111 if (UnaryOp->getOpcode() == UO_AddrOf)
7112 ActionIdx = 1; // If its an address-of operator, just remove it.
7113 if (!PointeeTy->isIncompleteType() &&
7114 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
7115 ActionIdx = 2; // If the pointee's size is sizeof(char),
7116 // suggest an explicit length.
7118 // If the function is defined as a builtin macro, do not show macro
7120 SourceLocation SL = SizeOfArg->getExprLoc();
7121 SourceRange DSR = Dest->getSourceRange();
7122 SourceRange SSR = SizeOfArg->getSourceRange();
7123 SourceManager &SM = getSourceManager();
7125 if (SM.isMacroArgExpansion(SL)) {
7126 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
7127 SL = SM.getSpellingLoc(SL);
7128 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
7129 SM.getSpellingLoc(DSR.getEnd()));
7130 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
7131 SM.getSpellingLoc(SSR.getEnd()));
7134 DiagRuntimeBehavior(SL, SizeOfArg,
7135 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
7141 DiagRuntimeBehavior(SL, SizeOfArg,
7142 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
7150 // Also check for cases where the sizeof argument is the exact same
7151 // type as the memory argument, and where it points to a user-defined
7153 if (SizeOfArgTy != QualType()) {
7154 if (PointeeTy->isRecordType() &&
7155 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
7156 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
7157 PDiag(diag::warn_sizeof_pointer_type_memaccess)
7158 << FnName << SizeOfArgTy << ArgIdx
7159 << PointeeTy << Dest->getSourceRange()
7160 << LenExpr->getSourceRange());
7164 } else if (DestTy->isArrayType()) {
7168 if (PointeeTy == QualType())
7171 // Always complain about dynamic classes.
7173 if (const CXXRecordDecl *ContainedRD =
7174 getContainedDynamicClass(PointeeTy, IsContained)) {
7176 unsigned OperationType = 0;
7177 // "overwritten" if we're warning about the destination for any call
7178 // but memcmp; otherwise a verb appropriate to the call.
7179 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
7180 if (BId == Builtin::BImemcpy)
7182 else if(BId == Builtin::BImemmove)
7184 else if (BId == Builtin::BImemcmp)
7188 DiagRuntimeBehavior(
7189 Dest->getExprLoc(), Dest,
7190 PDiag(diag::warn_dyn_class_memaccess)
7191 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
7192 << FnName << IsContained << ContainedRD << OperationType
7193 << Call->getCallee()->getSourceRange());
7194 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
7195 BId != Builtin::BImemset)
7196 DiagRuntimeBehavior(
7197 Dest->getExprLoc(), Dest,
7198 PDiag(diag::warn_arc_object_memaccess)
7199 << ArgIdx << FnName << PointeeTy
7200 << Call->getCallee()->getSourceRange());
7204 DiagRuntimeBehavior(
7205 Dest->getExprLoc(), Dest,
7206 PDiag(diag::note_bad_memaccess_silence)
7207 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
7212 // A little helper routine: ignore addition and subtraction of integer literals.
7213 // This intentionally does not ignore all integer constant expressions because
7214 // we don't want to remove sizeof().
7215 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
7216 Ex = Ex->IgnoreParenCasts();
7219 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
7220 if (!BO || !BO->isAdditiveOp())
7223 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
7224 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
7226 if (isa<IntegerLiteral>(RHS))
7228 else if (isa<IntegerLiteral>(LHS))
7237 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
7238 ASTContext &Context) {
7239 // Only handle constant-sized or VLAs, but not flexible members.
7240 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
7241 // Only issue the FIXIT for arrays of size > 1.
7242 if (CAT->getSize().getSExtValue() <= 1)
7244 } else if (!Ty->isVariableArrayType()) {
7250 // Warn if the user has made the 'size' argument to strlcpy or strlcat
7251 // be the size of the source, instead of the destination.
7252 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
7253 IdentifierInfo *FnName) {
7255 // Don't crash if the user has the wrong number of arguments
7256 unsigned NumArgs = Call->getNumArgs();
7257 if ((NumArgs != 3) && (NumArgs != 4))
7260 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
7261 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
7262 const Expr *CompareWithSrc = nullptr;
7264 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
7265 Call->getLocStart(), Call->getRParenLoc()))
7268 // Look for 'strlcpy(dst, x, sizeof(x))'
7269 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
7270 CompareWithSrc = Ex;
7272 // Look for 'strlcpy(dst, x, strlen(x))'
7273 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
7274 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
7275 SizeCall->getNumArgs() == 1)
7276 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
7280 if (!CompareWithSrc)
7283 // Determine if the argument to sizeof/strlen is equal to the source
7284 // argument. In principle there's all kinds of things you could do
7285 // here, for instance creating an == expression and evaluating it with
7286 // EvaluateAsBooleanCondition, but this uses a more direct technique:
7287 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
7291 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
7292 if (!CompareWithSrcDRE ||
7293 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
7296 const Expr *OriginalSizeArg = Call->getArg(2);
7297 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
7298 << OriginalSizeArg->getSourceRange() << FnName;
7300 // Output a FIXIT hint if the destination is an array (rather than a
7301 // pointer to an array). This could be enhanced to handle some
7302 // pointers if we know the actual size, like if DstArg is 'array+2'
7303 // we could say 'sizeof(array)-2'.
7304 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
7305 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
7308 SmallString<128> sizeString;
7309 llvm::raw_svector_ostream OS(sizeString);
7311 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7314 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
7315 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
7319 /// Check if two expressions refer to the same declaration.
7320 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
7321 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
7322 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
7323 return D1->getDecl() == D2->getDecl();
7327 static const Expr *getStrlenExprArg(const Expr *E) {
7328 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7329 const FunctionDecl *FD = CE->getDirectCallee();
7330 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
7332 return CE->getArg(0)->IgnoreParenCasts();
7337 // Warn on anti-patterns as the 'size' argument to strncat.
7338 // The correct size argument should look like following:
7339 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
7340 void Sema::CheckStrncatArguments(const CallExpr *CE,
7341 IdentifierInfo *FnName) {
7342 // Don't crash if the user has the wrong number of arguments.
7343 if (CE->getNumArgs() < 3)
7345 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
7346 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
7347 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
7349 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
7350 CE->getRParenLoc()))
7353 // Identify common expressions, which are wrongly used as the size argument
7354 // to strncat and may lead to buffer overflows.
7355 unsigned PatternType = 0;
7356 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
7358 if (referToTheSameDecl(SizeOfArg, DstArg))
7361 else if (referToTheSameDecl(SizeOfArg, SrcArg))
7363 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
7364 if (BE->getOpcode() == BO_Sub) {
7365 const Expr *L = BE->getLHS()->IgnoreParenCasts();
7366 const Expr *R = BE->getRHS()->IgnoreParenCasts();
7367 // - sizeof(dst) - strlen(dst)
7368 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
7369 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
7371 // - sizeof(src) - (anything)
7372 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
7377 if (PatternType == 0)
7380 // Generate the diagnostic.
7381 SourceLocation SL = LenArg->getLocStart();
7382 SourceRange SR = LenArg->getSourceRange();
7383 SourceManager &SM = getSourceManager();
7385 // If the function is defined as a builtin macro, do not show macro expansion.
7386 if (SM.isMacroArgExpansion(SL)) {
7387 SL = SM.getSpellingLoc(SL);
7388 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
7389 SM.getSpellingLoc(SR.getEnd()));
7392 // Check if the destination is an array (rather than a pointer to an array).
7393 QualType DstTy = DstArg->getType();
7394 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
7396 if (!isKnownSizeArray) {
7397 if (PatternType == 1)
7398 Diag(SL, diag::warn_strncat_wrong_size) << SR;
7400 Diag(SL, diag::warn_strncat_src_size) << SR;
7404 if (PatternType == 1)
7405 Diag(SL, diag::warn_strncat_large_size) << SR;
7407 Diag(SL, diag::warn_strncat_src_size) << SR;
7409 SmallString<128> sizeString;
7410 llvm::raw_svector_ostream OS(sizeString);
7412 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7415 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7418 Diag(SL, diag::note_strncat_wrong_size)
7419 << FixItHint::CreateReplacement(SR, OS.str());
7422 //===--- CHECK: Return Address of Stack Variable --------------------------===//
7424 static const Expr *EvalVal(const Expr *E,
7425 SmallVectorImpl<const DeclRefExpr *> &refVars,
7426 const Decl *ParentDecl);
7427 static const Expr *EvalAddr(const Expr *E,
7428 SmallVectorImpl<const DeclRefExpr *> &refVars,
7429 const Decl *ParentDecl);
7431 /// CheckReturnStackAddr - Check if a return statement returns the address
7432 /// of a stack variable.
7434 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
7435 SourceLocation ReturnLoc) {
7437 const Expr *stackE = nullptr;
7438 SmallVector<const DeclRefExpr *, 8> refVars;
7440 // Perform checking for returned stack addresses, local blocks,
7441 // label addresses or references to temporaries.
7442 if (lhsType->isPointerType() ||
7443 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
7444 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
7445 } else if (lhsType->isReferenceType()) {
7446 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
7450 return; // Nothing suspicious was found.
7452 // Parameters are initialized in the calling scope, so taking the address
7453 // of a parameter reference doesn't need a warning.
7454 for (auto *DRE : refVars)
7455 if (isa<ParmVarDecl>(DRE->getDecl()))
7458 SourceLocation diagLoc;
7459 SourceRange diagRange;
7460 if (refVars.empty()) {
7461 diagLoc = stackE->getLocStart();
7462 diagRange = stackE->getSourceRange();
7464 // We followed through a reference variable. 'stackE' contains the
7465 // problematic expression but we will warn at the return statement pointing
7466 // at the reference variable. We will later display the "trail" of
7467 // reference variables using notes.
7468 diagLoc = refVars[0]->getLocStart();
7469 diagRange = refVars[0]->getSourceRange();
7472 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
7473 // address of local var
7474 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
7475 << DR->getDecl()->getDeclName() << diagRange;
7476 } else if (isa<BlockExpr>(stackE)) { // local block.
7477 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
7478 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
7479 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
7480 } else { // local temporary.
7481 // If there is an LValue->RValue conversion, then the value of the
7482 // reference type is used, not the reference.
7483 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
7484 if (ICE->getCastKind() == CK_LValueToRValue) {
7488 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
7489 << lhsType->isReferenceType() << diagRange;
7492 // Display the "trail" of reference variables that we followed until we
7493 // found the problematic expression using notes.
7494 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
7495 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
7496 // If this var binds to another reference var, show the range of the next
7497 // var, otherwise the var binds to the problematic expression, in which case
7498 // show the range of the expression.
7499 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
7500 : stackE->getSourceRange();
7501 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
7502 << VD->getDeclName() << range;
7506 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
7507 /// check if the expression in a return statement evaluates to an address
7508 /// to a location on the stack, a local block, an address of a label, or a
7509 /// reference to local temporary. The recursion is used to traverse the
7510 /// AST of the return expression, with recursion backtracking when we
7511 /// encounter a subexpression that (1) clearly does not lead to one of the
7512 /// above problematic expressions (2) is something we cannot determine leads to
7513 /// a problematic expression based on such local checking.
7515 /// Both EvalAddr and EvalVal follow through reference variables to evaluate
7516 /// the expression that they point to. Such variables are added to the
7517 /// 'refVars' vector so that we know what the reference variable "trail" was.
7519 /// EvalAddr processes expressions that are pointers that are used as
7520 /// references (and not L-values). EvalVal handles all other values.
7521 /// At the base case of the recursion is a check for the above problematic
7524 /// This implementation handles:
7526 /// * pointer-to-pointer casts
7527 /// * implicit conversions from array references to pointers
7528 /// * taking the address of fields
7529 /// * arbitrary interplay between "&" and "*" operators
7530 /// * pointer arithmetic from an address of a stack variable
7531 /// * taking the address of an array element where the array is on the stack
7532 static const Expr *EvalAddr(const Expr *E,
7533 SmallVectorImpl<const DeclRefExpr *> &refVars,
7534 const Decl *ParentDecl) {
7535 if (E->isTypeDependent())
7538 // We should only be called for evaluating pointer expressions.
7539 assert((E->getType()->isAnyPointerType() ||
7540 E->getType()->isBlockPointerType() ||
7541 E->getType()->isObjCQualifiedIdType()) &&
7542 "EvalAddr only works on pointers");
7544 E = E->IgnoreParens();
7546 // Our "symbolic interpreter" is just a dispatch off the currently
7547 // viewed AST node. We then recursively traverse the AST by calling
7548 // EvalAddr and EvalVal appropriately.
7549 switch (E->getStmtClass()) {
7550 case Stmt::DeclRefExprClass: {
7551 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7553 // If we leave the immediate function, the lifetime isn't about to end.
7554 if (DR->refersToEnclosingVariableOrCapture())
7557 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
7558 // If this is a reference variable, follow through to the expression that
7560 if (V->hasLocalStorage() &&
7561 V->getType()->isReferenceType() && V->hasInit()) {
7562 // Add the reference variable to the "trail".
7563 refVars.push_back(DR);
7564 return EvalAddr(V->getInit(), refVars, ParentDecl);
7570 case Stmt::UnaryOperatorClass: {
7571 // The only unary operator that make sense to handle here
7572 // is AddrOf. All others don't make sense as pointers.
7573 const UnaryOperator *U = cast<UnaryOperator>(E);
7575 if (U->getOpcode() == UO_AddrOf)
7576 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
7580 case Stmt::BinaryOperatorClass: {
7581 // Handle pointer arithmetic. All other binary operators are not valid
7583 const BinaryOperator *B = cast<BinaryOperator>(E);
7584 BinaryOperatorKind op = B->getOpcode();
7586 if (op != BO_Add && op != BO_Sub)
7589 const Expr *Base = B->getLHS();
7591 // Determine which argument is the real pointer base. It could be
7592 // the RHS argument instead of the LHS.
7593 if (!Base->getType()->isPointerType())
7596 assert(Base->getType()->isPointerType());
7597 return EvalAddr(Base, refVars, ParentDecl);
7600 // For conditional operators we need to see if either the LHS or RHS are
7601 // valid DeclRefExpr*s. If one of them is valid, we return it.
7602 case Stmt::ConditionalOperatorClass: {
7603 const ConditionalOperator *C = cast<ConditionalOperator>(E);
7605 // Handle the GNU extension for missing LHS.
7606 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
7607 if (const Expr *LHSExpr = C->getLHS()) {
7608 // In C++, we can have a throw-expression, which has 'void' type.
7609 if (!LHSExpr->getType()->isVoidType())
7610 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
7614 // In C++, we can have a throw-expression, which has 'void' type.
7615 if (C->getRHS()->getType()->isVoidType())
7618 return EvalAddr(C->getRHS(), refVars, ParentDecl);
7621 case Stmt::BlockExprClass:
7622 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
7623 return E; // local block.
7626 case Stmt::AddrLabelExprClass:
7627 return E; // address of label.
7629 case Stmt::ExprWithCleanupsClass:
7630 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7633 // For casts, we need to handle conversions from arrays to
7634 // pointer values, and pointer-to-pointer conversions.
7635 case Stmt::ImplicitCastExprClass:
7636 case Stmt::CStyleCastExprClass:
7637 case Stmt::CXXFunctionalCastExprClass:
7638 case Stmt::ObjCBridgedCastExprClass:
7639 case Stmt::CXXStaticCastExprClass:
7640 case Stmt::CXXDynamicCastExprClass:
7641 case Stmt::CXXConstCastExprClass:
7642 case Stmt::CXXReinterpretCastExprClass: {
7643 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
7644 switch (cast<CastExpr>(E)->getCastKind()) {
7645 case CK_LValueToRValue:
7647 case CK_BaseToDerived:
7648 case CK_DerivedToBase:
7649 case CK_UncheckedDerivedToBase:
7651 case CK_CPointerToObjCPointerCast:
7652 case CK_BlockPointerToObjCPointerCast:
7653 case CK_AnyPointerToBlockPointerCast:
7654 return EvalAddr(SubExpr, refVars, ParentDecl);
7656 case CK_ArrayToPointerDecay:
7657 return EvalVal(SubExpr, refVars, ParentDecl);
7660 if (SubExpr->getType()->isAnyPointerType() ||
7661 SubExpr->getType()->isBlockPointerType() ||
7662 SubExpr->getType()->isObjCQualifiedIdType())
7663 return EvalAddr(SubExpr, refVars, ParentDecl);
7672 case Stmt::MaterializeTemporaryExprClass:
7673 if (const Expr *Result =
7674 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7675 refVars, ParentDecl))
7679 // Everything else: we simply don't reason about them.
7685 /// EvalVal - This function is complements EvalAddr in the mutual recursion.
7686 /// See the comments for EvalAddr for more details.
7687 static const Expr *EvalVal(const Expr *E,
7688 SmallVectorImpl<const DeclRefExpr *> &refVars,
7689 const Decl *ParentDecl) {
7691 // We should only be called for evaluating non-pointer expressions, or
7692 // expressions with a pointer type that are not used as references but
7694 // are l-values (e.g., DeclRefExpr with a pointer type).
7696 // Our "symbolic interpreter" is just a dispatch off the currently
7697 // viewed AST node. We then recursively traverse the AST by calling
7698 // EvalAddr and EvalVal appropriately.
7700 E = E->IgnoreParens();
7701 switch (E->getStmtClass()) {
7702 case Stmt::ImplicitCastExprClass: {
7703 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
7704 if (IE->getValueKind() == VK_LValue) {
7705 E = IE->getSubExpr();
7711 case Stmt::ExprWithCleanupsClass:
7712 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7715 case Stmt::DeclRefExprClass: {
7716 // When we hit a DeclRefExpr we are looking at code that refers to a
7717 // variable's name. If it's not a reference variable we check if it has
7718 // local storage within the function, and if so, return the expression.
7719 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7721 // If we leave the immediate function, the lifetime isn't about to end.
7722 if (DR->refersToEnclosingVariableOrCapture())
7725 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
7726 // Check if it refers to itself, e.g. "int& i = i;".
7727 if (V == ParentDecl)
7730 if (V->hasLocalStorage()) {
7731 if (!V->getType()->isReferenceType())
7734 // Reference variable, follow through to the expression that
7737 // Add the reference variable to the "trail".
7738 refVars.push_back(DR);
7739 return EvalVal(V->getInit(), refVars, V);
7747 case Stmt::UnaryOperatorClass: {
7748 // The only unary operator that make sense to handle here
7749 // is Deref. All others don't resolve to a "name." This includes
7750 // handling all sorts of rvalues passed to a unary operator.
7751 const UnaryOperator *U = cast<UnaryOperator>(E);
7753 if (U->getOpcode() == UO_Deref)
7754 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
7759 case Stmt::ArraySubscriptExprClass: {
7760 // Array subscripts are potential references to data on the stack. We
7761 // retrieve the DeclRefExpr* for the array variable if it indeed
7762 // has local storage.
7763 const auto *ASE = cast<ArraySubscriptExpr>(E);
7764 if (ASE->isTypeDependent())
7766 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
7769 case Stmt::OMPArraySectionExprClass: {
7770 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
7774 case Stmt::ConditionalOperatorClass: {
7775 // For conditional operators we need to see if either the LHS or RHS are
7776 // non-NULL Expr's. If one is non-NULL, we return it.
7777 const ConditionalOperator *C = cast<ConditionalOperator>(E);
7779 // Handle the GNU extension for missing LHS.
7780 if (const Expr *LHSExpr = C->getLHS()) {
7781 // In C++, we can have a throw-expression, which has 'void' type.
7782 if (!LHSExpr->getType()->isVoidType())
7783 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
7787 // In C++, we can have a throw-expression, which has 'void' type.
7788 if (C->getRHS()->getType()->isVoidType())
7791 return EvalVal(C->getRHS(), refVars, ParentDecl);
7794 // Accesses to members are potential references to data on the stack.
7795 case Stmt::MemberExprClass: {
7796 const MemberExpr *M = cast<MemberExpr>(E);
7798 // Check for indirect access. We only want direct field accesses.
7802 // Check whether the member type is itself a reference, in which case
7803 // we're not going to refer to the member, but to what the member refers
7805 if (M->getMemberDecl()->getType()->isReferenceType())
7808 return EvalVal(M->getBase(), refVars, ParentDecl);
7811 case Stmt::MaterializeTemporaryExprClass:
7812 if (const Expr *Result =
7813 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7814 refVars, ParentDecl))
7819 // Check that we don't return or take the address of a reference to a
7820 // temporary. This is only useful in C++.
7821 if (!E->isTypeDependent() && E->isRValue())
7824 // Everything else: we simply don't reason about them.
7831 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
7832 SourceLocation ReturnLoc,
7834 const AttrVec *Attrs,
7835 const FunctionDecl *FD) {
7836 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
7838 // Check if the return value is null but should not be.
7839 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
7840 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
7841 CheckNonNullExpr(*this, RetValExp))
7842 Diag(ReturnLoc, diag::warn_null_ret)
7843 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
7845 // C++11 [basic.stc.dynamic.allocation]p4:
7846 // If an allocation function declared with a non-throwing
7847 // exception-specification fails to allocate storage, it shall return
7848 // a null pointer. Any other allocation function that fails to allocate
7849 // storage shall indicate failure only by throwing an exception [...]
7851 OverloadedOperatorKind Op = FD->getOverloadedOperator();
7852 if (Op == OO_New || Op == OO_Array_New) {
7853 const FunctionProtoType *Proto
7854 = FD->getType()->castAs<FunctionProtoType>();
7855 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
7856 CheckNonNullExpr(*this, RetValExp))
7857 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
7858 << FD << getLangOpts().CPlusPlus11;
7863 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
7865 /// Check for comparisons of floating point operands using != and ==.
7866 /// Issue a warning if these are no self-comparisons, as they are not likely
7867 /// to do what the programmer intended.
7868 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
7869 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
7870 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
7872 // Special case: check for x == x (which is OK).
7873 // Do not emit warnings for such cases.
7874 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
7875 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
7876 if (DRL->getDecl() == DRR->getDecl())
7879 // Special case: check for comparisons against literals that can be exactly
7880 // represented by APFloat. In such cases, do not emit a warning. This
7881 // is a heuristic: often comparison against such literals are used to
7882 // detect if a value in a variable has not changed. This clearly can
7883 // lead to false negatives.
7884 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
7888 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
7892 // Check for comparisons with builtin types.
7893 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
7894 if (CL->getBuiltinCallee())
7897 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
7898 if (CR->getBuiltinCallee())
7901 // Emit the diagnostic.
7902 Diag(Loc, diag::warn_floatingpoint_eq)
7903 << LHS->getSourceRange() << RHS->getSourceRange();
7906 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
7907 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
7911 /// Structure recording the 'active' range of an integer-valued
7914 /// The number of bits active in the int.
7917 /// True if the int is known not to have negative values.
7920 IntRange(unsigned Width, bool NonNegative)
7921 : Width(Width), NonNegative(NonNegative)
7924 /// Returns the range of the bool type.
7925 static IntRange forBoolType() {
7926 return IntRange(1, true);
7929 /// Returns the range of an opaque value of the given integral type.
7930 static IntRange forValueOfType(ASTContext &C, QualType T) {
7931 return forValueOfCanonicalType(C,
7932 T->getCanonicalTypeInternal().getTypePtr());
7935 /// Returns the range of an opaque value of a canonical integral type.
7936 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
7937 assert(T->isCanonicalUnqualified());
7939 if (const VectorType *VT = dyn_cast<VectorType>(T))
7940 T = VT->getElementType().getTypePtr();
7941 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
7942 T = CT->getElementType().getTypePtr();
7943 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7944 T = AT->getValueType().getTypePtr();
7946 // For enum types, use the known bit width of the enumerators.
7947 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
7948 EnumDecl *Enum = ET->getDecl();
7949 if (!Enum->isCompleteDefinition())
7950 return IntRange(C.getIntWidth(QualType(T, 0)), false);
7952 unsigned NumPositive = Enum->getNumPositiveBits();
7953 unsigned NumNegative = Enum->getNumNegativeBits();
7955 if (NumNegative == 0)
7956 return IntRange(NumPositive, true/*NonNegative*/);
7958 return IntRange(std::max(NumPositive + 1, NumNegative),
7959 false/*NonNegative*/);
7962 const BuiltinType *BT = cast<BuiltinType>(T);
7963 assert(BT->isInteger());
7965 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7968 /// Returns the "target" range of a canonical integral type, i.e.
7969 /// the range of values expressible in the type.
7971 /// This matches forValueOfCanonicalType except that enums have the
7972 /// full range of their type, not the range of their enumerators.
7973 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
7974 assert(T->isCanonicalUnqualified());
7976 if (const VectorType *VT = dyn_cast<VectorType>(T))
7977 T = VT->getElementType().getTypePtr();
7978 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
7979 T = CT->getElementType().getTypePtr();
7980 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7981 T = AT->getValueType().getTypePtr();
7982 if (const EnumType *ET = dyn_cast<EnumType>(T))
7983 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
7985 const BuiltinType *BT = cast<BuiltinType>(T);
7986 assert(BT->isInteger());
7988 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7991 /// Returns the supremum of two ranges: i.e. their conservative merge.
7992 static IntRange join(IntRange L, IntRange R) {
7993 return IntRange(std::max(L.Width, R.Width),
7994 L.NonNegative && R.NonNegative);
7997 /// Returns the infinum of two ranges: i.e. their aggressive merge.
7998 static IntRange meet(IntRange L, IntRange R) {
7999 return IntRange(std::min(L.Width, R.Width),
8000 L.NonNegative || R.NonNegative);
8004 IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
8005 if (value.isSigned() && value.isNegative())
8006 return IntRange(value.getMinSignedBits(), false);
8008 if (value.getBitWidth() > MaxWidth)
8009 value = value.trunc(MaxWidth);
8011 // isNonNegative() just checks the sign bit without considering
8013 return IntRange(value.getActiveBits(), true);
8016 IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
8017 unsigned MaxWidth) {
8019 return GetValueRange(C, result.getInt(), MaxWidth);
8021 if (result.isVector()) {
8022 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
8023 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
8024 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
8025 R = IntRange::join(R, El);
8030 if (result.isComplexInt()) {
8031 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
8032 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
8033 return IntRange::join(R, I);
8036 // This can happen with lossless casts to intptr_t of "based" lvalues.
8037 // Assume it might use arbitrary bits.
8038 // FIXME: The only reason we need to pass the type in here is to get
8039 // the sign right on this one case. It would be nice if APValue
8041 assert(result.isLValue() || result.isAddrLabelDiff());
8042 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
8045 QualType GetExprType(const Expr *E) {
8046 QualType Ty = E->getType();
8047 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
8048 Ty = AtomicRHS->getValueType();
8052 /// Pseudo-evaluate the given integer expression, estimating the
8053 /// range of values it might take.
8055 /// \param MaxWidth - the width to which the value will be truncated
8056 IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
8057 E = E->IgnoreParens();
8059 // Try a full evaluation first.
8060 Expr::EvalResult result;
8061 if (E->EvaluateAsRValue(result, C))
8062 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
8064 // I think we only want to look through implicit casts here; if the
8065 // user has an explicit widening cast, we should treat the value as
8066 // being of the new, wider type.
8067 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
8068 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
8069 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
8071 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
8073 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
8074 CE->getCastKind() == CK_BooleanToSignedIntegral;
8076 // Assume that non-integer casts can span the full range of the type.
8078 return OutputTypeRange;
8081 = GetExprRange(C, CE->getSubExpr(),
8082 std::min(MaxWidth, OutputTypeRange.Width));
8084 // Bail out if the subexpr's range is as wide as the cast type.
8085 if (SubRange.Width >= OutputTypeRange.Width)
8086 return OutputTypeRange;
8088 // Otherwise, we take the smaller width, and we're non-negative if
8089 // either the output type or the subexpr is.
8090 return IntRange(SubRange.Width,
8091 SubRange.NonNegative || OutputTypeRange.NonNegative);
8094 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
8095 // If we can fold the condition, just take that operand.
8097 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
8098 return GetExprRange(C, CondResult ? CO->getTrueExpr()
8099 : CO->getFalseExpr(),
8102 // Otherwise, conservatively merge.
8103 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
8104 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
8105 return IntRange::join(L, R);
8108 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
8109 switch (BO->getOpcode()) {
8111 // Boolean-valued operations are single-bit and positive.
8120 return IntRange::forBoolType();
8122 // The type of the assignments is the type of the LHS, so the RHS
8123 // is not necessarily the same type.
8132 return IntRange::forValueOfType(C, GetExprType(E));
8134 // Simple assignments just pass through the RHS, which will have
8135 // been coerced to the LHS type.
8138 return GetExprRange(C, BO->getRHS(), MaxWidth);
8140 // Operations with opaque sources are black-listed.
8143 return IntRange::forValueOfType(C, GetExprType(E));
8145 // Bitwise-and uses the *infinum* of the two source ranges.
8148 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
8149 GetExprRange(C, BO->getRHS(), MaxWidth));
8151 // Left shift gets black-listed based on a judgement call.
8153 // ...except that we want to treat '1 << (blah)' as logically
8154 // positive. It's an important idiom.
8155 if (IntegerLiteral *I
8156 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
8157 if (I->getValue() == 1) {
8158 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
8159 return IntRange(R.Width, /*NonNegative*/ true);
8165 return IntRange::forValueOfType(C, GetExprType(E));
8167 // Right shift by a constant can narrow its left argument.
8169 case BO_ShrAssign: {
8170 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8172 // If the shift amount is a positive constant, drop the width by
8175 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
8176 shift.isNonNegative()) {
8177 unsigned zext = shift.getZExtValue();
8178 if (zext >= L.Width)
8179 L.Width = (L.NonNegative ? 0 : 1);
8187 // Comma acts as its right operand.
8189 return GetExprRange(C, BO->getRHS(), MaxWidth);
8191 // Black-list pointer subtractions.
8193 if (BO->getLHS()->getType()->isPointerType())
8194 return IntRange::forValueOfType(C, GetExprType(E));
8197 // The width of a division result is mostly determined by the size
8200 // Don't 'pre-truncate' the operands.
8201 unsigned opWidth = C.getIntWidth(GetExprType(E));
8202 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8204 // If the divisor is constant, use that.
8205 llvm::APSInt divisor;
8206 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
8207 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
8208 if (log2 >= L.Width)
8209 L.Width = (L.NonNegative ? 0 : 1);
8211 L.Width = std::min(L.Width - log2, MaxWidth);
8215 // Otherwise, just use the LHS's width.
8216 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8217 return IntRange(L.Width, L.NonNegative && R.NonNegative);
8220 // The result of a remainder can't be larger than the result of
8223 // Don't 'pre-truncate' the operands.
8224 unsigned opWidth = C.getIntWidth(GetExprType(E));
8225 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8226 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8228 IntRange meet = IntRange::meet(L, R);
8229 meet.Width = std::min(meet.Width, MaxWidth);
8233 // The default behavior is okay for these.
8241 // The default case is to treat the operation as if it were closed
8242 // on the narrowest type that encompasses both operands.
8243 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8244 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
8245 return IntRange::join(L, R);
8248 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
8249 switch (UO->getOpcode()) {
8250 // Boolean-valued operations are white-listed.
8252 return IntRange::forBoolType();
8254 // Operations with opaque sources are black-listed.
8256 case UO_AddrOf: // should be impossible
8257 return IntRange::forValueOfType(C, GetExprType(E));
8260 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
8264 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
8265 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
8267 if (const auto *BitField = E->getSourceBitField())
8268 return IntRange(BitField->getBitWidthValue(C),
8269 BitField->getType()->isUnsignedIntegerOrEnumerationType());
8271 return IntRange::forValueOfType(C, GetExprType(E));
8274 IntRange GetExprRange(ASTContext &C, const Expr *E) {
8275 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
8278 /// Checks whether the given value, which currently has the given
8279 /// source semantics, has the same value when coerced through the
8280 /// target semantics.
8281 bool IsSameFloatAfterCast(const llvm::APFloat &value,
8282 const llvm::fltSemantics &Src,
8283 const llvm::fltSemantics &Tgt) {
8284 llvm::APFloat truncated = value;
8287 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
8288 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
8290 return truncated.bitwiseIsEqual(value);
8293 /// Checks whether the given value, which currently has the given
8294 /// source semantics, has the same value when coerced through the
8295 /// target semantics.
8297 /// The value might be a vector of floats (or a complex number).
8298 bool IsSameFloatAfterCast(const APValue &value,
8299 const llvm::fltSemantics &Src,
8300 const llvm::fltSemantics &Tgt) {
8301 if (value.isFloat())
8302 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
8304 if (value.isVector()) {
8305 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
8306 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
8311 assert(value.isComplexFloat());
8312 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
8313 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
8316 void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
8318 bool IsZero(Sema &S, Expr *E) {
8319 // Suppress cases where we are comparing against an enum constant.
8320 if (const DeclRefExpr *DR =
8321 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
8322 if (isa<EnumConstantDecl>(DR->getDecl()))
8325 // Suppress cases where the '0' value is expanded from a macro.
8326 if (E->getLocStart().isMacroID())
8330 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
8333 bool HasEnumType(Expr *E) {
8334 // Strip off implicit integral promotions.
8335 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8336 if (ICE->getCastKind() != CK_IntegralCast &&
8337 ICE->getCastKind() != CK_NoOp)
8339 E = ICE->getSubExpr();
8342 return E->getType()->isEnumeralType();
8345 void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
8346 // Disable warning in template instantiations.
8347 if (S.inTemplateInstantiation())
8350 BinaryOperatorKind op = E->getOpcode();
8351 if (E->isValueDependent())
8354 if (op == BO_LT && IsZero(S, E->getRHS())) {
8355 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
8356 << "< 0" << "false" << HasEnumType(E->getLHS())
8357 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8358 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
8359 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
8360 << ">= 0" << "true" << HasEnumType(E->getLHS())
8361 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8362 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
8363 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
8364 << "0 >" << "false" << HasEnumType(E->getRHS())
8365 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8366 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
8367 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
8368 << "0 <=" << "true" << HasEnumType(E->getRHS())
8369 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8373 void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant,
8374 Expr *Other, const llvm::APSInt &Value,
8376 // Disable warning in template instantiations.
8377 if (S.inTemplateInstantiation())
8380 // TODO: Investigate using GetExprRange() to get tighter bounds
8381 // on the bit ranges.
8382 QualType OtherT = Other->getType();
8383 if (const auto *AT = OtherT->getAs<AtomicType>())
8384 OtherT = AT->getValueType();
8385 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
8386 unsigned OtherWidth = OtherRange.Width;
8388 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
8390 // 0 values are handled later by CheckTrivialUnsignedComparison().
8391 if ((Value == 0) && (!OtherIsBooleanType))
8394 BinaryOperatorKind op = E->getOpcode();
8397 // Used for diagnostic printout.
8399 LiteralConstant = 0,
8402 } LiteralOrBoolConstant = LiteralConstant;
8404 if (!OtherIsBooleanType) {
8405 QualType ConstantT = Constant->getType();
8406 QualType CommonT = E->getLHS()->getType();
8408 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
8410 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
8411 "comparison with non-integer type");
8413 bool ConstantSigned = ConstantT->isSignedIntegerType();
8414 bool CommonSigned = CommonT->isSignedIntegerType();
8416 bool EqualityOnly = false;
8419 // The common type is signed, therefore no signed to unsigned conversion.
8420 if (!OtherRange.NonNegative) {
8421 // Check that the constant is representable in type OtherT.
8422 if (ConstantSigned) {
8423 if (OtherWidth >= Value.getMinSignedBits())
8425 } else { // !ConstantSigned
8426 if (OtherWidth >= Value.getActiveBits() + 1)
8429 } else { // !OtherSigned
8430 // Check that the constant is representable in type OtherT.
8431 // Negative values are out of range.
8432 if (ConstantSigned) {
8433 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
8435 } else { // !ConstantSigned
8436 if (OtherWidth >= Value.getActiveBits())
8440 } else { // !CommonSigned
8441 if (OtherRange.NonNegative) {
8442 if (OtherWidth >= Value.getActiveBits())
8444 } else { // OtherSigned
8445 assert(!ConstantSigned &&
8446 "Two signed types converted to unsigned types.");
8447 // Check to see if the constant is representable in OtherT.
8448 if (OtherWidth > Value.getActiveBits())
8450 // Check to see if the constant is equivalent to a negative value
8452 if (S.Context.getIntWidth(ConstantT) ==
8453 S.Context.getIntWidth(CommonT) &&
8454 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
8456 // The constant value rests between values that OtherT can represent
8457 // after conversion. Relational comparison still works, but equality
8458 // comparisons will be tautological.
8459 EqualityOnly = true;
8463 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
8465 if (op == BO_EQ || op == BO_NE) {
8466 IsTrue = op == BO_NE;
8467 } else if (EqualityOnly) {
8469 } else if (RhsConstant) {
8470 if (op == BO_GT || op == BO_GE)
8471 IsTrue = !PositiveConstant;
8472 else // op == BO_LT || op == BO_LE
8473 IsTrue = PositiveConstant;
8475 if (op == BO_LT || op == BO_LE)
8476 IsTrue = !PositiveConstant;
8477 else // op == BO_GT || op == BO_GE
8478 IsTrue = PositiveConstant;
8481 // Other isKnownToHaveBooleanValue
8482 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
8483 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
8484 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
8486 static const struct LinkedConditions {
8487 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
8488 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
8489 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
8490 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
8491 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
8492 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
8495 // Constant on LHS. | Constant on RHS. |
8496 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
8497 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
8498 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
8499 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
8500 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
8501 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
8502 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
8505 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
8507 enum ConstantValue ConstVal = Zero;
8508 if (Value.isUnsigned() || Value.isNonNegative()) {
8510 LiteralOrBoolConstant =
8511 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
8513 } else if (Value == 1) {
8514 LiteralOrBoolConstant =
8515 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
8518 LiteralOrBoolConstant = LiteralConstant;
8525 CompareBoolWithConstantResult CmpRes;
8529 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
8532 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
8535 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
8538 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
8541 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
8544 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
8551 if (CmpRes == AFals) {
8553 } else if (CmpRes == ATrue) {
8560 // If this is a comparison to an enum constant, include that
8561 // constant in the diagnostic.
8562 const EnumConstantDecl *ED = nullptr;
8563 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
8564 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
8566 SmallString<64> PrettySourceValue;
8567 llvm::raw_svector_ostream OS(PrettySourceValue);
8569 OS << '\'' << *ED << "' (" << Value << ")";
8573 S.DiagRuntimeBehavior(
8574 E->getOperatorLoc(), E,
8575 S.PDiag(diag::warn_out_of_range_compare)
8576 << OS.str() << LiteralOrBoolConstant
8577 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
8578 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
8581 /// Analyze the operands of the given comparison. Implements the
8582 /// fallback case from AnalyzeComparison.
8583 void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
8584 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8585 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
8588 /// \brief Implements -Wsign-compare.
8590 /// \param E the binary operator to check for warnings
8591 void AnalyzeComparison(Sema &S, BinaryOperator *E) {
8592 // The type the comparison is being performed in.
8593 QualType T = E->getLHS()->getType();
8595 // Only analyze comparison operators where both sides have been converted to
8597 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
8598 return AnalyzeImpConvsInComparison(S, E);
8600 // Don't analyze value-dependent comparisons directly.
8601 if (E->isValueDependent())
8602 return AnalyzeImpConvsInComparison(S, E);
8604 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
8605 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
8607 bool IsComparisonConstant = false;
8609 // Check whether an integer constant comparison results in a value
8610 // of 'true' or 'false'.
8611 if (T->isIntegralType(S.Context)) {
8612 llvm::APSInt RHSValue;
8613 bool IsRHSIntegralLiteral =
8614 RHS->isIntegerConstantExpr(RHSValue, S.Context);
8615 llvm::APSInt LHSValue;
8616 bool IsLHSIntegralLiteral =
8617 LHS->isIntegerConstantExpr(LHSValue, S.Context);
8618 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
8619 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
8620 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
8621 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
8623 IsComparisonConstant =
8624 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
8625 } else if (!T->hasUnsignedIntegerRepresentation())
8626 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
8628 // We don't do anything special if this isn't an unsigned integral
8629 // comparison: we're only interested in integral comparisons, and
8630 // signed comparisons only happen in cases we don't care to warn about.
8632 // We also don't care about value-dependent expressions or expressions
8633 // whose result is a constant.
8634 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
8635 return AnalyzeImpConvsInComparison(S, E);
8637 // Check to see if one of the (unmodified) operands is of different
8639 Expr *signedOperand, *unsignedOperand;
8640 if (LHS->getType()->hasSignedIntegerRepresentation()) {
8641 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
8642 "unsigned comparison between two signed integer expressions?");
8643 signedOperand = LHS;
8644 unsignedOperand = RHS;
8645 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
8646 signedOperand = RHS;
8647 unsignedOperand = LHS;
8649 CheckTrivialUnsignedComparison(S, E);
8650 return AnalyzeImpConvsInComparison(S, E);
8653 // Otherwise, calculate the effective range of the signed operand.
8654 IntRange signedRange = GetExprRange(S.Context, signedOperand);
8656 // Go ahead and analyze implicit conversions in the operands. Note
8657 // that we skip the implicit conversions on both sides.
8658 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
8659 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
8661 // If the signed range is non-negative, -Wsign-compare won't fire,
8662 // but we should still check for comparisons which are always true
8664 if (signedRange.NonNegative)
8665 return CheckTrivialUnsignedComparison(S, E);
8667 // For (in)equality comparisons, if the unsigned operand is a
8668 // constant which cannot collide with a overflowed signed operand,
8669 // then reinterpreting the signed operand as unsigned will not
8670 // change the result of the comparison.
8671 if (E->isEqualityOp()) {
8672 unsigned comparisonWidth = S.Context.getIntWidth(T);
8673 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
8675 // We should never be unable to prove that the unsigned operand is
8677 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
8679 if (unsignedRange.Width < comparisonWidth)
8683 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
8684 S.PDiag(diag::warn_mixed_sign_comparison)
8685 << LHS->getType() << RHS->getType()
8686 << LHS->getSourceRange() << RHS->getSourceRange());
8689 /// Analyzes an attempt to assign the given value to a bitfield.
8691 /// Returns true if there was something fishy about the attempt.
8692 bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
8693 SourceLocation InitLoc) {
8694 assert(Bitfield->isBitField());
8695 if (Bitfield->isInvalidDecl())
8698 // White-list bool bitfields.
8699 QualType BitfieldType = Bitfield->getType();
8700 if (BitfieldType->isBooleanType())
8703 if (BitfieldType->isEnumeralType()) {
8704 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
8705 // If the underlying enum type was not explicitly specified as an unsigned
8706 // type and the enum contain only positive values, MSVC++ will cause an
8707 // inconsistency by storing this as a signed type.
8708 if (S.getLangOpts().CPlusPlus11 &&
8709 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
8710 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
8711 BitfieldEnumDecl->getNumNegativeBits() == 0) {
8712 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
8713 << BitfieldEnumDecl->getNameAsString();
8717 if (Bitfield->getType()->isBooleanType())
8720 // Ignore value- or type-dependent expressions.
8721 if (Bitfield->getBitWidth()->isValueDependent() ||
8722 Bitfield->getBitWidth()->isTypeDependent() ||
8723 Init->isValueDependent() ||
8724 Init->isTypeDependent())
8727 Expr *OriginalInit = Init->IgnoreParenImpCasts();
8728 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
8731 if (!OriginalInit->EvaluateAsInt(Value, S.Context,
8732 Expr::SE_AllowSideEffects)) {
8733 // The RHS is not constant. If the RHS has an enum type, make sure the
8734 // bitfield is wide enough to hold all the values of the enum without
8736 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
8737 EnumDecl *ED = EnumTy->getDecl();
8738 bool SignedBitfield = BitfieldType->isSignedIntegerType();
8740 // Enum types are implicitly signed on Windows, so check if there are any
8741 // negative enumerators to see if the enum was intended to be signed or
8743 bool SignedEnum = ED->getNumNegativeBits() > 0;
8745 // Check for surprising sign changes when assigning enum values to a
8746 // bitfield of different signedness. If the bitfield is signed and we
8747 // have exactly the right number of bits to store this unsigned enum,
8748 // suggest changing the enum to an unsigned type. This typically happens
8749 // on Windows where unfixed enums always use an underlying type of 'int'.
8750 unsigned DiagID = 0;
8751 if (SignedEnum && !SignedBitfield) {
8752 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
8753 } else if (SignedBitfield && !SignedEnum &&
8754 ED->getNumPositiveBits() == FieldWidth) {
8755 DiagID = diag::warn_signed_bitfield_enum_conversion;
8759 S.Diag(InitLoc, DiagID) << Bitfield << ED;
8760 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
8761 SourceRange TypeRange =
8762 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
8763 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
8764 << SignedEnum << TypeRange;
8767 // Compute the required bitwidth. If the enum has negative values, we need
8768 // one more bit than the normal number of positive bits to represent the
8770 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
8771 ED->getNumNegativeBits())
8772 : ED->getNumPositiveBits();
8774 // Check the bitwidth.
8775 if (BitsNeeded > FieldWidth) {
8776 Expr *WidthExpr = Bitfield->getBitWidth();
8777 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
8779 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
8780 << BitsNeeded << ED << WidthExpr->getSourceRange();
8787 unsigned OriginalWidth = Value.getBitWidth();
8789 if (!Value.isSigned() || Value.isNegative())
8790 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
8791 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
8792 OriginalWidth = Value.getMinSignedBits();
8794 if (OriginalWidth <= FieldWidth)
8797 // Compute the value which the bitfield will contain.
8798 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
8799 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
8801 // Check whether the stored value is equal to the original value.
8802 TruncatedValue = TruncatedValue.extend(OriginalWidth);
8803 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
8806 // Special-case bitfields of width 1: booleans are naturally 0/1, and
8807 // therefore don't strictly fit into a signed bitfield of width 1.
8808 if (FieldWidth == 1 && Value == 1)
8811 std::string PrettyValue = Value.toString(10);
8812 std::string PrettyTrunc = TruncatedValue.toString(10);
8814 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
8815 << PrettyValue << PrettyTrunc << OriginalInit->getType()
8816 << Init->getSourceRange();
8821 /// Analyze the given simple or compound assignment for warning-worthy
8823 void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
8824 // Just recurse on the LHS.
8825 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8827 // We want to recurse on the RHS as normal unless we're assigning to
8829 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
8830 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
8831 E->getOperatorLoc())) {
8832 // Recurse, ignoring any implicit conversions on the RHS.
8833 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
8834 E->getOperatorLoc());
8838 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
8841 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
8842 void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
8843 SourceLocation CContext, unsigned diag,
8844 bool pruneControlFlow = false) {
8845 if (pruneControlFlow) {
8846 S.DiagRuntimeBehavior(E->getExprLoc(), E,
8848 << SourceType << T << E->getSourceRange()
8849 << SourceRange(CContext));
8852 S.Diag(E->getExprLoc(), diag)
8853 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
8856 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
8857 void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
8858 unsigned diag, bool pruneControlFlow = false) {
8859 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
8863 /// Diagnose an implicit cast from a floating point value to an integer value.
8864 void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
8866 SourceLocation CContext) {
8867 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
8868 const bool PruneWarnings = S.inTemplateInstantiation();
8870 Expr *InnerE = E->IgnoreParenImpCasts();
8871 // We also want to warn on, e.g., "int i = -1.234"
8872 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
8873 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
8874 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
8876 const bool IsLiteral =
8877 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
8879 llvm::APFloat Value(0.0);
8881 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
8883 return DiagnoseImpCast(S, E, T, CContext,
8884 diag::warn_impcast_float_integer, PruneWarnings);
8887 bool isExact = false;
8889 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
8890 T->hasUnsignedIntegerRepresentation());
8891 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
8892 &isExact) == llvm::APFloat::opOK &&
8894 if (IsLiteral) return;
8895 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
8899 unsigned DiagID = 0;
8901 // Warn on floating point literal to integer.
8902 DiagID = diag::warn_impcast_literal_float_to_integer;
8903 } else if (IntegerValue == 0) {
8904 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
8905 return DiagnoseImpCast(S, E, T, CContext,
8906 diag::warn_impcast_float_integer, PruneWarnings);
8908 // Warn on non-zero to zero conversion.
8909 DiagID = diag::warn_impcast_float_to_integer_zero;
8911 if (IntegerValue.isUnsigned()) {
8912 if (!IntegerValue.isMaxValue()) {
8913 return DiagnoseImpCast(S, E, T, CContext,
8914 diag::warn_impcast_float_integer, PruneWarnings);
8916 } else { // IntegerValue.isSigned()
8917 if (!IntegerValue.isMaxSignedValue() &&
8918 !IntegerValue.isMinSignedValue()) {
8919 return DiagnoseImpCast(S, E, T, CContext,
8920 diag::warn_impcast_float_integer, PruneWarnings);
8923 // Warn on evaluatable floating point expression to integer conversion.
8924 DiagID = diag::warn_impcast_float_to_integer;
8927 // FIXME: Force the precision of the source value down so we don't print
8928 // digits which are usually useless (we don't really care here if we
8929 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
8930 // would automatically print the shortest representation, but it's a bit
8931 // tricky to implement.
8932 SmallString<16> PrettySourceValue;
8933 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
8934 precision = (precision * 59 + 195) / 196;
8935 Value.toString(PrettySourceValue, precision);
8937 SmallString<16> PrettyTargetValue;
8939 PrettyTargetValue = Value.isZero() ? "false" : "true";
8941 IntegerValue.toString(PrettyTargetValue);
8943 if (PruneWarnings) {
8944 S.DiagRuntimeBehavior(E->getExprLoc(), E,
8946 << E->getType() << T.getUnqualifiedType()
8947 << PrettySourceValue << PrettyTargetValue
8948 << E->getSourceRange() << SourceRange(CContext));
8950 S.Diag(E->getExprLoc(), DiagID)
8951 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
8952 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
8956 std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
8957 if (!Range.Width) return "0";
8959 llvm::APSInt ValueInRange = Value;
8960 ValueInRange.setIsSigned(!Range.NonNegative);
8961 ValueInRange = ValueInRange.trunc(Range.Width);
8962 return ValueInRange.toString(10);
8965 bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
8966 if (!isa<ImplicitCastExpr>(Ex))
8969 Expr *InnerE = Ex->IgnoreParenImpCasts();
8970 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
8971 const Type *Source =
8972 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
8973 if (Target->isDependentType())
8976 const BuiltinType *FloatCandidateBT =
8977 dyn_cast<BuiltinType>(ToBool ? Source : Target);
8978 const Type *BoolCandidateType = ToBool ? Target : Source;
8980 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
8981 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
8984 void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
8985 SourceLocation CC) {
8986 unsigned NumArgs = TheCall->getNumArgs();
8987 for (unsigned i = 0; i < NumArgs; ++i) {
8988 Expr *CurrA = TheCall->getArg(i);
8989 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
8992 bool IsSwapped = ((i > 0) &&
8993 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
8994 IsSwapped |= ((i < (NumArgs - 1)) &&
8995 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
8997 // Warn on this floating-point to bool conversion.
8998 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
8999 CurrA->getType(), CC,
9000 diag::warn_impcast_floating_point_to_bool);
9005 void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
9006 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
9010 // Don't warn on functions which have return type nullptr_t.
9011 if (isa<CallExpr>(E))
9014 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
9015 const Expr::NullPointerConstantKind NullKind =
9016 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
9017 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
9020 // Return if target type is a safe conversion.
9021 if (T->isAnyPointerType() || T->isBlockPointerType() ||
9022 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
9025 SourceLocation Loc = E->getSourceRange().getBegin();
9027 // Venture through the macro stacks to get to the source of macro arguments.
9028 // The new location is a better location than the complete location that was
9030 while (S.SourceMgr.isMacroArgExpansion(Loc))
9031 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
9033 while (S.SourceMgr.isMacroArgExpansion(CC))
9034 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
9036 // __null is usually wrapped in a macro. Go up a macro if that is the case.
9037 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
9038 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
9039 Loc, S.SourceMgr, S.getLangOpts());
9040 if (MacroName == "NULL")
9041 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
9044 // Only warn if the null and context location are in the same macro expansion.
9045 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
9048 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
9049 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
9050 << FixItHint::CreateReplacement(Loc,
9051 S.getFixItZeroLiteralForType(T, Loc));
9054 void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9055 ObjCArrayLiteral *ArrayLiteral);
9056 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9057 ObjCDictionaryLiteral *DictionaryLiteral);
9059 /// Check a single element within a collection literal against the
9060 /// target element type.
9061 void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
9062 Expr *Element, unsigned ElementKind) {
9063 // Skip a bitcast to 'id' or qualified 'id'.
9064 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
9065 if (ICE->getCastKind() == CK_BitCast &&
9066 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
9067 Element = ICE->getSubExpr();
9070 QualType ElementType = Element->getType();
9071 ExprResult ElementResult(Element);
9072 if (ElementType->getAs<ObjCObjectPointerType>() &&
9073 S.CheckSingleAssignmentConstraints(TargetElementType,
9076 != Sema::Compatible) {
9077 S.Diag(Element->getLocStart(),
9078 diag::warn_objc_collection_literal_element)
9079 << ElementType << ElementKind << TargetElementType
9080 << Element->getSourceRange();
9083 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
9084 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
9085 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
9086 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
9089 /// Check an Objective-C array literal being converted to the given
9091 void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9092 ObjCArrayLiteral *ArrayLiteral) {
9096 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9100 if (TargetObjCPtr->isUnspecialized() ||
9101 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9102 != S.NSArrayDecl->getCanonicalDecl())
9105 auto TypeArgs = TargetObjCPtr->getTypeArgs();
9106 if (TypeArgs.size() != 1)
9109 QualType TargetElementType = TypeArgs[0];
9110 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
9111 checkObjCCollectionLiteralElement(S, TargetElementType,
9112 ArrayLiteral->getElement(I),
9117 /// Check an Objective-C dictionary literal being converted to the given
9119 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9120 ObjCDictionaryLiteral *DictionaryLiteral) {
9121 if (!S.NSDictionaryDecl)
9124 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9128 if (TargetObjCPtr->isUnspecialized() ||
9129 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9130 != S.NSDictionaryDecl->getCanonicalDecl())
9133 auto TypeArgs = TargetObjCPtr->getTypeArgs();
9134 if (TypeArgs.size() != 2)
9137 QualType TargetKeyType = TypeArgs[0];
9138 QualType TargetObjectType = TypeArgs[1];
9139 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
9140 auto Element = DictionaryLiteral->getKeyValueElement(I);
9141 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
9142 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
9146 // Helper function to filter out cases for constant width constant conversion.
9147 // Don't warn on char array initialization or for non-decimal values.
9148 bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
9149 SourceLocation CC) {
9150 // If initializing from a constant, and the constant starts with '0',
9151 // then it is a binary, octal, or hexadecimal. Allow these constants
9152 // to fill all the bits, even if there is a sign change.
9153 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
9154 const char FirstLiteralCharacter =
9155 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
9156 if (FirstLiteralCharacter == '0')
9160 // If the CC location points to a '{', and the type is char, then assume
9161 // assume it is an array initialization.
9162 if (CC.isValid() && T->isCharType()) {
9163 const char FirstContextCharacter =
9164 S.getSourceManager().getCharacterData(CC)[0];
9165 if (FirstContextCharacter == '{')
9172 void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
9173 SourceLocation CC, bool *ICContext = nullptr) {
9174 if (E->isTypeDependent() || E->isValueDependent()) return;
9176 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
9177 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
9178 if (Source == Target) return;
9179 if (Target->isDependentType()) return;
9181 // If the conversion context location is invalid don't complain. We also
9182 // don't want to emit a warning if the issue occurs from the expansion of
9183 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
9184 // delay this check as long as possible. Once we detect we are in that
9185 // scenario, we just return.
9189 // Diagnose implicit casts to bool.
9190 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
9191 if (isa<StringLiteral>(E))
9192 // Warn on string literal to bool. Checks for string literals in logical
9193 // and expressions, for instance, assert(0 && "error here"), are
9194 // prevented by a check in AnalyzeImplicitConversions().
9195 return DiagnoseImpCast(S, E, T, CC,
9196 diag::warn_impcast_string_literal_to_bool);
9197 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
9198 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
9199 // This covers the literal expressions that evaluate to Objective-C
9201 return DiagnoseImpCast(S, E, T, CC,
9202 diag::warn_impcast_objective_c_literal_to_bool);
9204 if (Source->isPointerType() || Source->canDecayToPointerType()) {
9205 // Warn on pointer to bool conversion that is always true.
9206 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
9211 // Check implicit casts from Objective-C collection literals to specialized
9212 // collection types, e.g., NSArray<NSString *> *.
9213 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
9214 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
9215 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
9216 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
9218 // Strip vector types.
9219 if (isa<VectorType>(Source)) {
9220 if (!isa<VectorType>(Target)) {
9221 if (S.SourceMgr.isInSystemMacro(CC))
9223 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
9226 // If the vector cast is cast between two vectors of the same size, it is
9227 // a bitcast, not a conversion.
9228 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
9231 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
9232 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
9234 if (auto VecTy = dyn_cast<VectorType>(Target))
9235 Target = VecTy->getElementType().getTypePtr();
9237 // Strip complex types.
9238 if (isa<ComplexType>(Source)) {
9239 if (!isa<ComplexType>(Target)) {
9240 if (S.SourceMgr.isInSystemMacro(CC))
9243 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
9246 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
9247 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
9250 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
9251 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
9253 // If the source is floating point...
9254 if (SourceBT && SourceBT->isFloatingPoint()) {
9255 // ...and the target is floating point...
9256 if (TargetBT && TargetBT->isFloatingPoint()) {
9257 // ...then warn if we're dropping FP rank.
9259 // Builtin FP kinds are ordered by increasing FP rank.
9260 if (SourceBT->getKind() > TargetBT->getKind()) {
9261 // Don't warn about float constants that are precisely
9262 // representable in the target type.
9263 Expr::EvalResult result;
9264 if (E->EvaluateAsRValue(result, S.Context)) {
9265 // Value might be a float, a float vector, or a float complex.
9266 if (IsSameFloatAfterCast(result.Val,
9267 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
9268 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
9272 if (S.SourceMgr.isInSystemMacro(CC))
9275 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
9277 // ... or possibly if we're increasing rank, too
9278 else if (TargetBT->getKind() > SourceBT->getKind()) {
9279 if (S.SourceMgr.isInSystemMacro(CC))
9282 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
9287 // If the target is integral, always warn.
9288 if (TargetBT && TargetBT->isInteger()) {
9289 if (S.SourceMgr.isInSystemMacro(CC))
9292 DiagnoseFloatingImpCast(S, E, T, CC);
9295 // Detect the case where a call result is converted from floating-point to
9296 // to bool, and the final argument to the call is converted from bool, to
9297 // discover this typo:
9299 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
9301 // FIXME: This is an incredibly special case; is there some more general
9302 // way to detect this class of misplaced-parentheses bug?
9303 if (Target->isBooleanType() && isa<CallExpr>(E)) {
9304 // Check last argument of function call to see if it is an
9305 // implicit cast from a type matching the type the result
9306 // is being cast to.
9307 CallExpr *CEx = cast<CallExpr>(E);
9308 if (unsigned NumArgs = CEx->getNumArgs()) {
9309 Expr *LastA = CEx->getArg(NumArgs - 1);
9310 Expr *InnerE = LastA->IgnoreParenImpCasts();
9311 if (isa<ImplicitCastExpr>(LastA) &&
9312 InnerE->getType()->isBooleanType()) {
9313 // Warn on this floating-point to bool conversion
9314 DiagnoseImpCast(S, E, T, CC,
9315 diag::warn_impcast_floating_point_to_bool);
9322 DiagnoseNullConversion(S, E, T, CC);
9324 S.DiscardMisalignedMemberAddress(Target, E);
9326 if (!Source->isIntegerType() || !Target->isIntegerType())
9329 // TODO: remove this early return once the false positives for constant->bool
9330 // in templates, macros, etc, are reduced or removed.
9331 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
9334 IntRange SourceRange = GetExprRange(S.Context, E);
9335 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
9337 if (SourceRange.Width > TargetRange.Width) {
9338 // If the source is a constant, use a default-on diagnostic.
9339 // TODO: this should happen for bitfield stores, too.
9340 llvm::APSInt Value(32);
9341 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
9342 if (S.SourceMgr.isInSystemMacro(CC))
9345 std::string PrettySourceValue = Value.toString(10);
9346 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
9348 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9349 S.PDiag(diag::warn_impcast_integer_precision_constant)
9350 << PrettySourceValue << PrettyTargetValue
9351 << E->getType() << T << E->getSourceRange()
9352 << clang::SourceRange(CC));
9356 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
9357 if (S.SourceMgr.isInSystemMacro(CC))
9360 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
9361 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
9362 /* pruneControlFlow */ true);
9363 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
9366 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
9367 SourceRange.NonNegative && Source->isSignedIntegerType()) {
9368 // Warn when doing a signed to signed conversion, warn if the positive
9369 // source value is exactly the width of the target type, which will
9370 // cause a negative value to be stored.
9373 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
9374 !S.SourceMgr.isInSystemMacro(CC)) {
9375 if (isSameWidthConstantConversion(S, E, T, CC)) {
9376 std::string PrettySourceValue = Value.toString(10);
9377 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
9379 S.DiagRuntimeBehavior(
9381 S.PDiag(diag::warn_impcast_integer_precision_constant)
9382 << PrettySourceValue << PrettyTargetValue << E->getType() << T
9383 << E->getSourceRange() << clang::SourceRange(CC));
9388 // Fall through for non-constants to give a sign conversion warning.
9391 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
9392 (!TargetRange.NonNegative && SourceRange.NonNegative &&
9393 SourceRange.Width == TargetRange.Width)) {
9394 if (S.SourceMgr.isInSystemMacro(CC))
9397 unsigned DiagID = diag::warn_impcast_integer_sign;
9399 // Traditionally, gcc has warned about this under -Wsign-compare.
9400 // We also want to warn about it in -Wconversion.
9401 // So if -Wconversion is off, use a completely identical diagnostic
9402 // in the sign-compare group.
9403 // The conditional-checking code will
9405 DiagID = diag::warn_impcast_integer_sign_conditional;
9409 return DiagnoseImpCast(S, E, T, CC, DiagID);
9412 // Diagnose conversions between different enumeration types.
9413 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
9414 // type, to give us better diagnostics.
9415 QualType SourceType = E->getType();
9416 if (!S.getLangOpts().CPlusPlus) {
9417 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9418 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
9419 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
9420 SourceType = S.Context.getTypeDeclType(Enum);
9421 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
9425 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
9426 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
9427 if (SourceEnum->getDecl()->hasNameForLinkage() &&
9428 TargetEnum->getDecl()->hasNameForLinkage() &&
9429 SourceEnum != TargetEnum) {
9430 if (S.SourceMgr.isInSystemMacro(CC))
9433 return DiagnoseImpCast(S, E, SourceType, T, CC,
9434 diag::warn_impcast_different_enum_types);
9438 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9439 SourceLocation CC, QualType T);
9441 void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
9442 SourceLocation CC, bool &ICContext) {
9443 E = E->IgnoreParenImpCasts();
9445 if (isa<ConditionalOperator>(E))
9446 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
9448 AnalyzeImplicitConversions(S, E, CC);
9449 if (E->getType() != T)
9450 return CheckImplicitConversion(S, E, T, CC, &ICContext);
9453 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9454 SourceLocation CC, QualType T) {
9455 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
9457 bool Suspicious = false;
9458 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
9459 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
9461 // If -Wconversion would have warned about either of the candidates
9462 // for a signedness conversion to the context type...
9463 if (!Suspicious) return;
9465 // ...but it's currently ignored...
9466 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
9469 // ...then check whether it would have warned about either of the
9470 // candidates for a signedness conversion to the condition type.
9471 if (E->getType() == T) return;
9474 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
9475 E->getType(), CC, &Suspicious);
9477 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
9478 E->getType(), CC, &Suspicious);
9481 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9482 /// Input argument E is a logical expression.
9483 void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
9484 if (S.getLangOpts().Bool)
9486 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
9489 /// AnalyzeImplicitConversions - Find and report any interesting
9490 /// implicit conversions in the given expression. There are a couple
9491 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
9492 void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
9493 QualType T = OrigE->getType();
9494 Expr *E = OrigE->IgnoreParenImpCasts();
9496 if (E->isTypeDependent() || E->isValueDependent())
9499 // For conditional operators, we analyze the arguments as if they
9500 // were being fed directly into the output.
9501 if (isa<ConditionalOperator>(E)) {
9502 ConditionalOperator *CO = cast<ConditionalOperator>(E);
9503 CheckConditionalOperator(S, CO, CC, T);
9507 // Check implicit argument conversions for function calls.
9508 if (CallExpr *Call = dyn_cast<CallExpr>(E))
9509 CheckImplicitArgumentConversions(S, Call, CC);
9511 // Go ahead and check any implicit conversions we might have skipped.
9512 // The non-canonical typecheck is just an optimization;
9513 // CheckImplicitConversion will filter out dead implicit conversions.
9514 if (E->getType() != T)
9515 CheckImplicitConversion(S, E, T, CC);
9517 // Now continue drilling into this expression.
9519 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
9520 // The bound subexpressions in a PseudoObjectExpr are not reachable
9521 // as transitive children.
9522 // FIXME: Use a more uniform representation for this.
9523 for (auto *SE : POE->semantics())
9524 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
9525 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
9528 // Skip past explicit casts.
9529 if (isa<ExplicitCastExpr>(E)) {
9530 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
9531 return AnalyzeImplicitConversions(S, E, CC);
9534 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9535 // Do a somewhat different check with comparison operators.
9536 if (BO->isComparisonOp())
9537 return AnalyzeComparison(S, BO);
9539 // And with simple assignments.
9540 if (BO->getOpcode() == BO_Assign)
9541 return AnalyzeAssignment(S, BO);
9544 // These break the otherwise-useful invariant below. Fortunately,
9545 // we don't really need to recurse into them, because any internal
9546 // expressions should have been analyzed already when they were
9547 // built into statements.
9548 if (isa<StmtExpr>(E)) return;
9550 // Don't descend into unevaluated contexts.
9551 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
9553 // Now just recurse over the expression's children.
9554 CC = E->getExprLoc();
9555 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
9556 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
9557 for (Stmt *SubStmt : E->children()) {
9558 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
9562 if (IsLogicalAndOperator &&
9563 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
9564 // Ignore checking string literals that are in logical and operators.
9565 // This is a common pattern for asserts.
9567 AnalyzeImplicitConversions(S, ChildExpr, CC);
9570 if (BO && BO->isLogicalOp()) {
9571 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
9572 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
9573 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
9575 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
9576 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
9577 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
9580 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
9581 if (U->getOpcode() == UO_LNot)
9582 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
9585 } // end anonymous namespace
9587 /// Diagnose integer type and any valid implicit convertion to it.
9588 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
9589 // Taking into account implicit conversions,
9590 // allow any integer.
9591 if (!E->getType()->isIntegerType()) {
9592 S.Diag(E->getLocStart(),
9593 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
9596 // Potentially emit standard warnings for implicit conversions if enabled
9597 // using -Wconversion.
9598 CheckImplicitConversion(S, E, IntT, E->getLocStart());
9602 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
9603 // Returns true when emitting a warning about taking the address of a reference.
9604 static bool CheckForReference(Sema &SemaRef, const Expr *E,
9605 const PartialDiagnostic &PD) {
9606 E = E->IgnoreParenImpCasts();
9608 const FunctionDecl *FD = nullptr;
9610 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9611 if (!DRE->getDecl()->getType()->isReferenceType())
9613 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9614 if (!M->getMemberDecl()->getType()->isReferenceType())
9616 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
9617 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
9619 FD = Call->getDirectCallee();
9624 SemaRef.Diag(E->getExprLoc(), PD);
9626 // If possible, point to location of function.
9628 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
9634 // Returns true if the SourceLocation is expanded from any macro body.
9635 // Returns false if the SourceLocation is invalid, is from not in a macro
9636 // expansion, or is from expanded from a top-level macro argument.
9637 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
9638 if (Loc.isInvalid())
9641 while (Loc.isMacroID()) {
9642 if (SM.isMacroBodyExpansion(Loc))
9644 Loc = SM.getImmediateMacroCallerLoc(Loc);
9650 /// \brief Diagnose pointers that are always non-null.
9651 /// \param E the expression containing the pointer
9652 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
9653 /// compared to a null pointer
9654 /// \param IsEqual True when the comparison is equal to a null pointer
9655 /// \param Range Extra SourceRange to highlight in the diagnostic
9656 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
9657 Expr::NullPointerConstantKind NullKind,
9658 bool IsEqual, SourceRange Range) {
9662 // Don't warn inside macros.
9663 if (E->getExprLoc().isMacroID()) {
9664 const SourceManager &SM = getSourceManager();
9665 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
9666 IsInAnyMacroBody(SM, Range.getBegin()))
9669 E = E->IgnoreImpCasts();
9671 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
9673 if (isa<CXXThisExpr>(E)) {
9674 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
9675 : diag::warn_this_bool_conversion;
9676 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
9680 bool IsAddressOf = false;
9682 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9683 if (UO->getOpcode() != UO_AddrOf)
9686 E = UO->getSubExpr();
9690 unsigned DiagID = IsCompare
9691 ? diag::warn_address_of_reference_null_compare
9692 : diag::warn_address_of_reference_bool_conversion;
9693 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
9695 if (CheckForReference(*this, E, PD)) {
9700 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
9701 bool IsParam = isa<NonNullAttr>(NonnullAttr);
9703 llvm::raw_string_ostream S(Str);
9704 E->printPretty(S, nullptr, getPrintingPolicy());
9705 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
9706 : diag::warn_cast_nonnull_to_bool;
9707 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
9708 << E->getSourceRange() << Range << IsEqual;
9709 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
9712 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
9713 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
9714 if (auto *Callee = Call->getDirectCallee()) {
9715 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
9716 ComplainAboutNonnullParamOrCall(A);
9722 // Expect to find a single Decl. Skip anything more complicated.
9723 ValueDecl *D = nullptr;
9724 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
9726 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9727 D = M->getMemberDecl();
9730 // Weak Decls can be null.
9731 if (!D || D->isWeak())
9734 // Check for parameter decl with nonnull attribute
9735 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
9736 if (getCurFunction() &&
9737 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
9738 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
9739 ComplainAboutNonnullParamOrCall(A);
9743 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
9744 auto ParamIter = llvm::find(FD->parameters(), PV);
9745 assert(ParamIter != FD->param_end());
9746 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
9748 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
9749 if (!NonNull->args_size()) {
9750 ComplainAboutNonnullParamOrCall(NonNull);
9754 for (unsigned ArgNo : NonNull->args()) {
9755 if (ArgNo == ParamNo) {
9756 ComplainAboutNonnullParamOrCall(NonNull);
9765 QualType T = D->getType();
9766 const bool IsArray = T->isArrayType();
9767 const bool IsFunction = T->isFunctionType();
9769 // Address of function is used to silence the function warning.
9770 if (IsAddressOf && IsFunction) {
9775 if (!IsAddressOf && !IsFunction && !IsArray)
9778 // Pretty print the expression for the diagnostic.
9780 llvm::raw_string_ostream S(Str);
9781 E->printPretty(S, nullptr, getPrintingPolicy());
9783 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
9784 : diag::warn_impcast_pointer_to_bool;
9791 DiagType = AddressOf;
9792 else if (IsFunction)
9793 DiagType = FunctionPointer;
9795 DiagType = ArrayPointer;
9797 llvm_unreachable("Could not determine diagnostic.");
9798 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
9799 << Range << IsEqual;
9804 // Suggest '&' to silence the function warning.
9805 Diag(E->getExprLoc(), diag::note_function_warning_silence)
9806 << FixItHint::CreateInsertion(E->getLocStart(), "&");
9808 // Check to see if '()' fixit should be emitted.
9809 QualType ReturnType;
9810 UnresolvedSet<4> NonTemplateOverloads;
9811 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
9812 if (ReturnType.isNull())
9816 // There are two cases here. If there is null constant, the only suggest
9817 // for a pointer return type. If the null is 0, then suggest if the return
9818 // type is a pointer or an integer type.
9819 if (!ReturnType->isPointerType()) {
9820 if (NullKind == Expr::NPCK_ZeroExpression ||
9821 NullKind == Expr::NPCK_ZeroLiteral) {
9822 if (!ReturnType->isIntegerType())
9828 } else { // !IsCompare
9829 // For function to bool, only suggest if the function pointer has bool
9831 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
9834 Diag(E->getExprLoc(), diag::note_function_to_function_call)
9835 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
9838 /// Diagnoses "dangerous" implicit conversions within the given
9839 /// expression (which is a full expression). Implements -Wconversion
9840 /// and -Wsign-compare.
9842 /// \param CC the "context" location of the implicit conversion, i.e.
9843 /// the most location of the syntactic entity requiring the implicit
9845 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
9846 // Don't diagnose in unevaluated contexts.
9847 if (isUnevaluatedContext())
9850 // Don't diagnose for value- or type-dependent expressions.
9851 if (E->isTypeDependent() || E->isValueDependent())
9854 // Check for array bounds violations in cases where the check isn't triggered
9855 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
9856 // ArraySubscriptExpr is on the RHS of a variable initialization.
9857 CheckArrayAccess(E);
9859 // This is not the right CC for (e.g.) a variable initialization.
9860 AnalyzeImplicitConversions(*this, E, CC);
9863 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9864 /// Input argument E is a logical expression.
9865 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
9866 ::CheckBoolLikeConversion(*this, E, CC);
9869 /// Diagnose when expression is an integer constant expression and its evaluation
9870 /// results in integer overflow
9871 void Sema::CheckForIntOverflow (Expr *E) {
9872 // Use a work list to deal with nested struct initializers.
9873 SmallVector<Expr *, 2> Exprs(1, E);
9876 Expr *E = Exprs.pop_back_val();
9878 if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
9879 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
9883 if (auto InitList = dyn_cast<InitListExpr>(E))
9884 Exprs.append(InitList->inits().begin(), InitList->inits().end());
9885 } while (!Exprs.empty());
9889 /// \brief Visitor for expressions which looks for unsequenced operations on the
9891 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
9892 typedef EvaluatedExprVisitor<SequenceChecker> Base;
9894 /// \brief A tree of sequenced regions within an expression. Two regions are
9895 /// unsequenced if one is an ancestor or a descendent of the other. When we
9896 /// finish processing an expression with sequencing, such as a comma
9897 /// expression, we fold its tree nodes into its parent, since they are
9898 /// unsequenced with respect to nodes we will visit later.
9899 class SequenceTree {
9901 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
9902 unsigned Parent : 31;
9903 unsigned Merged : 1;
9905 SmallVector<Value, 8> Values;
9908 /// \brief A region within an expression which may be sequenced with respect
9909 /// to some other region.
9911 explicit Seq(unsigned N) : Index(N) {}
9913 friend class SequenceTree;
9918 SequenceTree() { Values.push_back(Value(0)); }
9919 Seq root() const { return Seq(0); }
9921 /// \brief Create a new sequence of operations, which is an unsequenced
9922 /// subset of \p Parent. This sequence of operations is sequenced with
9923 /// respect to other children of \p Parent.
9924 Seq allocate(Seq Parent) {
9925 Values.push_back(Value(Parent.Index));
9926 return Seq(Values.size() - 1);
9929 /// \brief Merge a sequence of operations into its parent.
9931 Values[S.Index].Merged = true;
9934 /// \brief Determine whether two operations are unsequenced. This operation
9935 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
9936 /// should have been merged into its parent as appropriate.
9937 bool isUnsequenced(Seq Cur, Seq Old) {
9938 unsigned C = representative(Cur.Index);
9939 unsigned Target = representative(Old.Index);
9940 while (C >= Target) {
9943 C = Values[C].Parent;
9949 /// \brief Pick a representative for a sequence.
9950 unsigned representative(unsigned K) {
9951 if (Values[K].Merged)
9952 // Perform path compression as we go.
9953 return Values[K].Parent = representative(Values[K].Parent);
9958 /// An object for which we can track unsequenced uses.
9959 typedef NamedDecl *Object;
9961 /// Different flavors of object usage which we track. We only track the
9962 /// least-sequenced usage of each kind.
9964 /// A read of an object. Multiple unsequenced reads are OK.
9966 /// A modification of an object which is sequenced before the value
9967 /// computation of the expression, such as ++n in C++.
9969 /// A modification of an object which is not sequenced before the value
9970 /// computation of the expression, such as n++.
9973 UK_Count = UK_ModAsSideEffect + 1
9977 Usage() : Use(nullptr), Seq() {}
9979 SequenceTree::Seq Seq;
9983 UsageInfo() : Diagnosed(false) {}
9984 Usage Uses[UK_Count];
9985 /// Have we issued a diagnostic for this variable already?
9988 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
9991 /// Sequenced regions within the expression.
9993 /// Declaration modifications and references which we have seen.
9994 UsageInfoMap UsageMap;
9995 /// The region we are currently within.
9996 SequenceTree::Seq Region;
9997 /// Filled in with declarations which were modified as a side-effect
9998 /// (that is, post-increment operations).
9999 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
10000 /// Expressions to check later. We defer checking these to reduce
10002 SmallVectorImpl<Expr *> &WorkList;
10004 /// RAII object wrapping the visitation of a sequenced subexpression of an
10005 /// expression. At the end of this process, the side-effects of the evaluation
10006 /// become sequenced with respect to the value computation of the result, so
10007 /// we downgrade any UK_ModAsSideEffect within the evaluation to
10009 struct SequencedSubexpression {
10010 SequencedSubexpression(SequenceChecker &Self)
10011 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
10012 Self.ModAsSideEffect = &ModAsSideEffect;
10014 ~SequencedSubexpression() {
10015 for (auto &M : llvm::reverse(ModAsSideEffect)) {
10016 UsageInfo &U = Self.UsageMap[M.first];
10017 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
10018 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
10019 SideEffectUsage = M.second;
10021 Self.ModAsSideEffect = OldModAsSideEffect;
10024 SequenceChecker &Self;
10025 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
10026 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
10029 /// RAII object wrapping the visitation of a subexpression which we might
10030 /// choose to evaluate as a constant. If any subexpression is evaluated and
10031 /// found to be non-constant, this allows us to suppress the evaluation of
10032 /// the outer expression.
10033 class EvaluationTracker {
10035 EvaluationTracker(SequenceChecker &Self)
10036 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
10037 Self.EvalTracker = this;
10039 ~EvaluationTracker() {
10040 Self.EvalTracker = Prev;
10042 Prev->EvalOK &= EvalOK;
10045 bool evaluate(const Expr *E, bool &Result) {
10046 if (!EvalOK || E->isValueDependent())
10048 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
10053 SequenceChecker &Self;
10054 EvaluationTracker *Prev;
10058 /// \brief Find the object which is produced by the specified expression,
10060 Object getObject(Expr *E, bool Mod) const {
10061 E = E->IgnoreParenCasts();
10062 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10063 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
10064 return getObject(UO->getSubExpr(), Mod);
10065 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10066 if (BO->getOpcode() == BO_Comma)
10067 return getObject(BO->getRHS(), Mod);
10068 if (Mod && BO->isAssignmentOp())
10069 return getObject(BO->getLHS(), Mod);
10070 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10071 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
10072 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
10073 return ME->getMemberDecl();
10074 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10075 // FIXME: If this is a reference, map through to its value.
10076 return DRE->getDecl();
10080 /// \brief Note that an object was modified or used by an expression.
10081 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
10082 Usage &U = UI.Uses[UK];
10083 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
10084 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
10085 ModAsSideEffect->push_back(std::make_pair(O, U));
10090 /// \brief Check whether a modification or use conflicts with a prior usage.
10091 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
10096 const Usage &U = UI.Uses[OtherKind];
10097 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
10101 Expr *ModOrUse = Ref;
10102 if (OtherKind == UK_Use)
10103 std::swap(Mod, ModOrUse);
10105 SemaRef.Diag(Mod->getExprLoc(),
10106 IsModMod ? diag::warn_unsequenced_mod_mod
10107 : diag::warn_unsequenced_mod_use)
10108 << O << SourceRange(ModOrUse->getExprLoc());
10109 UI.Diagnosed = true;
10112 void notePreUse(Object O, Expr *Use) {
10113 UsageInfo &U = UsageMap[O];
10114 // Uses conflict with other modifications.
10115 checkUsage(O, U, Use, UK_ModAsValue, false);
10117 void notePostUse(Object O, Expr *Use) {
10118 UsageInfo &U = UsageMap[O];
10119 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
10120 addUsage(U, O, Use, UK_Use);
10123 void notePreMod(Object O, Expr *Mod) {
10124 UsageInfo &U = UsageMap[O];
10125 // Modifications conflict with other modifications and with uses.
10126 checkUsage(O, U, Mod, UK_ModAsValue, true);
10127 checkUsage(O, U, Mod, UK_Use, false);
10129 void notePostMod(Object O, Expr *Use, UsageKind UK) {
10130 UsageInfo &U = UsageMap[O];
10131 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
10132 addUsage(U, O, Use, UK);
10136 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
10137 : Base(S.Context), SemaRef(S), Region(Tree.root()),
10138 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
10142 void VisitStmt(Stmt *S) {
10143 // Skip all statements which aren't expressions for now.
10146 void VisitExpr(Expr *E) {
10147 // By default, just recurse to evaluated subexpressions.
10148 Base::VisitStmt(E);
10151 void VisitCastExpr(CastExpr *E) {
10152 Object O = Object();
10153 if (E->getCastKind() == CK_LValueToRValue)
10154 O = getObject(E->getSubExpr(), false);
10163 void VisitBinComma(BinaryOperator *BO) {
10164 // C++11 [expr.comma]p1:
10165 // Every value computation and side effect associated with the left
10166 // expression is sequenced before every value computation and side
10167 // effect associated with the right expression.
10168 SequenceTree::Seq LHS = Tree.allocate(Region);
10169 SequenceTree::Seq RHS = Tree.allocate(Region);
10170 SequenceTree::Seq OldRegion = Region;
10173 SequencedSubexpression SeqLHS(*this);
10175 Visit(BO->getLHS());
10179 Visit(BO->getRHS());
10181 Region = OldRegion;
10183 // Forget that LHS and RHS are sequenced. They are both unsequenced
10184 // with respect to other stuff.
10189 void VisitBinAssign(BinaryOperator *BO) {
10190 // The modification is sequenced after the value computation of the LHS
10191 // and RHS, so check it before inspecting the operands and update the
10193 Object O = getObject(BO->getLHS(), true);
10195 return VisitExpr(BO);
10199 // C++11 [expr.ass]p7:
10200 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
10203 // Therefore, for a compound assignment operator, O is considered used
10204 // everywhere except within the evaluation of E1 itself.
10205 if (isa<CompoundAssignOperator>(BO))
10208 Visit(BO->getLHS());
10210 if (isa<CompoundAssignOperator>(BO))
10211 notePostUse(O, BO);
10213 Visit(BO->getRHS());
10215 // C++11 [expr.ass]p1:
10216 // the assignment is sequenced [...] before the value computation of the
10217 // assignment expression.
10218 // C11 6.5.16/3 has no such rule.
10219 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10220 : UK_ModAsSideEffect);
10223 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
10224 VisitBinAssign(CAO);
10227 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10228 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10229 void VisitUnaryPreIncDec(UnaryOperator *UO) {
10230 Object O = getObject(UO->getSubExpr(), true);
10232 return VisitExpr(UO);
10235 Visit(UO->getSubExpr());
10236 // C++11 [expr.pre.incr]p1:
10237 // the expression ++x is equivalent to x+=1
10238 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10239 : UK_ModAsSideEffect);
10242 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10243 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10244 void VisitUnaryPostIncDec(UnaryOperator *UO) {
10245 Object O = getObject(UO->getSubExpr(), true);
10247 return VisitExpr(UO);
10250 Visit(UO->getSubExpr());
10251 notePostMod(O, UO, UK_ModAsSideEffect);
10254 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
10255 void VisitBinLOr(BinaryOperator *BO) {
10256 // The side-effects of the LHS of an '&&' are sequenced before the
10257 // value computation of the RHS, and hence before the value computation
10258 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
10259 // as if they were unconditionally sequenced.
10260 EvaluationTracker Eval(*this);
10262 SequencedSubexpression Sequenced(*this);
10263 Visit(BO->getLHS());
10267 if (Eval.evaluate(BO->getLHS(), Result)) {
10269 Visit(BO->getRHS());
10271 // Check for unsequenced operations in the RHS, treating it as an
10272 // entirely separate evaluation.
10274 // FIXME: If there are operations in the RHS which are unsequenced
10275 // with respect to operations outside the RHS, and those operations
10276 // are unconditionally evaluated, diagnose them.
10277 WorkList.push_back(BO->getRHS());
10280 void VisitBinLAnd(BinaryOperator *BO) {
10281 EvaluationTracker Eval(*this);
10283 SequencedSubexpression Sequenced(*this);
10284 Visit(BO->getLHS());
10288 if (Eval.evaluate(BO->getLHS(), Result)) {
10290 Visit(BO->getRHS());
10292 WorkList.push_back(BO->getRHS());
10296 // Only visit the condition, unless we can be sure which subexpression will
10298 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
10299 EvaluationTracker Eval(*this);
10301 SequencedSubexpression Sequenced(*this);
10302 Visit(CO->getCond());
10306 if (Eval.evaluate(CO->getCond(), Result))
10307 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
10309 WorkList.push_back(CO->getTrueExpr());
10310 WorkList.push_back(CO->getFalseExpr());
10314 void VisitCallExpr(CallExpr *CE) {
10315 // C++11 [intro.execution]p15:
10316 // When calling a function [...], every value computation and side effect
10317 // associated with any argument expression, or with the postfix expression
10318 // designating the called function, is sequenced before execution of every
10319 // expression or statement in the body of the function [and thus before
10320 // the value computation of its result].
10321 SequencedSubexpression Sequenced(*this);
10322 Base::VisitCallExpr(CE);
10324 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
10327 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
10328 // This is a call, so all subexpressions are sequenced before the result.
10329 SequencedSubexpression Sequenced(*this);
10331 if (!CCE->isListInitialization())
10332 return VisitExpr(CCE);
10334 // In C++11, list initializations are sequenced.
10335 SmallVector<SequenceTree::Seq, 32> Elts;
10336 SequenceTree::Seq Parent = Region;
10337 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
10338 E = CCE->arg_end();
10340 Region = Tree.allocate(Parent);
10341 Elts.push_back(Region);
10345 // Forget that the initializers are sequenced.
10347 for (unsigned I = 0; I < Elts.size(); ++I)
10348 Tree.merge(Elts[I]);
10351 void VisitInitListExpr(InitListExpr *ILE) {
10352 if (!SemaRef.getLangOpts().CPlusPlus11)
10353 return VisitExpr(ILE);
10355 // In C++11, list initializations are sequenced.
10356 SmallVector<SequenceTree::Seq, 32> Elts;
10357 SequenceTree::Seq Parent = Region;
10358 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
10359 Expr *E = ILE->getInit(I);
10361 Region = Tree.allocate(Parent);
10362 Elts.push_back(Region);
10366 // Forget that the initializers are sequenced.
10368 for (unsigned I = 0; I < Elts.size(); ++I)
10369 Tree.merge(Elts[I]);
10372 } // end anonymous namespace
10374 void Sema::CheckUnsequencedOperations(Expr *E) {
10375 SmallVector<Expr *, 8> WorkList;
10376 WorkList.push_back(E);
10377 while (!WorkList.empty()) {
10378 Expr *Item = WorkList.pop_back_val();
10379 SequenceChecker(*this, Item, WorkList);
10383 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
10384 bool IsConstexpr) {
10385 CheckImplicitConversions(E, CheckLoc);
10386 if (!E->isInstantiationDependent())
10387 CheckUnsequencedOperations(E);
10388 if (!IsConstexpr && !E->isValueDependent())
10389 CheckForIntOverflow(E);
10390 DiagnoseMisalignedMembers();
10393 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
10394 FieldDecl *BitField,
10396 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
10399 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
10400 SourceLocation Loc) {
10401 if (!PType->isVariablyModifiedType())
10403 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
10404 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
10407 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
10408 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
10411 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
10412 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
10416 const ArrayType *AT = S.Context.getAsArrayType(PType);
10420 if (AT->getSizeModifier() != ArrayType::Star) {
10421 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
10425 S.Diag(Loc, diag::err_array_star_in_function_definition);
10428 /// CheckParmsForFunctionDef - Check that the parameters of the given
10429 /// function are appropriate for the definition of a function. This
10430 /// takes care of any checks that cannot be performed on the
10431 /// declaration itself, e.g., that the types of each of the function
10432 /// parameters are complete.
10433 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
10434 bool CheckParameterNames) {
10435 bool HasInvalidParm = false;
10436 for (ParmVarDecl *Param : Parameters) {
10437 // C99 6.7.5.3p4: the parameters in a parameter type list in a
10438 // function declarator that is part of a function definition of
10439 // that function shall not have incomplete type.
10441 // This is also C++ [dcl.fct]p6.
10442 if (!Param->isInvalidDecl() &&
10443 RequireCompleteType(Param->getLocation(), Param->getType(),
10444 diag::err_typecheck_decl_incomplete_type)) {
10445 Param->setInvalidDecl();
10446 HasInvalidParm = true;
10449 // C99 6.9.1p5: If the declarator includes a parameter type list, the
10450 // declaration of each parameter shall include an identifier.
10451 if (CheckParameterNames &&
10452 Param->getIdentifier() == nullptr &&
10453 !Param->isImplicit() &&
10454 !getLangOpts().CPlusPlus)
10455 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
10458 // If the function declarator is not part of a definition of that
10459 // function, parameters may have incomplete type and may use the [*]
10460 // notation in their sequences of declarator specifiers to specify
10461 // variable length array types.
10462 QualType PType = Param->getOriginalType();
10463 // FIXME: This diagnostic should point the '[*]' if source-location
10464 // information is added for it.
10465 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
10467 // MSVC destroys objects passed by value in the callee. Therefore a
10468 // function definition which takes such a parameter must be able to call the
10469 // object's destructor. However, we don't perform any direct access check
10471 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
10473 .areArgsDestroyedLeftToRightInCallee()) {
10474 if (!Param->isInvalidDecl()) {
10475 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
10476 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
10477 if (!ClassDecl->isInvalidDecl() &&
10478 !ClassDecl->hasIrrelevantDestructor() &&
10479 !ClassDecl->isDependentContext()) {
10480 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10481 MarkFunctionReferenced(Param->getLocation(), Destructor);
10482 DiagnoseUseOfDecl(Destructor, Param->getLocation());
10488 // Parameters with the pass_object_size attribute only need to be marked
10489 // constant at function definitions. Because we lack information about
10490 // whether we're on a declaration or definition when we're instantiating the
10491 // attribute, we need to check for constness here.
10492 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
10493 if (!Param->getType().isConstQualified())
10494 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
10495 << Attr->getSpelling() << 1;
10498 return HasInvalidParm;
10501 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr
10503 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
10504 ASTContext &Context) {
10505 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
10506 return Context.getDeclAlign(DRE->getDecl());
10508 if (const auto *ME = dyn_cast<MemberExpr>(E))
10509 return Context.getDeclAlign(ME->getMemberDecl());
10514 /// CheckCastAlign - Implements -Wcast-align, which warns when a
10515 /// pointer cast increases the alignment requirements.
10516 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
10517 // This is actually a lot of work to potentially be doing on every
10518 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
10519 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
10522 // Ignore dependent types.
10523 if (T->isDependentType() || Op->getType()->isDependentType())
10526 // Require that the destination be a pointer type.
10527 const PointerType *DestPtr = T->getAs<PointerType>();
10528 if (!DestPtr) return;
10530 // If the destination has alignment 1, we're done.
10531 QualType DestPointee = DestPtr->getPointeeType();
10532 if (DestPointee->isIncompleteType()) return;
10533 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
10534 if (DestAlign.isOne()) return;
10536 // Require that the source be a pointer type.
10537 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
10538 if (!SrcPtr) return;
10539 QualType SrcPointee = SrcPtr->getPointeeType();
10541 // Whitelist casts from cv void*. We already implicitly
10542 // whitelisted casts to cv void*, since they have alignment 1.
10543 // Also whitelist casts involving incomplete types, which implicitly
10544 // includes 'void'.
10545 if (SrcPointee->isIncompleteType()) return;
10547 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
10549 if (auto *CE = dyn_cast<CastExpr>(Op)) {
10550 if (CE->getCastKind() == CK_ArrayToPointerDecay)
10551 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
10552 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
10553 if (UO->getOpcode() == UO_AddrOf)
10554 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
10557 if (SrcAlign >= DestAlign) return;
10559 Diag(TRange.getBegin(), diag::warn_cast_align)
10560 << Op->getType() << T
10561 << static_cast<unsigned>(SrcAlign.getQuantity())
10562 << static_cast<unsigned>(DestAlign.getQuantity())
10563 << TRange << Op->getSourceRange();
10566 /// \brief Check whether this array fits the idiom of a size-one tail padded
10567 /// array member of a struct.
10569 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
10570 /// commonly used to emulate flexible arrays in C89 code.
10571 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
10572 const NamedDecl *ND) {
10573 if (Size != 1 || !ND) return false;
10575 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
10576 if (!FD) return false;
10578 // Don't consider sizes resulting from macro expansions or template argument
10579 // substitution to form C89 tail-padded arrays.
10581 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
10583 TypeLoc TL = TInfo->getTypeLoc();
10584 // Look through typedefs.
10585 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
10586 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
10587 TInfo = TDL->getTypeSourceInfo();
10590 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
10591 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
10592 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
10598 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
10599 if (!RD) return false;
10600 if (RD->isUnion()) return false;
10601 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10602 if (!CRD->isStandardLayout()) return false;
10605 // See if this is the last field decl in the record.
10606 const Decl *D = FD;
10607 while ((D = D->getNextDeclInContext()))
10608 if (isa<FieldDecl>(D))
10613 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
10614 const ArraySubscriptExpr *ASE,
10615 bool AllowOnePastEnd, bool IndexNegated) {
10616 IndexExpr = IndexExpr->IgnoreParenImpCasts();
10617 if (IndexExpr->isValueDependent())
10620 const Type *EffectiveType =
10621 BaseExpr->getType()->getPointeeOrArrayElementType();
10622 BaseExpr = BaseExpr->IgnoreParenCasts();
10623 const ConstantArrayType *ArrayTy =
10624 Context.getAsConstantArrayType(BaseExpr->getType());
10628 llvm::APSInt index;
10629 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
10634 const NamedDecl *ND = nullptr;
10635 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10636 ND = dyn_cast<NamedDecl>(DRE->getDecl());
10637 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
10638 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
10640 if (index.isUnsigned() || !index.isNegative()) {
10641 llvm::APInt size = ArrayTy->getSize();
10642 if (!size.isStrictlyPositive())
10645 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
10646 if (BaseType != EffectiveType) {
10647 // Make sure we're comparing apples to apples when comparing index to size
10648 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
10649 uint64_t array_typesize = Context.getTypeSize(BaseType);
10650 // Handle ptrarith_typesize being zero, such as when casting to void*
10651 if (!ptrarith_typesize) ptrarith_typesize = 1;
10652 if (ptrarith_typesize != array_typesize) {
10653 // There's a cast to a different size type involved
10654 uint64_t ratio = array_typesize / ptrarith_typesize;
10655 // TODO: Be smarter about handling cases where array_typesize is not a
10656 // multiple of ptrarith_typesize
10657 if (ptrarith_typesize * ratio == array_typesize)
10658 size *= llvm::APInt(size.getBitWidth(), ratio);
10662 if (size.getBitWidth() > index.getBitWidth())
10663 index = index.zext(size.getBitWidth());
10664 else if (size.getBitWidth() < index.getBitWidth())
10665 size = size.zext(index.getBitWidth());
10667 // For array subscripting the index must be less than size, but for pointer
10668 // arithmetic also allow the index (offset) to be equal to size since
10669 // computing the next address after the end of the array is legal and
10670 // commonly done e.g. in C++ iterators and range-based for loops.
10671 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
10674 // Also don't warn for arrays of size 1 which are members of some
10675 // structure. These are often used to approximate flexible arrays in C89
10677 if (IsTailPaddedMemberArray(*this, size, ND))
10680 // Suppress the warning if the subscript expression (as identified by the
10681 // ']' location) and the index expression are both from macro expansions
10682 // within a system header.
10684 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
10685 ASE->getRBracketLoc());
10686 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
10687 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
10688 IndexExpr->getLocStart());
10689 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
10694 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
10696 DiagID = diag::warn_array_index_exceeds_bounds;
10698 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10699 PDiag(DiagID) << index.toString(10, true)
10700 << size.toString(10, true)
10701 << (unsigned)size.getLimitedValue(~0U)
10702 << IndexExpr->getSourceRange());
10704 unsigned DiagID = diag::warn_array_index_precedes_bounds;
10706 DiagID = diag::warn_ptr_arith_precedes_bounds;
10707 if (index.isNegative()) index = -index;
10710 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10711 PDiag(DiagID) << index.toString(10, true)
10712 << IndexExpr->getSourceRange());
10716 // Try harder to find a NamedDecl to point at in the note.
10717 while (const ArraySubscriptExpr *ASE =
10718 dyn_cast<ArraySubscriptExpr>(BaseExpr))
10719 BaseExpr = ASE->getBase()->IgnoreParenCasts();
10720 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10721 ND = dyn_cast<NamedDecl>(DRE->getDecl());
10722 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
10723 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
10727 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
10728 PDiag(diag::note_array_index_out_of_bounds)
10729 << ND->getDeclName());
10732 void Sema::CheckArrayAccess(const Expr *expr) {
10733 int AllowOnePastEnd = 0;
10735 expr = expr->IgnoreParenImpCasts();
10736 switch (expr->getStmtClass()) {
10737 case Stmt::ArraySubscriptExprClass: {
10738 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
10739 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
10740 AllowOnePastEnd > 0);
10743 case Stmt::OMPArraySectionExprClass: {
10744 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
10745 if (ASE->getLowerBound())
10746 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
10747 /*ASE=*/nullptr, AllowOnePastEnd > 0);
10750 case Stmt::UnaryOperatorClass: {
10751 // Only unwrap the * and & unary operators
10752 const UnaryOperator *UO = cast<UnaryOperator>(expr);
10753 expr = UO->getSubExpr();
10754 switch (UO->getOpcode()) {
10766 case Stmt::ConditionalOperatorClass: {
10767 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
10768 if (const Expr *lhs = cond->getLHS())
10769 CheckArrayAccess(lhs);
10770 if (const Expr *rhs = cond->getRHS())
10771 CheckArrayAccess(rhs);
10774 case Stmt::CXXOperatorCallExprClass: {
10775 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
10776 for (const auto *Arg : OCE->arguments())
10777 CheckArrayAccess(Arg);
10786 //===--- CHECK: Objective-C retain cycles ----------------------------------//
10789 struct RetainCycleOwner {
10790 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
10793 SourceLocation Loc;
10796 void setLocsFrom(Expr *e) {
10797 Loc = e->getExprLoc();
10798 Range = e->getSourceRange();
10801 } // end anonymous namespace
10803 /// Consider whether capturing the given variable can possibly lead to
10804 /// a retain cycle.
10805 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
10806 // In ARC, it's captured strongly iff the variable has __strong
10807 // lifetime. In MRR, it's captured strongly if the variable is
10808 // __block and has an appropriate type.
10809 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10812 owner.Variable = var;
10814 owner.setLocsFrom(ref);
10818 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
10820 e = e->IgnoreParens();
10821 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
10822 switch (cast->getCastKind()) {
10824 case CK_LValueBitCast:
10825 case CK_LValueToRValue:
10826 case CK_ARCReclaimReturnedObject:
10827 e = cast->getSubExpr();
10835 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
10836 ObjCIvarDecl *ivar = ref->getDecl();
10837 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10840 // Try to find a retain cycle in the base.
10841 if (!findRetainCycleOwner(S, ref->getBase(), owner))
10844 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
10845 owner.Indirect = true;
10849 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
10850 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
10851 if (!var) return false;
10852 return considerVariable(var, ref, owner);
10855 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
10856 if (member->isArrow()) return false;
10858 // Don't count this as an indirect ownership.
10859 e = member->getBase();
10863 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
10864 // Only pay attention to pseudo-objects on property references.
10865 ObjCPropertyRefExpr *pre
10866 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
10868 if (!pre) return false;
10869 if (pre->isImplicitProperty()) return false;
10870 ObjCPropertyDecl *property = pre->getExplicitProperty();
10871 if (!property->isRetaining() &&
10872 !(property->getPropertyIvarDecl() &&
10873 property->getPropertyIvarDecl()->getType()
10874 .getObjCLifetime() == Qualifiers::OCL_Strong))
10877 owner.Indirect = true;
10878 if (pre->isSuperReceiver()) {
10879 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
10880 if (!owner.Variable)
10882 owner.Loc = pre->getLocation();
10883 owner.Range = pre->getSourceRange();
10886 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
10887 ->getSourceExpr());
10898 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
10899 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
10900 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
10901 Context(Context), Variable(variable), Capturer(nullptr),
10902 VarWillBeReased(false) {}
10903 ASTContext &Context;
10906 bool VarWillBeReased;
10908 void VisitDeclRefExpr(DeclRefExpr *ref) {
10909 if (ref->getDecl() == Variable && !Capturer)
10913 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
10914 if (Capturer) return;
10915 Visit(ref->getBase());
10916 if (Capturer && ref->isFreeIvar())
10920 void VisitBlockExpr(BlockExpr *block) {
10921 // Look inside nested blocks
10922 if (block->getBlockDecl()->capturesVariable(Variable))
10923 Visit(block->getBlockDecl()->getBody());
10926 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
10927 if (Capturer) return;
10928 if (OVE->getSourceExpr())
10929 Visit(OVE->getSourceExpr());
10931 void VisitBinaryOperator(BinaryOperator *BinOp) {
10932 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
10934 Expr *LHS = BinOp->getLHS();
10935 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
10936 if (DRE->getDecl() != Variable)
10938 if (Expr *RHS = BinOp->getRHS()) {
10939 RHS = RHS->IgnoreParenCasts();
10940 llvm::APSInt Value;
10942 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
10947 } // end anonymous namespace
10949 /// Check whether the given argument is a block which captures a
10951 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
10952 assert(owner.Variable && owner.Loc.isValid());
10954 e = e->IgnoreParenCasts();
10956 // Look through [^{...} copy] and Block_copy(^{...}).
10957 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
10958 Selector Cmd = ME->getSelector();
10959 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
10960 e = ME->getInstanceReceiver();
10963 e = e->IgnoreParenCasts();
10965 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
10966 if (CE->getNumArgs() == 1) {
10967 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
10969 const IdentifierInfo *FnI = Fn->getIdentifier();
10970 if (FnI && FnI->isStr("_Block_copy")) {
10971 e = CE->getArg(0)->IgnoreParenCasts();
10977 BlockExpr *block = dyn_cast<BlockExpr>(e);
10978 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
10981 FindCaptureVisitor visitor(S.Context, owner.Variable);
10982 visitor.Visit(block->getBlockDecl()->getBody());
10983 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
10986 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
10987 RetainCycleOwner &owner) {
10989 assert(owner.Variable && owner.Loc.isValid());
10991 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
10992 << owner.Variable << capturer->getSourceRange();
10993 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
10994 << owner.Indirect << owner.Range;
10997 /// Check for a keyword selector that starts with the word 'add' or
10999 static bool isSetterLikeSelector(Selector sel) {
11000 if (sel.isUnarySelector()) return false;
11002 StringRef str = sel.getNameForSlot(0);
11003 while (!str.empty() && str.front() == '_') str = str.substr(1);
11004 if (str.startswith("set"))
11005 str = str.substr(3);
11006 else if (str.startswith("add")) {
11007 // Specially whitelist 'addOperationWithBlock:'.
11008 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
11010 str = str.substr(3);
11015 if (str.empty()) return true;
11016 return !isLowercase(str.front());
11019 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
11020 ObjCMessageExpr *Message) {
11021 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
11022 Message->getReceiverInterface(),
11023 NSAPI::ClassId_NSMutableArray);
11024 if (!IsMutableArray) {
11028 Selector Sel = Message->getSelector();
11030 Optional<NSAPI::NSArrayMethodKind> MKOpt =
11031 S.NSAPIObj->getNSArrayMethodKind(Sel);
11036 NSAPI::NSArrayMethodKind MK = *MKOpt;
11039 case NSAPI::NSMutableArr_addObject:
11040 case NSAPI::NSMutableArr_insertObjectAtIndex:
11041 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
11043 case NSAPI::NSMutableArr_replaceObjectAtIndex:
11054 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
11055 ObjCMessageExpr *Message) {
11056 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
11057 Message->getReceiverInterface(),
11058 NSAPI::ClassId_NSMutableDictionary);
11059 if (!IsMutableDictionary) {
11063 Selector Sel = Message->getSelector();
11065 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
11066 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
11071 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
11074 case NSAPI::NSMutableDict_setObjectForKey:
11075 case NSAPI::NSMutableDict_setValueForKey:
11076 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
11086 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
11087 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
11088 Message->getReceiverInterface(),
11089 NSAPI::ClassId_NSMutableSet);
11091 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
11092 Message->getReceiverInterface(),
11093 NSAPI::ClassId_NSMutableOrderedSet);
11094 if (!IsMutableSet && !IsMutableOrderedSet) {
11098 Selector Sel = Message->getSelector();
11100 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
11105 NSAPI::NSSetMethodKind MK = *MKOpt;
11108 case NSAPI::NSMutableSet_addObject:
11109 case NSAPI::NSOrderedSet_setObjectAtIndex:
11110 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
11111 case NSAPI::NSOrderedSet_insertObjectAtIndex:
11113 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
11120 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
11121 if (!Message->isInstanceMessage()) {
11125 Optional<int> ArgOpt;
11127 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
11128 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
11129 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
11133 int ArgIndex = *ArgOpt;
11135 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
11136 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
11137 Arg = OE->getSourceExpr()->IgnoreImpCasts();
11140 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
11141 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
11142 if (ArgRE->isObjCSelfExpr()) {
11143 Diag(Message->getSourceRange().getBegin(),
11144 diag::warn_objc_circular_container)
11145 << ArgRE->getDecl()->getName() << StringRef("super");
11149 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
11151 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
11152 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
11155 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
11156 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
11157 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
11158 ValueDecl *Decl = ReceiverRE->getDecl();
11159 Diag(Message->getSourceRange().getBegin(),
11160 diag::warn_objc_circular_container)
11161 << Decl->getName() << Decl->getName();
11162 if (!ArgRE->isObjCSelfExpr()) {
11163 Diag(Decl->getLocation(),
11164 diag::note_objc_circular_container_declared_here)
11165 << Decl->getName();
11169 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
11170 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
11171 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
11172 ObjCIvarDecl *Decl = IvarRE->getDecl();
11173 Diag(Message->getSourceRange().getBegin(),
11174 diag::warn_objc_circular_container)
11175 << Decl->getName() << Decl->getName();
11176 Diag(Decl->getLocation(),
11177 diag::note_objc_circular_container_declared_here)
11178 << Decl->getName();
11185 /// Check a message send to see if it's likely to cause a retain cycle.
11186 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
11187 // Only check instance methods whose selector looks like a setter.
11188 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
11191 // Try to find a variable that the receiver is strongly owned by.
11192 RetainCycleOwner owner;
11193 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
11194 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
11197 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
11198 owner.Variable = getCurMethodDecl()->getSelfDecl();
11199 owner.Loc = msg->getSuperLoc();
11200 owner.Range = msg->getSuperLoc();
11203 // Check whether the receiver is captured by any of the arguments.
11204 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
11205 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
11206 return diagnoseRetainCycle(*this, capturer, owner);
11209 /// Check a property assign to see if it's likely to cause a retain cycle.
11210 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
11211 RetainCycleOwner owner;
11212 if (!findRetainCycleOwner(*this, receiver, owner))
11215 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
11216 diagnoseRetainCycle(*this, capturer, owner);
11219 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
11220 RetainCycleOwner Owner;
11221 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
11224 // Because we don't have an expression for the variable, we have to set the
11225 // location explicitly here.
11226 Owner.Loc = Var->getLocation();
11227 Owner.Range = Var->getSourceRange();
11229 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
11230 diagnoseRetainCycle(*this, Capturer, Owner);
11233 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
11234 Expr *RHS, bool isProperty) {
11235 // Check if RHS is an Objective-C object literal, which also can get
11236 // immediately zapped in a weak reference. Note that we explicitly
11237 // allow ObjCStringLiterals, since those are designed to never really die.
11238 RHS = RHS->IgnoreParenImpCasts();
11240 // This enum needs to match with the 'select' in
11241 // warn_objc_arc_literal_assign (off-by-1).
11242 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
11243 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
11246 S.Diag(Loc, diag::warn_arc_literal_assign)
11248 << (isProperty ? 0 : 1)
11249 << RHS->getSourceRange();
11254 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
11255 Qualifiers::ObjCLifetime LT,
11256 Expr *RHS, bool isProperty) {
11257 // Strip off any implicit cast added to get to the one ARC-specific.
11258 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11259 if (cast->getCastKind() == CK_ARCConsumeObject) {
11260 S.Diag(Loc, diag::warn_arc_retained_assign)
11261 << (LT == Qualifiers::OCL_ExplicitNone)
11262 << (isProperty ? 0 : 1)
11263 << RHS->getSourceRange();
11266 RHS = cast->getSubExpr();
11269 if (LT == Qualifiers::OCL_Weak &&
11270 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
11276 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
11277 QualType LHS, Expr *RHS) {
11278 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
11280 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
11283 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
11289 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
11290 Expr *LHS, Expr *RHS) {
11292 // PropertyRef on LHS type need be directly obtained from
11293 // its declaration as it has a PseudoType.
11294 ObjCPropertyRefExpr *PRE
11295 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
11296 if (PRE && !PRE->isImplicitProperty()) {
11297 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11299 LHSType = PD->getType();
11302 if (LHSType.isNull())
11303 LHSType = LHS->getType();
11305 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
11307 if (LT == Qualifiers::OCL_Weak) {
11308 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
11309 getCurFunction()->markSafeWeakUse(LHS);
11312 if (checkUnsafeAssigns(Loc, LHSType, RHS))
11315 // FIXME. Check for other life times.
11316 if (LT != Qualifiers::OCL_None)
11320 if (PRE->isImplicitProperty())
11322 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11326 unsigned Attributes = PD->getPropertyAttributes();
11327 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
11328 // when 'assign' attribute was not explicitly specified
11329 // by user, ignore it and rely on property type itself
11330 // for lifetime info.
11331 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
11332 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
11333 LHSType->isObjCRetainableType())
11336 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11337 if (cast->getCastKind() == CK_ARCConsumeObject) {
11338 Diag(Loc, diag::warn_arc_retained_property_assign)
11339 << RHS->getSourceRange();
11342 RHS = cast->getSubExpr();
11345 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
11346 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
11352 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
11355 bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
11356 SourceLocation StmtLoc,
11357 const NullStmt *Body) {
11358 // Do not warn if the body is a macro that expands to nothing, e.g:
11364 if (Body->hasLeadingEmptyMacro())
11367 // Get line numbers of statement and body.
11368 bool StmtLineInvalid;
11369 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
11371 if (StmtLineInvalid)
11374 bool BodyLineInvalid;
11375 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
11377 if (BodyLineInvalid)
11380 // Warn if null statement and body are on the same line.
11381 if (StmtLine != BodyLine)
11386 } // end anonymous namespace
11388 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
11391 // Since this is a syntactic check, don't emit diagnostic for template
11392 // instantiations, this just adds noise.
11393 if (CurrentInstantiationScope)
11396 // The body should be a null statement.
11397 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11401 // Do the usual checks.
11402 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11405 Diag(NBody->getSemiLoc(), DiagID);
11406 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11409 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
11410 const Stmt *PossibleBody) {
11411 assert(!CurrentInstantiationScope); // Ensured by caller
11413 SourceLocation StmtLoc;
11416 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
11417 StmtLoc = FS->getRParenLoc();
11418 Body = FS->getBody();
11419 DiagID = diag::warn_empty_for_body;
11420 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
11421 StmtLoc = WS->getCond()->getSourceRange().getEnd();
11422 Body = WS->getBody();
11423 DiagID = diag::warn_empty_while_body;
11425 return; // Neither `for' nor `while'.
11427 // The body should be a null statement.
11428 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11432 // Skip expensive checks if diagnostic is disabled.
11433 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
11436 // Do the usual checks.
11437 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11440 // `for(...);' and `while(...);' are popular idioms, so in order to keep
11441 // noise level low, emit diagnostics only if for/while is followed by a
11442 // CompoundStmt, e.g.:
11443 // for (int i = 0; i < n; i++);
11447 // or if for/while is followed by a statement with more indentation
11448 // than for/while itself:
11449 // for (int i = 0; i < n; i++);
11451 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
11452 if (!ProbableTypo) {
11453 bool BodyColInvalid;
11454 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
11455 PossibleBody->getLocStart(),
11457 if (BodyColInvalid)
11460 bool StmtColInvalid;
11461 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
11464 if (StmtColInvalid)
11467 if (BodyCol > StmtCol)
11468 ProbableTypo = true;
11471 if (ProbableTypo) {
11472 Diag(NBody->getSemiLoc(), DiagID);
11473 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11477 //===--- CHECK: Warn on self move with std::move. -------------------------===//
11479 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
11480 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
11481 SourceLocation OpLoc) {
11482 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
11485 if (inTemplateInstantiation())
11488 // Strip parens and casts away.
11489 LHSExpr = LHSExpr->IgnoreParenImpCasts();
11490 RHSExpr = RHSExpr->IgnoreParenImpCasts();
11492 // Check for a call expression
11493 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
11494 if (!CE || CE->getNumArgs() != 1)
11497 // Check for a call to std::move
11498 const FunctionDecl *FD = CE->getDirectCallee();
11499 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
11500 !FD->getIdentifier()->isStr("move"))
11503 // Get argument from std::move
11504 RHSExpr = CE->getArg(0);
11506 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11507 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11509 // Two DeclRefExpr's, check that the decls are the same.
11510 if (LHSDeclRef && RHSDeclRef) {
11511 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11513 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11514 RHSDeclRef->getDecl()->getCanonicalDecl())
11517 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11518 << LHSExpr->getSourceRange()
11519 << RHSExpr->getSourceRange();
11523 // Member variables require a different approach to check for self moves.
11524 // MemberExpr's are the same if every nested MemberExpr refers to the same
11525 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
11526 // the base Expr's are CXXThisExpr's.
11527 const Expr *LHSBase = LHSExpr;
11528 const Expr *RHSBase = RHSExpr;
11529 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
11530 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
11531 if (!LHSME || !RHSME)
11534 while (LHSME && RHSME) {
11535 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
11536 RHSME->getMemberDecl()->getCanonicalDecl())
11539 LHSBase = LHSME->getBase();
11540 RHSBase = RHSME->getBase();
11541 LHSME = dyn_cast<MemberExpr>(LHSBase);
11542 RHSME = dyn_cast<MemberExpr>(RHSBase);
11545 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
11546 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
11547 if (LHSDeclRef && RHSDeclRef) {
11548 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11550 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11551 RHSDeclRef->getDecl()->getCanonicalDecl())
11554 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11555 << LHSExpr->getSourceRange()
11556 << RHSExpr->getSourceRange();
11560 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
11561 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11562 << LHSExpr->getSourceRange()
11563 << RHSExpr->getSourceRange();
11566 //===--- Layout compatibility ----------------------------------------------//
11570 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
11572 /// \brief Check if two enumeration types are layout-compatible.
11573 bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
11574 // C++11 [dcl.enum] p8:
11575 // Two enumeration types are layout-compatible if they have the same
11576 // underlying type.
11577 return ED1->isComplete() && ED2->isComplete() &&
11578 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
11581 /// \brief Check if two fields are layout-compatible.
11582 bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
11583 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
11586 if (Field1->isBitField() != Field2->isBitField())
11589 if (Field1->isBitField()) {
11590 // Make sure that the bit-fields are the same length.
11591 unsigned Bits1 = Field1->getBitWidthValue(C);
11592 unsigned Bits2 = Field2->getBitWidthValue(C);
11594 if (Bits1 != Bits2)
11601 /// \brief Check if two standard-layout structs are layout-compatible.
11602 /// (C++11 [class.mem] p17)
11603 bool isLayoutCompatibleStruct(ASTContext &C,
11606 // If both records are C++ classes, check that base classes match.
11607 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
11608 // If one of records is a CXXRecordDecl we are in C++ mode,
11609 // thus the other one is a CXXRecordDecl, too.
11610 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
11611 // Check number of base classes.
11612 if (D1CXX->getNumBases() != D2CXX->getNumBases())
11615 // Check the base classes.
11616 for (CXXRecordDecl::base_class_const_iterator
11617 Base1 = D1CXX->bases_begin(),
11618 BaseEnd1 = D1CXX->bases_end(),
11619 Base2 = D2CXX->bases_begin();
11621 ++Base1, ++Base2) {
11622 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
11625 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
11626 // If only RD2 is a C++ class, it should have zero base classes.
11627 if (D2CXX->getNumBases() > 0)
11631 // Check the fields.
11632 RecordDecl::field_iterator Field2 = RD2->field_begin(),
11633 Field2End = RD2->field_end(),
11634 Field1 = RD1->field_begin(),
11635 Field1End = RD1->field_end();
11636 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
11637 if (!isLayoutCompatible(C, *Field1, *Field2))
11640 if (Field1 != Field1End || Field2 != Field2End)
11646 /// \brief Check if two standard-layout unions are layout-compatible.
11647 /// (C++11 [class.mem] p18)
11648 bool isLayoutCompatibleUnion(ASTContext &C,
11651 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
11652 for (auto *Field2 : RD2->fields())
11653 UnmatchedFields.insert(Field2);
11655 for (auto *Field1 : RD1->fields()) {
11656 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
11657 I = UnmatchedFields.begin(),
11658 E = UnmatchedFields.end();
11660 for ( ; I != E; ++I) {
11661 if (isLayoutCompatible(C, Field1, *I)) {
11662 bool Result = UnmatchedFields.erase(*I);
11672 return UnmatchedFields.empty();
11675 bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
11676 if (RD1->isUnion() != RD2->isUnion())
11679 if (RD1->isUnion())
11680 return isLayoutCompatibleUnion(C, RD1, RD2);
11682 return isLayoutCompatibleStruct(C, RD1, RD2);
11685 /// \brief Check if two types are layout-compatible in C++11 sense.
11686 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
11687 if (T1.isNull() || T2.isNull())
11690 // C++11 [basic.types] p11:
11691 // If two types T1 and T2 are the same type, then T1 and T2 are
11692 // layout-compatible types.
11693 if (C.hasSameType(T1, T2))
11696 T1 = T1.getCanonicalType().getUnqualifiedType();
11697 T2 = T2.getCanonicalType().getUnqualifiedType();
11699 const Type::TypeClass TC1 = T1->getTypeClass();
11700 const Type::TypeClass TC2 = T2->getTypeClass();
11705 if (TC1 == Type::Enum) {
11706 return isLayoutCompatible(C,
11707 cast<EnumType>(T1)->getDecl(),
11708 cast<EnumType>(T2)->getDecl());
11709 } else if (TC1 == Type::Record) {
11710 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
11713 return isLayoutCompatible(C,
11714 cast<RecordType>(T1)->getDecl(),
11715 cast<RecordType>(T2)->getDecl());
11720 } // end anonymous namespace
11722 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
11725 /// \brief Given a type tag expression find the type tag itself.
11727 /// \param TypeExpr Type tag expression, as it appears in user's code.
11729 /// \param VD Declaration of an identifier that appears in a type tag.
11731 /// \param MagicValue Type tag magic value.
11732 bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
11733 const ValueDecl **VD, uint64_t *MagicValue) {
11738 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
11740 switch (TypeExpr->getStmtClass()) {
11741 case Stmt::UnaryOperatorClass: {
11742 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
11743 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
11744 TypeExpr = UO->getSubExpr();
11750 case Stmt::DeclRefExprClass: {
11751 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
11752 *VD = DRE->getDecl();
11756 case Stmt::IntegerLiteralClass: {
11757 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
11758 llvm::APInt MagicValueAPInt = IL->getValue();
11759 if (MagicValueAPInt.getActiveBits() <= 64) {
11760 *MagicValue = MagicValueAPInt.getZExtValue();
11766 case Stmt::BinaryConditionalOperatorClass:
11767 case Stmt::ConditionalOperatorClass: {
11768 const AbstractConditionalOperator *ACO =
11769 cast<AbstractConditionalOperator>(TypeExpr);
11771 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
11773 TypeExpr = ACO->getTrueExpr();
11775 TypeExpr = ACO->getFalseExpr();
11781 case Stmt::BinaryOperatorClass: {
11782 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
11783 if (BO->getOpcode() == BO_Comma) {
11784 TypeExpr = BO->getRHS();
11796 /// \brief Retrieve the C type corresponding to type tag TypeExpr.
11798 /// \param TypeExpr Expression that specifies a type tag.
11800 /// \param MagicValues Registered magic values.
11802 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
11805 /// \param TypeInfo Information about the corresponding C type.
11807 /// \returns true if the corresponding C type was found.
11808 bool GetMatchingCType(
11809 const IdentifierInfo *ArgumentKind,
11810 const Expr *TypeExpr, const ASTContext &Ctx,
11811 const llvm::DenseMap<Sema::TypeTagMagicValue,
11812 Sema::TypeTagData> *MagicValues,
11813 bool &FoundWrongKind,
11814 Sema::TypeTagData &TypeInfo) {
11815 FoundWrongKind = false;
11817 // Variable declaration that has type_tag_for_datatype attribute.
11818 const ValueDecl *VD = nullptr;
11820 uint64_t MagicValue;
11822 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
11826 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
11827 if (I->getArgumentKind() != ArgumentKind) {
11828 FoundWrongKind = true;
11831 TypeInfo.Type = I->getMatchingCType();
11832 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
11833 TypeInfo.MustBeNull = I->getMustBeNull();
11842 llvm::DenseMap<Sema::TypeTagMagicValue,
11843 Sema::TypeTagData>::const_iterator I =
11844 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
11845 if (I == MagicValues->end())
11848 TypeInfo = I->second;
11851 } // end anonymous namespace
11853 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
11854 uint64_t MagicValue, QualType Type,
11855 bool LayoutCompatible,
11857 if (!TypeTagForDatatypeMagicValues)
11858 TypeTagForDatatypeMagicValues.reset(
11859 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
11861 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
11862 (*TypeTagForDatatypeMagicValues)[Magic] =
11863 TypeTagData(Type, LayoutCompatible, MustBeNull);
11867 bool IsSameCharType(QualType T1, QualType T2) {
11868 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
11872 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
11876 BuiltinType::Kind T1Kind = BT1->getKind();
11877 BuiltinType::Kind T2Kind = BT2->getKind();
11879 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
11880 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
11881 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
11882 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
11884 } // end anonymous namespace
11886 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
11887 const Expr * const *ExprArgs) {
11888 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
11889 bool IsPointerAttr = Attr->getIsPointer();
11891 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
11892 bool FoundWrongKind;
11893 TypeTagData TypeInfo;
11894 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
11895 TypeTagForDatatypeMagicValues.get(),
11896 FoundWrongKind, TypeInfo)) {
11897 if (FoundWrongKind)
11898 Diag(TypeTagExpr->getExprLoc(),
11899 diag::warn_type_tag_for_datatype_wrong_kind)
11900 << TypeTagExpr->getSourceRange();
11904 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
11905 if (IsPointerAttr) {
11906 // Skip implicit cast of pointer to `void *' (as a function argument).
11907 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
11908 if (ICE->getType()->isVoidPointerType() &&
11909 ICE->getCastKind() == CK_BitCast)
11910 ArgumentExpr = ICE->getSubExpr();
11912 QualType ArgumentType = ArgumentExpr->getType();
11914 // Passing a `void*' pointer shouldn't trigger a warning.
11915 if (IsPointerAttr && ArgumentType->isVoidPointerType())
11918 if (TypeInfo.MustBeNull) {
11919 // Type tag with matching void type requires a null pointer.
11920 if (!ArgumentExpr->isNullPointerConstant(Context,
11921 Expr::NPC_ValueDependentIsNotNull)) {
11922 Diag(ArgumentExpr->getExprLoc(),
11923 diag::warn_type_safety_null_pointer_required)
11924 << ArgumentKind->getName()
11925 << ArgumentExpr->getSourceRange()
11926 << TypeTagExpr->getSourceRange();
11931 QualType RequiredType = TypeInfo.Type;
11933 RequiredType = Context.getPointerType(RequiredType);
11935 bool mismatch = false;
11936 if (!TypeInfo.LayoutCompatible) {
11937 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
11939 // C++11 [basic.fundamental] p1:
11940 // Plain char, signed char, and unsigned char are three distinct types.
11942 // But we treat plain `char' as equivalent to `signed char' or `unsigned
11943 // char' depending on the current char signedness mode.
11945 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
11946 RequiredType->getPointeeType())) ||
11947 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
11951 mismatch = !isLayoutCompatible(Context,
11952 ArgumentType->getPointeeType(),
11953 RequiredType->getPointeeType());
11955 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
11958 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
11959 << ArgumentType << ArgumentKind
11960 << TypeInfo.LayoutCompatible << RequiredType
11961 << ArgumentExpr->getSourceRange()
11962 << TypeTagExpr->getSourceRange();
11965 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
11966 CharUnits Alignment) {
11967 MisalignedMembers.emplace_back(E, RD, MD, Alignment);
11970 void Sema::DiagnoseMisalignedMembers() {
11971 for (MisalignedMember &m : MisalignedMembers) {
11972 const NamedDecl *ND = m.RD;
11973 if (ND->getName().empty()) {
11974 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
11977 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
11978 << m.MD << ND << m.E->getSourceRange();
11980 MisalignedMembers.clear();
11983 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
11984 E = E->IgnoreParens();
11985 if (!T->isPointerType() && !T->isIntegerType())
11987 if (isa<UnaryOperator>(E) &&
11988 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
11989 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
11990 if (isa<MemberExpr>(Op)) {
11991 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
11992 MisalignedMember(Op));
11993 if (MA != MisalignedMembers.end() &&
11994 (T->isIntegerType() ||
11995 (T->isPointerType() &&
11996 Context.getTypeAlignInChars(T->getPointeeType()) <= MA->Alignment)))
11997 MisalignedMembers.erase(MA);
12002 void Sema::RefersToMemberWithReducedAlignment(
12004 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
12006 const auto *ME = dyn_cast<MemberExpr>(E);
12010 // No need to check expressions with an __unaligned-qualified type.
12011 if (E->getType().getQualifiers().hasUnaligned())
12014 // For a chain of MemberExpr like "a.b.c.d" this list
12015 // will keep FieldDecl's like [d, c, b].
12016 SmallVector<FieldDecl *, 4> ReverseMemberChain;
12017 const MemberExpr *TopME = nullptr;
12018 bool AnyIsPacked = false;
12020 QualType BaseType = ME->getBase()->getType();
12022 BaseType = BaseType->getPointeeType();
12023 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
12025 ValueDecl *MD = ME->getMemberDecl();
12026 auto *FD = dyn_cast<FieldDecl>(MD);
12027 // We do not care about non-data members.
12028 if (!FD || FD->isInvalidDecl())
12032 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
12033 ReverseMemberChain.push_back(FD);
12036 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
12038 assert(TopME && "We did not compute a topmost MemberExpr!");
12040 // Not the scope of this diagnostic.
12044 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
12045 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
12046 // TODO: The innermost base of the member expression may be too complicated.
12047 // For now, just disregard these cases. This is left for future
12049 if (!DRE && !isa<CXXThisExpr>(TopBase))
12052 // Alignment expected by the whole expression.
12053 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
12055 // No need to do anything else with this case.
12056 if (ExpectedAlignment.isOne())
12059 // Synthesize offset of the whole access.
12061 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
12063 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
12066 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
12067 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
12068 ReverseMemberChain.back()->getParent()->getTypeForDecl());
12070 // The base expression of the innermost MemberExpr may give
12071 // stronger guarantees than the class containing the member.
12072 if (DRE && !TopME->isArrow()) {
12073 const ValueDecl *VD = DRE->getDecl();
12074 if (!VD->getType()->isReferenceType())
12075 CompleteObjectAlignment =
12076 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
12079 // Check if the synthesized offset fulfills the alignment.
12080 if (Offset % ExpectedAlignment != 0 ||
12081 // It may fulfill the offset it but the effective alignment may still be
12082 // lower than the expected expression alignment.
12083 CompleteObjectAlignment < ExpectedAlignment) {
12084 // If this happens, we want to determine a sensible culprit of this.
12085 // Intuitively, watching the chain of member expressions from right to
12086 // left, we start with the required alignment (as required by the field
12087 // type) but some packed attribute in that chain has reduced the alignment.
12088 // It may happen that another packed structure increases it again. But if
12089 // we are here such increase has not been enough. So pointing the first
12090 // FieldDecl that either is packed or else its RecordDecl is,
12091 // seems reasonable.
12092 FieldDecl *FD = nullptr;
12093 CharUnits Alignment;
12094 for (FieldDecl *FDI : ReverseMemberChain) {
12095 if (FDI->hasAttr<PackedAttr>() ||
12096 FDI->getParent()->hasAttr<PackedAttr>()) {
12098 Alignment = std::min(
12099 Context.getTypeAlignInChars(FD->getType()),
12100 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
12104 assert(FD && "We did not find a packed FieldDecl!");
12105 Action(E, FD->getParent(), FD, Alignment);
12109 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
12110 using namespace std::placeholders;
12111 RefersToMemberWithReducedAlignment(
12112 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,