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/Sema/Sema.h"
16 #include "clang/Sema/SemaInternal.h"
17 #include "clang/Sema/ScopeInfo.h"
18 #include "clang/Analysis/Analyses/FormatString.h"
19 #include "clang/AST/ASTContext.h"
20 #include "clang/AST/CharUnits.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/ExprCXX.h"
24 #include "clang/AST/ExprObjC.h"
25 #include "clang/AST/EvaluatedExprVisitor.h"
26 #include "clang/AST/DeclObjC.h"
27 #include "clang/AST/StmtCXX.h"
28 #include "clang/AST/StmtObjC.h"
29 #include "clang/Lex/Preprocessor.h"
30 #include "llvm/ADT/BitVector.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "clang/Basic/TargetBuiltins.h"
34 #include "clang/Basic/TargetInfo.h"
35 #include "clang/Basic/ConvertUTF.h"
37 using namespace clang
;
40 SourceLocation
Sema::getLocationOfStringLiteralByte(const StringLiteral
*SL
,
41 unsigned ByteNo
) const {
42 return SL
->getLocationOfByte(ByteNo
, PP
.getSourceManager(),
43 PP
.getLangOptions(), PP
.getTargetInfo());
47 /// CheckablePrintfAttr - does a function call have a "printf" attribute
48 /// and arguments that merit checking?
49 bool Sema::CheckablePrintfAttr(const FormatAttr
*Format
, CallExpr
*TheCall
) {
50 if (Format
->getType() == "printf") return true;
51 if (Format
->getType() == "printf0") {
52 // printf0 allows null "format" string; if so don't check format/args
53 unsigned format_idx
= Format
->getFormatIdx() - 1;
54 // Does the index refer to the implicit object argument?
55 if (isa
<CXXMemberCallExpr
>(TheCall
)) {
60 if (format_idx
< TheCall
->getNumArgs()) {
61 Expr
*Format
= TheCall
->getArg(format_idx
)->IgnoreParenCasts();
62 if (!Format
->isNullPointerConstant(Context
,
63 Expr::NPC_ValueDependentIsNull
))
70 /// Checks that a call expression's argument count is the desired number.
71 /// This is useful when doing custom type-checking. Returns true on error.
72 static bool checkArgCount(Sema
&S
, CallExpr
*call
, unsigned desiredArgCount
) {
73 unsigned argCount
= call
->getNumArgs();
74 if (argCount
== desiredArgCount
) return false;
76 if (argCount
< desiredArgCount
)
77 return S
.Diag(call
->getLocEnd(), diag::err_typecheck_call_too_few_args
)
78 << 0 /*function call*/ << desiredArgCount
<< argCount
79 << call
->getSourceRange();
81 // Highlight all the excess arguments.
82 SourceRange
range(call
->getArg(desiredArgCount
)->getLocStart(),
83 call
->getArg(argCount
- 1)->getLocEnd());
85 return S
.Diag(range
.getBegin(), diag::err_typecheck_call_too_many_args
)
86 << 0 /*function call*/ << desiredArgCount
<< argCount
87 << call
->getArg(1)->getSourceRange();
91 Sema::CheckBuiltinFunctionCall(unsigned BuiltinID
, CallExpr
*TheCall
) {
92 ExprResult
TheCallResult(Owned(TheCall
));
94 // Find out if any arguments are required to be integer constant expressions.
95 unsigned ICEArguments
= 0;
96 ASTContext::GetBuiltinTypeError Error
;
97 Context
.GetBuiltinType(BuiltinID
, Error
, &ICEArguments
);
98 if (Error
!= ASTContext::GE_None
)
99 ICEArguments
= 0; // Don't diagnose previously diagnosed errors.
101 // If any arguments are required to be ICE's, check and diagnose.
102 for (unsigned ArgNo
= 0; ICEArguments
!= 0; ++ArgNo
) {
103 // Skip arguments not required to be ICE's.
104 if ((ICEArguments
& (1 << ArgNo
)) == 0) continue;
107 if (SemaBuiltinConstantArg(TheCall
, ArgNo
, Result
))
109 ICEArguments
&= ~(1 << ArgNo
);
113 case Builtin::BI__builtin___CFStringMakeConstantString
:
114 assert(TheCall
->getNumArgs() == 1 &&
115 "Wrong # arguments to builtin CFStringMakeConstantString");
116 if (CheckObjCString(TheCall
->getArg(0)))
119 case Builtin::BI__builtin_stdarg_start
:
120 case Builtin::BI__builtin_va_start
:
121 if (SemaBuiltinVAStart(TheCall
))
124 case Builtin::BI__builtin_isgreater
:
125 case Builtin::BI__builtin_isgreaterequal
:
126 case Builtin::BI__builtin_isless
:
127 case Builtin::BI__builtin_islessequal
:
128 case Builtin::BI__builtin_islessgreater
:
129 case Builtin::BI__builtin_isunordered
:
130 if (SemaBuiltinUnorderedCompare(TheCall
))
133 case Builtin::BI__builtin_fpclassify
:
134 if (SemaBuiltinFPClassification(TheCall
, 6))
137 case Builtin::BI__builtin_isfinite
:
138 case Builtin::BI__builtin_isinf
:
139 case Builtin::BI__builtin_isinf_sign
:
140 case Builtin::BI__builtin_isnan
:
141 case Builtin::BI__builtin_isnormal
:
142 if (SemaBuiltinFPClassification(TheCall
, 1))
145 case Builtin::BI__builtin_shufflevector
:
146 return SemaBuiltinShuffleVector(TheCall
);
147 // TheCall will be freed by the smart pointer here, but that's fine, since
148 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
149 case Builtin::BI__builtin_prefetch
:
150 if (SemaBuiltinPrefetch(TheCall
))
153 case Builtin::BI__builtin_object_size
:
154 if (SemaBuiltinObjectSize(TheCall
))
157 case Builtin::BI__builtin_longjmp
:
158 if (SemaBuiltinLongjmp(TheCall
))
162 case Builtin::BI__builtin_classify_type
:
163 if (checkArgCount(*this, TheCall
, 1)) return true;
164 TheCall
->setType(Context
.IntTy
);
166 case Builtin::BI__builtin_constant_p
:
167 if (checkArgCount(*this, TheCall
, 1)) return true;
168 TheCall
->setType(Context
.IntTy
);
170 case Builtin::BI__sync_fetch_and_add
:
171 case Builtin::BI__sync_fetch_and_sub
:
172 case Builtin::BI__sync_fetch_and_or
:
173 case Builtin::BI__sync_fetch_and_and
:
174 case Builtin::BI__sync_fetch_and_xor
:
175 case Builtin::BI__sync_add_and_fetch
:
176 case Builtin::BI__sync_sub_and_fetch
:
177 case Builtin::BI__sync_and_and_fetch
:
178 case Builtin::BI__sync_or_and_fetch
:
179 case Builtin::BI__sync_xor_and_fetch
:
180 case Builtin::BI__sync_val_compare_and_swap
:
181 case Builtin::BI__sync_bool_compare_and_swap
:
182 case Builtin::BI__sync_lock_test_and_set
:
183 case Builtin::BI__sync_lock_release
:
184 case Builtin::BI__sync_swap
:
185 return SemaBuiltinAtomicOverloaded(move(TheCallResult
));
188 // Since the target specific builtins for each arch overlap, only check those
189 // of the arch we are compiling for.
190 if (BuiltinID
>= Builtin::FirstTSBuiltin
) {
191 switch (Context
.Target
.getTriple().getArch()) {
192 case llvm::Triple::arm
:
193 case llvm::Triple::thumb
:
194 if (CheckARMBuiltinFunctionCall(BuiltinID
, TheCall
))
202 return move(TheCallResult
);
205 // Get the valid immediate range for the specified NEON type code.
206 static unsigned RFT(unsigned t
, bool shift
= false) {
207 bool quad
= t
& 0x10;
211 return shift
? 7 : (8 << (int)quad
) - 1;
213 return shift
? 15 : (4 << (int)quad
) - 1;
215 return shift
? 31 : (2 << (int)quad
) - 1;
217 return shift
? 63 : (1 << (int)quad
) - 1;
219 assert(!shift
&& "cannot shift float types!");
220 return (2 << (int)quad
) - 1;
222 return shift
? 7 : (8 << (int)quad
) - 1;
224 return shift
? 15 : (4 << (int)quad
) - 1;
226 assert(!shift
&& "cannot shift float types!");
227 return (4 << (int)quad
) - 1;
232 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID
, CallExpr
*TheCall
) {
238 #define GET_NEON_OVERLOAD_CHECK
239 #include "clang/Basic/arm_neon.inc"
240 #undef GET_NEON_OVERLOAD_CHECK
243 // For NEON intrinsics which are overloaded on vector element type, validate
244 // the immediate which specifies which variant to emit.
246 unsigned ArgNo
= TheCall
->getNumArgs()-1;
247 if (SemaBuiltinConstantArg(TheCall
, ArgNo
, Result
))
250 TV
= Result
.getLimitedValue(32);
251 if ((TV
> 31) || (mask
& (1 << TV
)) == 0)
252 return Diag(TheCall
->getLocStart(), diag::err_invalid_neon_type_code
)
253 << TheCall
->getArg(ArgNo
)->getSourceRange();
256 // For NEON intrinsics which take an immediate value as part of the
257 // instruction, range check them here.
258 unsigned i
= 0, l
= 0, u
= 0;
260 default: return false;
261 case ARM::BI__builtin_arm_ssat
: i
= 1; l
= 1; u
= 31; break;
262 case ARM::BI__builtin_arm_usat
: i
= 1; u
= 31; break;
263 case ARM::BI__builtin_arm_vcvtr_f
:
264 case ARM::BI__builtin_arm_vcvtr_d
: i
= 1; u
= 1; break;
265 #define GET_NEON_IMMEDIATE_CHECK
266 #include "clang/Basic/arm_neon.inc"
267 #undef GET_NEON_IMMEDIATE_CHECK
270 // Check that the immediate argument is actually a constant.
271 if (SemaBuiltinConstantArg(TheCall
, i
, Result
))
274 // Range check against the upper/lower values for this isntruction.
275 unsigned Val
= Result
.getZExtValue();
276 if (Val
< l
|| Val
> (u
+ l
))
277 return Diag(TheCall
->getLocStart(), diag::err_argument_invalid_range
)
278 << l
<< u
+l
<< TheCall
->getArg(i
)->getSourceRange();
280 // FIXME: VFP Intrinsics should error if VFP not present.
284 /// CheckFunctionCall - Check a direct function call for various correctness
285 /// and safety properties not strictly enforced by the C type system.
286 bool Sema::CheckFunctionCall(FunctionDecl
*FDecl
, CallExpr
*TheCall
) {
287 // Get the IdentifierInfo* for the called function.
288 IdentifierInfo
*FnInfo
= FDecl
->getIdentifier();
290 // None of the checks below are needed for functions that don't have
291 // simple names (e.g., C++ conversion functions).
295 // FIXME: This mechanism should be abstracted to be less fragile and
296 // more efficient. For example, just map function ids to custom
299 // Printf and scanf checking.
300 for (specific_attr_iterator
<FormatAttr
>
301 i
= FDecl
->specific_attr_begin
<FormatAttr
>(),
302 e
= FDecl
->specific_attr_end
<FormatAttr
>(); i
!= e
; ++i
) {
304 const FormatAttr
*Format
= *i
;
305 const bool b
= Format
->getType() == "scanf";
306 if (b
|| CheckablePrintfAttr(Format
, TheCall
)) {
307 bool HasVAListArg
= Format
->getFirstArg() == 0;
308 CheckPrintfScanfArguments(TheCall
, HasVAListArg
,
309 Format
->getFormatIdx() - 1,
310 HasVAListArg
? 0 : Format
->getFirstArg() - 1,
315 for (specific_attr_iterator
<NonNullAttr
>
316 i
= FDecl
->specific_attr_begin
<NonNullAttr
>(),
317 e
= FDecl
->specific_attr_end
<NonNullAttr
>(); i
!= e
; ++i
) {
318 CheckNonNullArguments(*i
, TheCall
->getArgs(),
319 TheCall
->getCallee()->getLocStart());
322 // Memset/memcpy/memmove handling
324 switch (FDecl
->getBuiltinID()) {
325 case Builtin::BI__builtin_memset
:
326 case Builtin::BI__builtin___memset_chk
:
327 case Builtin::BImemset
:
331 case Builtin::BI__builtin_memcpy
:
332 case Builtin::BI__builtin___memcpy_chk
:
333 case Builtin::BImemcpy
:
337 case Builtin::BI__builtin_memmove
:
338 case Builtin::BI__builtin___memmove_chk
:
339 case Builtin::BImemmove
:
344 if (FDecl
->getLinkage() == ExternalLinkage
&&
345 (!getLangOptions().CPlusPlus
|| FDecl
->isExternC())) {
346 if (FnInfo
->isStr("memset"))
348 else if (FnInfo
->isStr("memcpy"))
350 else if (FnInfo
->isStr("memmove"))
357 CheckMemsetcpymoveArguments(TheCall
, CheckedMemoryFunction(CMF
), FnInfo
);
362 bool Sema::CheckBlockCall(NamedDecl
*NDecl
, CallExpr
*TheCall
) {
364 const FormatAttr
*Format
= NDecl
->getAttr
<FormatAttr
>();
368 const VarDecl
*V
= dyn_cast
<VarDecl
>(NDecl
);
372 QualType Ty
= V
->getType();
373 if (!Ty
->isBlockPointerType())
376 const bool b
= Format
->getType() == "scanf";
377 if (!b
&& !CheckablePrintfAttr(Format
, TheCall
))
380 bool HasVAListArg
= Format
->getFirstArg() == 0;
381 CheckPrintfScanfArguments(TheCall
, HasVAListArg
, Format
->getFormatIdx() - 1,
382 HasVAListArg
? 0 : Format
->getFirstArg() - 1, !b
);
387 /// SemaBuiltinAtomicOverloaded - We have a call to a function like
388 /// __sync_fetch_and_add, which is an overloaded function based on the pointer
389 /// type of its first argument. The main ActOnCallExpr routines have already
390 /// promoted the types of arguments because all of these calls are prototyped as
393 /// This function goes through and does final semantic checking for these
396 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult
) {
397 CallExpr
*TheCall
= (CallExpr
*)TheCallResult
.get();
398 DeclRefExpr
*DRE
=cast
<DeclRefExpr
>(TheCall
->getCallee()->IgnoreParenCasts());
399 FunctionDecl
*FDecl
= cast
<FunctionDecl
>(DRE
->getDecl());
401 // Ensure that we have at least one argument to do type inference from.
402 if (TheCall
->getNumArgs() < 1) {
403 Diag(TheCall
->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least
)
404 << 0 << 1 << TheCall
->getNumArgs()
405 << TheCall
->getCallee()->getSourceRange();
409 // Inspect the first argument of the atomic builtin. This should always be
410 // a pointer type, whose element is an integral scalar or pointer type.
411 // Because it is a pointer type, we don't have to worry about any implicit
413 // FIXME: We don't allow floating point scalars as input.
414 Expr
*FirstArg
= TheCall
->getArg(0);
415 const PointerType
*pointerType
= FirstArg
->getType()->getAs
<PointerType
>();
417 Diag(DRE
->getLocStart(), diag::err_atomic_builtin_must_be_pointer
)
418 << FirstArg
->getType() << FirstArg
->getSourceRange();
422 QualType ValType
= pointerType
->getPointeeType();
423 if (!ValType
->isIntegerType() && !ValType
->isAnyPointerType() &&
424 !ValType
->isBlockPointerType()) {
425 Diag(DRE
->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr
)
426 << FirstArg
->getType() << FirstArg
->getSourceRange();
430 switch (ValType
.getObjCLifetime()) {
431 case Qualifiers::OCL_None
:
432 case Qualifiers::OCL_ExplicitNone
:
436 case Qualifiers::OCL_Weak
:
437 case Qualifiers::OCL_Strong
:
438 case Qualifiers::OCL_Autoreleasing
:
439 Diag(DRE
->getLocStart(), diag::err_arc_atomic_ownership
)
440 << ValType
<< FirstArg
->getSourceRange();
444 // The majority of builtins return a value, but a few have special return
445 // types, so allow them to override appropriately below.
446 QualType ResultType
= ValType
;
448 // We need to figure out which concrete builtin this maps onto. For example,
449 // __sync_fetch_and_add with a 2 byte object turns into
450 // __sync_fetch_and_add_2.
451 #define BUILTIN_ROW(x) \
452 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
453 Builtin::BI##x##_8, Builtin::BI##x##_16 }
455 static const unsigned BuiltinIndices
[][5] = {
456 BUILTIN_ROW(__sync_fetch_and_add
),
457 BUILTIN_ROW(__sync_fetch_and_sub
),
458 BUILTIN_ROW(__sync_fetch_and_or
),
459 BUILTIN_ROW(__sync_fetch_and_and
),
460 BUILTIN_ROW(__sync_fetch_and_xor
),
462 BUILTIN_ROW(__sync_add_and_fetch
),
463 BUILTIN_ROW(__sync_sub_and_fetch
),
464 BUILTIN_ROW(__sync_and_and_fetch
),
465 BUILTIN_ROW(__sync_or_and_fetch
),
466 BUILTIN_ROW(__sync_xor_and_fetch
),
468 BUILTIN_ROW(__sync_val_compare_and_swap
),
469 BUILTIN_ROW(__sync_bool_compare_and_swap
),
470 BUILTIN_ROW(__sync_lock_test_and_set
),
471 BUILTIN_ROW(__sync_lock_release
),
472 BUILTIN_ROW(__sync_swap
)
476 // Determine the index of the size.
478 switch (Context
.getTypeSizeInChars(ValType
).getQuantity()) {
479 case 1: SizeIndex
= 0; break;
480 case 2: SizeIndex
= 1; break;
481 case 4: SizeIndex
= 2; break;
482 case 8: SizeIndex
= 3; break;
483 case 16: SizeIndex
= 4; break;
485 Diag(DRE
->getLocStart(), diag::err_atomic_builtin_pointer_size
)
486 << FirstArg
->getType() << FirstArg
->getSourceRange();
490 // Each of these builtins has one pointer argument, followed by some number of
491 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
492 // that we ignore. Find out which row of BuiltinIndices to read from as well
493 // as the number of fixed args.
494 unsigned BuiltinID
= FDecl
->getBuiltinID();
495 unsigned BuiltinIndex
, NumFixed
= 1;
497 default: assert(0 && "Unknown overloaded atomic builtin!");
498 case Builtin::BI__sync_fetch_and_add
: BuiltinIndex
= 0; break;
499 case Builtin::BI__sync_fetch_and_sub
: BuiltinIndex
= 1; break;
500 case Builtin::BI__sync_fetch_and_or
: BuiltinIndex
= 2; break;
501 case Builtin::BI__sync_fetch_and_and
: BuiltinIndex
= 3; break;
502 case Builtin::BI__sync_fetch_and_xor
: BuiltinIndex
= 4; break;
504 case Builtin::BI__sync_add_and_fetch
: BuiltinIndex
= 5; break;
505 case Builtin::BI__sync_sub_and_fetch
: BuiltinIndex
= 6; break;
506 case Builtin::BI__sync_and_and_fetch
: BuiltinIndex
= 7; break;
507 case Builtin::BI__sync_or_and_fetch
: BuiltinIndex
= 8; break;
508 case Builtin::BI__sync_xor_and_fetch
: BuiltinIndex
= 9; break;
510 case Builtin::BI__sync_val_compare_and_swap
:
514 case Builtin::BI__sync_bool_compare_and_swap
:
517 ResultType
= Context
.BoolTy
;
519 case Builtin::BI__sync_lock_test_and_set
: BuiltinIndex
= 12; break;
520 case Builtin::BI__sync_lock_release
:
523 ResultType
= Context
.VoidTy
;
525 case Builtin::BI__sync_swap
: BuiltinIndex
= 14; break;
528 // Now that we know how many fixed arguments we expect, first check that we
529 // have at least that many.
530 if (TheCall
->getNumArgs() < 1+NumFixed
) {
531 Diag(TheCall
->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least
)
532 << 0 << 1+NumFixed
<< TheCall
->getNumArgs()
533 << TheCall
->getCallee()->getSourceRange();
537 // Get the decl for the concrete builtin from this, we can tell what the
538 // concrete integer type we should convert to is.
539 unsigned NewBuiltinID
= BuiltinIndices
[BuiltinIndex
][SizeIndex
];
540 const char *NewBuiltinName
= Context
.BuiltinInfo
.GetName(NewBuiltinID
);
541 IdentifierInfo
*NewBuiltinII
= PP
.getIdentifierInfo(NewBuiltinName
);
542 FunctionDecl
*NewBuiltinDecl
=
543 cast
<FunctionDecl
>(LazilyCreateBuiltin(NewBuiltinII
, NewBuiltinID
,
544 TUScope
, false, DRE
->getLocStart()));
546 // The first argument --- the pointer --- has a fixed type; we
547 // deduce the types of the rest of the arguments accordingly. Walk
548 // the remaining arguments, converting them to the deduced value type.
549 for (unsigned i
= 0; i
!= NumFixed
; ++i
) {
550 ExprResult Arg
= TheCall
->getArg(i
+1);
552 // If the argument is an implicit cast, then there was a promotion due to
553 // "...", just remove it now.
554 if (ImplicitCastExpr
*ICE
= dyn_cast
<ImplicitCastExpr
>(Arg
.get())) {
555 Arg
= ICE
->getSubExpr();
557 TheCall
->setArg(i
+1, Arg
.get());
560 // GCC does an implicit conversion to the pointer or integer ValType. This
561 // can fail in some cases (1i -> int**), check for this error case now.
562 CastKind Kind
= CK_Invalid
;
563 ExprValueKind VK
= VK_RValue
;
564 CXXCastPath BasePath
;
565 Arg
= CheckCastTypes(Arg
.get()->getLocStart(), Arg
.get()->getSourceRange(),
566 ValType
, Arg
.take(), Kind
, VK
, BasePath
);
570 // Okay, we have something that *can* be converted to the right type. Check
571 // to see if there is a potentially weird extension going on here. This can
572 // happen when you do an atomic operation on something like an char* and
573 // pass in 42. The 42 gets converted to char. This is even more strange
574 // for things like 45.123 -> char, etc.
575 // FIXME: Do this check.
576 Arg
= ImpCastExprToType(Arg
.take(), ValType
, Kind
, VK
, &BasePath
);
577 TheCall
->setArg(i
+1, Arg
.get());
580 // Switch the DeclRefExpr to refer to the new decl.
581 DRE
->setDecl(NewBuiltinDecl
);
582 DRE
->setType(NewBuiltinDecl
->getType());
584 // Set the callee in the CallExpr.
585 // FIXME: This leaks the original parens and implicit casts.
586 ExprResult PromotedCall
= UsualUnaryConversions(DRE
);
587 if (PromotedCall
.isInvalid())
589 TheCall
->setCallee(PromotedCall
.take());
591 // Change the result type of the call to match the original value type. This
592 // is arbitrary, but the codegen for these builtins ins design to handle it
594 TheCall
->setType(ResultType
);
596 return move(TheCallResult
);
600 /// CheckObjCString - Checks that the argument to the builtin
601 /// CFString constructor is correct
602 /// Note: It might also make sense to do the UTF-16 conversion here (would
603 /// simplify the backend).
604 bool Sema::CheckObjCString(Expr
*Arg
) {
605 Arg
= Arg
->IgnoreParenCasts();
606 StringLiteral
*Literal
= dyn_cast
<StringLiteral
>(Arg
);
608 if (!Literal
|| Literal
->isWide()) {
609 Diag(Arg
->getLocStart(), diag::err_cfstring_literal_not_string_constant
)
610 << Arg
->getSourceRange();
614 if (Literal
->containsNonAsciiOrNull()) {
615 llvm::StringRef String
= Literal
->getString();
616 unsigned NumBytes
= String
.size();
617 llvm::SmallVector
<UTF16
, 128> ToBuf(NumBytes
);
618 const UTF8
*FromPtr
= (UTF8
*)String
.data();
619 UTF16
*ToPtr
= &ToBuf
[0];
621 ConversionResult Result
= ConvertUTF8toUTF16(&FromPtr
, FromPtr
+ NumBytes
,
622 &ToPtr
, ToPtr
+ NumBytes
,
624 // Check for conversion failure.
625 if (Result
!= conversionOK
)
626 Diag(Arg
->getLocStart(),
627 diag::warn_cfstring_truncated
) << Arg
->getSourceRange();
632 /// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
633 /// Emit an error and return true on failure, return false on success.
634 bool Sema::SemaBuiltinVAStart(CallExpr
*TheCall
) {
635 Expr
*Fn
= TheCall
->getCallee();
636 if (TheCall
->getNumArgs() > 2) {
637 Diag(TheCall
->getArg(2)->getLocStart(),
638 diag::err_typecheck_call_too_many_args
)
639 << 0 /*function call*/ << 2 << TheCall
->getNumArgs()
640 << Fn
->getSourceRange()
641 << SourceRange(TheCall
->getArg(2)->getLocStart(),
642 (*(TheCall
->arg_end()-1))->getLocEnd());
646 if (TheCall
->getNumArgs() < 2) {
647 return Diag(TheCall
->getLocEnd(),
648 diag::err_typecheck_call_too_few_args_at_least
)
649 << 0 /*function call*/ << 2 << TheCall
->getNumArgs();
652 // Determine whether the current function is variadic or not.
653 BlockScopeInfo
*CurBlock
= getCurBlock();
656 isVariadic
= CurBlock
->TheDecl
->isVariadic();
657 else if (FunctionDecl
*FD
= getCurFunctionDecl())
658 isVariadic
= FD
->isVariadic();
660 isVariadic
= getCurMethodDecl()->isVariadic();
663 Diag(Fn
->getLocStart(), diag::err_va_start_used_in_non_variadic_function
);
667 // Verify that the second argument to the builtin is the last argument of the
668 // current function or method.
669 bool SecondArgIsLastNamedArgument
= false;
670 const Expr
*Arg
= TheCall
->getArg(1)->IgnoreParenCasts();
672 if (const DeclRefExpr
*DR
= dyn_cast
<DeclRefExpr
>(Arg
)) {
673 if (const ParmVarDecl
*PV
= dyn_cast
<ParmVarDecl
>(DR
->getDecl())) {
674 // FIXME: This isn't correct for methods (results in bogus warning).
675 // Get the last formal in the current function.
676 const ParmVarDecl
*LastArg
;
678 LastArg
= *(CurBlock
->TheDecl
->param_end()-1);
679 else if (FunctionDecl
*FD
= getCurFunctionDecl())
680 LastArg
= *(FD
->param_end()-1);
682 LastArg
= *(getCurMethodDecl()->param_end()-1);
683 SecondArgIsLastNamedArgument
= PV
== LastArg
;
687 if (!SecondArgIsLastNamedArgument
)
688 Diag(TheCall
->getArg(1)->getLocStart(),
689 diag::warn_second_parameter_of_va_start_not_last_named_argument
);
693 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
694 /// friends. This is declared to take (...), so we have to check everything.
695 bool Sema::SemaBuiltinUnorderedCompare(CallExpr
*TheCall
) {
696 if (TheCall
->getNumArgs() < 2)
697 return Diag(TheCall
->getLocEnd(), diag::err_typecheck_call_too_few_args
)
698 << 0 << 2 << TheCall
->getNumArgs()/*function call*/;
699 if (TheCall
->getNumArgs() > 2)
700 return Diag(TheCall
->getArg(2)->getLocStart(),
701 diag::err_typecheck_call_too_many_args
)
702 << 0 /*function call*/ << 2 << TheCall
->getNumArgs()
703 << SourceRange(TheCall
->getArg(2)->getLocStart(),
704 (*(TheCall
->arg_end()-1))->getLocEnd());
706 ExprResult OrigArg0
= TheCall
->getArg(0);
707 ExprResult OrigArg1
= TheCall
->getArg(1);
709 // Do standard promotions between the two arguments, returning their common
711 QualType Res
= UsualArithmeticConversions(OrigArg0
, OrigArg1
, false);
712 if (OrigArg0
.isInvalid() || OrigArg1
.isInvalid())
715 // Make sure any conversions are pushed back into the call; this is
716 // type safe since unordered compare builtins are declared as "_Bool
718 TheCall
->setArg(0, OrigArg0
.get());
719 TheCall
->setArg(1, OrigArg1
.get());
721 if (OrigArg0
.get()->isTypeDependent() || OrigArg1
.get()->isTypeDependent())
724 // If the common type isn't a real floating type, then the arguments were
725 // invalid for this operation.
726 if (!Res
->isRealFloatingType())
727 return Diag(OrigArg0
.get()->getLocStart(),
728 diag::err_typecheck_call_invalid_ordered_compare
)
729 << OrigArg0
.get()->getType() << OrigArg1
.get()->getType()
730 << SourceRange(OrigArg0
.get()->getLocStart(), OrigArg1
.get()->getLocEnd());
735 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
736 /// __builtin_isnan and friends. This is declared to take (...), so we have
737 /// to check everything. We expect the last argument to be a floating point
739 bool Sema::SemaBuiltinFPClassification(CallExpr
*TheCall
, unsigned NumArgs
) {
740 if (TheCall
->getNumArgs() < NumArgs
)
741 return Diag(TheCall
->getLocEnd(), diag::err_typecheck_call_too_few_args
)
742 << 0 << NumArgs
<< TheCall
->getNumArgs()/*function call*/;
743 if (TheCall
->getNumArgs() > NumArgs
)
744 return Diag(TheCall
->getArg(NumArgs
)->getLocStart(),
745 diag::err_typecheck_call_too_many_args
)
746 << 0 /*function call*/ << NumArgs
<< TheCall
->getNumArgs()
747 << SourceRange(TheCall
->getArg(NumArgs
)->getLocStart(),
748 (*(TheCall
->arg_end()-1))->getLocEnd());
750 Expr
*OrigArg
= TheCall
->getArg(NumArgs
-1);
752 if (OrigArg
->isTypeDependent())
755 // This operation requires a non-_Complex floating-point number.
756 if (!OrigArg
->getType()->isRealFloatingType())
757 return Diag(OrigArg
->getLocStart(),
758 diag::err_typecheck_call_invalid_unary_fp
)
759 << OrigArg
->getType() << OrigArg
->getSourceRange();
761 // If this is an implicit conversion from float -> double, remove it.
762 if (ImplicitCastExpr
*Cast
= dyn_cast
<ImplicitCastExpr
>(OrigArg
)) {
763 Expr
*CastArg
= Cast
->getSubExpr();
764 if (CastArg
->getType()->isSpecificBuiltinType(BuiltinType::Float
)) {
765 assert(Cast
->getType()->isSpecificBuiltinType(BuiltinType::Double
) &&
766 "promotion from float to double is the only expected cast here");
768 TheCall
->setArg(NumArgs
-1, CastArg
);
776 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
777 // This is declared to take (...), so we have to check everything.
778 ExprResult
Sema::SemaBuiltinShuffleVector(CallExpr
*TheCall
) {
779 if (TheCall
->getNumArgs() < 2)
780 return ExprError(Diag(TheCall
->getLocEnd(),
781 diag::err_typecheck_call_too_few_args_at_least
)
782 << 0 /*function call*/ << 2 << TheCall
->getNumArgs()
783 << TheCall
->getSourceRange());
785 // Determine which of the following types of shufflevector we're checking:
786 // 1) unary, vector mask: (lhs, mask)
787 // 2) binary, vector mask: (lhs, rhs, mask)
788 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
789 QualType resType
= TheCall
->getArg(0)->getType();
790 unsigned numElements
= 0;
792 if (!TheCall
->getArg(0)->isTypeDependent() &&
793 !TheCall
->getArg(1)->isTypeDependent()) {
794 QualType LHSType
= TheCall
->getArg(0)->getType();
795 QualType RHSType
= TheCall
->getArg(1)->getType();
797 if (!LHSType
->isVectorType() || !RHSType
->isVectorType()) {
798 Diag(TheCall
->getLocStart(), diag::err_shufflevector_non_vector
)
799 << SourceRange(TheCall
->getArg(0)->getLocStart(),
800 TheCall
->getArg(1)->getLocEnd());
804 numElements
= LHSType
->getAs
<VectorType
>()->getNumElements();
805 unsigned numResElements
= TheCall
->getNumArgs() - 2;
807 // Check to see if we have a call with 2 vector arguments, the unary shuffle
808 // with mask. If so, verify that RHS is an integer vector type with the
809 // same number of elts as lhs.
810 if (TheCall
->getNumArgs() == 2) {
811 if (!RHSType
->hasIntegerRepresentation() ||
812 RHSType
->getAs
<VectorType
>()->getNumElements() != numElements
)
813 Diag(TheCall
->getLocStart(), diag::err_shufflevector_incompatible_vector
)
814 << SourceRange(TheCall
->getArg(1)->getLocStart(),
815 TheCall
->getArg(1)->getLocEnd());
816 numResElements
= numElements
;
818 else if (!Context
.hasSameUnqualifiedType(LHSType
, RHSType
)) {
819 Diag(TheCall
->getLocStart(), diag::err_shufflevector_incompatible_vector
)
820 << SourceRange(TheCall
->getArg(0)->getLocStart(),
821 TheCall
->getArg(1)->getLocEnd());
823 } else if (numElements
!= numResElements
) {
824 QualType eltType
= LHSType
->getAs
<VectorType
>()->getElementType();
825 resType
= Context
.getVectorType(eltType
, numResElements
,
826 VectorType::GenericVector
);
830 for (unsigned i
= 2; i
< TheCall
->getNumArgs(); i
++) {
831 if (TheCall
->getArg(i
)->isTypeDependent() ||
832 TheCall
->getArg(i
)->isValueDependent())
835 llvm::APSInt
Result(32);
836 if (!TheCall
->getArg(i
)->isIntegerConstantExpr(Result
, Context
))
837 return ExprError(Diag(TheCall
->getLocStart(),
838 diag::err_shufflevector_nonconstant_argument
)
839 << TheCall
->getArg(i
)->getSourceRange());
841 if (Result
.getActiveBits() > 64 || Result
.getZExtValue() >= numElements
*2)
842 return ExprError(Diag(TheCall
->getLocStart(),
843 diag::err_shufflevector_argument_too_large
)
844 << TheCall
->getArg(i
)->getSourceRange());
847 llvm::SmallVector
<Expr
*, 32> exprs
;
849 for (unsigned i
= 0, e
= TheCall
->getNumArgs(); i
!= e
; i
++) {
850 exprs
.push_back(TheCall
->getArg(i
));
851 TheCall
->setArg(i
, 0);
854 return Owned(new (Context
) ShuffleVectorExpr(Context
, exprs
.begin(),
855 exprs
.size(), resType
,
856 TheCall
->getCallee()->getLocStart(),
857 TheCall
->getRParenLoc()));
860 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
861 // This is declared to take (const void*, ...) and can take two
862 // optional constant int args.
863 bool Sema::SemaBuiltinPrefetch(CallExpr
*TheCall
) {
864 unsigned NumArgs
= TheCall
->getNumArgs();
867 return Diag(TheCall
->getLocEnd(),
868 diag::err_typecheck_call_too_many_args_at_most
)
869 << 0 /*function call*/ << 3 << NumArgs
870 << TheCall
->getSourceRange();
872 // Argument 0 is checked for us and the remaining arguments must be
873 // constant integers.
874 for (unsigned i
= 1; i
!= NumArgs
; ++i
) {
875 Expr
*Arg
= TheCall
->getArg(i
);
878 if (SemaBuiltinConstantArg(TheCall
, i
, Result
))
881 // FIXME: gcc issues a warning and rewrites these to 0. These
882 // seems especially odd for the third argument since the default
885 if (Result
.getLimitedValue() > 1)
886 return Diag(TheCall
->getLocStart(), diag::err_argument_invalid_range
)
887 << "0" << "1" << Arg
->getSourceRange();
889 if (Result
.getLimitedValue() > 3)
890 return Diag(TheCall
->getLocStart(), diag::err_argument_invalid_range
)
891 << "0" << "3" << Arg
->getSourceRange();
898 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
899 /// TheCall is a constant expression.
900 bool Sema::SemaBuiltinConstantArg(CallExpr
*TheCall
, int ArgNum
,
901 llvm::APSInt
&Result
) {
902 Expr
*Arg
= TheCall
->getArg(ArgNum
);
903 DeclRefExpr
*DRE
=cast
<DeclRefExpr
>(TheCall
->getCallee()->IgnoreParenCasts());
904 FunctionDecl
*FDecl
= cast
<FunctionDecl
>(DRE
->getDecl());
906 if (Arg
->isTypeDependent() || Arg
->isValueDependent()) return false;
908 if (!Arg
->isIntegerConstantExpr(Result
, Context
))
909 return Diag(TheCall
->getLocStart(), diag::err_constant_integer_arg_type
)
910 << FDecl
->getDeclName() << Arg
->getSourceRange();
915 /// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
916 /// int type). This simply type checks that type is one of the defined
918 // For compatibility check 0-3, llvm only handles 0 and 2.
919 bool Sema::SemaBuiltinObjectSize(CallExpr
*TheCall
) {
922 // Check constant-ness first.
923 if (SemaBuiltinConstantArg(TheCall
, 1, Result
))
926 Expr
*Arg
= TheCall
->getArg(1);
927 if (Result
.getSExtValue() < 0 || Result
.getSExtValue() > 3) {
928 return Diag(TheCall
->getLocStart(), diag::err_argument_invalid_range
)
929 << "0" << "3" << SourceRange(Arg
->getLocStart(), Arg
->getLocEnd());
935 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
936 /// This checks that val is a constant 1.
937 bool Sema::SemaBuiltinLongjmp(CallExpr
*TheCall
) {
938 Expr
*Arg
= TheCall
->getArg(1);
941 // TODO: This is less than ideal. Overload this to take a value.
942 if (SemaBuiltinConstantArg(TheCall
, 1, Result
))
946 return Diag(TheCall
->getLocStart(), diag::err_builtin_longjmp_invalid_val
)
947 << SourceRange(Arg
->getLocStart(), Arg
->getLocEnd());
952 // Handle i > 1 ? "x" : "y", recursively.
953 bool Sema::SemaCheckStringLiteral(const Expr
*E
, const CallExpr
*TheCall
,
955 unsigned format_idx
, unsigned firstDataArg
,
958 if (E
->isTypeDependent() || E
->isValueDependent())
961 E
= E
->IgnoreParens();
963 switch (E
->getStmtClass()) {
964 case Stmt::BinaryConditionalOperatorClass
:
965 case Stmt::ConditionalOperatorClass
: {
966 const AbstractConditionalOperator
*C
= cast
<AbstractConditionalOperator
>(E
);
967 return SemaCheckStringLiteral(C
->getTrueExpr(), TheCall
, HasVAListArg
,
968 format_idx
, firstDataArg
, isPrintf
)
969 && SemaCheckStringLiteral(C
->getFalseExpr(), TheCall
, HasVAListArg
,
970 format_idx
, firstDataArg
, isPrintf
);
973 case Stmt::IntegerLiteralClass
:
974 // Technically -Wformat-nonliteral does not warn about this case.
975 // The behavior of printf and friends in this case is implementation
976 // dependent. Ideally if the format string cannot be null then
977 // it should have a 'nonnull' attribute in the function prototype.
980 case Stmt::ImplicitCastExprClass
: {
981 E
= cast
<ImplicitCastExpr
>(E
)->getSubExpr();
985 case Stmt::OpaqueValueExprClass
:
986 if (const Expr
*src
= cast
<OpaqueValueExpr
>(E
)->getSourceExpr()) {
992 case Stmt::PredefinedExprClass
:
993 // While __func__, etc., are technically not string literals, they
994 // cannot contain format specifiers and thus are not a security
998 case Stmt::DeclRefExprClass
: {
999 const DeclRefExpr
*DR
= cast
<DeclRefExpr
>(E
);
1001 // As an exception, do not flag errors for variables binding to
1002 // const string literals.
1003 if (const VarDecl
*VD
= dyn_cast
<VarDecl
>(DR
->getDecl())) {
1004 bool isConstant
= false;
1005 QualType T
= DR
->getType();
1007 if (const ArrayType
*AT
= Context
.getAsArrayType(T
)) {
1008 isConstant
= AT
->getElementType().isConstant(Context
);
1009 } else if (const PointerType
*PT
= T
->getAs
<PointerType
>()) {
1010 isConstant
= T
.isConstant(Context
) &&
1011 PT
->getPointeeType().isConstant(Context
);
1015 if (const Expr
*Init
= VD
->getAnyInitializer())
1016 return SemaCheckStringLiteral(Init
, TheCall
,
1017 HasVAListArg
, format_idx
, firstDataArg
,
1021 // For vprintf* functions (i.e., HasVAListArg==true), we add a
1022 // special check to see if the format string is a function parameter
1023 // of the function calling the printf function. If the function
1024 // has an attribute indicating it is a printf-like function, then we
1025 // should suppress warnings concerning non-literals being used in a call
1026 // to a vprintf function. For example:
1029 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
1031 // va_start(ap, fmt);
1032 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
1036 // FIXME: We don't have full attribute support yet, so just check to see
1037 // if the argument is a DeclRefExpr that references a parameter. We'll
1038 // add proper support for checking the attribute later.
1040 if (isa
<ParmVarDecl
>(VD
))
1047 case Stmt::CallExprClass
: {
1048 const CallExpr
*CE
= cast
<CallExpr
>(E
);
1049 if (const ImplicitCastExpr
*ICE
1050 = dyn_cast
<ImplicitCastExpr
>(CE
->getCallee())) {
1051 if (const DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(ICE
->getSubExpr())) {
1052 if (const FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(DRE
->getDecl())) {
1053 if (const FormatArgAttr
*FA
= FD
->getAttr
<FormatArgAttr
>()) {
1054 unsigned ArgIndex
= FA
->getFormatIdx();
1055 const Expr
*Arg
= CE
->getArg(ArgIndex
- 1);
1057 return SemaCheckStringLiteral(Arg
, TheCall
, HasVAListArg
,
1058 format_idx
, firstDataArg
, isPrintf
);
1066 case Stmt::ObjCStringLiteralClass
:
1067 case Stmt::StringLiteralClass
: {
1068 const StringLiteral
*StrE
= NULL
;
1070 if (const ObjCStringLiteral
*ObjCFExpr
= dyn_cast
<ObjCStringLiteral
>(E
))
1071 StrE
= ObjCFExpr
->getString();
1073 StrE
= cast
<StringLiteral
>(E
);
1076 CheckFormatString(StrE
, E
, TheCall
, HasVAListArg
, format_idx
,
1077 firstDataArg
, isPrintf
);
1090 Sema::CheckNonNullArguments(const NonNullAttr
*NonNull
,
1091 const Expr
* const *ExprArgs
,
1092 SourceLocation CallSiteLoc
) {
1093 for (NonNullAttr::args_iterator i
= NonNull
->args_begin(),
1094 e
= NonNull
->args_end();
1096 const Expr
*ArgExpr
= ExprArgs
[*i
];
1097 if (ArgExpr
->isNullPointerConstant(Context
,
1098 Expr::NPC_ValueDependentIsNotNull
))
1099 Diag(CallSiteLoc
, diag::warn_null_arg
) << ArgExpr
->getSourceRange();
1103 /// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar
1104 /// functions) for correct use of format strings.
1106 Sema::CheckPrintfScanfArguments(const CallExpr
*TheCall
, bool HasVAListArg
,
1107 unsigned format_idx
, unsigned firstDataArg
,
1110 const Expr
*Fn
= TheCall
->getCallee();
1112 // The way the format attribute works in GCC, the implicit this argument
1113 // of member functions is counted. However, it doesn't appear in our own
1114 // lists, so decrement format_idx in that case.
1115 if (isa
<CXXMemberCallExpr
>(TheCall
)) {
1116 const CXXMethodDecl
*method_decl
=
1117 dyn_cast
<CXXMethodDecl
>(TheCall
->getCalleeDecl());
1118 if (method_decl
&& method_decl
->isInstance()) {
1119 // Catch a format attribute mistakenly referring to the object argument.
1120 if (format_idx
== 0)
1123 if(firstDataArg
!= 0)
1128 // CHECK: printf/scanf-like function is called with no format string.
1129 if (format_idx
>= TheCall
->getNumArgs()) {
1130 Diag(TheCall
->getRParenLoc(), diag::warn_missing_format_string
)
1131 << Fn
->getSourceRange();
1135 const Expr
*OrigFormatExpr
= TheCall
->getArg(format_idx
)->IgnoreParenCasts();
1137 // CHECK: format string is not a string literal.
1139 // Dynamically generated format strings are difficult to
1140 // automatically vet at compile time. Requiring that format strings
1141 // are string literals: (1) permits the checking of format strings by
1142 // the compiler and thereby (2) can practically remove the source of
1143 // many format string exploits.
1145 // Format string can be either ObjC string (e.g. @"%d") or
1146 // C string (e.g. "%d")
1147 // ObjC string uses the same format specifiers as C string, so we can use
1148 // the same format string checking logic for both ObjC and C strings.
1149 if (SemaCheckStringLiteral(OrigFormatExpr
, TheCall
, HasVAListArg
, format_idx
,
1150 firstDataArg
, isPrintf
))
1151 return; // Literal format string found, check done!
1153 // If there are no arguments specified, warn with -Wformat-security, otherwise
1154 // warn only with -Wformat-nonliteral.
1155 if (TheCall
->getNumArgs() == format_idx
+1)
1156 Diag(TheCall
->getArg(format_idx
)->getLocStart(),
1157 diag::warn_format_nonliteral_noargs
)
1158 << OrigFormatExpr
->getSourceRange();
1160 Diag(TheCall
->getArg(format_idx
)->getLocStart(),
1161 diag::warn_format_nonliteral
)
1162 << OrigFormatExpr
->getSourceRange();
1166 class CheckFormatHandler
: public analyze_format_string::FormatStringHandler
{
1169 const StringLiteral
*FExpr
;
1170 const Expr
*OrigFormatExpr
;
1171 const unsigned FirstDataArg
;
1172 const unsigned NumDataArgs
;
1173 const bool IsObjCLiteral
;
1174 const char *Beg
; // Start of format string.
1175 const bool HasVAListArg
;
1176 const CallExpr
*TheCall
;
1178 llvm::BitVector CoveredArgs
;
1179 bool usesPositionalArgs
;
1182 CheckFormatHandler(Sema
&s
, const StringLiteral
*fexpr
,
1183 const Expr
*origFormatExpr
, unsigned firstDataArg
,
1184 unsigned numDataArgs
, bool isObjCLiteral
,
1185 const char *beg
, bool hasVAListArg
,
1186 const CallExpr
*theCall
, unsigned formatIdx
)
1187 : S(s
), FExpr(fexpr
), OrigFormatExpr(origFormatExpr
),
1188 FirstDataArg(firstDataArg
),
1189 NumDataArgs(numDataArgs
),
1190 IsObjCLiteral(isObjCLiteral
), Beg(beg
),
1191 HasVAListArg(hasVAListArg
),
1192 TheCall(theCall
), FormatIdx(formatIdx
),
1193 usesPositionalArgs(false), atFirstArg(true) {
1194 CoveredArgs
.resize(numDataArgs
);
1195 CoveredArgs
.reset();
1198 void DoneProcessing();
1200 void HandleIncompleteSpecifier(const char *startSpecifier
,
1201 unsigned specifierLen
);
1203 virtual void HandleInvalidPosition(const char *startSpecifier
,
1204 unsigned specifierLen
,
1205 analyze_format_string::PositionContext p
);
1207 virtual void HandleZeroPosition(const char *startPos
, unsigned posLen
);
1209 void HandleNullChar(const char *nullCharacter
);
1212 bool HandleInvalidConversionSpecifier(unsigned argIndex
, SourceLocation Loc
,
1213 const char *startSpec
,
1214 unsigned specifierLen
,
1215 const char *csStart
, unsigned csLen
);
1217 SourceRange
getFormatStringRange();
1218 CharSourceRange
getSpecifierRange(const char *startSpecifier
,
1219 unsigned specifierLen
);
1220 SourceLocation
getLocationOfByte(const char *x
);
1222 const Expr
*getDataArg(unsigned i
) const;
1224 bool CheckNumArgs(const analyze_format_string::FormatSpecifier
&FS
,
1225 const analyze_format_string::ConversionSpecifier
&CS
,
1226 const char *startSpecifier
, unsigned specifierLen
,
1231 SourceRange
CheckFormatHandler::getFormatStringRange() {
1232 return OrigFormatExpr
->getSourceRange();
1235 CharSourceRange
CheckFormatHandler::
1236 getSpecifierRange(const char *startSpecifier
, unsigned specifierLen
) {
1237 SourceLocation Start
= getLocationOfByte(startSpecifier
);
1238 SourceLocation End
= getLocationOfByte(startSpecifier
+ specifierLen
- 1);
1240 // Advance the end SourceLocation by one due to half-open ranges.
1241 End
= End
.getFileLocWithOffset(1);
1243 return CharSourceRange::getCharRange(Start
, End
);
1246 SourceLocation
CheckFormatHandler::getLocationOfByte(const char *x
) {
1247 return S
.getLocationOfStringLiteralByte(FExpr
, x
- Beg
);
1250 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier
,
1251 unsigned specifierLen
){
1252 SourceLocation Loc
= getLocationOfByte(startSpecifier
);
1253 S
.Diag(Loc
, diag::warn_printf_incomplete_specifier
)
1254 << getSpecifierRange(startSpecifier
, specifierLen
);
1258 CheckFormatHandler::HandleInvalidPosition(const char *startPos
, unsigned posLen
,
1259 analyze_format_string::PositionContext p
) {
1260 SourceLocation Loc
= getLocationOfByte(startPos
);
1261 S
.Diag(Loc
, diag::warn_format_invalid_positional_specifier
)
1262 << (unsigned) p
<< getSpecifierRange(startPos
, posLen
);
1265 void CheckFormatHandler::HandleZeroPosition(const char *startPos
,
1267 SourceLocation Loc
= getLocationOfByte(startPos
);
1268 S
.Diag(Loc
, diag::warn_format_zero_positional_specifier
)
1269 << getSpecifierRange(startPos
, posLen
);
1272 void CheckFormatHandler::HandleNullChar(const char *nullCharacter
) {
1273 if (!IsObjCLiteral
) {
1274 // The presence of a null character is likely an error.
1275 S
.Diag(getLocationOfByte(nullCharacter
),
1276 diag::warn_printf_format_string_contains_null_char
)
1277 << getFormatStringRange();
1281 const Expr
*CheckFormatHandler::getDataArg(unsigned i
) const {
1282 return TheCall
->getArg(FirstDataArg
+ i
);
1285 void CheckFormatHandler::DoneProcessing() {
1286 // Does the number of data arguments exceed the number of
1287 // format conversions in the format string?
1288 if (!HasVAListArg
) {
1289 // Find any arguments that weren't covered.
1291 signed notCoveredArg
= CoveredArgs
.find_first();
1292 if (notCoveredArg
>= 0) {
1293 assert((unsigned)notCoveredArg
< NumDataArgs
);
1294 S
.Diag(getDataArg((unsigned) notCoveredArg
)->getLocStart(),
1295 diag::warn_printf_data_arg_not_used
)
1296 << getFormatStringRange();
1302 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex
,
1304 const char *startSpec
,
1305 unsigned specifierLen
,
1306 const char *csStart
,
1309 bool keepGoing
= true;
1310 if (argIndex
< NumDataArgs
) {
1311 // Consider the argument coverered, even though the specifier doesn't
1313 CoveredArgs
.set(argIndex
);
1316 // If argIndex exceeds the number of data arguments we
1317 // don't issue a warning because that is just a cascade of warnings (and
1318 // they may have intended '%%' anyway). We don't want to continue processing
1319 // the format string after this point, however, as we will like just get
1320 // gibberish when trying to match arguments.
1324 S
.Diag(Loc
, diag::warn_format_invalid_conversion
)
1325 << llvm::StringRef(csStart
, csLen
)
1326 << getSpecifierRange(startSpec
, specifierLen
);
1332 CheckFormatHandler::CheckNumArgs(
1333 const analyze_format_string::FormatSpecifier
&FS
,
1334 const analyze_format_string::ConversionSpecifier
&CS
,
1335 const char *startSpecifier
, unsigned specifierLen
, unsigned argIndex
) {
1337 if (argIndex
>= NumDataArgs
) {
1338 if (FS
.usesPositionalArg()) {
1339 S
.Diag(getLocationOfByte(CS
.getStart()),
1340 diag::warn_printf_positional_arg_exceeds_data_args
)
1341 << (argIndex
+1) << NumDataArgs
1342 << getSpecifierRange(startSpecifier
, specifierLen
);
1345 S
.Diag(getLocationOfByte(CS
.getStart()),
1346 diag::warn_printf_insufficient_data_args
)
1347 << getSpecifierRange(startSpecifier
, specifierLen
);
1355 //===--- CHECK: Printf format string checking ------------------------------===//
1358 class CheckPrintfHandler
: public CheckFormatHandler
{
1360 CheckPrintfHandler(Sema
&s
, const StringLiteral
*fexpr
,
1361 const Expr
*origFormatExpr
, unsigned firstDataArg
,
1362 unsigned numDataArgs
, bool isObjCLiteral
,
1363 const char *beg
, bool hasVAListArg
,
1364 const CallExpr
*theCall
, unsigned formatIdx
)
1365 : CheckFormatHandler(s
, fexpr
, origFormatExpr
, firstDataArg
,
1366 numDataArgs
, isObjCLiteral
, beg
, hasVAListArg
,
1367 theCall
, formatIdx
) {}
1370 bool HandleInvalidPrintfConversionSpecifier(
1371 const analyze_printf::PrintfSpecifier
&FS
,
1372 const char *startSpecifier
,
1373 unsigned specifierLen
);
1375 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
&FS
,
1376 const char *startSpecifier
,
1377 unsigned specifierLen
);
1379 bool HandleAmount(const analyze_format_string::OptionalAmount
&Amt
, unsigned k
,
1380 const char *startSpecifier
, unsigned specifierLen
);
1381 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier
&FS
,
1382 const analyze_printf::OptionalAmount
&Amt
,
1384 const char *startSpecifier
, unsigned specifierLen
);
1385 void HandleFlag(const analyze_printf::PrintfSpecifier
&FS
,
1386 const analyze_printf::OptionalFlag
&flag
,
1387 const char *startSpecifier
, unsigned specifierLen
);
1388 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier
&FS
,
1389 const analyze_printf::OptionalFlag
&ignoredFlag
,
1390 const analyze_printf::OptionalFlag
&flag
,
1391 const char *startSpecifier
, unsigned specifierLen
);
1395 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
1396 const analyze_printf::PrintfSpecifier
&FS
,
1397 const char *startSpecifier
,
1398 unsigned specifierLen
) {
1399 const analyze_printf::PrintfConversionSpecifier
&CS
=
1400 FS
.getConversionSpecifier();
1402 return HandleInvalidConversionSpecifier(FS
.getArgIndex(),
1403 getLocationOfByte(CS
.getStart()),
1404 startSpecifier
, specifierLen
,
1405 CS
.getStart(), CS
.getLength());
1408 bool CheckPrintfHandler::HandleAmount(
1409 const analyze_format_string::OptionalAmount
&Amt
,
1410 unsigned k
, const char *startSpecifier
,
1411 unsigned specifierLen
) {
1413 if (Amt
.hasDataArgument()) {
1414 if (!HasVAListArg
) {
1415 unsigned argIndex
= Amt
.getArgIndex();
1416 if (argIndex
>= NumDataArgs
) {
1417 S
.Diag(getLocationOfByte(Amt
.getStart()),
1418 diag::warn_printf_asterisk_missing_arg
)
1419 << k
<< getSpecifierRange(startSpecifier
, specifierLen
);
1420 // Don't do any more checking. We will just emit
1425 // Type check the data argument. It should be an 'int'.
1426 // Although not in conformance with C99, we also allow the argument to be
1427 // an 'unsigned int' as that is a reasonably safe case. GCC also
1428 // doesn't emit a warning for that case.
1429 CoveredArgs
.set(argIndex
);
1430 const Expr
*Arg
= getDataArg(argIndex
);
1431 QualType T
= Arg
->getType();
1433 const analyze_printf::ArgTypeResult
&ATR
= Amt
.getArgType(S
.Context
);
1434 assert(ATR
.isValid());
1436 if (!ATR
.matchesType(S
.Context
, T
)) {
1437 S
.Diag(getLocationOfByte(Amt
.getStart()),
1438 diag::warn_printf_asterisk_wrong_type
)
1440 << ATR
.getRepresentativeType(S
.Context
) << T
1441 << getSpecifierRange(startSpecifier
, specifierLen
)
1442 << Arg
->getSourceRange();
1443 // Don't do any more checking. We will just emit
1452 void CheckPrintfHandler::HandleInvalidAmount(
1453 const analyze_printf::PrintfSpecifier
&FS
,
1454 const analyze_printf::OptionalAmount
&Amt
,
1456 const char *startSpecifier
,
1457 unsigned specifierLen
) {
1458 const analyze_printf::PrintfConversionSpecifier
&CS
=
1459 FS
.getConversionSpecifier();
1460 switch (Amt
.getHowSpecified()) {
1461 case analyze_printf::OptionalAmount::Constant
:
1462 S
.Diag(getLocationOfByte(Amt
.getStart()),
1463 diag::warn_printf_nonsensical_optional_amount
)
1466 << getSpecifierRange(startSpecifier
, specifierLen
)
1467 << FixItHint::CreateRemoval(getSpecifierRange(Amt
.getStart(),
1468 Amt
.getConstantLength()));
1472 S
.Diag(getLocationOfByte(Amt
.getStart()),
1473 diag::warn_printf_nonsensical_optional_amount
)
1476 << getSpecifierRange(startSpecifier
, specifierLen
);
1481 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier
&FS
,
1482 const analyze_printf::OptionalFlag
&flag
,
1483 const char *startSpecifier
,
1484 unsigned specifierLen
) {
1485 // Warn about pointless flag with a fixit removal.
1486 const analyze_printf::PrintfConversionSpecifier
&CS
=
1487 FS
.getConversionSpecifier();
1488 S
.Diag(getLocationOfByte(flag
.getPosition()),
1489 diag::warn_printf_nonsensical_flag
)
1490 << flag
.toString() << CS
.toString()
1491 << getSpecifierRange(startSpecifier
, specifierLen
)
1492 << FixItHint::CreateRemoval(getSpecifierRange(flag
.getPosition(), 1));
1495 void CheckPrintfHandler::HandleIgnoredFlag(
1496 const analyze_printf::PrintfSpecifier
&FS
,
1497 const analyze_printf::OptionalFlag
&ignoredFlag
,
1498 const analyze_printf::OptionalFlag
&flag
,
1499 const char *startSpecifier
,
1500 unsigned specifierLen
) {
1501 // Warn about ignored flag with a fixit removal.
1502 S
.Diag(getLocationOfByte(ignoredFlag
.getPosition()),
1503 diag::warn_printf_ignored_flag
)
1504 << ignoredFlag
.toString() << flag
.toString()
1505 << getSpecifierRange(startSpecifier
, specifierLen
)
1506 << FixItHint::CreateRemoval(getSpecifierRange(
1507 ignoredFlag
.getPosition(), 1));
1511 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
1513 const char *startSpecifier
,
1514 unsigned specifierLen
) {
1516 using namespace analyze_format_string
;
1517 using namespace analyze_printf
;
1518 const PrintfConversionSpecifier
&CS
= FS
.getConversionSpecifier();
1520 if (FS
.consumesDataArgument()) {
1523 usesPositionalArgs
= FS
.usesPositionalArg();
1525 else if (usesPositionalArgs
!= FS
.usesPositionalArg()) {
1526 // Cannot mix-and-match positional and non-positional arguments.
1527 S
.Diag(getLocationOfByte(CS
.getStart()),
1528 diag::warn_format_mix_positional_nonpositional_args
)
1529 << getSpecifierRange(startSpecifier
, specifierLen
);
1534 // First check if the field width, precision, and conversion specifier
1535 // have matching data arguments.
1536 if (!HandleAmount(FS
.getFieldWidth(), /* field width */ 0,
1537 startSpecifier
, specifierLen
)) {
1541 if (!HandleAmount(FS
.getPrecision(), /* precision */ 1,
1542 startSpecifier
, specifierLen
)) {
1546 if (!CS
.consumesDataArgument()) {
1547 // FIXME: Technically specifying a precision or field width here
1548 // makes no sense. Worth issuing a warning at some point.
1552 // Consume the argument.
1553 unsigned argIndex
= FS
.getArgIndex();
1554 if (argIndex
< NumDataArgs
) {
1555 // The check to see if the argIndex is valid will come later.
1556 // We set the bit here because we may exit early from this
1557 // function if we encounter some other error.
1558 CoveredArgs
.set(argIndex
);
1561 // Check for using an Objective-C specific conversion specifier
1562 // in a non-ObjC literal.
1563 if (!IsObjCLiteral
&& CS
.isObjCArg()) {
1564 return HandleInvalidPrintfConversionSpecifier(FS
, startSpecifier
,
1568 // Check for invalid use of field width
1569 if (!FS
.hasValidFieldWidth()) {
1570 HandleInvalidAmount(FS
, FS
.getFieldWidth(), /* field width */ 0,
1571 startSpecifier
, specifierLen
);
1574 // Check for invalid use of precision
1575 if (!FS
.hasValidPrecision()) {
1576 HandleInvalidAmount(FS
, FS
.getPrecision(), /* precision */ 1,
1577 startSpecifier
, specifierLen
);
1580 // Check each flag does not conflict with any other component.
1581 if (!FS
.hasValidThousandsGroupingPrefix())
1582 HandleFlag(FS
, FS
.hasThousandsGrouping(), startSpecifier
, specifierLen
);
1583 if (!FS
.hasValidLeadingZeros())
1584 HandleFlag(FS
, FS
.hasLeadingZeros(), startSpecifier
, specifierLen
);
1585 if (!FS
.hasValidPlusPrefix())
1586 HandleFlag(FS
, FS
.hasPlusPrefix(), startSpecifier
, specifierLen
);
1587 if (!FS
.hasValidSpacePrefix())
1588 HandleFlag(FS
, FS
.hasSpacePrefix(), startSpecifier
, specifierLen
);
1589 if (!FS
.hasValidAlternativeForm())
1590 HandleFlag(FS
, FS
.hasAlternativeForm(), startSpecifier
, specifierLen
);
1591 if (!FS
.hasValidLeftJustified())
1592 HandleFlag(FS
, FS
.isLeftJustified(), startSpecifier
, specifierLen
);
1594 // Check that flags are not ignored by another flag
1595 if (FS
.hasSpacePrefix() && FS
.hasPlusPrefix()) // ' ' ignored by '+'
1596 HandleIgnoredFlag(FS
, FS
.hasSpacePrefix(), FS
.hasPlusPrefix(),
1597 startSpecifier
, specifierLen
);
1598 if (FS
.hasLeadingZeros() && FS
.isLeftJustified()) // '0' ignored by '-'
1599 HandleIgnoredFlag(FS
, FS
.hasLeadingZeros(), FS
.isLeftJustified(),
1600 startSpecifier
, specifierLen
);
1602 // Check the length modifier is valid with the given conversion specifier.
1603 const LengthModifier
&LM
= FS
.getLengthModifier();
1604 if (!FS
.hasValidLengthModifier())
1605 S
.Diag(getLocationOfByte(LM
.getStart()),
1606 diag::warn_format_nonsensical_length
)
1607 << LM
.toString() << CS
.toString()
1608 << getSpecifierRange(startSpecifier
, specifierLen
)
1609 << FixItHint::CreateRemoval(getSpecifierRange(LM
.getStart(),
1612 // Are we using '%n'?
1613 if (CS
.getKind() == ConversionSpecifier::nArg
) {
1614 // Issue a warning about this being a possible security issue.
1615 S
.Diag(getLocationOfByte(CS
.getStart()), diag::warn_printf_write_back
)
1616 << getSpecifierRange(startSpecifier
, specifierLen
);
1617 // Continue checking the other format specifiers.
1621 // The remaining checks depend on the data arguments.
1625 if (!CheckNumArgs(FS
, CS
, startSpecifier
, specifierLen
, argIndex
))
1628 // Now type check the data expression that matches the
1629 // format specifier.
1630 const Expr
*Ex
= getDataArg(argIndex
);
1631 const analyze_printf::ArgTypeResult
&ATR
= FS
.getArgType(S
.Context
);
1632 if (ATR
.isValid() && !ATR
.matchesType(S
.Context
, Ex
->getType())) {
1633 // Check if we didn't match because of an implicit cast from a 'char'
1634 // or 'short' to an 'int'. This is done because printf is a varargs
1636 if (const ImplicitCastExpr
*ICE
= dyn_cast
<ImplicitCastExpr
>(Ex
))
1637 if (ICE
->getType() == S
.Context
.IntTy
) {
1638 // All further checking is done on the subexpression.
1639 Ex
= ICE
->getSubExpr();
1640 if (ATR
.matchesType(S
.Context
, Ex
->getType()))
1644 // We may be able to offer a FixItHint if it is a supported type.
1645 PrintfSpecifier fixedFS
= FS
;
1646 bool success
= fixedFS
.fixType(Ex
->getType());
1649 // Get the fix string from the fixed format specifier
1650 llvm::SmallString
<128> buf
;
1651 llvm::raw_svector_ostream
os(buf
);
1652 fixedFS
.toString(os
);
1654 // FIXME: getRepresentativeType() perhaps should return a string
1655 // instead of a QualType to better handle when the representative
1656 // type is 'wint_t' (which is defined in the system headers).
1657 S
.Diag(getLocationOfByte(CS
.getStart()),
1658 diag::warn_printf_conversion_argument_type_mismatch
)
1659 << ATR
.getRepresentativeType(S
.Context
) << Ex
->getType()
1660 << getSpecifierRange(startSpecifier
, specifierLen
)
1661 << Ex
->getSourceRange()
1662 << FixItHint::CreateReplacement(
1663 getSpecifierRange(startSpecifier
, specifierLen
),
1667 S
.Diag(getLocationOfByte(CS
.getStart()),
1668 diag::warn_printf_conversion_argument_type_mismatch
)
1669 << ATR
.getRepresentativeType(S
.Context
) << Ex
->getType()
1670 << getSpecifierRange(startSpecifier
, specifierLen
)
1671 << Ex
->getSourceRange();
1678 //===--- CHECK: Scanf format string checking ------------------------------===//
1681 class CheckScanfHandler
: public CheckFormatHandler
{
1683 CheckScanfHandler(Sema
&s
, const StringLiteral
*fexpr
,
1684 const Expr
*origFormatExpr
, unsigned firstDataArg
,
1685 unsigned numDataArgs
, bool isObjCLiteral
,
1686 const char *beg
, bool hasVAListArg
,
1687 const CallExpr
*theCall
, unsigned formatIdx
)
1688 : CheckFormatHandler(s
, fexpr
, origFormatExpr
, firstDataArg
,
1689 numDataArgs
, isObjCLiteral
, beg
, hasVAListArg
,
1690 theCall
, formatIdx
) {}
1692 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier
&FS
,
1693 const char *startSpecifier
,
1694 unsigned specifierLen
);
1696 bool HandleInvalidScanfConversionSpecifier(
1697 const analyze_scanf::ScanfSpecifier
&FS
,
1698 const char *startSpecifier
,
1699 unsigned specifierLen
);
1701 void HandleIncompleteScanList(const char *start
, const char *end
);
1705 void CheckScanfHandler::HandleIncompleteScanList(const char *start
,
1707 S
.Diag(getLocationOfByte(end
), diag::warn_scanf_scanlist_incomplete
)
1708 << getSpecifierRange(start
, end
- start
);
1711 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
1712 const analyze_scanf::ScanfSpecifier
&FS
,
1713 const char *startSpecifier
,
1714 unsigned specifierLen
) {
1716 const analyze_scanf::ScanfConversionSpecifier
&CS
=
1717 FS
.getConversionSpecifier();
1719 return HandleInvalidConversionSpecifier(FS
.getArgIndex(),
1720 getLocationOfByte(CS
.getStart()),
1721 startSpecifier
, specifierLen
,
1722 CS
.getStart(), CS
.getLength());
1725 bool CheckScanfHandler::HandleScanfSpecifier(
1726 const analyze_scanf::ScanfSpecifier
&FS
,
1727 const char *startSpecifier
,
1728 unsigned specifierLen
) {
1730 using namespace analyze_scanf
;
1731 using namespace analyze_format_string
;
1733 const ScanfConversionSpecifier
&CS
= FS
.getConversionSpecifier();
1735 // Handle case where '%' and '*' don't consume an argument. These shouldn't
1736 // be used to decide if we are using positional arguments consistently.
1737 if (FS
.consumesDataArgument()) {
1740 usesPositionalArgs
= FS
.usesPositionalArg();
1742 else if (usesPositionalArgs
!= FS
.usesPositionalArg()) {
1743 // Cannot mix-and-match positional and non-positional arguments.
1744 S
.Diag(getLocationOfByte(CS
.getStart()),
1745 diag::warn_format_mix_positional_nonpositional_args
)
1746 << getSpecifierRange(startSpecifier
, specifierLen
);
1751 // Check if the field with is non-zero.
1752 const OptionalAmount
&Amt
= FS
.getFieldWidth();
1753 if (Amt
.getHowSpecified() == OptionalAmount::Constant
) {
1754 if (Amt
.getConstantAmount() == 0) {
1755 const CharSourceRange
&R
= getSpecifierRange(Amt
.getStart(),
1756 Amt
.getConstantLength());
1757 S
.Diag(getLocationOfByte(Amt
.getStart()),
1758 diag::warn_scanf_nonzero_width
)
1759 << R
<< FixItHint::CreateRemoval(R
);
1763 if (!FS
.consumesDataArgument()) {
1764 // FIXME: Technically specifying a precision or field width here
1765 // makes no sense. Worth issuing a warning at some point.
1769 // Consume the argument.
1770 unsigned argIndex
= FS
.getArgIndex();
1771 if (argIndex
< NumDataArgs
) {
1772 // The check to see if the argIndex is valid will come later.
1773 // We set the bit here because we may exit early from this
1774 // function if we encounter some other error.
1775 CoveredArgs
.set(argIndex
);
1778 // Check the length modifier is valid with the given conversion specifier.
1779 const LengthModifier
&LM
= FS
.getLengthModifier();
1780 if (!FS
.hasValidLengthModifier()) {
1781 S
.Diag(getLocationOfByte(LM
.getStart()),
1782 diag::warn_format_nonsensical_length
)
1783 << LM
.toString() << CS
.toString()
1784 << getSpecifierRange(startSpecifier
, specifierLen
)
1785 << FixItHint::CreateRemoval(getSpecifierRange(LM
.getStart(),
1789 // The remaining checks depend on the data arguments.
1793 if (!CheckNumArgs(FS
, CS
, startSpecifier
, specifierLen
, argIndex
))
1796 // FIXME: Check that the argument type matches the format specifier.
1801 void Sema::CheckFormatString(const StringLiteral
*FExpr
,
1802 const Expr
*OrigFormatExpr
,
1803 const CallExpr
*TheCall
, bool HasVAListArg
,
1804 unsigned format_idx
, unsigned firstDataArg
,
1807 // CHECK: is the format string a wide literal?
1808 if (FExpr
->isWide()) {
1809 Diag(FExpr
->getLocStart(),
1810 diag::warn_format_string_is_wide_literal
)
1811 << OrigFormatExpr
->getSourceRange();
1815 // Str - The format string. NOTE: this is NOT null-terminated!
1816 llvm::StringRef StrRef
= FExpr
->getString();
1817 const char *Str
= StrRef
.data();
1818 unsigned StrLen
= StrRef
.size();
1820 // CHECK: empty format string?
1822 Diag(FExpr
->getLocStart(), diag::warn_empty_format_string
)
1823 << OrigFormatExpr
->getSourceRange();
1828 CheckPrintfHandler
H(*this, FExpr
, OrigFormatExpr
, firstDataArg
,
1829 TheCall
->getNumArgs() - firstDataArg
,
1830 isa
<ObjCStringLiteral
>(OrigFormatExpr
), Str
,
1831 HasVAListArg
, TheCall
, format_idx
);
1833 if (!analyze_format_string::ParsePrintfString(H
, Str
, Str
+ StrLen
))
1837 CheckScanfHandler
H(*this, FExpr
, OrigFormatExpr
, firstDataArg
,
1838 TheCall
->getNumArgs() - firstDataArg
,
1839 isa
<ObjCStringLiteral
>(OrigFormatExpr
), Str
,
1840 HasVAListArg
, TheCall
, format_idx
);
1842 if (!analyze_format_string::ParseScanfString(H
, Str
, Str
+ StrLen
))
1847 //===--- CHECK: Standard memory functions ---------------------------------===//
1849 /// \brief Determine whether the given type is a dynamic class type (e.g.,
1850 /// whether it has a vtable).
1851 static bool isDynamicClassType(QualType T
) {
1852 if (CXXRecordDecl
*Record
= T
->getAsCXXRecordDecl())
1853 if (CXXRecordDecl
*Definition
= Record
->getDefinition())
1854 if (Definition
->isDynamicClass())
1860 /// \brief If E is a sizeof expression, returns its argument expression,
1861 /// otherwise returns NULL.
1862 static const Expr
*getSizeOfExprArg(const Expr
* E
) {
1863 if (const UnaryExprOrTypeTraitExpr
*SizeOf
=
1864 dyn_cast
<UnaryExprOrTypeTraitExpr
>(E
))
1865 if (SizeOf
->getKind() == clang::UETT_SizeOf
&& !SizeOf
->isArgumentType())
1866 return SizeOf
->getArgumentExpr()->IgnoreParenImpCasts();
1871 /// \brief If E is a sizeof expression, returns its argument type.
1872 static QualType
getSizeOfArgType(const Expr
* E
) {
1873 if (const UnaryExprOrTypeTraitExpr
*SizeOf
=
1874 dyn_cast
<UnaryExprOrTypeTraitExpr
>(E
))
1875 if (SizeOf
->getKind() == clang::UETT_SizeOf
)
1876 return SizeOf
->getTypeOfArgument();
1881 /// \brief Check for dangerous or invalid arguments to memset().
1883 /// This issues warnings on known problematic, dangerous or unspecified
1884 /// arguments to the standard 'memset', 'memcpy', and 'memmove' function calls.
1886 /// \param Call The call expression to diagnose.
1887 void Sema::CheckMemsetcpymoveArguments(const CallExpr
*Call
,
1888 CheckedMemoryFunction CMF
,
1889 IdentifierInfo
*FnName
) {
1890 // It is possible to have a non-standard definition of memset. Validate
1891 // we have enough arguments, and if not, abort further checking.
1892 if (Call
->getNumArgs() < 3)
1895 unsigned LastArg
= (CMF
== CMF_Memset
? 1 : 2);
1896 const Expr
*LenExpr
= Call
->getArg(2)->IgnoreParenImpCasts();
1898 // We have special checking when the length is a sizeof expression.
1899 QualType SizeOfArgTy
= getSizeOfArgType(LenExpr
);
1900 const Expr
*SizeOfArg
= getSizeOfExprArg(LenExpr
);
1901 llvm::FoldingSetNodeID SizeOfArgID
;
1903 for (unsigned ArgIdx
= 0; ArgIdx
!= LastArg
; ++ArgIdx
) {
1904 const Expr
*Dest
= Call
->getArg(ArgIdx
)->IgnoreParenImpCasts();
1905 SourceRange ArgRange
= Call
->getArg(ArgIdx
)->getSourceRange();
1907 QualType DestTy
= Dest
->getType();
1908 if (const PointerType
*DestPtrTy
= DestTy
->getAs
<PointerType
>()) {
1909 QualType PointeeTy
= DestPtrTy
->getPointeeType();
1911 // Never warn about void type pointers. This can be used to suppress
1913 if (PointeeTy
->isVoidType())
1916 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
1917 // actually comparing the expressions for equality. Because computing the
1918 // expression IDs can be expensive, we only do this if the diagnostic is
1921 Diags
.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess
,
1922 SizeOfArg
->getExprLoc())) {
1923 // We only compute IDs for expressions if the warning is enabled, and
1924 // cache the sizeof arg's ID.
1925 if (SizeOfArgID
== llvm::FoldingSetNodeID())
1926 SizeOfArg
->Profile(SizeOfArgID
, Context
, true);
1927 llvm::FoldingSetNodeID DestID
;
1928 Dest
->Profile(DestID
, Context
, true);
1929 if (DestID
== SizeOfArgID
) {
1930 unsigned ActionIdx
= 0; // Default is to suggest dereferencing.
1931 if (const UnaryOperator
*UnaryOp
= dyn_cast
<UnaryOperator
>(Dest
))
1932 if (UnaryOp
->getOpcode() == UO_AddrOf
)
1933 ActionIdx
= 1; // If its an address-of operator, just remove it.
1934 if (Context
.getTypeSize(PointeeTy
) == Context
.getCharWidth())
1935 ActionIdx
= 2; // If the pointee's size is sizeof(char),
1936 // suggest an explicit length.
1937 DiagRuntimeBehavior(SizeOfArg
->getExprLoc(), Dest
,
1938 PDiag(diag::warn_sizeof_pointer_expr_memaccess
)
1939 << FnName
<< ArgIdx
<< ActionIdx
1940 << Dest
->getSourceRange()
1941 << SizeOfArg
->getSourceRange());
1946 // Also check for cases where the sizeof argument is the exact same
1947 // type as the memory argument, and where it points to a user-defined
1949 if (SizeOfArgTy
!= QualType()) {
1950 if (PointeeTy
->isRecordType() &&
1951 Context
.typesAreCompatible(SizeOfArgTy
, DestTy
)) {
1952 DiagRuntimeBehavior(LenExpr
->getExprLoc(), Dest
,
1953 PDiag(diag::warn_sizeof_pointer_type_memaccess
)
1954 << FnName
<< SizeOfArgTy
<< ArgIdx
1955 << PointeeTy
<< Dest
->getSourceRange()
1956 << LenExpr
->getSourceRange());
1963 // Always complain about dynamic classes.
1964 if (isDynamicClassType(PointeeTy
))
1965 DiagID
= diag::warn_dyn_class_memaccess
;
1966 else if (PointeeTy
.hasNonTrivialObjCLifetime() && CMF
!= CMF_Memset
)
1967 DiagID
= diag::warn_arc_object_memaccess
;
1971 DiagRuntimeBehavior(
1972 Dest
->getExprLoc(), Dest
,
1974 << ArgIdx
<< FnName
<< PointeeTy
1975 << Call
->getCallee()->getSourceRange());
1977 DiagRuntimeBehavior(
1978 Dest
->getExprLoc(), Dest
,
1979 PDiag(diag::note_bad_memaccess_silence
)
1980 << FixItHint::CreateInsertion(ArgRange
.getBegin(), "(void*)"));
1986 //===--- CHECK: Return Address of Stack Variable --------------------------===//
1988 static Expr
*EvalVal(Expr
*E
, llvm::SmallVectorImpl
<DeclRefExpr
*> &refVars
);
1989 static Expr
*EvalAddr(Expr
* E
, llvm::SmallVectorImpl
<DeclRefExpr
*> &refVars
);
1991 /// CheckReturnStackAddr - Check if a return statement returns the address
1992 /// of a stack variable.
1994 Sema::CheckReturnStackAddr(Expr
*RetValExp
, QualType lhsType
,
1995 SourceLocation ReturnLoc
) {
1998 llvm::SmallVector
<DeclRefExpr
*, 8> refVars
;
2000 // Perform checking for returned stack addresses, local blocks,
2001 // label addresses or references to temporaries.
2002 if (lhsType
->isPointerType() ||
2003 (!getLangOptions().ObjCAutoRefCount
&& lhsType
->isBlockPointerType())) {
2004 stackE
= EvalAddr(RetValExp
, refVars
);
2005 } else if (lhsType
->isReferenceType()) {
2006 stackE
= EvalVal(RetValExp
, refVars
);
2010 return; // Nothing suspicious was found.
2012 SourceLocation diagLoc
;
2013 SourceRange diagRange
;
2014 if (refVars
.empty()) {
2015 diagLoc
= stackE
->getLocStart();
2016 diagRange
= stackE
->getSourceRange();
2018 // We followed through a reference variable. 'stackE' contains the
2019 // problematic expression but we will warn at the return statement pointing
2020 // at the reference variable. We will later display the "trail" of
2021 // reference variables using notes.
2022 diagLoc
= refVars
[0]->getLocStart();
2023 diagRange
= refVars
[0]->getSourceRange();
2026 if (DeclRefExpr
*DR
= dyn_cast
<DeclRefExpr
>(stackE
)) { //address of local var.
2027 Diag(diagLoc
, lhsType
->isReferenceType() ? diag::warn_ret_stack_ref
2028 : diag::warn_ret_stack_addr
)
2029 << DR
->getDecl()->getDeclName() << diagRange
;
2030 } else if (isa
<BlockExpr
>(stackE
)) { // local block.
2031 Diag(diagLoc
, diag::err_ret_local_block
) << diagRange
;
2032 } else if (isa
<AddrLabelExpr
>(stackE
)) { // address of label.
2033 Diag(diagLoc
, diag::warn_ret_addr_label
) << diagRange
;
2034 } else { // local temporary.
2035 Diag(diagLoc
, lhsType
->isReferenceType() ? diag::warn_ret_local_temp_ref
2036 : diag::warn_ret_local_temp_addr
)
2040 // Display the "trail" of reference variables that we followed until we
2041 // found the problematic expression using notes.
2042 for (unsigned i
= 0, e
= refVars
.size(); i
!= e
; ++i
) {
2043 VarDecl
*VD
= cast
<VarDecl
>(refVars
[i
]->getDecl());
2044 // If this var binds to another reference var, show the range of the next
2045 // var, otherwise the var binds to the problematic expression, in which case
2046 // show the range of the expression.
2047 SourceRange range
= (i
< e
-1) ? refVars
[i
+1]->getSourceRange()
2048 : stackE
->getSourceRange();
2049 Diag(VD
->getLocation(), diag::note_ref_var_local_bind
)
2050 << VD
->getDeclName() << range
;
2054 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
2055 /// check if the expression in a return statement evaluates to an address
2056 /// to a location on the stack, a local block, an address of a label, or a
2057 /// reference to local temporary. The recursion is used to traverse the
2058 /// AST of the return expression, with recursion backtracking when we
2059 /// encounter a subexpression that (1) clearly does not lead to one of the
2060 /// above problematic expressions (2) is something we cannot determine leads to
2061 /// a problematic expression based on such local checking.
2063 /// Both EvalAddr and EvalVal follow through reference variables to evaluate
2064 /// the expression that they point to. Such variables are added to the
2065 /// 'refVars' vector so that we know what the reference variable "trail" was.
2067 /// EvalAddr processes expressions that are pointers that are used as
2068 /// references (and not L-values). EvalVal handles all other values.
2069 /// At the base case of the recursion is a check for the above problematic
2072 /// This implementation handles:
2074 /// * pointer-to-pointer casts
2075 /// * implicit conversions from array references to pointers
2076 /// * taking the address of fields
2077 /// * arbitrary interplay between "&" and "*" operators
2078 /// * pointer arithmetic from an address of a stack variable
2079 /// * taking the address of an array element where the array is on the stack
2080 static Expr
*EvalAddr(Expr
*E
, llvm::SmallVectorImpl
<DeclRefExpr
*> &refVars
) {
2081 if (E
->isTypeDependent())
2084 // We should only be called for evaluating pointer expressions.
2085 assert((E
->getType()->isAnyPointerType() ||
2086 E
->getType()->isBlockPointerType() ||
2087 E
->getType()->isObjCQualifiedIdType()) &&
2088 "EvalAddr only works on pointers");
2090 E
= E
->IgnoreParens();
2092 // Our "symbolic interpreter" is just a dispatch off the currently
2093 // viewed AST node. We then recursively traverse the AST by calling
2094 // EvalAddr and EvalVal appropriately.
2095 switch (E
->getStmtClass()) {
2096 case Stmt::DeclRefExprClass
: {
2097 DeclRefExpr
*DR
= cast
<DeclRefExpr
>(E
);
2099 if (VarDecl
*V
= dyn_cast
<VarDecl
>(DR
->getDecl()))
2100 // If this is a reference variable, follow through to the expression that
2102 if (V
->hasLocalStorage() &&
2103 V
->getType()->isReferenceType() && V
->hasInit()) {
2104 // Add the reference variable to the "trail".
2105 refVars
.push_back(DR
);
2106 return EvalAddr(V
->getInit(), refVars
);
2112 case Stmt::UnaryOperatorClass
: {
2113 // The only unary operator that make sense to handle here
2114 // is AddrOf. All others don't make sense as pointers.
2115 UnaryOperator
*U
= cast
<UnaryOperator
>(E
);
2117 if (U
->getOpcode() == UO_AddrOf
)
2118 return EvalVal(U
->getSubExpr(), refVars
);
2123 case Stmt::BinaryOperatorClass
: {
2124 // Handle pointer arithmetic. All other binary operators are not valid
2126 BinaryOperator
*B
= cast
<BinaryOperator
>(E
);
2127 BinaryOperatorKind op
= B
->getOpcode();
2129 if (op
!= BO_Add
&& op
!= BO_Sub
)
2132 Expr
*Base
= B
->getLHS();
2134 // Determine which argument is the real pointer base. It could be
2135 // the RHS argument instead of the LHS.
2136 if (!Base
->getType()->isPointerType()) Base
= B
->getRHS();
2138 assert (Base
->getType()->isPointerType());
2139 return EvalAddr(Base
, refVars
);
2142 // For conditional operators we need to see if either the LHS or RHS are
2143 // valid DeclRefExpr*s. If one of them is valid, we return it.
2144 case Stmt::ConditionalOperatorClass
: {
2145 ConditionalOperator
*C
= cast
<ConditionalOperator
>(E
);
2147 // Handle the GNU extension for missing LHS.
2148 if (Expr
*lhsExpr
= C
->getLHS()) {
2149 // In C++, we can have a throw-expression, which has 'void' type.
2150 if (!lhsExpr
->getType()->isVoidType())
2151 if (Expr
* LHS
= EvalAddr(lhsExpr
, refVars
))
2155 // In C++, we can have a throw-expression, which has 'void' type.
2156 if (C
->getRHS()->getType()->isVoidType())
2159 return EvalAddr(C
->getRHS(), refVars
);
2162 case Stmt::BlockExprClass
:
2163 if (cast
<BlockExpr
>(E
)->getBlockDecl()->hasCaptures())
2164 return E
; // local block.
2167 case Stmt::AddrLabelExprClass
:
2168 return E
; // address of label.
2170 // For casts, we need to handle conversions from arrays to
2171 // pointer values, and pointer-to-pointer conversions.
2172 case Stmt::ImplicitCastExprClass
:
2173 case Stmt::CStyleCastExprClass
:
2174 case Stmt::CXXFunctionalCastExprClass
:
2175 case Stmt::ObjCBridgedCastExprClass
: {
2176 Expr
* SubExpr
= cast
<CastExpr
>(E
)->getSubExpr();
2177 QualType T
= SubExpr
->getType();
2179 if (SubExpr
->getType()->isPointerType() ||
2180 SubExpr
->getType()->isBlockPointerType() ||
2181 SubExpr
->getType()->isObjCQualifiedIdType())
2182 return EvalAddr(SubExpr
, refVars
);
2183 else if (T
->isArrayType())
2184 return EvalVal(SubExpr
, refVars
);
2189 // C++ casts. For dynamic casts, static casts, and const casts, we
2190 // are always converting from a pointer-to-pointer, so we just blow
2191 // through the cast. In the case the dynamic cast doesn't fail (and
2192 // return NULL), we take the conservative route and report cases
2193 // where we return the address of a stack variable. For Reinterpre
2194 // FIXME: The comment about is wrong; we're not always converting
2195 // from pointer to pointer. I'm guessing that this code should also
2196 // handle references to objects.
2197 case Stmt::CXXStaticCastExprClass
:
2198 case Stmt::CXXDynamicCastExprClass
:
2199 case Stmt::CXXConstCastExprClass
:
2200 case Stmt::CXXReinterpretCastExprClass
: {
2201 Expr
*S
= cast
<CXXNamedCastExpr
>(E
)->getSubExpr();
2202 if (S
->getType()->isPointerType() || S
->getType()->isBlockPointerType())
2203 return EvalAddr(S
, refVars
);
2208 case Stmt::MaterializeTemporaryExprClass
:
2209 if (Expr
*Result
= EvalAddr(
2210 cast
<MaterializeTemporaryExpr
>(E
)->GetTemporaryExpr(),
2216 // Everything else: we simply don't reason about them.
2223 /// EvalVal - This function is complements EvalAddr in the mutual recursion.
2224 /// See the comments for EvalAddr for more details.
2225 static Expr
*EvalVal(Expr
*E
, llvm::SmallVectorImpl
<DeclRefExpr
*> &refVars
) {
2227 // We should only be called for evaluating non-pointer expressions, or
2228 // expressions with a pointer type that are not used as references but instead
2229 // are l-values (e.g., DeclRefExpr with a pointer type).
2231 // Our "symbolic interpreter" is just a dispatch off the currently
2232 // viewed AST node. We then recursively traverse the AST by calling
2233 // EvalAddr and EvalVal appropriately.
2235 E
= E
->IgnoreParens();
2236 switch (E
->getStmtClass()) {
2237 case Stmt::ImplicitCastExprClass
: {
2238 ImplicitCastExpr
*IE
= cast
<ImplicitCastExpr
>(E
);
2239 if (IE
->getValueKind() == VK_LValue
) {
2240 E
= IE
->getSubExpr();
2246 case Stmt::DeclRefExprClass
: {
2247 // When we hit a DeclRefExpr we are looking at code that refers to a
2248 // variable's name. If it's not a reference variable we check if it has
2249 // local storage within the function, and if so, return the expression.
2250 DeclRefExpr
*DR
= cast
<DeclRefExpr
>(E
);
2252 if (VarDecl
*V
= dyn_cast
<VarDecl
>(DR
->getDecl()))
2253 if (V
->hasLocalStorage()) {
2254 if (!V
->getType()->isReferenceType())
2257 // Reference variable, follow through to the expression that
2260 // Add the reference variable to the "trail".
2261 refVars
.push_back(DR
);
2262 return EvalVal(V
->getInit(), refVars
);
2269 case Stmt::UnaryOperatorClass
: {
2270 // The only unary operator that make sense to handle here
2271 // is Deref. All others don't resolve to a "name." This includes
2272 // handling all sorts of rvalues passed to a unary operator.
2273 UnaryOperator
*U
= cast
<UnaryOperator
>(E
);
2275 if (U
->getOpcode() == UO_Deref
)
2276 return EvalAddr(U
->getSubExpr(), refVars
);
2281 case Stmt::ArraySubscriptExprClass
: {
2282 // Array subscripts are potential references to data on the stack. We
2283 // retrieve the DeclRefExpr* for the array variable if it indeed
2284 // has local storage.
2285 return EvalAddr(cast
<ArraySubscriptExpr
>(E
)->getBase(), refVars
);
2288 case Stmt::ConditionalOperatorClass
: {
2289 // For conditional operators we need to see if either the LHS or RHS are
2290 // non-NULL Expr's. If one is non-NULL, we return it.
2291 ConditionalOperator
*C
= cast
<ConditionalOperator
>(E
);
2293 // Handle the GNU extension for missing LHS.
2294 if (Expr
*lhsExpr
= C
->getLHS())
2295 if (Expr
*LHS
= EvalVal(lhsExpr
, refVars
))
2298 return EvalVal(C
->getRHS(), refVars
);
2301 // Accesses to members are potential references to data on the stack.
2302 case Stmt::MemberExprClass
: {
2303 MemberExpr
*M
= cast
<MemberExpr
>(E
);
2305 // Check for indirect access. We only want direct field accesses.
2309 // Check whether the member type is itself a reference, in which case
2310 // we're not going to refer to the member, but to what the member refers to.
2311 if (M
->getMemberDecl()->getType()->isReferenceType())
2314 return EvalVal(M
->getBase(), refVars
);
2317 case Stmt::MaterializeTemporaryExprClass
:
2318 if (Expr
*Result
= EvalVal(
2319 cast
<MaterializeTemporaryExpr
>(E
)->GetTemporaryExpr(),
2326 // Check that we don't return or take the address of a reference to a
2327 // temporary. This is only useful in C++.
2328 if (!E
->isTypeDependent() && E
->isRValue())
2331 // Everything else: we simply don't reason about them.
2337 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
2339 /// Check for comparisons of floating point operands using != and ==.
2340 /// Issue a warning if these are no self-comparisons, as they are not likely
2341 /// to do what the programmer intended.
2342 void Sema::CheckFloatComparison(SourceLocation loc
, Expr
* lex
, Expr
*rex
) {
2343 bool EmitWarning
= true;
2345 Expr
* LeftExprSansParen
= lex
->IgnoreParenImpCasts();
2346 Expr
* RightExprSansParen
= rex
->IgnoreParenImpCasts();
2348 // Special case: check for x == x (which is OK).
2349 // Do not emit warnings for such cases.
2350 if (DeclRefExpr
* DRL
= dyn_cast
<DeclRefExpr
>(LeftExprSansParen
))
2351 if (DeclRefExpr
* DRR
= dyn_cast
<DeclRefExpr
>(RightExprSansParen
))
2352 if (DRL
->getDecl() == DRR
->getDecl())
2353 EmitWarning
= false;
2356 // Special case: check for comparisons against literals that can be exactly
2357 // represented by APFloat. In such cases, do not emit a warning. This
2358 // is a heuristic: often comparison against such literals are used to
2359 // detect if a value in a variable has not changed. This clearly can
2360 // lead to false negatives.
2362 if (FloatingLiteral
* FLL
= dyn_cast
<FloatingLiteral
>(LeftExprSansParen
)) {
2364 EmitWarning
= false;
2366 if (FloatingLiteral
* FLR
= dyn_cast
<FloatingLiteral
>(RightExprSansParen
)){
2368 EmitWarning
= false;
2372 // Check for comparisons with builtin types.
2374 if (CallExpr
* CL
= dyn_cast
<CallExpr
>(LeftExprSansParen
))
2375 if (CL
->isBuiltinCall(Context
))
2376 EmitWarning
= false;
2379 if (CallExpr
* CR
= dyn_cast
<CallExpr
>(RightExprSansParen
))
2380 if (CR
->isBuiltinCall(Context
))
2381 EmitWarning
= false;
2383 // Emit the diagnostic.
2385 Diag(loc
, diag::warn_floatingpoint_eq
)
2386 << lex
->getSourceRange() << rex
->getSourceRange();
2389 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
2390 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
2394 /// Structure recording the 'active' range of an integer-valued
2397 /// The number of bits active in the int.
2400 /// True if the int is known not to have negative values.
2403 IntRange(unsigned Width
, bool NonNegative
)
2404 : Width(Width
), NonNegative(NonNegative
)
2407 /// Returns the range of the bool type.
2408 static IntRange
forBoolType() {
2409 return IntRange(1, true);
2412 /// Returns the range of an opaque value of the given integral type.
2413 static IntRange
forValueOfType(ASTContext
&C
, QualType T
) {
2414 return forValueOfCanonicalType(C
,
2415 T
->getCanonicalTypeInternal().getTypePtr());
2418 /// Returns the range of an opaque value of a canonical integral type.
2419 static IntRange
forValueOfCanonicalType(ASTContext
&C
, const Type
*T
) {
2420 assert(T
->isCanonicalUnqualified());
2422 if (const VectorType
*VT
= dyn_cast
<VectorType
>(T
))
2423 T
= VT
->getElementType().getTypePtr();
2424 if (const ComplexType
*CT
= dyn_cast
<ComplexType
>(T
))
2425 T
= CT
->getElementType().getTypePtr();
2427 // For enum types, use the known bit width of the enumerators.
2428 if (const EnumType
*ET
= dyn_cast
<EnumType
>(T
)) {
2429 EnumDecl
*Enum
= ET
->getDecl();
2430 if (!Enum
->isDefinition())
2431 return IntRange(C
.getIntWidth(QualType(T
, 0)), false);
2433 unsigned NumPositive
= Enum
->getNumPositiveBits();
2434 unsigned NumNegative
= Enum
->getNumNegativeBits();
2436 return IntRange(std::max(NumPositive
, NumNegative
), NumNegative
== 0);
2439 const BuiltinType
*BT
= cast
<BuiltinType
>(T
);
2440 assert(BT
->isInteger());
2442 return IntRange(C
.getIntWidth(QualType(T
, 0)), BT
->isUnsignedInteger());
2445 /// Returns the "target" range of a canonical integral type, i.e.
2446 /// the range of values expressible in the type.
2448 /// This matches forValueOfCanonicalType except that enums have the
2449 /// full range of their type, not the range of their enumerators.
2450 static IntRange
forTargetOfCanonicalType(ASTContext
&C
, const Type
*T
) {
2451 assert(T
->isCanonicalUnqualified());
2453 if (const VectorType
*VT
= dyn_cast
<VectorType
>(T
))
2454 T
= VT
->getElementType().getTypePtr();
2455 if (const ComplexType
*CT
= dyn_cast
<ComplexType
>(T
))
2456 T
= CT
->getElementType().getTypePtr();
2457 if (const EnumType
*ET
= dyn_cast
<EnumType
>(T
))
2458 T
= ET
->getDecl()->getIntegerType().getTypePtr();
2460 const BuiltinType
*BT
= cast
<BuiltinType
>(T
);
2461 assert(BT
->isInteger());
2463 return IntRange(C
.getIntWidth(QualType(T
, 0)), BT
->isUnsignedInteger());
2466 /// Returns the supremum of two ranges: i.e. their conservative merge.
2467 static IntRange
join(IntRange L
, IntRange R
) {
2468 return IntRange(std::max(L
.Width
, R
.Width
),
2469 L
.NonNegative
&& R
.NonNegative
);
2472 /// Returns the infinum of two ranges: i.e. their aggressive merge.
2473 static IntRange
meet(IntRange L
, IntRange R
) {
2474 return IntRange(std::min(L
.Width
, R
.Width
),
2475 L
.NonNegative
|| R
.NonNegative
);
2479 IntRange
GetValueRange(ASTContext
&C
, llvm::APSInt
&value
, unsigned MaxWidth
) {
2480 if (value
.isSigned() && value
.isNegative())
2481 return IntRange(value
.getMinSignedBits(), false);
2483 if (value
.getBitWidth() > MaxWidth
)
2484 value
= value
.trunc(MaxWidth
);
2486 // isNonNegative() just checks the sign bit without considering
2488 return IntRange(value
.getActiveBits(), true);
2491 IntRange
GetValueRange(ASTContext
&C
, APValue
&result
, QualType Ty
,
2492 unsigned MaxWidth
) {
2494 return GetValueRange(C
, result
.getInt(), MaxWidth
);
2496 if (result
.isVector()) {
2497 IntRange R
= GetValueRange(C
, result
.getVectorElt(0), Ty
, MaxWidth
);
2498 for (unsigned i
= 1, e
= result
.getVectorLength(); i
!= e
; ++i
) {
2499 IntRange El
= GetValueRange(C
, result
.getVectorElt(i
), Ty
, MaxWidth
);
2500 R
= IntRange::join(R
, El
);
2505 if (result
.isComplexInt()) {
2506 IntRange R
= GetValueRange(C
, result
.getComplexIntReal(), MaxWidth
);
2507 IntRange I
= GetValueRange(C
, result
.getComplexIntImag(), MaxWidth
);
2508 return IntRange::join(R
, I
);
2511 // This can happen with lossless casts to intptr_t of "based" lvalues.
2512 // Assume it might use arbitrary bits.
2513 // FIXME: The only reason we need to pass the type in here is to get
2514 // the sign right on this one case. It would be nice if APValue
2516 assert(result
.isLValue());
2517 return IntRange(MaxWidth
, Ty
->isUnsignedIntegerOrEnumerationType());
2520 /// Pseudo-evaluate the given integer expression, estimating the
2521 /// range of values it might take.
2523 /// \param MaxWidth - the width to which the value will be truncated
2524 IntRange
GetExprRange(ASTContext
&C
, Expr
*E
, unsigned MaxWidth
) {
2525 E
= E
->IgnoreParens();
2527 // Try a full evaluation first.
2528 Expr::EvalResult result
;
2529 if (E
->Evaluate(result
, C
))
2530 return GetValueRange(C
, result
.Val
, E
->getType(), MaxWidth
);
2532 // I think we only want to look through implicit casts here; if the
2533 // user has an explicit widening cast, we should treat the value as
2534 // being of the new, wider type.
2535 if (ImplicitCastExpr
*CE
= dyn_cast
<ImplicitCastExpr
>(E
)) {
2536 if (CE
->getCastKind() == CK_NoOp
)
2537 return GetExprRange(C
, CE
->getSubExpr(), MaxWidth
);
2539 IntRange OutputTypeRange
= IntRange::forValueOfType(C
, CE
->getType());
2541 bool isIntegerCast
= (CE
->getCastKind() == CK_IntegralCast
);
2543 // Assume that non-integer casts can span the full range of the type.
2545 return OutputTypeRange
;
2548 = GetExprRange(C
, CE
->getSubExpr(),
2549 std::min(MaxWidth
, OutputTypeRange
.Width
));
2551 // Bail out if the subexpr's range is as wide as the cast type.
2552 if (SubRange
.Width
>= OutputTypeRange
.Width
)
2553 return OutputTypeRange
;
2555 // Otherwise, we take the smaller width, and we're non-negative if
2556 // either the output type or the subexpr is.
2557 return IntRange(SubRange
.Width
,
2558 SubRange
.NonNegative
|| OutputTypeRange
.NonNegative
);
2561 if (ConditionalOperator
*CO
= dyn_cast
<ConditionalOperator
>(E
)) {
2562 // If we can fold the condition, just take that operand.
2564 if (CO
->getCond()->EvaluateAsBooleanCondition(CondResult
, C
))
2565 return GetExprRange(C
, CondResult
? CO
->getTrueExpr()
2566 : CO
->getFalseExpr(),
2569 // Otherwise, conservatively merge.
2570 IntRange L
= GetExprRange(C
, CO
->getTrueExpr(), MaxWidth
);
2571 IntRange R
= GetExprRange(C
, CO
->getFalseExpr(), MaxWidth
);
2572 return IntRange::join(L
, R
);
2575 if (BinaryOperator
*BO
= dyn_cast
<BinaryOperator
>(E
)) {
2576 switch (BO
->getOpcode()) {
2578 // Boolean-valued operations are single-bit and positive.
2587 return IntRange::forBoolType();
2589 // The type of these compound assignments is the type of the LHS,
2590 // so the RHS is not necessarily an integer.
2596 return IntRange::forValueOfType(C
, E
->getType());
2598 // Operations with opaque sources are black-listed.
2601 return IntRange::forValueOfType(C
, E
->getType());
2603 // Bitwise-and uses the *infinum* of the two source ranges.
2606 return IntRange::meet(GetExprRange(C
, BO
->getLHS(), MaxWidth
),
2607 GetExprRange(C
, BO
->getRHS(), MaxWidth
));
2609 // Left shift gets black-listed based on a judgement call.
2611 // ...except that we want to treat '1 << (blah)' as logically
2612 // positive. It's an important idiom.
2613 if (IntegerLiteral
*I
2614 = dyn_cast
<IntegerLiteral
>(BO
->getLHS()->IgnoreParenCasts())) {
2615 if (I
->getValue() == 1) {
2616 IntRange R
= IntRange::forValueOfType(C
, E
->getType());
2617 return IntRange(R
.Width
, /*NonNegative*/ true);
2623 return IntRange::forValueOfType(C
, E
->getType());
2625 // Right shift by a constant can narrow its left argument.
2627 case BO_ShrAssign
: {
2628 IntRange L
= GetExprRange(C
, BO
->getLHS(), MaxWidth
);
2630 // If the shift amount is a positive constant, drop the width by
2633 if (BO
->getRHS()->isIntegerConstantExpr(shift
, C
) &&
2634 shift
.isNonNegative()) {
2635 unsigned zext
= shift
.getZExtValue();
2636 if (zext
>= L
.Width
)
2637 L
.Width
= (L
.NonNegative
? 0 : 1);
2645 // Comma acts as its right operand.
2647 return GetExprRange(C
, BO
->getRHS(), MaxWidth
);
2649 // Black-list pointer subtractions.
2651 if (BO
->getLHS()->getType()->isPointerType())
2652 return IntRange::forValueOfType(C
, E
->getType());
2659 // Treat every other operator as if it were closed on the
2660 // narrowest type that encompasses both operands.
2661 IntRange L
= GetExprRange(C
, BO
->getLHS(), MaxWidth
);
2662 IntRange R
= GetExprRange(C
, BO
->getRHS(), MaxWidth
);
2663 return IntRange::join(L
, R
);
2666 if (UnaryOperator
*UO
= dyn_cast
<UnaryOperator
>(E
)) {
2667 switch (UO
->getOpcode()) {
2668 // Boolean-valued operations are white-listed.
2670 return IntRange::forBoolType();
2672 // Operations with opaque sources are black-listed.
2674 case UO_AddrOf
: // should be impossible
2675 return IntRange::forValueOfType(C
, E
->getType());
2678 return GetExprRange(C
, UO
->getSubExpr(), MaxWidth
);
2682 if (dyn_cast
<OffsetOfExpr
>(E
)) {
2683 IntRange::forValueOfType(C
, E
->getType());
2686 FieldDecl
*BitField
= E
->getBitField();
2688 llvm::APSInt BitWidthAP
= BitField
->getBitWidth()->EvaluateAsInt(C
);
2689 unsigned BitWidth
= BitWidthAP
.getZExtValue();
2691 return IntRange(BitWidth
,
2692 BitField
->getType()->isUnsignedIntegerOrEnumerationType());
2695 return IntRange::forValueOfType(C
, E
->getType());
2698 IntRange
GetExprRange(ASTContext
&C
, Expr
*E
) {
2699 return GetExprRange(C
, E
, C
.getIntWidth(E
->getType()));
2702 /// Checks whether the given value, which currently has the given
2703 /// source semantics, has the same value when coerced through the
2704 /// target semantics.
2705 bool IsSameFloatAfterCast(const llvm::APFloat
&value
,
2706 const llvm::fltSemantics
&Src
,
2707 const llvm::fltSemantics
&Tgt
) {
2708 llvm::APFloat truncated
= value
;
2711 truncated
.convert(Src
, llvm::APFloat::rmNearestTiesToEven
, &ignored
);
2712 truncated
.convert(Tgt
, llvm::APFloat::rmNearestTiesToEven
, &ignored
);
2714 return truncated
.bitwiseIsEqual(value
);
2717 /// Checks whether the given value, which currently has the given
2718 /// source semantics, has the same value when coerced through the
2719 /// target semantics.
2721 /// The value might be a vector of floats (or a complex number).
2722 bool IsSameFloatAfterCast(const APValue
&value
,
2723 const llvm::fltSemantics
&Src
,
2724 const llvm::fltSemantics
&Tgt
) {
2725 if (value
.isFloat())
2726 return IsSameFloatAfterCast(value
.getFloat(), Src
, Tgt
);
2728 if (value
.isVector()) {
2729 for (unsigned i
= 0, e
= value
.getVectorLength(); i
!= e
; ++i
)
2730 if (!IsSameFloatAfterCast(value
.getVectorElt(i
), Src
, Tgt
))
2735 assert(value
.isComplexFloat());
2736 return (IsSameFloatAfterCast(value
.getComplexFloatReal(), Src
, Tgt
) &&
2737 IsSameFloatAfterCast(value
.getComplexFloatImag(), Src
, Tgt
));
2740 void AnalyzeImplicitConversions(Sema
&S
, Expr
*E
, SourceLocation CC
);
2742 static bool IsZero(Sema
&S
, Expr
*E
) {
2743 // Suppress cases where we are comparing against an enum constant.
2744 if (const DeclRefExpr
*DR
=
2745 dyn_cast
<DeclRefExpr
>(E
->IgnoreParenImpCasts()))
2746 if (isa
<EnumConstantDecl
>(DR
->getDecl()))
2749 // Suppress cases where the '0' value is expanded from a macro.
2750 if (E
->getLocStart().isMacroID())
2754 return E
->isIntegerConstantExpr(Value
, S
.Context
) && Value
== 0;
2757 static bool HasEnumType(Expr
*E
) {
2758 // Strip off implicit integral promotions.
2759 while (ImplicitCastExpr
*ICE
= dyn_cast
<ImplicitCastExpr
>(E
)) {
2760 if (ICE
->getCastKind() != CK_IntegralCast
&&
2761 ICE
->getCastKind() != CK_NoOp
)
2763 E
= ICE
->getSubExpr();
2766 return E
->getType()->isEnumeralType();
2769 void CheckTrivialUnsignedComparison(Sema
&S
, BinaryOperator
*E
) {
2770 BinaryOperatorKind op
= E
->getOpcode();
2771 if (E
->isValueDependent())
2774 if (op
== BO_LT
&& IsZero(S
, E
->getRHS())) {
2775 S
.Diag(E
->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison
)
2776 << "< 0" << "false" << HasEnumType(E
->getLHS())
2777 << E
->getLHS()->getSourceRange() << E
->getRHS()->getSourceRange();
2778 } else if (op
== BO_GE
&& IsZero(S
, E
->getRHS())) {
2779 S
.Diag(E
->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison
)
2780 << ">= 0" << "true" << HasEnumType(E
->getLHS())
2781 << E
->getLHS()->getSourceRange() << E
->getRHS()->getSourceRange();
2782 } else if (op
== BO_GT
&& IsZero(S
, E
->getLHS())) {
2783 S
.Diag(E
->getOperatorLoc(), diag::warn_runsigned_always_true_comparison
)
2784 << "0 >" << "false" << HasEnumType(E
->getRHS())
2785 << E
->getLHS()->getSourceRange() << E
->getRHS()->getSourceRange();
2786 } else if (op
== BO_LE
&& IsZero(S
, E
->getLHS())) {
2787 S
.Diag(E
->getOperatorLoc(), diag::warn_runsigned_always_true_comparison
)
2788 << "0 <=" << "true" << HasEnumType(E
->getRHS())
2789 << E
->getLHS()->getSourceRange() << E
->getRHS()->getSourceRange();
2793 /// Analyze the operands of the given comparison. Implements the
2794 /// fallback case from AnalyzeComparison.
2795 void AnalyzeImpConvsInComparison(Sema
&S
, BinaryOperator
*E
) {
2796 AnalyzeImplicitConversions(S
, E
->getLHS(), E
->getOperatorLoc());
2797 AnalyzeImplicitConversions(S
, E
->getRHS(), E
->getOperatorLoc());
2800 /// \brief Implements -Wsign-compare.
2802 /// \param lex the left-hand expression
2803 /// \param rex the right-hand expression
2804 /// \param OpLoc the location of the joining operator
2805 /// \param BinOpc binary opcode or 0
2806 void AnalyzeComparison(Sema
&S
, BinaryOperator
*E
) {
2807 // The type the comparison is being performed in.
2808 QualType T
= E
->getLHS()->getType();
2809 assert(S
.Context
.hasSameUnqualifiedType(T
, E
->getRHS()->getType())
2810 && "comparison with mismatched types");
2812 // We don't do anything special if this isn't an unsigned integral
2813 // comparison: we're only interested in integral comparisons, and
2814 // signed comparisons only happen in cases we don't care to warn about.
2816 // We also don't care about value-dependent expressions or expressions
2817 // whose result is a constant.
2818 if (!T
->hasUnsignedIntegerRepresentation()
2819 || E
->isValueDependent() || E
->isIntegerConstantExpr(S
.Context
))
2820 return AnalyzeImpConvsInComparison(S
, E
);
2822 Expr
*lex
= E
->getLHS()->IgnoreParenImpCasts();
2823 Expr
*rex
= E
->getRHS()->IgnoreParenImpCasts();
2825 // Check to see if one of the (unmodified) operands is of different
2827 Expr
*signedOperand
, *unsignedOperand
;
2828 if (lex
->getType()->hasSignedIntegerRepresentation()) {
2829 assert(!rex
->getType()->hasSignedIntegerRepresentation() &&
2830 "unsigned comparison between two signed integer expressions?");
2831 signedOperand
= lex
;
2832 unsignedOperand
= rex
;
2833 } else if (rex
->getType()->hasSignedIntegerRepresentation()) {
2834 signedOperand
= rex
;
2835 unsignedOperand
= lex
;
2837 CheckTrivialUnsignedComparison(S
, E
);
2838 return AnalyzeImpConvsInComparison(S
, E
);
2841 // Otherwise, calculate the effective range of the signed operand.
2842 IntRange signedRange
= GetExprRange(S
.Context
, signedOperand
);
2844 // Go ahead and analyze implicit conversions in the operands. Note
2845 // that we skip the implicit conversions on both sides.
2846 AnalyzeImplicitConversions(S
, lex
, E
->getOperatorLoc());
2847 AnalyzeImplicitConversions(S
, rex
, E
->getOperatorLoc());
2849 // If the signed range is non-negative, -Wsign-compare won't fire,
2850 // but we should still check for comparisons which are always true
2852 if (signedRange
.NonNegative
)
2853 return CheckTrivialUnsignedComparison(S
, E
);
2855 // For (in)equality comparisons, if the unsigned operand is a
2856 // constant which cannot collide with a overflowed signed operand,
2857 // then reinterpreting the signed operand as unsigned will not
2858 // change the result of the comparison.
2859 if (E
->isEqualityOp()) {
2860 unsigned comparisonWidth
= S
.Context
.getIntWidth(T
);
2861 IntRange unsignedRange
= GetExprRange(S
.Context
, unsignedOperand
);
2863 // We should never be unable to prove that the unsigned operand is
2865 assert(unsignedRange
.NonNegative
&& "unsigned range includes negative?");
2867 if (unsignedRange
.Width
< comparisonWidth
)
2871 S
.Diag(E
->getOperatorLoc(), diag::warn_mixed_sign_comparison
)
2872 << lex
->getType() << rex
->getType()
2873 << lex
->getSourceRange() << rex
->getSourceRange();
2876 /// Analyzes an attempt to assign the given value to a bitfield.
2878 /// Returns true if there was something fishy about the attempt.
2879 bool AnalyzeBitFieldAssignment(Sema
&S
, FieldDecl
*Bitfield
, Expr
*Init
,
2880 SourceLocation InitLoc
) {
2881 assert(Bitfield
->isBitField());
2882 if (Bitfield
->isInvalidDecl())
2885 // White-list bool bitfields.
2886 if (Bitfield
->getType()->isBooleanType())
2889 // Ignore value- or type-dependent expressions.
2890 if (Bitfield
->getBitWidth()->isValueDependent() ||
2891 Bitfield
->getBitWidth()->isTypeDependent() ||
2892 Init
->isValueDependent() ||
2893 Init
->isTypeDependent())
2896 Expr
*OriginalInit
= Init
->IgnoreParenImpCasts();
2898 llvm::APSInt
Width(32);
2899 Expr::EvalResult InitValue
;
2900 if (!Bitfield
->getBitWidth()->isIntegerConstantExpr(Width
, S
.Context
) ||
2901 !OriginalInit
->Evaluate(InitValue
, S
.Context
) ||
2902 !InitValue
.Val
.isInt())
2905 const llvm::APSInt
&Value
= InitValue
.Val
.getInt();
2906 unsigned OriginalWidth
= Value
.getBitWidth();
2907 unsigned FieldWidth
= Width
.getZExtValue();
2909 if (OriginalWidth
<= FieldWidth
)
2912 llvm::APSInt TruncatedValue
= Value
.trunc(FieldWidth
);
2914 // It's fairly common to write values into signed bitfields
2915 // that, if sign-extended, would end up becoming a different
2916 // value. We don't want to warn about that.
2917 if (Value
.isSigned() && Value
.isNegative())
2918 TruncatedValue
= TruncatedValue
.sext(OriginalWidth
);
2920 TruncatedValue
= TruncatedValue
.zext(OriginalWidth
);
2922 if (Value
== TruncatedValue
)
2925 std::string PrettyValue
= Value
.toString(10);
2926 std::string PrettyTrunc
= TruncatedValue
.toString(10);
2928 S
.Diag(InitLoc
, diag::warn_impcast_bitfield_precision_constant
)
2929 << PrettyValue
<< PrettyTrunc
<< OriginalInit
->getType()
2930 << Init
->getSourceRange();
2935 /// Analyze the given simple or compound assignment for warning-worthy
2937 void AnalyzeAssignment(Sema
&S
, BinaryOperator
*E
) {
2938 // Just recurse on the LHS.
2939 AnalyzeImplicitConversions(S
, E
->getLHS(), E
->getOperatorLoc());
2941 // We want to recurse on the RHS as normal unless we're assigning to
2943 if (FieldDecl
*Bitfield
= E
->getLHS()->getBitField()) {
2944 if (AnalyzeBitFieldAssignment(S
, Bitfield
, E
->getRHS(),
2945 E
->getOperatorLoc())) {
2946 // Recurse, ignoring any implicit conversions on the RHS.
2947 return AnalyzeImplicitConversions(S
, E
->getRHS()->IgnoreParenImpCasts(),
2948 E
->getOperatorLoc());
2952 AnalyzeImplicitConversions(S
, E
->getRHS(), E
->getOperatorLoc());
2955 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
2956 void DiagnoseImpCast(Sema
&S
, Expr
*E
, QualType SourceType
, QualType T
,
2957 SourceLocation CContext
, unsigned diag
) {
2958 S
.Diag(E
->getExprLoc(), diag
)
2959 << SourceType
<< T
<< E
->getSourceRange() << SourceRange(CContext
);
2962 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
2963 void DiagnoseImpCast(Sema
&S
, Expr
*E
, QualType T
, SourceLocation CContext
,
2965 DiagnoseImpCast(S
, E
, E
->getType(), T
, CContext
, diag
);
2968 /// Diagnose an implicit cast from a literal expression. Also attemps to supply
2969 /// fixit hints when the cast wouldn't lose information to simply write the
2970 /// expression with the expected type.
2971 void DiagnoseFloatingLiteralImpCast(Sema
&S
, FloatingLiteral
*FL
, QualType T
,
2972 SourceLocation CContext
) {
2973 // Emit the primary warning first, then try to emit a fixit hint note if
2975 S
.Diag(FL
->getExprLoc(), diag::warn_impcast_literal_float_to_integer
)
2976 << FL
->getType() << T
<< FL
->getSourceRange() << SourceRange(CContext
);
2978 const llvm::APFloat
&Value
= FL
->getValue();
2980 // Don't attempt to fix PPC double double literals.
2981 if (&Value
.getSemantics() == &llvm::APFloat::PPCDoubleDouble
)
2984 // Try to convert this exactly to an 64-bit integer. FIXME: It would be
2985 // nice to support arbitrarily large integers here.
2986 bool isExact
= false;
2987 uint64_t IntegerPart
;
2988 if (Value
.convertToInteger(&IntegerPart
, 64, /*isSigned=*/true,
2989 llvm::APFloat::rmTowardZero
, &isExact
)
2990 != llvm::APFloat::opOK
|| !isExact
)
2993 llvm::APInt
IntegerValue(64, IntegerPart
, /*isSigned=*/true);
2995 std::string LiteralValue
= IntegerValue
.toString(10, /*isSigned=*/true);
2996 S
.Diag(FL
->getExprLoc(), diag::note_fix_integral_float_as_integer
)
2997 << FixItHint::CreateReplacement(FL
->getSourceRange(), LiteralValue
);
3000 std::string
PrettyPrintInRange(const llvm::APSInt
&Value
, IntRange Range
) {
3001 if (!Range
.Width
) return "0";
3003 llvm::APSInt ValueInRange
= Value
;
3004 ValueInRange
.setIsSigned(!Range
.NonNegative
);
3005 ValueInRange
= ValueInRange
.trunc(Range
.Width
);
3006 return ValueInRange
.toString(10);
3009 static bool isFromSystemMacro(Sema
&S
, SourceLocation loc
) {
3010 SourceManager
&smgr
= S
.Context
.getSourceManager();
3011 return loc
.isMacroID() && smgr
.isInSystemHeader(smgr
.getSpellingLoc(loc
));
3014 void CheckImplicitConversion(Sema
&S
, Expr
*E
, QualType T
,
3015 SourceLocation CC
, bool *ICContext
= 0) {
3016 if (E
->isTypeDependent() || E
->isValueDependent()) return;
3018 const Type
*Source
= S
.Context
.getCanonicalType(E
->getType()).getTypePtr();
3019 const Type
*Target
= S
.Context
.getCanonicalType(T
).getTypePtr();
3020 if (Source
== Target
) return;
3021 if (Target
->isDependentType()) return;
3023 // If the conversion context location is invalid don't complain.
3024 // We also don't want to emit a warning if the issue occurs from the
3025 // instantiation of a system macro. The problem is that 'getSpellingLoc()'
3026 // is slow, so we delay this check as long as possible. Once we detect
3027 // we are in that scenario, we just return.
3031 // Never diagnose implicit casts to bool.
3032 if (Target
->isSpecificBuiltinType(BuiltinType::Bool
))
3035 // Strip vector types.
3036 if (isa
<VectorType
>(Source
)) {
3037 if (!isa
<VectorType
>(Target
)) {
3038 if (isFromSystemMacro(S
, CC
))
3040 return DiagnoseImpCast(S
, E
, T
, CC
, diag::warn_impcast_vector_scalar
);
3043 // If the vector cast is cast between two vectors of the same size, it is
3044 // a bitcast, not a conversion.
3045 if (S
.Context
.getTypeSize(Source
) == S
.Context
.getTypeSize(Target
))
3048 Source
= cast
<VectorType
>(Source
)->getElementType().getTypePtr();
3049 Target
= cast
<VectorType
>(Target
)->getElementType().getTypePtr();
3052 // Strip complex types.
3053 if (isa
<ComplexType
>(Source
)) {
3054 if (!isa
<ComplexType
>(Target
)) {
3055 if (isFromSystemMacro(S
, CC
))
3058 return DiagnoseImpCast(S
, E
, T
, CC
, diag::warn_impcast_complex_scalar
);
3061 Source
= cast
<ComplexType
>(Source
)->getElementType().getTypePtr();
3062 Target
= cast
<ComplexType
>(Target
)->getElementType().getTypePtr();
3065 const BuiltinType
*SourceBT
= dyn_cast
<BuiltinType
>(Source
);
3066 const BuiltinType
*TargetBT
= dyn_cast
<BuiltinType
>(Target
);
3068 // If the source is floating point...
3069 if (SourceBT
&& SourceBT
->isFloatingPoint()) {
3070 // ...and the target is floating point...
3071 if (TargetBT
&& TargetBT
->isFloatingPoint()) {
3072 // ...then warn if we're dropping FP rank.
3074 // Builtin FP kinds are ordered by increasing FP rank.
3075 if (SourceBT
->getKind() > TargetBT
->getKind()) {
3076 // Don't warn about float constants that are precisely
3077 // representable in the target type.
3078 Expr::EvalResult result
;
3079 if (E
->Evaluate(result
, S
.Context
)) {
3080 // Value might be a float, a float vector, or a float complex.
3081 if (IsSameFloatAfterCast(result
.Val
,
3082 S
.Context
.getFloatTypeSemantics(QualType(TargetBT
, 0)),
3083 S
.Context
.getFloatTypeSemantics(QualType(SourceBT
, 0))))
3087 if (isFromSystemMacro(S
, CC
))
3090 DiagnoseImpCast(S
, E
, T
, CC
, diag::warn_impcast_float_precision
);
3095 // If the target is integral, always warn.
3096 if ((TargetBT
&& TargetBT
->isInteger())) {
3097 if (isFromSystemMacro(S
, CC
))
3100 Expr
*InnerE
= E
->IgnoreParenImpCasts();
3101 if (FloatingLiteral
*FL
= dyn_cast
<FloatingLiteral
>(InnerE
)) {
3102 DiagnoseFloatingLiteralImpCast(S
, FL
, T
, CC
);
3104 DiagnoseImpCast(S
, E
, T
, CC
, diag::warn_impcast_float_integer
);
3111 if (!Source
->isIntegerType() || !Target
->isIntegerType())
3114 if ((E
->isNullPointerConstant(S
.Context
, Expr::NPC_ValueDependentIsNotNull
)
3115 == Expr::NPCK_GNUNull
) && Target
->isIntegerType()) {
3116 S
.Diag(E
->getExprLoc(), diag::warn_impcast_null_pointer_to_integer
)
3117 << E
->getSourceRange() << clang::SourceRange(CC
);
3121 IntRange SourceRange
= GetExprRange(S
.Context
, E
);
3122 IntRange TargetRange
= IntRange::forTargetOfCanonicalType(S
.Context
, Target
);
3124 if (SourceRange
.Width
> TargetRange
.Width
) {
3125 // If the source is a constant, use a default-on diagnostic.
3126 // TODO: this should happen for bitfield stores, too.
3127 llvm::APSInt
Value(32);
3128 if (E
->isIntegerConstantExpr(Value
, S
.Context
)) {
3129 if (isFromSystemMacro(S
, CC
))
3132 std::string PrettySourceValue
= Value
.toString(10);
3133 std::string PrettyTargetValue
= PrettyPrintInRange(Value
, TargetRange
);
3135 S
.Diag(E
->getExprLoc(), diag::warn_impcast_integer_precision_constant
)
3136 << PrettySourceValue
<< PrettyTargetValue
3137 << E
->getType() << T
<< E
->getSourceRange() << clang::SourceRange(CC
);
3141 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
3142 if (isFromSystemMacro(S
, CC
))
3145 if (SourceRange
.Width
== 64 && TargetRange
.Width
== 32)
3146 return DiagnoseImpCast(S
, E
, T
, CC
, diag::warn_impcast_integer_64_32
);
3147 return DiagnoseImpCast(S
, E
, T
, CC
, diag::warn_impcast_integer_precision
);
3150 if ((TargetRange
.NonNegative
&& !SourceRange
.NonNegative
) ||
3151 (!TargetRange
.NonNegative
&& SourceRange
.NonNegative
&&
3152 SourceRange
.Width
== TargetRange
.Width
)) {
3154 if (isFromSystemMacro(S
, CC
))
3157 unsigned DiagID
= diag::warn_impcast_integer_sign
;
3159 // Traditionally, gcc has warned about this under -Wsign-compare.
3160 // We also want to warn about it in -Wconversion.
3161 // So if -Wconversion is off, use a completely identical diagnostic
3162 // in the sign-compare group.
3163 // The conditional-checking code will
3165 DiagID
= diag::warn_impcast_integer_sign_conditional
;
3169 return DiagnoseImpCast(S
, E
, T
, CC
, DiagID
);
3172 // Diagnose conversions between different enumeration types.
3173 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
3174 // type, to give us better diagnostics.
3175 QualType SourceType
= E
->getType();
3176 if (!S
.getLangOptions().CPlusPlus
) {
3177 if (DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(E
))
3178 if (EnumConstantDecl
*ECD
= dyn_cast
<EnumConstantDecl
>(DRE
->getDecl())) {
3179 EnumDecl
*Enum
= cast
<EnumDecl
>(ECD
->getDeclContext());
3180 SourceType
= S
.Context
.getTypeDeclType(Enum
);
3181 Source
= S
.Context
.getCanonicalType(SourceType
).getTypePtr();
3185 if (const EnumType
*SourceEnum
= Source
->getAs
<EnumType
>())
3186 if (const EnumType
*TargetEnum
= Target
->getAs
<EnumType
>())
3187 if ((SourceEnum
->getDecl()->getIdentifier() ||
3188 SourceEnum
->getDecl()->getTypedefNameForAnonDecl()) &&
3189 (TargetEnum
->getDecl()->getIdentifier() ||
3190 TargetEnum
->getDecl()->getTypedefNameForAnonDecl()) &&
3191 SourceEnum
!= TargetEnum
) {
3192 if (isFromSystemMacro(S
, CC
))
3195 return DiagnoseImpCast(S
, E
, SourceType
, T
, CC
,
3196 diag::warn_impcast_different_enum_types
);
3202 void CheckConditionalOperator(Sema
&S
, ConditionalOperator
*E
, QualType T
);
3204 void CheckConditionalOperand(Sema
&S
, Expr
*E
, QualType T
,
3205 SourceLocation CC
, bool &ICContext
) {
3206 E
= E
->IgnoreParenImpCasts();
3208 if (isa
<ConditionalOperator
>(E
))
3209 return CheckConditionalOperator(S
, cast
<ConditionalOperator
>(E
), T
);
3211 AnalyzeImplicitConversions(S
, E
, CC
);
3212 if (E
->getType() != T
)
3213 return CheckImplicitConversion(S
, E
, T
, CC
, &ICContext
);
3217 void CheckConditionalOperator(Sema
&S
, ConditionalOperator
*E
, QualType T
) {
3218 SourceLocation CC
= E
->getQuestionLoc();
3220 AnalyzeImplicitConversions(S
, E
->getCond(), CC
);
3222 bool Suspicious
= false;
3223 CheckConditionalOperand(S
, E
->getTrueExpr(), T
, CC
, Suspicious
);
3224 CheckConditionalOperand(S
, E
->getFalseExpr(), T
, CC
, Suspicious
);
3226 // If -Wconversion would have warned about either of the candidates
3227 // for a signedness conversion to the context type...
3228 if (!Suspicious
) return;
3230 // ...but it's currently ignored...
3231 if (S
.Diags
.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional
,
3235 // ...and -Wsign-compare isn't...
3236 if (!S
.Diags
.getDiagnosticLevel(diag::warn_mixed_sign_conditional
, CC
))
3239 // ...then check whether it would have warned about either of the
3240 // candidates for a signedness conversion to the condition type.
3241 if (E
->getType() != T
) {
3243 CheckImplicitConversion(S
, E
->getTrueExpr()->IgnoreParenImpCasts(),
3244 E
->getType(), CC
, &Suspicious
);
3246 CheckImplicitConversion(S
, E
->getFalseExpr()->IgnoreParenImpCasts(),
3247 E
->getType(), CC
, &Suspicious
);
3252 // If so, emit a diagnostic under -Wsign-compare.
3253 Expr
*lex
= E
->getTrueExpr()->IgnoreParenImpCasts();
3254 Expr
*rex
= E
->getFalseExpr()->IgnoreParenImpCasts();
3255 S
.Diag(E
->getQuestionLoc(), diag::warn_mixed_sign_conditional
)
3256 << lex
->getType() << rex
->getType()
3257 << lex
->getSourceRange() << rex
->getSourceRange();
3260 /// AnalyzeImplicitConversions - Find and report any interesting
3261 /// implicit conversions in the given expression. There are a couple
3262 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
3263 void AnalyzeImplicitConversions(Sema
&S
, Expr
*OrigE
, SourceLocation CC
) {
3264 QualType T
= OrigE
->getType();
3265 Expr
*E
= OrigE
->IgnoreParenImpCasts();
3267 // For conditional operators, we analyze the arguments as if they
3268 // were being fed directly into the output.
3269 if (isa
<ConditionalOperator
>(E
)) {
3270 ConditionalOperator
*CO
= cast
<ConditionalOperator
>(E
);
3271 CheckConditionalOperator(S
, CO
, T
);
3275 // Go ahead and check any implicit conversions we might have skipped.
3276 // The non-canonical typecheck is just an optimization;
3277 // CheckImplicitConversion will filter out dead implicit conversions.
3278 if (E
->getType() != T
)
3279 CheckImplicitConversion(S
, E
, T
, CC
);
3281 // Now continue drilling into this expression.
3283 // Skip past explicit casts.
3284 if (isa
<ExplicitCastExpr
>(E
)) {
3285 E
= cast
<ExplicitCastExpr
>(E
)->getSubExpr()->IgnoreParenImpCasts();
3286 return AnalyzeImplicitConversions(S
, E
, CC
);
3289 if (BinaryOperator
*BO
= dyn_cast
<BinaryOperator
>(E
)) {
3290 // Do a somewhat different check with comparison operators.
3291 if (BO
->isComparisonOp())
3292 return AnalyzeComparison(S
, BO
);
3294 // And with assignments and compound assignments.
3295 if (BO
->isAssignmentOp())
3296 return AnalyzeAssignment(S
, BO
);
3299 // These break the otherwise-useful invariant below. Fortunately,
3300 // we don't really need to recurse into them, because any internal
3301 // expressions should have been analyzed already when they were
3302 // built into statements.
3303 if (isa
<StmtExpr
>(E
)) return;
3305 // Don't descend into unevaluated contexts.
3306 if (isa
<UnaryExprOrTypeTraitExpr
>(E
)) return;
3308 // Now just recurse over the expression's children.
3309 CC
= E
->getExprLoc();
3310 for (Stmt::child_range I
= E
->children(); I
; ++I
)
3311 AnalyzeImplicitConversions(S
, cast
<Expr
>(*I
), CC
);
3314 } // end anonymous namespace
3316 /// Diagnoses "dangerous" implicit conversions within the given
3317 /// expression (which is a full expression). Implements -Wconversion
3318 /// and -Wsign-compare.
3320 /// \param CC the "context" location of the implicit conversion, i.e.
3321 /// the most location of the syntactic entity requiring the implicit
3323 void Sema::CheckImplicitConversions(Expr
*E
, SourceLocation CC
) {
3324 // Don't diagnose in unevaluated contexts.
3325 if (ExprEvalContexts
.back().Context
== Sema::Unevaluated
)
3328 // Don't diagnose for value- or type-dependent expressions.
3329 if (E
->isTypeDependent() || E
->isValueDependent())
3332 // This is not the right CC for (e.g.) a variable initialization.
3333 AnalyzeImplicitConversions(*this, E
, CC
);
3336 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc
,
3337 FieldDecl
*BitField
,
3339 (void) AnalyzeBitFieldAssignment(*this, BitField
, Init
, InitLoc
);
3342 /// CheckParmsForFunctionDef - Check that the parameters of the given
3343 /// function are appropriate for the definition of a function. This
3344 /// takes care of any checks that cannot be performed on the
3345 /// declaration itself, e.g., that the types of each of the function
3346 /// parameters are complete.
3347 bool Sema::CheckParmsForFunctionDef(ParmVarDecl
**P
, ParmVarDecl
**PEnd
,
3348 bool CheckParameterNames
) {
3349 bool HasInvalidParm
= false;
3350 for (; P
!= PEnd
; ++P
) {
3351 ParmVarDecl
*Param
= *P
;
3353 // C99 6.7.5.3p4: the parameters in a parameter type list in a
3354 // function declarator that is part of a function definition of
3355 // that function shall not have incomplete type.
3357 // This is also C++ [dcl.fct]p6.
3358 if (!Param
->isInvalidDecl() &&
3359 RequireCompleteType(Param
->getLocation(), Param
->getType(),
3360 diag::err_typecheck_decl_incomplete_type
)) {
3361 Param
->setInvalidDecl();
3362 HasInvalidParm
= true;
3365 // C99 6.9.1p5: If the declarator includes a parameter type list, the
3366 // declaration of each parameter shall include an identifier.
3367 if (CheckParameterNames
&&
3368 Param
->getIdentifier() == 0 &&
3369 !Param
->isImplicit() &&
3370 !getLangOptions().CPlusPlus
)
3371 Diag(Param
->getLocation(), diag::err_parameter_name_omitted
);
3374 // If the function declarator is not part of a definition of that
3375 // function, parameters may have incomplete type and may use the [*]
3376 // notation in their sequences of declarator specifiers to specify
3377 // variable length array types.
3378 QualType PType
= Param
->getOriginalType();
3379 if (const ArrayType
*AT
= Context
.getAsArrayType(PType
)) {
3380 if (AT
->getSizeModifier() == ArrayType::Star
) {
3381 // FIXME: This diagnosic should point the the '[*]' if source-location
3382 // information is added for it.
3383 Diag(Param
->getLocation(), diag::err_array_star_in_function_definition
);
3388 return HasInvalidParm
;
3391 /// CheckCastAlign - Implements -Wcast-align, which warns when a
3392 /// pointer cast increases the alignment requirements.
3393 void Sema::CheckCastAlign(Expr
*Op
, QualType T
, SourceRange TRange
) {
3394 // This is actually a lot of work to potentially be doing on every
3395 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
3396 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align
,
3398 == Diagnostic::Ignored
)
3401 // Ignore dependent types.
3402 if (T
->isDependentType() || Op
->getType()->isDependentType())
3405 // Require that the destination be a pointer type.
3406 const PointerType
*DestPtr
= T
->getAs
<PointerType
>();
3407 if (!DestPtr
) return;
3409 // If the destination has alignment 1, we're done.
3410 QualType DestPointee
= DestPtr
->getPointeeType();
3411 if (DestPointee
->isIncompleteType()) return;
3412 CharUnits DestAlign
= Context
.getTypeAlignInChars(DestPointee
);
3413 if (DestAlign
.isOne()) return;
3415 // Require that the source be a pointer type.
3416 const PointerType
*SrcPtr
= Op
->getType()->getAs
<PointerType
>();
3417 if (!SrcPtr
) return;
3418 QualType SrcPointee
= SrcPtr
->getPointeeType();
3420 // Whitelist casts from cv void*. We already implicitly
3421 // whitelisted casts to cv void*, since they have alignment 1.
3422 // Also whitelist casts involving incomplete types, which implicitly
3424 if (SrcPointee
->isIncompleteType()) return;
3426 CharUnits SrcAlign
= Context
.getTypeAlignInChars(SrcPointee
);
3427 if (SrcAlign
>= DestAlign
) return;
3429 Diag(TRange
.getBegin(), diag::warn_cast_align
)
3430 << Op
->getType() << T
3431 << static_cast<unsigned>(SrcAlign
.getQuantity())
3432 << static_cast<unsigned>(DestAlign
.getQuantity())
3433 << TRange
<< Op
->getSourceRange();
3436 static void CheckArrayAccess_Check(Sema
&S
,
3437 const clang::ArraySubscriptExpr
*E
) {
3438 const Expr
*BaseExpr
= E
->getBase()->IgnoreParenImpCasts();
3439 const ConstantArrayType
*ArrayTy
=
3440 S
.Context
.getAsConstantArrayType(BaseExpr
->getType());
3444 const Expr
*IndexExpr
= E
->getIdx();
3445 if (IndexExpr
->isValueDependent())
3448 if (!IndexExpr
->isIntegerConstantExpr(index
, S
.Context
))
3451 if (index
.isUnsigned() || !index
.isNegative()) {
3452 llvm::APInt size
= ArrayTy
->getSize();
3453 if (!size
.isStrictlyPositive())
3455 if (size
.getBitWidth() > index
.getBitWidth())
3456 index
= index
.sext(size
.getBitWidth());
3457 else if (size
.getBitWidth() < index
.getBitWidth())
3458 size
= size
.sext(index
.getBitWidth());
3460 if (index
.slt(size
))
3463 S
.DiagRuntimeBehavior(E
->getBase()->getLocStart(), BaseExpr
,
3464 S
.PDiag(diag::warn_array_index_exceeds_bounds
)
3465 << index
.toString(10, true)
3466 << size
.toString(10, true)
3467 << IndexExpr
->getSourceRange());
3469 S
.DiagRuntimeBehavior(E
->getBase()->getLocStart(), BaseExpr
,
3470 S
.PDiag(diag::warn_array_index_precedes_bounds
)
3471 << index
.toString(10, true)
3472 << IndexExpr
->getSourceRange());
3475 const NamedDecl
*ND
= NULL
;
3476 if (const DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(BaseExpr
))
3477 ND
= dyn_cast
<NamedDecl
>(DRE
->getDecl());
3478 if (const MemberExpr
*ME
= dyn_cast
<MemberExpr
>(BaseExpr
))
3479 ND
= dyn_cast
<NamedDecl
>(ME
->getMemberDecl());
3481 S
.DiagRuntimeBehavior(ND
->getLocStart(), BaseExpr
,
3482 S
.PDiag(diag::note_array_index_out_of_bounds
)
3483 << ND
->getDeclName());
3486 void Sema::CheckArrayAccess(const Expr
*expr
) {
3488 expr
= expr
->IgnoreParens();
3489 switch (expr
->getStmtClass()) {
3490 case Stmt::ArraySubscriptExprClass
:
3491 CheckArrayAccess_Check(*this, cast
<ArraySubscriptExpr
>(expr
));
3493 case Stmt::ConditionalOperatorClass
: {
3494 const ConditionalOperator
*cond
= cast
<ConditionalOperator
>(expr
);
3495 if (const Expr
*lhs
= cond
->getLHS())
3496 CheckArrayAccess(lhs
);
3497 if (const Expr
*rhs
= cond
->getRHS())
3498 CheckArrayAccess(rhs
);
3507 //===--- CHECK: Objective-C retain cycles ----------------------------------//
3510 struct RetainCycleOwner
{
3511 RetainCycleOwner() : Variable(0), Indirect(false) {}
3517 void setLocsFrom(Expr
*e
) {
3518 Loc
= e
->getExprLoc();
3519 Range
= e
->getSourceRange();
3524 /// Consider whether capturing the given variable can possibly lead to
3526 static bool considerVariable(VarDecl
*var
, Expr
*ref
, RetainCycleOwner
&owner
) {
3527 // In ARC, it's captured strongly iff the variable has __strong
3528 // lifetime. In MRR, it's captured strongly if the variable is
3529 // __block and has an appropriate type.
3530 if (var
->getType().getObjCLifetime() != Qualifiers::OCL_Strong
)
3533 owner
.Variable
= var
;
3534 owner
.setLocsFrom(ref
);
3538 static bool findRetainCycleOwner(Expr
*e
, RetainCycleOwner
&owner
) {
3540 e
= e
->IgnoreParens();
3541 if (CastExpr
*cast
= dyn_cast
<CastExpr
>(e
)) {
3542 switch (cast
->getCastKind()) {
3544 case CK_LValueBitCast
:
3545 case CK_LValueToRValue
:
3546 e
= cast
->getSubExpr();
3549 case CK_GetObjCProperty
: {
3550 // Bail out if this isn't a strong explicit property.
3551 const ObjCPropertyRefExpr
*pre
= cast
->getSubExpr()->getObjCProperty();
3552 if (pre
->isImplicitProperty()) return false;
3553 ObjCPropertyDecl
*property
= pre
->getExplicitProperty();
3554 if (!(property
->getPropertyAttributes() &
3555 (ObjCPropertyDecl::OBJC_PR_retain
|
3556 ObjCPropertyDecl::OBJC_PR_copy
|
3557 ObjCPropertyDecl::OBJC_PR_strong
)) &&
3558 !(property
->getPropertyIvarDecl() &&
3559 property
->getPropertyIvarDecl()->getType()
3560 .getObjCLifetime() == Qualifiers::OCL_Strong
))
3563 owner
.Indirect
= true;
3564 e
= const_cast<Expr
*>(pre
->getBase());
3573 if (ObjCIvarRefExpr
*ref
= dyn_cast
<ObjCIvarRefExpr
>(e
)) {
3574 ObjCIvarDecl
*ivar
= ref
->getDecl();
3575 if (ivar
->getType().getObjCLifetime() != Qualifiers::OCL_Strong
)
3578 // Try to find a retain cycle in the base.
3579 if (!findRetainCycleOwner(ref
->getBase(), owner
))
3582 if (ref
->isFreeIvar()) owner
.setLocsFrom(ref
);
3583 owner
.Indirect
= true;
3587 if (DeclRefExpr
*ref
= dyn_cast
<DeclRefExpr
>(e
)) {
3588 VarDecl
*var
= dyn_cast
<VarDecl
>(ref
->getDecl());
3589 if (!var
) return false;
3590 return considerVariable(var
, ref
, owner
);
3593 if (BlockDeclRefExpr
*ref
= dyn_cast
<BlockDeclRefExpr
>(e
)) {
3594 owner
.Variable
= ref
->getDecl();
3595 owner
.setLocsFrom(ref
);
3599 if (MemberExpr
*member
= dyn_cast
<MemberExpr
>(e
)) {
3600 if (member
->isArrow()) return false;
3602 // Don't count this as an indirect ownership.
3603 e
= member
->getBase();
3614 struct FindCaptureVisitor
: EvaluatedExprVisitor
<FindCaptureVisitor
> {
3615 FindCaptureVisitor(ASTContext
&Context
, VarDecl
*variable
)
3616 : EvaluatedExprVisitor
<FindCaptureVisitor
>(Context
),
3617 Variable(variable
), Capturer(0) {}
3622 void VisitDeclRefExpr(DeclRefExpr
*ref
) {
3623 if (ref
->getDecl() == Variable
&& !Capturer
)
3627 void VisitBlockDeclRefExpr(BlockDeclRefExpr
*ref
) {
3628 if (ref
->getDecl() == Variable
&& !Capturer
)
3632 void VisitObjCIvarRefExpr(ObjCIvarRefExpr
*ref
) {
3633 if (Capturer
) return;
3634 Visit(ref
->getBase());
3635 if (Capturer
&& ref
->isFreeIvar())
3639 void VisitBlockExpr(BlockExpr
*block
) {
3640 // Look inside nested blocks
3641 if (block
->getBlockDecl()->capturesVariable(Variable
))
3642 Visit(block
->getBlockDecl()->getBody());
3647 /// Check whether the given argument is a block which captures a
3649 static Expr
*findCapturingExpr(Sema
&S
, Expr
*e
, RetainCycleOwner
&owner
) {
3650 assert(owner
.Variable
&& owner
.Loc
.isValid());
3652 e
= e
->IgnoreParenCasts();
3653 BlockExpr
*block
= dyn_cast
<BlockExpr
>(e
);
3654 if (!block
|| !block
->getBlockDecl()->capturesVariable(owner
.Variable
))
3657 FindCaptureVisitor
visitor(S
.Context
, owner
.Variable
);
3658 visitor
.Visit(block
->getBlockDecl()->getBody());
3659 return visitor
.Capturer
;
3662 static void diagnoseRetainCycle(Sema
&S
, Expr
*capturer
,
3663 RetainCycleOwner
&owner
) {
3665 assert(owner
.Variable
&& owner
.Loc
.isValid());
3667 S
.Diag(capturer
->getExprLoc(), diag::warn_arc_retain_cycle
)
3668 << owner
.Variable
<< capturer
->getSourceRange();
3669 S
.Diag(owner
.Loc
, diag::note_arc_retain_cycle_owner
)
3670 << owner
.Indirect
<< owner
.Range
;
3673 /// Check for a keyword selector that starts with the word 'add' or
3675 static bool isSetterLikeSelector(Selector sel
) {
3676 if (sel
.isUnarySelector()) return false;
3678 llvm::StringRef str
= sel
.getNameForSlot(0);
3679 while (!str
.empty() && str
.front() == '_') str
= str
.substr(1);
3680 if (str
.startswith("set") || str
.startswith("add"))
3681 str
= str
.substr(3);
3685 if (str
.empty()) return true;
3686 return !islower(str
.front());
3689 /// Check a message send to see if it's likely to cause a retain cycle.
3690 void Sema::checkRetainCycles(ObjCMessageExpr
*msg
) {
3691 // Only check instance methods whose selector looks like a setter.
3692 if (!msg
->isInstanceMessage() || !isSetterLikeSelector(msg
->getSelector()))
3695 // Try to find a variable that the receiver is strongly owned by.
3696 RetainCycleOwner owner
;
3697 if (msg
->getReceiverKind() == ObjCMessageExpr::Instance
) {
3698 if (!findRetainCycleOwner(msg
->getInstanceReceiver(), owner
))
3701 assert(msg
->getReceiverKind() == ObjCMessageExpr::SuperInstance
);
3702 owner
.Variable
= getCurMethodDecl()->getSelfDecl();
3703 owner
.Loc
= msg
->getSuperLoc();
3704 owner
.Range
= msg
->getSuperLoc();
3707 // Check whether the receiver is captured by any of the arguments.
3708 for (unsigned i
= 0, e
= msg
->getNumArgs(); i
!= e
; ++i
)
3709 if (Expr
*capturer
= findCapturingExpr(*this, msg
->getArg(i
), owner
))
3710 return diagnoseRetainCycle(*this, capturer
, owner
);
3713 /// Check a property assign to see if it's likely to cause a retain cycle.
3714 void Sema::checkRetainCycles(Expr
*receiver
, Expr
*argument
) {
3715 RetainCycleOwner owner
;
3716 if (!findRetainCycleOwner(receiver
, owner
))
3719 if (Expr
*capturer
= findCapturingExpr(*this, argument
, owner
))
3720 diagnoseRetainCycle(*this, capturer
, owner
);
3723 void Sema::checkUnsafeAssigns(SourceLocation Loc
,
3724 QualType LHS
, Expr
*RHS
) {
3725 Qualifiers::ObjCLifetime LT
= LHS
.getObjCLifetime();
3726 if (LT
!= Qualifiers::OCL_Weak
&& LT
!= Qualifiers::OCL_ExplicitNone
)
3728 if (ImplicitCastExpr
*cast
= dyn_cast
<ImplicitCastExpr
>(RHS
))
3729 if (cast
->getCastKind() == CK_ObjCConsumeObject
)
3730 Diag(Loc
, diag::warn_arc_retained_assign
)
3731 << (LT
== Qualifiers::OCL_ExplicitNone
)
3732 << RHS
->getSourceRange();