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/DeclObjC.h"
26 #include "clang/AST/StmtCXX.h"
27 #include "clang/AST/StmtObjC.h"
28 #include "clang/Lex/Preprocessor.h"
29 #include "llvm/ADT/BitVector.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "clang/Basic/TargetBuiltins.h"
33 #include "clang/Basic/TargetInfo.h"
34 #include "clang/Basic/ConvertUTF.h"
36 using namespace clang
;
39 SourceLocation
Sema::getLocationOfStringLiteralByte(const StringLiteral
*SL
,
40 unsigned ByteNo
) const {
41 return SL
->getLocationOfByte(ByteNo
, PP
.getSourceManager(),
42 PP
.getLangOptions(), PP
.getTargetInfo());
46 /// CheckablePrintfAttr - does a function call have a "printf" attribute
47 /// and arguments that merit checking?
48 bool Sema::CheckablePrintfAttr(const FormatAttr
*Format
, CallExpr
*TheCall
) {
49 if (Format
->getType() == "printf") return true;
50 if (Format
->getType() == "printf0") {
51 // printf0 allows null "format" string; if so don't check format/args
52 unsigned format_idx
= Format
->getFormatIdx() - 1;
53 // Does the index refer to the implicit object argument?
54 if (isa
<CXXMemberCallExpr
>(TheCall
)) {
59 if (format_idx
< TheCall
->getNumArgs()) {
60 Expr
*Format
= TheCall
->getArg(format_idx
)->IgnoreParenCasts();
61 if (!Format
->isNullPointerConstant(Context
,
62 Expr::NPC_ValueDependentIsNull
))
70 Sema::CheckBuiltinFunctionCall(unsigned BuiltinID
, CallExpr
*TheCall
) {
71 ExprResult
TheCallResult(Owned(TheCall
));
73 // Find out if any arguments are required to be integer constant expressions.
74 unsigned ICEArguments
= 0;
75 ASTContext::GetBuiltinTypeError Error
;
76 Context
.GetBuiltinType(BuiltinID
, Error
, &ICEArguments
);
77 if (Error
!= ASTContext::GE_None
)
78 ICEArguments
= 0; // Don't diagnose previously diagnosed errors.
80 // If any arguments are required to be ICE's, check and diagnose.
81 for (unsigned ArgNo
= 0; ICEArguments
!= 0; ++ArgNo
) {
82 // Skip arguments not required to be ICE's.
83 if ((ICEArguments
& (1 << ArgNo
)) == 0) continue;
86 if (SemaBuiltinConstantArg(TheCall
, ArgNo
, Result
))
88 ICEArguments
&= ~(1 << ArgNo
);
92 case Builtin::BI__builtin___CFStringMakeConstantString
:
93 assert(TheCall
->getNumArgs() == 1 &&
94 "Wrong # arguments to builtin CFStringMakeConstantString");
95 if (CheckObjCString(TheCall
->getArg(0)))
98 case Builtin::BI__builtin_stdarg_start
:
99 case Builtin::BI__builtin_va_start
:
100 if (SemaBuiltinVAStart(TheCall
))
103 case Builtin::BI__builtin_isgreater
:
104 case Builtin::BI__builtin_isgreaterequal
:
105 case Builtin::BI__builtin_isless
:
106 case Builtin::BI__builtin_islessequal
:
107 case Builtin::BI__builtin_islessgreater
:
108 case Builtin::BI__builtin_isunordered
:
109 if (SemaBuiltinUnorderedCompare(TheCall
))
112 case Builtin::BI__builtin_fpclassify
:
113 if (SemaBuiltinFPClassification(TheCall
, 6))
116 case Builtin::BI__builtin_isfinite
:
117 case Builtin::BI__builtin_isinf
:
118 case Builtin::BI__builtin_isinf_sign
:
119 case Builtin::BI__builtin_isnan
:
120 case Builtin::BI__builtin_isnormal
:
121 if (SemaBuiltinFPClassification(TheCall
, 1))
124 case Builtin::BI__builtin_shufflevector
:
125 return SemaBuiltinShuffleVector(TheCall
);
126 // TheCall will be freed by the smart pointer here, but that's fine, since
127 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
128 case Builtin::BI__builtin_prefetch
:
129 if (SemaBuiltinPrefetch(TheCall
))
132 case Builtin::BI__builtin_object_size
:
133 if (SemaBuiltinObjectSize(TheCall
))
136 case Builtin::BI__builtin_longjmp
:
137 if (SemaBuiltinLongjmp(TheCall
))
140 case Builtin::BI__builtin_constant_p
:
141 if (TheCall
->getNumArgs() == 0)
142 return Diag(TheCall
->getLocEnd(), diag::err_typecheck_call_too_few_args
)
143 << 0 /*function call*/ << 1 << 0 << TheCall
->getSourceRange();
144 if (TheCall
->getNumArgs() > 1)
145 return Diag(TheCall
->getArg(1)->getLocStart(),
146 diag::err_typecheck_call_too_many_args
)
147 << 0 /*function call*/ << 1 << TheCall
->getNumArgs()
148 << TheCall
->getArg(1)->getSourceRange();
150 case Builtin::BI__sync_fetch_and_add
:
151 case Builtin::BI__sync_fetch_and_sub
:
152 case Builtin::BI__sync_fetch_and_or
:
153 case Builtin::BI__sync_fetch_and_and
:
154 case Builtin::BI__sync_fetch_and_xor
:
155 case Builtin::BI__sync_add_and_fetch
:
156 case Builtin::BI__sync_sub_and_fetch
:
157 case Builtin::BI__sync_and_and_fetch
:
158 case Builtin::BI__sync_or_and_fetch
:
159 case Builtin::BI__sync_xor_and_fetch
:
160 case Builtin::BI__sync_val_compare_and_swap
:
161 case Builtin::BI__sync_bool_compare_and_swap
:
162 case Builtin::BI__sync_lock_test_and_set
:
163 case Builtin::BI__sync_lock_release
:
164 return SemaBuiltinAtomicOverloaded(move(TheCallResult
));
167 // Since the target specific builtins for each arch overlap, only check those
168 // of the arch we are compiling for.
169 if (BuiltinID
>= Builtin::FirstTSBuiltin
) {
170 switch (Context
.Target
.getTriple().getArch()) {
171 case llvm::Triple::arm
:
172 case llvm::Triple::thumb
:
173 if (CheckARMBuiltinFunctionCall(BuiltinID
, TheCall
))
181 return move(TheCallResult
);
184 // Get the valid immediate range for the specified NEON type code.
185 static unsigned RFT(unsigned t
, bool shift
= false) {
186 bool quad
= t
& 0x10;
190 return shift
? 7 : (8 << (int)quad
) - 1;
192 return shift
? 15 : (4 << (int)quad
) - 1;
194 return shift
? 31 : (2 << (int)quad
) - 1;
196 return shift
? 63 : (1 << (int)quad
) - 1;
198 assert(!shift
&& "cannot shift float types!");
199 return (2 << (int)quad
) - 1;
201 return shift
? 7 : (8 << (int)quad
) - 1;
203 return shift
? 15 : (4 << (int)quad
) - 1;
205 assert(!shift
&& "cannot shift float types!");
206 return (4 << (int)quad
) - 1;
211 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID
, CallExpr
*TheCall
) {
217 #define GET_NEON_OVERLOAD_CHECK
218 #include "clang/Basic/arm_neon.inc"
219 #undef GET_NEON_OVERLOAD_CHECK
222 // For NEON intrinsics which are overloaded on vector element type, validate
223 // the immediate which specifies which variant to emit.
225 unsigned ArgNo
= TheCall
->getNumArgs()-1;
226 if (SemaBuiltinConstantArg(TheCall
, ArgNo
, Result
))
229 TV
= Result
.getLimitedValue(32);
230 if ((TV
> 31) || (mask
& (1 << TV
)) == 0)
231 return Diag(TheCall
->getLocStart(), diag::err_invalid_neon_type_code
)
232 << TheCall
->getArg(ArgNo
)->getSourceRange();
235 // For NEON intrinsics which take an immediate value as part of the
236 // instruction, range check them here.
237 unsigned i
= 0, l
= 0, u
= 0;
239 default: return false;
240 case ARM::BI__builtin_arm_ssat
: i
= 1; l
= 1; u
= 31; break;
241 case ARM::BI__builtin_arm_usat
: i
= 1; u
= 31; break;
242 case ARM::BI__builtin_arm_vcvtr_f
:
243 case ARM::BI__builtin_arm_vcvtr_d
: i
= 1; u
= 1; break;
244 #define GET_NEON_IMMEDIATE_CHECK
245 #include "clang/Basic/arm_neon.inc"
246 #undef GET_NEON_IMMEDIATE_CHECK
249 // Check that the immediate argument is actually a constant.
250 if (SemaBuiltinConstantArg(TheCall
, i
, Result
))
253 // Range check against the upper/lower values for this isntruction.
254 unsigned Val
= Result
.getZExtValue();
255 if (Val
< l
|| Val
> (u
+ l
))
256 return Diag(TheCall
->getLocStart(), diag::err_argument_invalid_range
)
257 << l
<< u
+l
<< TheCall
->getArg(i
)->getSourceRange();
259 // FIXME: VFP Intrinsics should error if VFP not present.
263 /// CheckFunctionCall - Check a direct function call for various correctness
264 /// and safety properties not strictly enforced by the C type system.
265 bool Sema::CheckFunctionCall(FunctionDecl
*FDecl
, CallExpr
*TheCall
) {
266 // Get the IdentifierInfo* for the called function.
267 IdentifierInfo
*FnInfo
= FDecl
->getIdentifier();
269 // None of the checks below are needed for functions that don't have
270 // simple names (e.g., C++ conversion functions).
274 // FIXME: This mechanism should be abstracted to be less fragile and
275 // more efficient. For example, just map function ids to custom
278 // Printf and scanf checking.
279 for (specific_attr_iterator
<FormatAttr
>
280 i
= FDecl
->specific_attr_begin
<FormatAttr
>(),
281 e
= FDecl
->specific_attr_end
<FormatAttr
>(); i
!= e
; ++i
) {
283 const FormatAttr
*Format
= *i
;
284 const bool b
= Format
->getType() == "scanf";
285 if (b
|| CheckablePrintfAttr(Format
, TheCall
)) {
286 bool HasVAListArg
= Format
->getFirstArg() == 0;
287 CheckPrintfScanfArguments(TheCall
, HasVAListArg
,
288 Format
->getFormatIdx() - 1,
289 HasVAListArg
? 0 : Format
->getFirstArg() - 1,
294 for (specific_attr_iterator
<NonNullAttr
>
295 i
= FDecl
->specific_attr_begin
<NonNullAttr
>(),
296 e
= FDecl
->specific_attr_end
<NonNullAttr
>(); i
!= e
; ++i
) {
297 CheckNonNullArguments(*i
, TheCall
);
303 bool Sema::CheckBlockCall(NamedDecl
*NDecl
, CallExpr
*TheCall
) {
305 const FormatAttr
*Format
= NDecl
->getAttr
<FormatAttr
>();
309 const VarDecl
*V
= dyn_cast
<VarDecl
>(NDecl
);
313 QualType Ty
= V
->getType();
314 if (!Ty
->isBlockPointerType())
317 const bool b
= Format
->getType() == "scanf";
318 if (!b
&& !CheckablePrintfAttr(Format
, TheCall
))
321 bool HasVAListArg
= Format
->getFirstArg() == 0;
322 CheckPrintfScanfArguments(TheCall
, HasVAListArg
, Format
->getFormatIdx() - 1,
323 HasVAListArg
? 0 : Format
->getFirstArg() - 1, !b
);
328 /// SemaBuiltinAtomicOverloaded - We have a call to a function like
329 /// __sync_fetch_and_add, which is an overloaded function based on the pointer
330 /// type of its first argument. The main ActOnCallExpr routines have already
331 /// promoted the types of arguments because all of these calls are prototyped as
334 /// This function goes through and does final semantic checking for these
337 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult
) {
338 CallExpr
*TheCall
= (CallExpr
*)TheCallResult
.get();
339 DeclRefExpr
*DRE
=cast
<DeclRefExpr
>(TheCall
->getCallee()->IgnoreParenCasts());
340 FunctionDecl
*FDecl
= cast
<FunctionDecl
>(DRE
->getDecl());
342 // Ensure that we have at least one argument to do type inference from.
343 if (TheCall
->getNumArgs() < 1) {
344 Diag(TheCall
->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least
)
345 << 0 << 1 << TheCall
->getNumArgs()
346 << TheCall
->getCallee()->getSourceRange();
350 // Inspect the first argument of the atomic builtin. This should always be
351 // a pointer type, whose element is an integral scalar or pointer type.
352 // Because it is a pointer type, we don't have to worry about any implicit
354 // FIXME: We don't allow floating point scalars as input.
355 Expr
*FirstArg
= TheCall
->getArg(0);
356 if (!FirstArg
->getType()->isPointerType()) {
357 Diag(DRE
->getLocStart(), diag::err_atomic_builtin_must_be_pointer
)
358 << FirstArg
->getType() << FirstArg
->getSourceRange();
363 FirstArg
->getType()->getAs
<PointerType
>()->getPointeeType();
364 if (!ValType
->isIntegerType() && !ValType
->isAnyPointerType() &&
365 !ValType
->isBlockPointerType()) {
366 Diag(DRE
->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr
)
367 << FirstArg
->getType() << FirstArg
->getSourceRange();
371 // The majority of builtins return a value, but a few have special return
372 // types, so allow them to override appropriately below.
373 QualType ResultType
= ValType
;
375 // We need to figure out which concrete builtin this maps onto. For example,
376 // __sync_fetch_and_add with a 2 byte object turns into
377 // __sync_fetch_and_add_2.
378 #define BUILTIN_ROW(x) \
379 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
380 Builtin::BI##x##_8, Builtin::BI##x##_16 }
382 static const unsigned BuiltinIndices
[][5] = {
383 BUILTIN_ROW(__sync_fetch_and_add
),
384 BUILTIN_ROW(__sync_fetch_and_sub
),
385 BUILTIN_ROW(__sync_fetch_and_or
),
386 BUILTIN_ROW(__sync_fetch_and_and
),
387 BUILTIN_ROW(__sync_fetch_and_xor
),
389 BUILTIN_ROW(__sync_add_and_fetch
),
390 BUILTIN_ROW(__sync_sub_and_fetch
),
391 BUILTIN_ROW(__sync_and_and_fetch
),
392 BUILTIN_ROW(__sync_or_and_fetch
),
393 BUILTIN_ROW(__sync_xor_and_fetch
),
395 BUILTIN_ROW(__sync_val_compare_and_swap
),
396 BUILTIN_ROW(__sync_bool_compare_and_swap
),
397 BUILTIN_ROW(__sync_lock_test_and_set
),
398 BUILTIN_ROW(__sync_lock_release
)
402 // Determine the index of the size.
404 switch (Context
.getTypeSizeInChars(ValType
).getQuantity()) {
405 case 1: SizeIndex
= 0; break;
406 case 2: SizeIndex
= 1; break;
407 case 4: SizeIndex
= 2; break;
408 case 8: SizeIndex
= 3; break;
409 case 16: SizeIndex
= 4; break;
411 Diag(DRE
->getLocStart(), diag::err_atomic_builtin_pointer_size
)
412 << FirstArg
->getType() << FirstArg
->getSourceRange();
416 // Each of these builtins has one pointer argument, followed by some number of
417 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
418 // that we ignore. Find out which row of BuiltinIndices to read from as well
419 // as the number of fixed args.
420 unsigned BuiltinID
= FDecl
->getBuiltinID();
421 unsigned BuiltinIndex
, NumFixed
= 1;
423 default: assert(0 && "Unknown overloaded atomic builtin!");
424 case Builtin::BI__sync_fetch_and_add
: BuiltinIndex
= 0; break;
425 case Builtin::BI__sync_fetch_and_sub
: BuiltinIndex
= 1; break;
426 case Builtin::BI__sync_fetch_and_or
: BuiltinIndex
= 2; break;
427 case Builtin::BI__sync_fetch_and_and
: BuiltinIndex
= 3; break;
428 case Builtin::BI__sync_fetch_and_xor
: BuiltinIndex
= 4; break;
430 case Builtin::BI__sync_add_and_fetch
: BuiltinIndex
= 5; break;
431 case Builtin::BI__sync_sub_and_fetch
: BuiltinIndex
= 6; break;
432 case Builtin::BI__sync_and_and_fetch
: BuiltinIndex
= 7; break;
433 case Builtin::BI__sync_or_and_fetch
: BuiltinIndex
= 8; break;
434 case Builtin::BI__sync_xor_and_fetch
: BuiltinIndex
= 9; break;
436 case Builtin::BI__sync_val_compare_and_swap
:
440 case Builtin::BI__sync_bool_compare_and_swap
:
443 ResultType
= Context
.BoolTy
;
445 case Builtin::BI__sync_lock_test_and_set
: BuiltinIndex
= 12; break;
446 case Builtin::BI__sync_lock_release
:
449 ResultType
= Context
.VoidTy
;
453 // Now that we know how many fixed arguments we expect, first check that we
454 // have at least that many.
455 if (TheCall
->getNumArgs() < 1+NumFixed
) {
456 Diag(TheCall
->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least
)
457 << 0 << 1+NumFixed
<< TheCall
->getNumArgs()
458 << TheCall
->getCallee()->getSourceRange();
462 // Get the decl for the concrete builtin from this, we can tell what the
463 // concrete integer type we should convert to is.
464 unsigned NewBuiltinID
= BuiltinIndices
[BuiltinIndex
][SizeIndex
];
465 const char *NewBuiltinName
= Context
.BuiltinInfo
.GetName(NewBuiltinID
);
466 IdentifierInfo
*NewBuiltinII
= PP
.getIdentifierInfo(NewBuiltinName
);
467 FunctionDecl
*NewBuiltinDecl
=
468 cast
<FunctionDecl
>(LazilyCreateBuiltin(NewBuiltinII
, NewBuiltinID
,
469 TUScope
, false, DRE
->getLocStart()));
471 // The first argument --- the pointer --- has a fixed type; we
472 // deduce the types of the rest of the arguments accordingly. Walk
473 // the remaining arguments, converting them to the deduced value type.
474 for (unsigned i
= 0; i
!= NumFixed
; ++i
) {
475 Expr
*Arg
= TheCall
->getArg(i
+1);
477 // If the argument is an implicit cast, then there was a promotion due to
478 // "...", just remove it now.
479 if (ImplicitCastExpr
*ICE
= dyn_cast
<ImplicitCastExpr
>(Arg
)) {
480 Arg
= ICE
->getSubExpr();
482 TheCall
->setArg(i
+1, Arg
);
485 // GCC does an implicit conversion to the pointer or integer ValType. This
486 // can fail in some cases (1i -> int**), check for this error case now.
487 CastKind Kind
= CK_Invalid
;
488 ExprValueKind VK
= VK_RValue
;
489 CXXCastPath BasePath
;
490 if (CheckCastTypes(Arg
->getSourceRange(), ValType
, Arg
, Kind
, VK
, BasePath
))
493 // Okay, we have something that *can* be converted to the right type. Check
494 // to see if there is a potentially weird extension going on here. This can
495 // happen when you do an atomic operation on something like an char* and
496 // pass in 42. The 42 gets converted to char. This is even more strange
497 // for things like 45.123 -> char, etc.
498 // FIXME: Do this check.
499 ImpCastExprToType(Arg
, ValType
, Kind
, VK
, &BasePath
);
500 TheCall
->setArg(i
+1, Arg
);
503 // Switch the DeclRefExpr to refer to the new decl.
504 DRE
->setDecl(NewBuiltinDecl
);
505 DRE
->setType(NewBuiltinDecl
->getType());
507 // Set the callee in the CallExpr.
508 // FIXME: This leaks the original parens and implicit casts.
509 Expr
*PromotedCall
= DRE
;
510 UsualUnaryConversions(PromotedCall
);
511 TheCall
->setCallee(PromotedCall
);
513 // Change the result type of the call to match the original value type. This
514 // is arbitrary, but the codegen for these builtins ins design to handle it
516 TheCall
->setType(ResultType
);
518 return move(TheCallResult
);
522 /// CheckObjCString - Checks that the argument to the builtin
523 /// CFString constructor is correct
524 /// Note: It might also make sense to do the UTF-16 conversion here (would
525 /// simplify the backend).
526 bool Sema::CheckObjCString(Expr
*Arg
) {
527 Arg
= Arg
->IgnoreParenCasts();
528 StringLiteral
*Literal
= dyn_cast
<StringLiteral
>(Arg
);
530 if (!Literal
|| Literal
->isWide()) {
531 Diag(Arg
->getLocStart(), diag::err_cfstring_literal_not_string_constant
)
532 << Arg
->getSourceRange();
536 size_t NulPos
= Literal
->getString().find('\0');
537 if (NulPos
!= llvm::StringRef::npos
) {
538 Diag(getLocationOfStringLiteralByte(Literal
, NulPos
),
539 diag::warn_cfstring_literal_contains_nul_character
)
540 << Arg
->getSourceRange();
542 if (Literal
->containsNonAsciiOrNull()) {
543 llvm::StringRef String
= Literal
->getString();
544 unsigned NumBytes
= String
.size();
545 llvm::SmallVector
<UTF16
, 128> ToBuf(NumBytes
);
546 const UTF8
*FromPtr
= (UTF8
*)String
.data();
547 UTF16
*ToPtr
= &ToBuf
[0];
549 ConversionResult Result
= ConvertUTF8toUTF16(&FromPtr
, FromPtr
+ NumBytes
,
550 &ToPtr
, ToPtr
+ NumBytes
,
552 // Check for conversion failure.
553 if (Result
!= conversionOK
)
554 Diag(Arg
->getLocStart(),
555 diag::warn_cfstring_truncated
) << Arg
->getSourceRange();
560 /// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
561 /// Emit an error and return true on failure, return false on success.
562 bool Sema::SemaBuiltinVAStart(CallExpr
*TheCall
) {
563 Expr
*Fn
= TheCall
->getCallee();
564 if (TheCall
->getNumArgs() > 2) {
565 Diag(TheCall
->getArg(2)->getLocStart(),
566 diag::err_typecheck_call_too_many_args
)
567 << 0 /*function call*/ << 2 << TheCall
->getNumArgs()
568 << Fn
->getSourceRange()
569 << SourceRange(TheCall
->getArg(2)->getLocStart(),
570 (*(TheCall
->arg_end()-1))->getLocEnd());
574 if (TheCall
->getNumArgs() < 2) {
575 return Diag(TheCall
->getLocEnd(),
576 diag::err_typecheck_call_too_few_args_at_least
)
577 << 0 /*function call*/ << 2 << TheCall
->getNumArgs();
580 // Determine whether the current function is variadic or not.
581 BlockScopeInfo
*CurBlock
= getCurBlock();
584 isVariadic
= CurBlock
->TheDecl
->isVariadic();
585 else if (FunctionDecl
*FD
= getCurFunctionDecl())
586 isVariadic
= FD
->isVariadic();
588 isVariadic
= getCurMethodDecl()->isVariadic();
591 Diag(Fn
->getLocStart(), diag::err_va_start_used_in_non_variadic_function
);
595 // Verify that the second argument to the builtin is the last argument of the
596 // current function or method.
597 bool SecondArgIsLastNamedArgument
= false;
598 const Expr
*Arg
= TheCall
->getArg(1)->IgnoreParenCasts();
600 if (const DeclRefExpr
*DR
= dyn_cast
<DeclRefExpr
>(Arg
)) {
601 if (const ParmVarDecl
*PV
= dyn_cast
<ParmVarDecl
>(DR
->getDecl())) {
602 // FIXME: This isn't correct for methods (results in bogus warning).
603 // Get the last formal in the current function.
604 const ParmVarDecl
*LastArg
;
606 LastArg
= *(CurBlock
->TheDecl
->param_end()-1);
607 else if (FunctionDecl
*FD
= getCurFunctionDecl())
608 LastArg
= *(FD
->param_end()-1);
610 LastArg
= *(getCurMethodDecl()->param_end()-1);
611 SecondArgIsLastNamedArgument
= PV
== LastArg
;
615 if (!SecondArgIsLastNamedArgument
)
616 Diag(TheCall
->getArg(1)->getLocStart(),
617 diag::warn_second_parameter_of_va_start_not_last_named_argument
);
621 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
622 /// friends. This is declared to take (...), so we have to check everything.
623 bool Sema::SemaBuiltinUnorderedCompare(CallExpr
*TheCall
) {
624 if (TheCall
->getNumArgs() < 2)
625 return Diag(TheCall
->getLocEnd(), diag::err_typecheck_call_too_few_args
)
626 << 0 << 2 << TheCall
->getNumArgs()/*function call*/;
627 if (TheCall
->getNumArgs() > 2)
628 return Diag(TheCall
->getArg(2)->getLocStart(),
629 diag::err_typecheck_call_too_many_args
)
630 << 0 /*function call*/ << 2 << TheCall
->getNumArgs()
631 << SourceRange(TheCall
->getArg(2)->getLocStart(),
632 (*(TheCall
->arg_end()-1))->getLocEnd());
634 Expr
*OrigArg0
= TheCall
->getArg(0);
635 Expr
*OrigArg1
= TheCall
->getArg(1);
637 // Do standard promotions between the two arguments, returning their common
639 QualType Res
= UsualArithmeticConversions(OrigArg0
, OrigArg1
, false);
641 // Make sure any conversions are pushed back into the call; this is
642 // type safe since unordered compare builtins are declared as "_Bool
644 TheCall
->setArg(0, OrigArg0
);
645 TheCall
->setArg(1, OrigArg1
);
647 if (OrigArg0
->isTypeDependent() || OrigArg1
->isTypeDependent())
650 // If the common type isn't a real floating type, then the arguments were
651 // invalid for this operation.
652 if (!Res
->isRealFloatingType())
653 return Diag(OrigArg0
->getLocStart(),
654 diag::err_typecheck_call_invalid_ordered_compare
)
655 << OrigArg0
->getType() << OrigArg1
->getType()
656 << SourceRange(OrigArg0
->getLocStart(), OrigArg1
->getLocEnd());
661 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
662 /// __builtin_isnan and friends. This is declared to take (...), so we have
663 /// to check everything. We expect the last argument to be a floating point
665 bool Sema::SemaBuiltinFPClassification(CallExpr
*TheCall
, unsigned NumArgs
) {
666 if (TheCall
->getNumArgs() < NumArgs
)
667 return Diag(TheCall
->getLocEnd(), diag::err_typecheck_call_too_few_args
)
668 << 0 << NumArgs
<< TheCall
->getNumArgs()/*function call*/;
669 if (TheCall
->getNumArgs() > NumArgs
)
670 return Diag(TheCall
->getArg(NumArgs
)->getLocStart(),
671 diag::err_typecheck_call_too_many_args
)
672 << 0 /*function call*/ << NumArgs
<< TheCall
->getNumArgs()
673 << SourceRange(TheCall
->getArg(NumArgs
)->getLocStart(),
674 (*(TheCall
->arg_end()-1))->getLocEnd());
676 Expr
*OrigArg
= TheCall
->getArg(NumArgs
-1);
678 if (OrigArg
->isTypeDependent())
681 // This operation requires a non-_Complex floating-point number.
682 if (!OrigArg
->getType()->isRealFloatingType())
683 return Diag(OrigArg
->getLocStart(),
684 diag::err_typecheck_call_invalid_unary_fp
)
685 << OrigArg
->getType() << OrigArg
->getSourceRange();
687 // If this is an implicit conversion from float -> double, remove it.
688 if (ImplicitCastExpr
*Cast
= dyn_cast
<ImplicitCastExpr
>(OrigArg
)) {
689 Expr
*CastArg
= Cast
->getSubExpr();
690 if (CastArg
->getType()->isSpecificBuiltinType(BuiltinType::Float
)) {
691 assert(Cast
->getType()->isSpecificBuiltinType(BuiltinType::Double
) &&
692 "promotion from float to double is the only expected cast here");
694 TheCall
->setArg(NumArgs
-1, CastArg
);
702 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
703 // This is declared to take (...), so we have to check everything.
704 ExprResult
Sema::SemaBuiltinShuffleVector(CallExpr
*TheCall
) {
705 if (TheCall
->getNumArgs() < 2)
706 return ExprError(Diag(TheCall
->getLocEnd(),
707 diag::err_typecheck_call_too_few_args_at_least
)
708 << 0 /*function call*/ << 2 << TheCall
->getNumArgs()
709 << TheCall
->getSourceRange());
711 // Determine which of the following types of shufflevector we're checking:
712 // 1) unary, vector mask: (lhs, mask)
713 // 2) binary, vector mask: (lhs, rhs, mask)
714 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
715 QualType resType
= TheCall
->getArg(0)->getType();
716 unsigned numElements
= 0;
718 if (!TheCall
->getArg(0)->isTypeDependent() &&
719 !TheCall
->getArg(1)->isTypeDependent()) {
720 QualType LHSType
= TheCall
->getArg(0)->getType();
721 QualType RHSType
= TheCall
->getArg(1)->getType();
723 if (!LHSType
->isVectorType() || !RHSType
->isVectorType()) {
724 Diag(TheCall
->getLocStart(), diag::err_shufflevector_non_vector
)
725 << SourceRange(TheCall
->getArg(0)->getLocStart(),
726 TheCall
->getArg(1)->getLocEnd());
730 numElements
= LHSType
->getAs
<VectorType
>()->getNumElements();
731 unsigned numResElements
= TheCall
->getNumArgs() - 2;
733 // Check to see if we have a call with 2 vector arguments, the unary shuffle
734 // with mask. If so, verify that RHS is an integer vector type with the
735 // same number of elts as lhs.
736 if (TheCall
->getNumArgs() == 2) {
737 if (!RHSType
->hasIntegerRepresentation() ||
738 RHSType
->getAs
<VectorType
>()->getNumElements() != numElements
)
739 Diag(TheCall
->getLocStart(), diag::err_shufflevector_incompatible_vector
)
740 << SourceRange(TheCall
->getArg(1)->getLocStart(),
741 TheCall
->getArg(1)->getLocEnd());
742 numResElements
= numElements
;
744 else if (!Context
.hasSameUnqualifiedType(LHSType
, RHSType
)) {
745 Diag(TheCall
->getLocStart(), diag::err_shufflevector_incompatible_vector
)
746 << SourceRange(TheCall
->getArg(0)->getLocStart(),
747 TheCall
->getArg(1)->getLocEnd());
749 } else if (numElements
!= numResElements
) {
750 QualType eltType
= LHSType
->getAs
<VectorType
>()->getElementType();
751 resType
= Context
.getVectorType(eltType
, numResElements
,
752 VectorType::GenericVector
);
756 for (unsigned i
= 2; i
< TheCall
->getNumArgs(); i
++) {
757 if (TheCall
->getArg(i
)->isTypeDependent() ||
758 TheCall
->getArg(i
)->isValueDependent())
761 llvm::APSInt
Result(32);
762 if (!TheCall
->getArg(i
)->isIntegerConstantExpr(Result
, Context
))
763 return ExprError(Diag(TheCall
->getLocStart(),
764 diag::err_shufflevector_nonconstant_argument
)
765 << TheCall
->getArg(i
)->getSourceRange());
767 if (Result
.getActiveBits() > 64 || Result
.getZExtValue() >= numElements
*2)
768 return ExprError(Diag(TheCall
->getLocStart(),
769 diag::err_shufflevector_argument_too_large
)
770 << TheCall
->getArg(i
)->getSourceRange());
773 llvm::SmallVector
<Expr
*, 32> exprs
;
775 for (unsigned i
= 0, e
= TheCall
->getNumArgs(); i
!= e
; i
++) {
776 exprs
.push_back(TheCall
->getArg(i
));
777 TheCall
->setArg(i
, 0);
780 return Owned(new (Context
) ShuffleVectorExpr(Context
, exprs
.begin(),
781 exprs
.size(), resType
,
782 TheCall
->getCallee()->getLocStart(),
783 TheCall
->getRParenLoc()));
786 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
787 // This is declared to take (const void*, ...) and can take two
788 // optional constant int args.
789 bool Sema::SemaBuiltinPrefetch(CallExpr
*TheCall
) {
790 unsigned NumArgs
= TheCall
->getNumArgs();
793 return Diag(TheCall
->getLocEnd(),
794 diag::err_typecheck_call_too_many_args_at_most
)
795 << 0 /*function call*/ << 3 << NumArgs
796 << TheCall
->getSourceRange();
798 // Argument 0 is checked for us and the remaining arguments must be
799 // constant integers.
800 for (unsigned i
= 1; i
!= NumArgs
; ++i
) {
801 Expr
*Arg
= TheCall
->getArg(i
);
804 if (SemaBuiltinConstantArg(TheCall
, i
, Result
))
807 // FIXME: gcc issues a warning and rewrites these to 0. These
808 // seems especially odd for the third argument since the default
811 if (Result
.getLimitedValue() > 1)
812 return Diag(TheCall
->getLocStart(), diag::err_argument_invalid_range
)
813 << "0" << "1" << Arg
->getSourceRange();
815 if (Result
.getLimitedValue() > 3)
816 return Diag(TheCall
->getLocStart(), diag::err_argument_invalid_range
)
817 << "0" << "3" << Arg
->getSourceRange();
824 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
825 /// TheCall is a constant expression.
826 bool Sema::SemaBuiltinConstantArg(CallExpr
*TheCall
, int ArgNum
,
827 llvm::APSInt
&Result
) {
828 Expr
*Arg
= TheCall
->getArg(ArgNum
);
829 DeclRefExpr
*DRE
=cast
<DeclRefExpr
>(TheCall
->getCallee()->IgnoreParenCasts());
830 FunctionDecl
*FDecl
= cast
<FunctionDecl
>(DRE
->getDecl());
832 if (Arg
->isTypeDependent() || Arg
->isValueDependent()) return false;
834 if (!Arg
->isIntegerConstantExpr(Result
, Context
))
835 return Diag(TheCall
->getLocStart(), diag::err_constant_integer_arg_type
)
836 << FDecl
->getDeclName() << Arg
->getSourceRange();
841 /// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
842 /// int type). This simply type checks that type is one of the defined
844 // For compatability check 0-3, llvm only handles 0 and 2.
845 bool Sema::SemaBuiltinObjectSize(CallExpr
*TheCall
) {
848 // Check constant-ness first.
849 if (SemaBuiltinConstantArg(TheCall
, 1, Result
))
852 Expr
*Arg
= TheCall
->getArg(1);
853 if (Result
.getSExtValue() < 0 || Result
.getSExtValue() > 3) {
854 return Diag(TheCall
->getLocStart(), diag::err_argument_invalid_range
)
855 << "0" << "3" << SourceRange(Arg
->getLocStart(), Arg
->getLocEnd());
861 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
862 /// This checks that val is a constant 1.
863 bool Sema::SemaBuiltinLongjmp(CallExpr
*TheCall
) {
864 Expr
*Arg
= TheCall
->getArg(1);
867 // TODO: This is less than ideal. Overload this to take a value.
868 if (SemaBuiltinConstantArg(TheCall
, 1, Result
))
872 return Diag(TheCall
->getLocStart(), diag::err_builtin_longjmp_invalid_val
)
873 << SourceRange(Arg
->getLocStart(), Arg
->getLocEnd());
878 // Handle i > 1 ? "x" : "y", recursivelly
879 bool Sema::SemaCheckStringLiteral(const Expr
*E
, const CallExpr
*TheCall
,
881 unsigned format_idx
, unsigned firstDataArg
,
884 if (E
->isTypeDependent() || E
->isValueDependent())
887 switch (E
->getStmtClass()) {
888 case Stmt::ConditionalOperatorClass
: {
889 const ConditionalOperator
*C
= cast
<ConditionalOperator
>(E
);
890 return SemaCheckStringLiteral(C
->getTrueExpr(), TheCall
, HasVAListArg
,
891 format_idx
, firstDataArg
, isPrintf
)
892 && SemaCheckStringLiteral(C
->getRHS(), TheCall
, HasVAListArg
,
893 format_idx
, firstDataArg
, isPrintf
);
896 case Stmt::IntegerLiteralClass
:
897 // Technically -Wformat-nonliteral does not warn about this case.
898 // The behavior of printf and friends in this case is implementation
899 // dependent. Ideally if the format string cannot be null then
900 // it should have a 'nonnull' attribute in the function prototype.
903 case Stmt::ImplicitCastExprClass
: {
904 E
= cast
<ImplicitCastExpr
>(E
)->getSubExpr();
908 case Stmt::ParenExprClass
: {
909 E
= cast
<ParenExpr
>(E
)->getSubExpr();
913 case Stmt::DeclRefExprClass
: {
914 const DeclRefExpr
*DR
= cast
<DeclRefExpr
>(E
);
916 // As an exception, do not flag errors for variables binding to
917 // const string literals.
918 if (const VarDecl
*VD
= dyn_cast
<VarDecl
>(DR
->getDecl())) {
919 bool isConstant
= false;
920 QualType T
= DR
->getType();
922 if (const ArrayType
*AT
= Context
.getAsArrayType(T
)) {
923 isConstant
= AT
->getElementType().isConstant(Context
);
924 } else if (const PointerType
*PT
= T
->getAs
<PointerType
>()) {
925 isConstant
= T
.isConstant(Context
) &&
926 PT
->getPointeeType().isConstant(Context
);
930 if (const Expr
*Init
= VD
->getAnyInitializer())
931 return SemaCheckStringLiteral(Init
, TheCall
,
932 HasVAListArg
, format_idx
, firstDataArg
,
936 // For vprintf* functions (i.e., HasVAListArg==true), we add a
937 // special check to see if the format string is a function parameter
938 // of the function calling the printf function. If the function
939 // has an attribute indicating it is a printf-like function, then we
940 // should suppress warnings concerning non-literals being used in a call
941 // to a vprintf function. For example:
944 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
946 // va_start(ap, fmt);
947 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
951 // FIXME: We don't have full attribute support yet, so just check to see
952 // if the argument is a DeclRefExpr that references a parameter. We'll
953 // add proper support for checking the attribute later.
955 if (isa
<ParmVarDecl
>(VD
))
962 case Stmt::CallExprClass
: {
963 const CallExpr
*CE
= cast
<CallExpr
>(E
);
964 if (const ImplicitCastExpr
*ICE
965 = dyn_cast
<ImplicitCastExpr
>(CE
->getCallee())) {
966 if (const DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(ICE
->getSubExpr())) {
967 if (const FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(DRE
->getDecl())) {
968 if (const FormatArgAttr
*FA
= FD
->getAttr
<FormatArgAttr
>()) {
969 unsigned ArgIndex
= FA
->getFormatIdx();
970 const Expr
*Arg
= CE
->getArg(ArgIndex
- 1);
972 return SemaCheckStringLiteral(Arg
, TheCall
, HasVAListArg
,
973 format_idx
, firstDataArg
, isPrintf
);
981 case Stmt::ObjCStringLiteralClass
:
982 case Stmt::StringLiteralClass
: {
983 const StringLiteral
*StrE
= NULL
;
985 if (const ObjCStringLiteral
*ObjCFExpr
= dyn_cast
<ObjCStringLiteral
>(E
))
986 StrE
= ObjCFExpr
->getString();
988 StrE
= cast
<StringLiteral
>(E
);
991 CheckFormatString(StrE
, E
, TheCall
, HasVAListArg
, format_idx
,
992 firstDataArg
, isPrintf
);
1005 Sema::CheckNonNullArguments(const NonNullAttr
*NonNull
,
1006 const CallExpr
*TheCall
) {
1007 for (NonNullAttr::args_iterator i
= NonNull
->args_begin(),
1008 e
= NonNull
->args_end();
1010 const Expr
*ArgExpr
= TheCall
->getArg(*i
);
1011 if (ArgExpr
->isNullPointerConstant(Context
,
1012 Expr::NPC_ValueDependentIsNotNull
))
1013 Diag(TheCall
->getCallee()->getLocStart(), diag::warn_null_arg
)
1014 << ArgExpr
->getSourceRange();
1018 /// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar
1019 /// functions) for correct use of format strings.
1021 Sema::CheckPrintfScanfArguments(const CallExpr
*TheCall
, bool HasVAListArg
,
1022 unsigned format_idx
, unsigned firstDataArg
,
1025 const Expr
*Fn
= TheCall
->getCallee();
1027 // The way the format attribute works in GCC, the implicit this argument
1028 // of member functions is counted. However, it doesn't appear in our own
1029 // lists, so decrement format_idx in that case.
1030 if (isa
<CXXMemberCallExpr
>(TheCall
)) {
1031 const CXXMethodDecl
*method_decl
=
1032 dyn_cast
<CXXMethodDecl
>(TheCall
->getCalleeDecl());
1033 if (method_decl
&& method_decl
->isInstance()) {
1034 // Catch a format attribute mistakenly referring to the object argument.
1035 if (format_idx
== 0)
1038 if(firstDataArg
!= 0)
1043 // CHECK: printf/scanf-like function is called with no format string.
1044 if (format_idx
>= TheCall
->getNumArgs()) {
1045 Diag(TheCall
->getRParenLoc(), diag::warn_missing_format_string
)
1046 << Fn
->getSourceRange();
1050 const Expr
*OrigFormatExpr
= TheCall
->getArg(format_idx
)->IgnoreParenCasts();
1052 // CHECK: format string is not a string literal.
1054 // Dynamically generated format strings are difficult to
1055 // automatically vet at compile time. Requiring that format strings
1056 // are string literals: (1) permits the checking of format strings by
1057 // the compiler and thereby (2) can practically remove the source of
1058 // many format string exploits.
1060 // Format string can be either ObjC string (e.g. @"%d") or
1061 // C string (e.g. "%d")
1062 // ObjC string uses the same format specifiers as C string, so we can use
1063 // the same format string checking logic for both ObjC and C strings.
1064 if (SemaCheckStringLiteral(OrigFormatExpr
, TheCall
, HasVAListArg
, format_idx
,
1065 firstDataArg
, isPrintf
))
1066 return; // Literal format string found, check done!
1068 // If there are no arguments specified, warn with -Wformat-security, otherwise
1069 // warn only with -Wformat-nonliteral.
1070 if (TheCall
->getNumArgs() == format_idx
+1)
1071 Diag(TheCall
->getArg(format_idx
)->getLocStart(),
1072 diag::warn_format_nonliteral_noargs
)
1073 << OrigFormatExpr
->getSourceRange();
1075 Diag(TheCall
->getArg(format_idx
)->getLocStart(),
1076 diag::warn_format_nonliteral
)
1077 << OrigFormatExpr
->getSourceRange();
1081 class CheckFormatHandler
: public analyze_format_string::FormatStringHandler
{
1084 const StringLiteral
*FExpr
;
1085 const Expr
*OrigFormatExpr
;
1086 const unsigned FirstDataArg
;
1087 const unsigned NumDataArgs
;
1088 const bool IsObjCLiteral
;
1089 const char *Beg
; // Start of format string.
1090 const bool HasVAListArg
;
1091 const CallExpr
*TheCall
;
1093 llvm::BitVector CoveredArgs
;
1094 bool usesPositionalArgs
;
1097 CheckFormatHandler(Sema
&s
, const StringLiteral
*fexpr
,
1098 const Expr
*origFormatExpr
, unsigned firstDataArg
,
1099 unsigned numDataArgs
, bool isObjCLiteral
,
1100 const char *beg
, bool hasVAListArg
,
1101 const CallExpr
*theCall
, unsigned formatIdx
)
1102 : S(s
), FExpr(fexpr
), OrigFormatExpr(origFormatExpr
),
1103 FirstDataArg(firstDataArg
),
1104 NumDataArgs(numDataArgs
),
1105 IsObjCLiteral(isObjCLiteral
), Beg(beg
),
1106 HasVAListArg(hasVAListArg
),
1107 TheCall(theCall
), FormatIdx(formatIdx
),
1108 usesPositionalArgs(false), atFirstArg(true) {
1109 CoveredArgs
.resize(numDataArgs
);
1110 CoveredArgs
.reset();
1113 void DoneProcessing();
1115 void HandleIncompleteSpecifier(const char *startSpecifier
,
1116 unsigned specifierLen
);
1118 virtual void HandleInvalidPosition(const char *startSpecifier
,
1119 unsigned specifierLen
,
1120 analyze_format_string::PositionContext p
);
1122 virtual void HandleZeroPosition(const char *startPos
, unsigned posLen
);
1124 void HandleNullChar(const char *nullCharacter
);
1127 bool HandleInvalidConversionSpecifier(unsigned argIndex
, SourceLocation Loc
,
1128 const char *startSpec
,
1129 unsigned specifierLen
,
1130 const char *csStart
, unsigned csLen
);
1132 SourceRange
getFormatStringRange();
1133 CharSourceRange
getSpecifierRange(const char *startSpecifier
,
1134 unsigned specifierLen
);
1135 SourceLocation
getLocationOfByte(const char *x
);
1137 const Expr
*getDataArg(unsigned i
) const;
1139 bool CheckNumArgs(const analyze_format_string::FormatSpecifier
&FS
,
1140 const analyze_format_string::ConversionSpecifier
&CS
,
1141 const char *startSpecifier
, unsigned specifierLen
,
1146 SourceRange
CheckFormatHandler::getFormatStringRange() {
1147 return OrigFormatExpr
->getSourceRange();
1150 CharSourceRange
CheckFormatHandler::
1151 getSpecifierRange(const char *startSpecifier
, unsigned specifierLen
) {
1152 SourceLocation Start
= getLocationOfByte(startSpecifier
);
1153 SourceLocation End
= getLocationOfByte(startSpecifier
+ specifierLen
- 1);
1155 // Advance the end SourceLocation by one due to half-open ranges.
1156 End
= End
.getFileLocWithOffset(1);
1158 return CharSourceRange::getCharRange(Start
, End
);
1161 SourceLocation
CheckFormatHandler::getLocationOfByte(const char *x
) {
1162 return S
.getLocationOfStringLiteralByte(FExpr
, x
- Beg
);
1165 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier
,
1166 unsigned specifierLen
){
1167 SourceLocation Loc
= getLocationOfByte(startSpecifier
);
1168 S
.Diag(Loc
, diag::warn_printf_incomplete_specifier
)
1169 << getSpecifierRange(startSpecifier
, specifierLen
);
1173 CheckFormatHandler::HandleInvalidPosition(const char *startPos
, unsigned posLen
,
1174 analyze_format_string::PositionContext p
) {
1175 SourceLocation Loc
= getLocationOfByte(startPos
);
1176 S
.Diag(Loc
, diag::warn_format_invalid_positional_specifier
)
1177 << (unsigned) p
<< getSpecifierRange(startPos
, posLen
);
1180 void CheckFormatHandler::HandleZeroPosition(const char *startPos
,
1182 SourceLocation Loc
= getLocationOfByte(startPos
);
1183 S
.Diag(Loc
, diag::warn_format_zero_positional_specifier
)
1184 << getSpecifierRange(startPos
, posLen
);
1187 void CheckFormatHandler::HandleNullChar(const char *nullCharacter
) {
1188 // The presence of a null character is likely an error.
1189 S
.Diag(getLocationOfByte(nullCharacter
),
1190 diag::warn_printf_format_string_contains_null_char
)
1191 << getFormatStringRange();
1194 const Expr
*CheckFormatHandler::getDataArg(unsigned i
) const {
1195 return TheCall
->getArg(FirstDataArg
+ i
);
1198 void CheckFormatHandler::DoneProcessing() {
1199 // Does the number of data arguments exceed the number of
1200 // format conversions in the format string?
1201 if (!HasVAListArg
) {
1202 // Find any arguments that weren't covered.
1204 signed notCoveredArg
= CoveredArgs
.find_first();
1205 if (notCoveredArg
>= 0) {
1206 assert((unsigned)notCoveredArg
< NumDataArgs
);
1207 S
.Diag(getDataArg((unsigned) notCoveredArg
)->getLocStart(),
1208 diag::warn_printf_data_arg_not_used
)
1209 << getFormatStringRange();
1215 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex
,
1217 const char *startSpec
,
1218 unsigned specifierLen
,
1219 const char *csStart
,
1222 bool keepGoing
= true;
1223 if (argIndex
< NumDataArgs
) {
1224 // Consider the argument coverered, even though the specifier doesn't
1226 CoveredArgs
.set(argIndex
);
1229 // If argIndex exceeds the number of data arguments we
1230 // don't issue a warning because that is just a cascade of warnings (and
1231 // they may have intended '%%' anyway). We don't want to continue processing
1232 // the format string after this point, however, as we will like just get
1233 // gibberish when trying to match arguments.
1237 S
.Diag(Loc
, diag::warn_format_invalid_conversion
)
1238 << llvm::StringRef(csStart
, csLen
)
1239 << getSpecifierRange(startSpec
, specifierLen
);
1245 CheckFormatHandler::CheckNumArgs(
1246 const analyze_format_string::FormatSpecifier
&FS
,
1247 const analyze_format_string::ConversionSpecifier
&CS
,
1248 const char *startSpecifier
, unsigned specifierLen
, unsigned argIndex
) {
1250 if (argIndex
>= NumDataArgs
) {
1251 if (FS
.usesPositionalArg()) {
1252 S
.Diag(getLocationOfByte(CS
.getStart()),
1253 diag::warn_printf_positional_arg_exceeds_data_args
)
1254 << (argIndex
+1) << NumDataArgs
1255 << getSpecifierRange(startSpecifier
, specifierLen
);
1258 S
.Diag(getLocationOfByte(CS
.getStart()),
1259 diag::warn_printf_insufficient_data_args
)
1260 << getSpecifierRange(startSpecifier
, specifierLen
);
1268 //===--- CHECK: Printf format string checking ------------------------------===//
1271 class CheckPrintfHandler
: public CheckFormatHandler
{
1273 CheckPrintfHandler(Sema
&s
, const StringLiteral
*fexpr
,
1274 const Expr
*origFormatExpr
, unsigned firstDataArg
,
1275 unsigned numDataArgs
, bool isObjCLiteral
,
1276 const char *beg
, bool hasVAListArg
,
1277 const CallExpr
*theCall
, unsigned formatIdx
)
1278 : CheckFormatHandler(s
, fexpr
, origFormatExpr
, firstDataArg
,
1279 numDataArgs
, isObjCLiteral
, beg
, hasVAListArg
,
1280 theCall
, formatIdx
) {}
1283 bool HandleInvalidPrintfConversionSpecifier(
1284 const analyze_printf::PrintfSpecifier
&FS
,
1285 const char *startSpecifier
,
1286 unsigned specifierLen
);
1288 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
&FS
,
1289 const char *startSpecifier
,
1290 unsigned specifierLen
);
1292 bool HandleAmount(const analyze_format_string::OptionalAmount
&Amt
, unsigned k
,
1293 const char *startSpecifier
, unsigned specifierLen
);
1294 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier
&FS
,
1295 const analyze_printf::OptionalAmount
&Amt
,
1297 const char *startSpecifier
, unsigned specifierLen
);
1298 void HandleFlag(const analyze_printf::PrintfSpecifier
&FS
,
1299 const analyze_printf::OptionalFlag
&flag
,
1300 const char *startSpecifier
, unsigned specifierLen
);
1301 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier
&FS
,
1302 const analyze_printf::OptionalFlag
&ignoredFlag
,
1303 const analyze_printf::OptionalFlag
&flag
,
1304 const char *startSpecifier
, unsigned specifierLen
);
1308 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
1309 const analyze_printf::PrintfSpecifier
&FS
,
1310 const char *startSpecifier
,
1311 unsigned specifierLen
) {
1312 const analyze_printf::PrintfConversionSpecifier
&CS
=
1313 FS
.getConversionSpecifier();
1315 return HandleInvalidConversionSpecifier(FS
.getArgIndex(),
1316 getLocationOfByte(CS
.getStart()),
1317 startSpecifier
, specifierLen
,
1318 CS
.getStart(), CS
.getLength());
1321 bool CheckPrintfHandler::HandleAmount(
1322 const analyze_format_string::OptionalAmount
&Amt
,
1323 unsigned k
, const char *startSpecifier
,
1324 unsigned specifierLen
) {
1326 if (Amt
.hasDataArgument()) {
1327 if (!HasVAListArg
) {
1328 unsigned argIndex
= Amt
.getArgIndex();
1329 if (argIndex
>= NumDataArgs
) {
1330 S
.Diag(getLocationOfByte(Amt
.getStart()),
1331 diag::warn_printf_asterisk_missing_arg
)
1332 << k
<< getSpecifierRange(startSpecifier
, specifierLen
);
1333 // Don't do any more checking. We will just emit
1338 // Type check the data argument. It should be an 'int'.
1339 // Although not in conformance with C99, we also allow the argument to be
1340 // an 'unsigned int' as that is a reasonably safe case. GCC also
1341 // doesn't emit a warning for that case.
1342 CoveredArgs
.set(argIndex
);
1343 const Expr
*Arg
= getDataArg(argIndex
);
1344 QualType T
= Arg
->getType();
1346 const analyze_printf::ArgTypeResult
&ATR
= Amt
.getArgType(S
.Context
);
1347 assert(ATR
.isValid());
1349 if (!ATR
.matchesType(S
.Context
, T
)) {
1350 S
.Diag(getLocationOfByte(Amt
.getStart()),
1351 diag::warn_printf_asterisk_wrong_type
)
1353 << ATR
.getRepresentativeType(S
.Context
) << T
1354 << getSpecifierRange(startSpecifier
, specifierLen
)
1355 << Arg
->getSourceRange();
1356 // Don't do any more checking. We will just emit
1365 void CheckPrintfHandler::HandleInvalidAmount(
1366 const analyze_printf::PrintfSpecifier
&FS
,
1367 const analyze_printf::OptionalAmount
&Amt
,
1369 const char *startSpecifier
,
1370 unsigned specifierLen
) {
1371 const analyze_printf::PrintfConversionSpecifier
&CS
=
1372 FS
.getConversionSpecifier();
1373 switch (Amt
.getHowSpecified()) {
1374 case analyze_printf::OptionalAmount::Constant
:
1375 S
.Diag(getLocationOfByte(Amt
.getStart()),
1376 diag::warn_printf_nonsensical_optional_amount
)
1379 << getSpecifierRange(startSpecifier
, specifierLen
)
1380 << FixItHint::CreateRemoval(getSpecifierRange(Amt
.getStart(),
1381 Amt
.getConstantLength()));
1385 S
.Diag(getLocationOfByte(Amt
.getStart()),
1386 diag::warn_printf_nonsensical_optional_amount
)
1389 << getSpecifierRange(startSpecifier
, specifierLen
);
1394 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier
&FS
,
1395 const analyze_printf::OptionalFlag
&flag
,
1396 const char *startSpecifier
,
1397 unsigned specifierLen
) {
1398 // Warn about pointless flag with a fixit removal.
1399 const analyze_printf::PrintfConversionSpecifier
&CS
=
1400 FS
.getConversionSpecifier();
1401 S
.Diag(getLocationOfByte(flag
.getPosition()),
1402 diag::warn_printf_nonsensical_flag
)
1403 << flag
.toString() << CS
.toString()
1404 << getSpecifierRange(startSpecifier
, specifierLen
)
1405 << FixItHint::CreateRemoval(getSpecifierRange(flag
.getPosition(), 1));
1408 void CheckPrintfHandler::HandleIgnoredFlag(
1409 const analyze_printf::PrintfSpecifier
&FS
,
1410 const analyze_printf::OptionalFlag
&ignoredFlag
,
1411 const analyze_printf::OptionalFlag
&flag
,
1412 const char *startSpecifier
,
1413 unsigned specifierLen
) {
1414 // Warn about ignored flag with a fixit removal.
1415 S
.Diag(getLocationOfByte(ignoredFlag
.getPosition()),
1416 diag::warn_printf_ignored_flag
)
1417 << ignoredFlag
.toString() << flag
.toString()
1418 << getSpecifierRange(startSpecifier
, specifierLen
)
1419 << FixItHint::CreateRemoval(getSpecifierRange(
1420 ignoredFlag
.getPosition(), 1));
1424 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
1426 const char *startSpecifier
,
1427 unsigned specifierLen
) {
1429 using namespace analyze_format_string
;
1430 using namespace analyze_printf
;
1431 const PrintfConversionSpecifier
&CS
= FS
.getConversionSpecifier();
1433 if (FS
.consumesDataArgument()) {
1436 usesPositionalArgs
= FS
.usesPositionalArg();
1438 else if (usesPositionalArgs
!= FS
.usesPositionalArg()) {
1439 // Cannot mix-and-match positional and non-positional arguments.
1440 S
.Diag(getLocationOfByte(CS
.getStart()),
1441 diag::warn_format_mix_positional_nonpositional_args
)
1442 << getSpecifierRange(startSpecifier
, specifierLen
);
1447 // First check if the field width, precision, and conversion specifier
1448 // have matching data arguments.
1449 if (!HandleAmount(FS
.getFieldWidth(), /* field width */ 0,
1450 startSpecifier
, specifierLen
)) {
1454 if (!HandleAmount(FS
.getPrecision(), /* precision */ 1,
1455 startSpecifier
, specifierLen
)) {
1459 if (!CS
.consumesDataArgument()) {
1460 // FIXME: Technically specifying a precision or field width here
1461 // makes no sense. Worth issuing a warning at some point.
1465 // Consume the argument.
1466 unsigned argIndex
= FS
.getArgIndex();
1467 if (argIndex
< NumDataArgs
) {
1468 // The check to see if the argIndex is valid will come later.
1469 // We set the bit here because we may exit early from this
1470 // function if we encounter some other error.
1471 CoveredArgs
.set(argIndex
);
1474 // Check for using an Objective-C specific conversion specifier
1475 // in a non-ObjC literal.
1476 if (!IsObjCLiteral
&& CS
.isObjCArg()) {
1477 return HandleInvalidPrintfConversionSpecifier(FS
, startSpecifier
,
1481 // Check for invalid use of field width
1482 if (!FS
.hasValidFieldWidth()) {
1483 HandleInvalidAmount(FS
, FS
.getFieldWidth(), /* field width */ 0,
1484 startSpecifier
, specifierLen
);
1487 // Check for invalid use of precision
1488 if (!FS
.hasValidPrecision()) {
1489 HandleInvalidAmount(FS
, FS
.getPrecision(), /* precision */ 1,
1490 startSpecifier
, specifierLen
);
1493 // Check each flag does not conflict with any other component.
1494 if (!FS
.hasValidLeadingZeros())
1495 HandleFlag(FS
, FS
.hasLeadingZeros(), startSpecifier
, specifierLen
);
1496 if (!FS
.hasValidPlusPrefix())
1497 HandleFlag(FS
, FS
.hasPlusPrefix(), startSpecifier
, specifierLen
);
1498 if (!FS
.hasValidSpacePrefix())
1499 HandleFlag(FS
, FS
.hasSpacePrefix(), startSpecifier
, specifierLen
);
1500 if (!FS
.hasValidAlternativeForm())
1501 HandleFlag(FS
, FS
.hasAlternativeForm(), startSpecifier
, specifierLen
);
1502 if (!FS
.hasValidLeftJustified())
1503 HandleFlag(FS
, FS
.isLeftJustified(), startSpecifier
, specifierLen
);
1505 // Check that flags are not ignored by another flag
1506 if (FS
.hasSpacePrefix() && FS
.hasPlusPrefix()) // ' ' ignored by '+'
1507 HandleIgnoredFlag(FS
, FS
.hasSpacePrefix(), FS
.hasPlusPrefix(),
1508 startSpecifier
, specifierLen
);
1509 if (FS
.hasLeadingZeros() && FS
.isLeftJustified()) // '0' ignored by '-'
1510 HandleIgnoredFlag(FS
, FS
.hasLeadingZeros(), FS
.isLeftJustified(),
1511 startSpecifier
, specifierLen
);
1513 // Check the length modifier is valid with the given conversion specifier.
1514 const LengthModifier
&LM
= FS
.getLengthModifier();
1515 if (!FS
.hasValidLengthModifier())
1516 S
.Diag(getLocationOfByte(LM
.getStart()),
1517 diag::warn_format_nonsensical_length
)
1518 << LM
.toString() << CS
.toString()
1519 << getSpecifierRange(startSpecifier
, specifierLen
)
1520 << FixItHint::CreateRemoval(getSpecifierRange(LM
.getStart(),
1523 // Are we using '%n'?
1524 if (CS
.getKind() == ConversionSpecifier::nArg
) {
1525 // Issue a warning about this being a possible security issue.
1526 S
.Diag(getLocationOfByte(CS
.getStart()), diag::warn_printf_write_back
)
1527 << getSpecifierRange(startSpecifier
, specifierLen
);
1528 // Continue checking the other format specifiers.
1532 // The remaining checks depend on the data arguments.
1536 if (!CheckNumArgs(FS
, CS
, startSpecifier
, specifierLen
, argIndex
))
1539 // Now type check the data expression that matches the
1540 // format specifier.
1541 const Expr
*Ex
= getDataArg(argIndex
);
1542 const analyze_printf::ArgTypeResult
&ATR
= FS
.getArgType(S
.Context
);
1543 if (ATR
.isValid() && !ATR
.matchesType(S
.Context
, Ex
->getType())) {
1544 // Check if we didn't match because of an implicit cast from a 'char'
1545 // or 'short' to an 'int'. This is done because printf is a varargs
1547 if (const ImplicitCastExpr
*ICE
= dyn_cast
<ImplicitCastExpr
>(Ex
))
1548 if (ICE
->getType() == S
.Context
.IntTy
) {
1549 // All further checking is done on the subexpression.
1550 Ex
= ICE
->getSubExpr();
1551 if (ATR
.matchesType(S
.Context
, Ex
->getType()))
1555 // We may be able to offer a FixItHint if it is a supported type.
1556 PrintfSpecifier fixedFS
= FS
;
1557 bool success
= fixedFS
.fixType(Ex
->getType());
1560 // Get the fix string from the fixed format specifier
1561 llvm::SmallString
<128> buf
;
1562 llvm::raw_svector_ostream
os(buf
);
1563 fixedFS
.toString(os
);
1565 // FIXME: getRepresentativeType() perhaps should return a string
1566 // instead of a QualType to better handle when the representative
1567 // type is 'wint_t' (which is defined in the system headers).
1568 S
.Diag(getLocationOfByte(CS
.getStart()),
1569 diag::warn_printf_conversion_argument_type_mismatch
)
1570 << ATR
.getRepresentativeType(S
.Context
) << Ex
->getType()
1571 << getSpecifierRange(startSpecifier
, specifierLen
)
1572 << Ex
->getSourceRange()
1573 << FixItHint::CreateReplacement(
1574 getSpecifierRange(startSpecifier
, specifierLen
),
1578 S
.Diag(getLocationOfByte(CS
.getStart()),
1579 diag::warn_printf_conversion_argument_type_mismatch
)
1580 << ATR
.getRepresentativeType(S
.Context
) << Ex
->getType()
1581 << getSpecifierRange(startSpecifier
, specifierLen
)
1582 << Ex
->getSourceRange();
1589 //===--- CHECK: Scanf format string checking ------------------------------===//
1592 class CheckScanfHandler
: public CheckFormatHandler
{
1594 CheckScanfHandler(Sema
&s
, const StringLiteral
*fexpr
,
1595 const Expr
*origFormatExpr
, unsigned firstDataArg
,
1596 unsigned numDataArgs
, bool isObjCLiteral
,
1597 const char *beg
, bool hasVAListArg
,
1598 const CallExpr
*theCall
, unsigned formatIdx
)
1599 : CheckFormatHandler(s
, fexpr
, origFormatExpr
, firstDataArg
,
1600 numDataArgs
, isObjCLiteral
, beg
, hasVAListArg
,
1601 theCall
, formatIdx
) {}
1603 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier
&FS
,
1604 const char *startSpecifier
,
1605 unsigned specifierLen
);
1607 bool HandleInvalidScanfConversionSpecifier(
1608 const analyze_scanf::ScanfSpecifier
&FS
,
1609 const char *startSpecifier
,
1610 unsigned specifierLen
);
1612 void HandleIncompleteScanList(const char *start
, const char *end
);
1616 void CheckScanfHandler::HandleIncompleteScanList(const char *start
,
1618 S
.Diag(getLocationOfByte(end
), diag::warn_scanf_scanlist_incomplete
)
1619 << getSpecifierRange(start
, end
- start
);
1622 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
1623 const analyze_scanf::ScanfSpecifier
&FS
,
1624 const char *startSpecifier
,
1625 unsigned specifierLen
) {
1627 const analyze_scanf::ScanfConversionSpecifier
&CS
=
1628 FS
.getConversionSpecifier();
1630 return HandleInvalidConversionSpecifier(FS
.getArgIndex(),
1631 getLocationOfByte(CS
.getStart()),
1632 startSpecifier
, specifierLen
,
1633 CS
.getStart(), CS
.getLength());
1636 bool CheckScanfHandler::HandleScanfSpecifier(
1637 const analyze_scanf::ScanfSpecifier
&FS
,
1638 const char *startSpecifier
,
1639 unsigned specifierLen
) {
1641 using namespace analyze_scanf
;
1642 using namespace analyze_format_string
;
1644 const ScanfConversionSpecifier
&CS
= FS
.getConversionSpecifier();
1646 // Handle case where '%' and '*' don't consume an argument. These shouldn't
1647 // be used to decide if we are using positional arguments consistently.
1648 if (FS
.consumesDataArgument()) {
1651 usesPositionalArgs
= FS
.usesPositionalArg();
1653 else if (usesPositionalArgs
!= FS
.usesPositionalArg()) {
1654 // Cannot mix-and-match positional and non-positional arguments.
1655 S
.Diag(getLocationOfByte(CS
.getStart()),
1656 diag::warn_format_mix_positional_nonpositional_args
)
1657 << getSpecifierRange(startSpecifier
, specifierLen
);
1662 // Check if the field with is non-zero.
1663 const OptionalAmount
&Amt
= FS
.getFieldWidth();
1664 if (Amt
.getHowSpecified() == OptionalAmount::Constant
) {
1665 if (Amt
.getConstantAmount() == 0) {
1666 const CharSourceRange
&R
= getSpecifierRange(Amt
.getStart(),
1667 Amt
.getConstantLength());
1668 S
.Diag(getLocationOfByte(Amt
.getStart()),
1669 diag::warn_scanf_nonzero_width
)
1670 << R
<< FixItHint::CreateRemoval(R
);
1674 if (!FS
.consumesDataArgument()) {
1675 // FIXME: Technically specifying a precision or field width here
1676 // makes no sense. Worth issuing a warning at some point.
1680 // Consume the argument.
1681 unsigned argIndex
= FS
.getArgIndex();
1682 if (argIndex
< NumDataArgs
) {
1683 // The check to see if the argIndex is valid will come later.
1684 // We set the bit here because we may exit early from this
1685 // function if we encounter some other error.
1686 CoveredArgs
.set(argIndex
);
1689 // Check the length modifier is valid with the given conversion specifier.
1690 const LengthModifier
&LM
= FS
.getLengthModifier();
1691 if (!FS
.hasValidLengthModifier()) {
1692 S
.Diag(getLocationOfByte(LM
.getStart()),
1693 diag::warn_format_nonsensical_length
)
1694 << LM
.toString() << CS
.toString()
1695 << getSpecifierRange(startSpecifier
, specifierLen
)
1696 << FixItHint::CreateRemoval(getSpecifierRange(LM
.getStart(),
1700 // The remaining checks depend on the data arguments.
1704 if (!CheckNumArgs(FS
, CS
, startSpecifier
, specifierLen
, argIndex
))
1707 // FIXME: Check that the argument type matches the format specifier.
1712 void Sema::CheckFormatString(const StringLiteral
*FExpr
,
1713 const Expr
*OrigFormatExpr
,
1714 const CallExpr
*TheCall
, bool HasVAListArg
,
1715 unsigned format_idx
, unsigned firstDataArg
,
1718 // CHECK: is the format string a wide literal?
1719 if (FExpr
->isWide()) {
1720 Diag(FExpr
->getLocStart(),
1721 diag::warn_format_string_is_wide_literal
)
1722 << OrigFormatExpr
->getSourceRange();
1726 // Str - The format string. NOTE: this is NOT null-terminated!
1727 llvm::StringRef StrRef
= FExpr
->getString();
1728 const char *Str
= StrRef
.data();
1729 unsigned StrLen
= StrRef
.size();
1731 // CHECK: empty format string?
1733 Diag(FExpr
->getLocStart(), diag::warn_empty_format_string
)
1734 << OrigFormatExpr
->getSourceRange();
1739 CheckPrintfHandler
H(*this, FExpr
, OrigFormatExpr
, firstDataArg
,
1740 TheCall
->getNumArgs() - firstDataArg
,
1741 isa
<ObjCStringLiteral
>(OrigFormatExpr
), Str
,
1742 HasVAListArg
, TheCall
, format_idx
);
1744 if (!analyze_format_string::ParsePrintfString(H
, Str
, Str
+ StrLen
))
1748 CheckScanfHandler
H(*this, FExpr
, OrigFormatExpr
, firstDataArg
,
1749 TheCall
->getNumArgs() - firstDataArg
,
1750 isa
<ObjCStringLiteral
>(OrigFormatExpr
), Str
,
1751 HasVAListArg
, TheCall
, format_idx
);
1753 if (!analyze_format_string::ParseScanfString(H
, Str
, Str
+ StrLen
))
1758 //===--- CHECK: Return Address of Stack Variable --------------------------===//
1760 static Expr
*EvalVal(Expr
*E
, llvm::SmallVectorImpl
<DeclRefExpr
*> &refVars
);
1761 static Expr
*EvalAddr(Expr
* E
, llvm::SmallVectorImpl
<DeclRefExpr
*> &refVars
);
1763 /// CheckReturnStackAddr - Check if a return statement returns the address
1764 /// of a stack variable.
1766 Sema::CheckReturnStackAddr(Expr
*RetValExp
, QualType lhsType
,
1767 SourceLocation ReturnLoc
) {
1770 llvm::SmallVector
<DeclRefExpr
*, 8> refVars
;
1772 // Perform checking for returned stack addresses, local blocks,
1773 // label addresses or references to temporaries.
1774 if (lhsType
->isPointerType() || lhsType
->isBlockPointerType()) {
1775 stackE
= EvalAddr(RetValExp
, refVars
);
1776 } else if (lhsType
->isReferenceType()) {
1777 stackE
= EvalVal(RetValExp
, refVars
);
1781 return; // Nothing suspicious was found.
1783 SourceLocation diagLoc
;
1784 SourceRange diagRange
;
1785 if (refVars
.empty()) {
1786 diagLoc
= stackE
->getLocStart();
1787 diagRange
= stackE
->getSourceRange();
1789 // We followed through a reference variable. 'stackE' contains the
1790 // problematic expression but we will warn at the return statement pointing
1791 // at the reference variable. We will later display the "trail" of
1792 // reference variables using notes.
1793 diagLoc
= refVars
[0]->getLocStart();
1794 diagRange
= refVars
[0]->getSourceRange();
1797 if (DeclRefExpr
*DR
= dyn_cast
<DeclRefExpr
>(stackE
)) { //address of local var.
1798 Diag(diagLoc
, lhsType
->isReferenceType() ? diag::warn_ret_stack_ref
1799 : diag::warn_ret_stack_addr
)
1800 << DR
->getDecl()->getDeclName() << diagRange
;
1801 } else if (isa
<BlockExpr
>(stackE
)) { // local block.
1802 Diag(diagLoc
, diag::err_ret_local_block
) << diagRange
;
1803 } else if (isa
<AddrLabelExpr
>(stackE
)) { // address of label.
1804 Diag(diagLoc
, diag::warn_ret_addr_label
) << diagRange
;
1805 } else { // local temporary.
1806 Diag(diagLoc
, lhsType
->isReferenceType() ? diag::warn_ret_local_temp_ref
1807 : diag::warn_ret_local_temp_addr
)
1811 // Display the "trail" of reference variables that we followed until we
1812 // found the problematic expression using notes.
1813 for (unsigned i
= 0, e
= refVars
.size(); i
!= e
; ++i
) {
1814 VarDecl
*VD
= cast
<VarDecl
>(refVars
[i
]->getDecl());
1815 // If this var binds to another reference var, show the range of the next
1816 // var, otherwise the var binds to the problematic expression, in which case
1817 // show the range of the expression.
1818 SourceRange range
= (i
< e
-1) ? refVars
[i
+1]->getSourceRange()
1819 : stackE
->getSourceRange();
1820 Diag(VD
->getLocation(), diag::note_ref_var_local_bind
)
1821 << VD
->getDeclName() << range
;
1825 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
1826 /// check if the expression in a return statement evaluates to an address
1827 /// to a location on the stack, a local block, an address of a label, or a
1828 /// reference to local temporary. The recursion is used to traverse the
1829 /// AST of the return expression, with recursion backtracking when we
1830 /// encounter a subexpression that (1) clearly does not lead to one of the
1831 /// above problematic expressions (2) is something we cannot determine leads to
1832 /// a problematic expression based on such local checking.
1834 /// Both EvalAddr and EvalVal follow through reference variables to evaluate
1835 /// the expression that they point to. Such variables are added to the
1836 /// 'refVars' vector so that we know what the reference variable "trail" was.
1838 /// EvalAddr processes expressions that are pointers that are used as
1839 /// references (and not L-values). EvalVal handles all other values.
1840 /// At the base case of the recursion is a check for the above problematic
1843 /// This implementation handles:
1845 /// * pointer-to-pointer casts
1846 /// * implicit conversions from array references to pointers
1847 /// * taking the address of fields
1848 /// * arbitrary interplay between "&" and "*" operators
1849 /// * pointer arithmetic from an address of a stack variable
1850 /// * taking the address of an array element where the array is on the stack
1851 static Expr
*EvalAddr(Expr
*E
, llvm::SmallVectorImpl
<DeclRefExpr
*> &refVars
) {
1852 if (E
->isTypeDependent())
1855 // We should only be called for evaluating pointer expressions.
1856 assert((E
->getType()->isAnyPointerType() ||
1857 E
->getType()->isBlockPointerType() ||
1858 E
->getType()->isObjCQualifiedIdType()) &&
1859 "EvalAddr only works on pointers");
1861 // Our "symbolic interpreter" is just a dispatch off the currently
1862 // viewed AST node. We then recursively traverse the AST by calling
1863 // EvalAddr and EvalVal appropriately.
1864 switch (E
->getStmtClass()) {
1865 case Stmt::ParenExprClass
:
1866 // Ignore parentheses.
1867 return EvalAddr(cast
<ParenExpr
>(E
)->getSubExpr(), refVars
);
1869 case Stmt::DeclRefExprClass
: {
1870 DeclRefExpr
*DR
= cast
<DeclRefExpr
>(E
);
1872 if (VarDecl
*V
= dyn_cast
<VarDecl
>(DR
->getDecl()))
1873 // If this is a reference variable, follow through to the expression that
1875 if (V
->hasLocalStorage() &&
1876 V
->getType()->isReferenceType() && V
->hasInit()) {
1877 // Add the reference variable to the "trail".
1878 refVars
.push_back(DR
);
1879 return EvalAddr(V
->getInit(), refVars
);
1885 case Stmt::UnaryOperatorClass
: {
1886 // The only unary operator that make sense to handle here
1887 // is AddrOf. All others don't make sense as pointers.
1888 UnaryOperator
*U
= cast
<UnaryOperator
>(E
);
1890 if (U
->getOpcode() == UO_AddrOf
)
1891 return EvalVal(U
->getSubExpr(), refVars
);
1896 case Stmt::BinaryOperatorClass
: {
1897 // Handle pointer arithmetic. All other binary operators are not valid
1899 BinaryOperator
*B
= cast
<BinaryOperator
>(E
);
1900 BinaryOperatorKind op
= B
->getOpcode();
1902 if (op
!= BO_Add
&& op
!= BO_Sub
)
1905 Expr
*Base
= B
->getLHS();
1907 // Determine which argument is the real pointer base. It could be
1908 // the RHS argument instead of the LHS.
1909 if (!Base
->getType()->isPointerType()) Base
= B
->getRHS();
1911 assert (Base
->getType()->isPointerType());
1912 return EvalAddr(Base
, refVars
);
1915 // For conditional operators we need to see if either the LHS or RHS are
1916 // valid DeclRefExpr*s. If one of them is valid, we return it.
1917 case Stmt::ConditionalOperatorClass
: {
1918 ConditionalOperator
*C
= cast
<ConditionalOperator
>(E
);
1920 // Handle the GNU extension for missing LHS.
1921 if (Expr
*lhsExpr
= C
->getLHS()) {
1922 // In C++, we can have a throw-expression, which has 'void' type.
1923 if (!lhsExpr
->getType()->isVoidType())
1924 if (Expr
* LHS
= EvalAddr(lhsExpr
, refVars
))
1928 // In C++, we can have a throw-expression, which has 'void' type.
1929 if (C
->getRHS()->getType()->isVoidType())
1932 return EvalAddr(C
->getRHS(), refVars
);
1935 case Stmt::BlockExprClass
:
1936 if (cast
<BlockExpr
>(E
)->hasBlockDeclRefExprs())
1937 return E
; // local block.
1940 case Stmt::AddrLabelExprClass
:
1941 return E
; // address of label.
1943 // For casts, we need to handle conversions from arrays to
1944 // pointer values, and pointer-to-pointer conversions.
1945 case Stmt::ImplicitCastExprClass
:
1946 case Stmt::CStyleCastExprClass
:
1947 case Stmt::CXXFunctionalCastExprClass
: {
1948 Expr
* SubExpr
= cast
<CastExpr
>(E
)->getSubExpr();
1949 QualType T
= SubExpr
->getType();
1951 if (SubExpr
->getType()->isPointerType() ||
1952 SubExpr
->getType()->isBlockPointerType() ||
1953 SubExpr
->getType()->isObjCQualifiedIdType())
1954 return EvalAddr(SubExpr
, refVars
);
1955 else if (T
->isArrayType())
1956 return EvalVal(SubExpr
, refVars
);
1961 // C++ casts. For dynamic casts, static casts, and const casts, we
1962 // are always converting from a pointer-to-pointer, so we just blow
1963 // through the cast. In the case the dynamic cast doesn't fail (and
1964 // return NULL), we take the conservative route and report cases
1965 // where we return the address of a stack variable. For Reinterpre
1966 // FIXME: The comment about is wrong; we're not always converting
1967 // from pointer to pointer. I'm guessing that this code should also
1968 // handle references to objects.
1969 case Stmt::CXXStaticCastExprClass
:
1970 case Stmt::CXXDynamicCastExprClass
:
1971 case Stmt::CXXConstCastExprClass
:
1972 case Stmt::CXXReinterpretCastExprClass
: {
1973 Expr
*S
= cast
<CXXNamedCastExpr
>(E
)->getSubExpr();
1974 if (S
->getType()->isPointerType() || S
->getType()->isBlockPointerType())
1975 return EvalAddr(S
, refVars
);
1980 // Everything else: we simply don't reason about them.
1987 /// EvalVal - This function is complements EvalAddr in the mutual recursion.
1988 /// See the comments for EvalAddr for more details.
1989 static Expr
*EvalVal(Expr
*E
, llvm::SmallVectorImpl
<DeclRefExpr
*> &refVars
) {
1991 // We should only be called for evaluating non-pointer expressions, or
1992 // expressions with a pointer type that are not used as references but instead
1993 // are l-values (e.g., DeclRefExpr with a pointer type).
1995 // Our "symbolic interpreter" is just a dispatch off the currently
1996 // viewed AST node. We then recursively traverse the AST by calling
1997 // EvalAddr and EvalVal appropriately.
1998 switch (E
->getStmtClass()) {
1999 case Stmt::ImplicitCastExprClass
: {
2000 ImplicitCastExpr
*IE
= cast
<ImplicitCastExpr
>(E
);
2001 if (IE
->getValueKind() == VK_LValue
) {
2002 E
= IE
->getSubExpr();
2008 case Stmt::DeclRefExprClass
: {
2009 // When we hit a DeclRefExpr we are looking at code that refers to a
2010 // variable's name. If it's not a reference variable we check if it has
2011 // local storage within the function, and if so, return the expression.
2012 DeclRefExpr
*DR
= cast
<DeclRefExpr
>(E
);
2014 if (VarDecl
*V
= dyn_cast
<VarDecl
>(DR
->getDecl()))
2015 if (V
->hasLocalStorage()) {
2016 if (!V
->getType()->isReferenceType())
2019 // Reference variable, follow through to the expression that
2022 // Add the reference variable to the "trail".
2023 refVars
.push_back(DR
);
2024 return EvalVal(V
->getInit(), refVars
);
2031 case Stmt::ParenExprClass
: {
2032 // Ignore parentheses.
2033 E
= cast
<ParenExpr
>(E
)->getSubExpr();
2037 case Stmt::UnaryOperatorClass
: {
2038 // The only unary operator that make sense to handle here
2039 // is Deref. All others don't resolve to a "name." This includes
2040 // handling all sorts of rvalues passed to a unary operator.
2041 UnaryOperator
*U
= cast
<UnaryOperator
>(E
);
2043 if (U
->getOpcode() == UO_Deref
)
2044 return EvalAddr(U
->getSubExpr(), refVars
);
2049 case Stmt::ArraySubscriptExprClass
: {
2050 // Array subscripts are potential references to data on the stack. We
2051 // retrieve the DeclRefExpr* for the array variable if it indeed
2052 // has local storage.
2053 return EvalAddr(cast
<ArraySubscriptExpr
>(E
)->getBase(), refVars
);
2056 case Stmt::ConditionalOperatorClass
: {
2057 // For conditional operators we need to see if either the LHS or RHS are
2058 // non-NULL Expr's. If one is non-NULL, we return it.
2059 ConditionalOperator
*C
= cast
<ConditionalOperator
>(E
);
2061 // Handle the GNU extension for missing LHS.
2062 if (Expr
*lhsExpr
= C
->getLHS())
2063 if (Expr
*LHS
= EvalVal(lhsExpr
, refVars
))
2066 return EvalVal(C
->getRHS(), refVars
);
2069 // Accesses to members are potential references to data on the stack.
2070 case Stmt::MemberExprClass
: {
2071 MemberExpr
*M
= cast
<MemberExpr
>(E
);
2073 // Check for indirect access. We only want direct field accesses.
2077 // Check whether the member type is itself a reference, in which case
2078 // we're not going to refer to the member, but to what the member refers to.
2079 if (M
->getMemberDecl()->getType()->isReferenceType())
2082 return EvalVal(M
->getBase(), refVars
);
2086 // Check that we don't return or take the address of a reference to a
2087 // temporary. This is only useful in C++.
2088 if (!E
->isTypeDependent() && E
->isRValue())
2091 // Everything else: we simply don't reason about them.
2097 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
2099 /// Check for comparisons of floating point operands using != and ==.
2100 /// Issue a warning if these are no self-comparisons, as they are not likely
2101 /// to do what the programmer intended.
2102 void Sema::CheckFloatComparison(SourceLocation loc
, Expr
* lex
, Expr
*rex
) {
2103 bool EmitWarning
= true;
2105 Expr
* LeftExprSansParen
= lex
->IgnoreParenImpCasts();
2106 Expr
* RightExprSansParen
= rex
->IgnoreParenImpCasts();
2108 // Special case: check for x == x (which is OK).
2109 // Do not emit warnings for such cases.
2110 if (DeclRefExpr
* DRL
= dyn_cast
<DeclRefExpr
>(LeftExprSansParen
))
2111 if (DeclRefExpr
* DRR
= dyn_cast
<DeclRefExpr
>(RightExprSansParen
))
2112 if (DRL
->getDecl() == DRR
->getDecl())
2113 EmitWarning
= false;
2116 // Special case: check for comparisons against literals that can be exactly
2117 // represented by APFloat. In such cases, do not emit a warning. This
2118 // is a heuristic: often comparison against such literals are used to
2119 // detect if a value in a variable has not changed. This clearly can
2120 // lead to false negatives.
2122 if (FloatingLiteral
* FLL
= dyn_cast
<FloatingLiteral
>(LeftExprSansParen
)) {
2124 EmitWarning
= false;
2126 if (FloatingLiteral
* FLR
= dyn_cast
<FloatingLiteral
>(RightExprSansParen
)){
2128 EmitWarning
= false;
2132 // Check for comparisons with builtin types.
2134 if (CallExpr
* CL
= dyn_cast
<CallExpr
>(LeftExprSansParen
))
2135 if (CL
->isBuiltinCall(Context
))
2136 EmitWarning
= false;
2139 if (CallExpr
* CR
= dyn_cast
<CallExpr
>(RightExprSansParen
))
2140 if (CR
->isBuiltinCall(Context
))
2141 EmitWarning
= false;
2143 // Emit the diagnostic.
2145 Diag(loc
, diag::warn_floatingpoint_eq
)
2146 << lex
->getSourceRange() << rex
->getSourceRange();
2149 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
2150 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
2154 /// Structure recording the 'active' range of an integer-valued
2157 /// The number of bits active in the int.
2160 /// True if the int is known not to have negative values.
2163 IntRange(unsigned Width
, bool NonNegative
)
2164 : Width(Width
), NonNegative(NonNegative
)
2167 /// Returns the range of the bool type.
2168 static IntRange
forBoolType() {
2169 return IntRange(1, true);
2172 /// Returns the range of an opaque value of the given integral type.
2173 static IntRange
forValueOfType(ASTContext
&C
, QualType T
) {
2174 return forValueOfCanonicalType(C
,
2175 T
->getCanonicalTypeInternal().getTypePtr());
2178 /// Returns the range of an opaque value of a canonical integral type.
2179 static IntRange
forValueOfCanonicalType(ASTContext
&C
, const Type
*T
) {
2180 assert(T
->isCanonicalUnqualified());
2182 if (const VectorType
*VT
= dyn_cast
<VectorType
>(T
))
2183 T
= VT
->getElementType().getTypePtr();
2184 if (const ComplexType
*CT
= dyn_cast
<ComplexType
>(T
))
2185 T
= CT
->getElementType().getTypePtr();
2187 // For enum types, use the known bit width of the enumerators.
2188 if (const EnumType
*ET
= dyn_cast
<EnumType
>(T
)) {
2189 EnumDecl
*Enum
= ET
->getDecl();
2190 if (!Enum
->isDefinition())
2191 return IntRange(C
.getIntWidth(QualType(T
, 0)), false);
2193 unsigned NumPositive
= Enum
->getNumPositiveBits();
2194 unsigned NumNegative
= Enum
->getNumNegativeBits();
2196 return IntRange(std::max(NumPositive
, NumNegative
), NumNegative
== 0);
2199 const BuiltinType
*BT
= cast
<BuiltinType
>(T
);
2200 assert(BT
->isInteger());
2202 return IntRange(C
.getIntWidth(QualType(T
, 0)), BT
->isUnsignedInteger());
2205 /// Returns the "target" range of a canonical integral type, i.e.
2206 /// the range of values expressible in the type.
2208 /// This matches forValueOfCanonicalType except that enums have the
2209 /// full range of their type, not the range of their enumerators.
2210 static IntRange
forTargetOfCanonicalType(ASTContext
&C
, const Type
*T
) {
2211 assert(T
->isCanonicalUnqualified());
2213 if (const VectorType
*VT
= dyn_cast
<VectorType
>(T
))
2214 T
= VT
->getElementType().getTypePtr();
2215 if (const ComplexType
*CT
= dyn_cast
<ComplexType
>(T
))
2216 T
= CT
->getElementType().getTypePtr();
2217 if (const EnumType
*ET
= dyn_cast
<EnumType
>(T
))
2218 T
= ET
->getDecl()->getIntegerType().getTypePtr();
2220 const BuiltinType
*BT
= cast
<BuiltinType
>(T
);
2221 assert(BT
->isInteger());
2223 return IntRange(C
.getIntWidth(QualType(T
, 0)), BT
->isUnsignedInteger());
2226 /// Returns the supremum of two ranges: i.e. their conservative merge.
2227 static IntRange
join(IntRange L
, IntRange R
) {
2228 return IntRange(std::max(L
.Width
, R
.Width
),
2229 L
.NonNegative
&& R
.NonNegative
);
2232 /// Returns the infinum of two ranges: i.e. their aggressive merge.
2233 static IntRange
meet(IntRange L
, IntRange R
) {
2234 return IntRange(std::min(L
.Width
, R
.Width
),
2235 L
.NonNegative
|| R
.NonNegative
);
2239 IntRange
GetValueRange(ASTContext
&C
, llvm::APSInt
&value
, unsigned MaxWidth
) {
2240 if (value
.isSigned() && value
.isNegative())
2241 return IntRange(value
.getMinSignedBits(), false);
2243 if (value
.getBitWidth() > MaxWidth
)
2244 value
= value
.trunc(MaxWidth
);
2246 // isNonNegative() just checks the sign bit without considering
2248 return IntRange(value
.getActiveBits(), true);
2251 IntRange
GetValueRange(ASTContext
&C
, APValue
&result
, QualType Ty
,
2252 unsigned MaxWidth
) {
2254 return GetValueRange(C
, result
.getInt(), MaxWidth
);
2256 if (result
.isVector()) {
2257 IntRange R
= GetValueRange(C
, result
.getVectorElt(0), Ty
, MaxWidth
);
2258 for (unsigned i
= 1, e
= result
.getVectorLength(); i
!= e
; ++i
) {
2259 IntRange El
= GetValueRange(C
, result
.getVectorElt(i
), Ty
, MaxWidth
);
2260 R
= IntRange::join(R
, El
);
2265 if (result
.isComplexInt()) {
2266 IntRange R
= GetValueRange(C
, result
.getComplexIntReal(), MaxWidth
);
2267 IntRange I
= GetValueRange(C
, result
.getComplexIntImag(), MaxWidth
);
2268 return IntRange::join(R
, I
);
2271 // This can happen with lossless casts to intptr_t of "based" lvalues.
2272 // Assume it might use arbitrary bits.
2273 // FIXME: The only reason we need to pass the type in here is to get
2274 // the sign right on this one case. It would be nice if APValue
2276 assert(result
.isLValue());
2277 return IntRange(MaxWidth
, Ty
->isUnsignedIntegerType());
2280 /// Pseudo-evaluate the given integer expression, estimating the
2281 /// range of values it might take.
2283 /// \param MaxWidth - the width to which the value will be truncated
2284 IntRange
GetExprRange(ASTContext
&C
, Expr
*E
, unsigned MaxWidth
) {
2285 E
= E
->IgnoreParens();
2287 // Try a full evaluation first.
2288 Expr::EvalResult result
;
2289 if (E
->Evaluate(result
, C
))
2290 return GetValueRange(C
, result
.Val
, E
->getType(), MaxWidth
);
2292 // I think we only want to look through implicit casts here; if the
2293 // user has an explicit widening cast, we should treat the value as
2294 // being of the new, wider type.
2295 if (ImplicitCastExpr
*CE
= dyn_cast
<ImplicitCastExpr
>(E
)) {
2296 if (CE
->getCastKind() == CK_NoOp
)
2297 return GetExprRange(C
, CE
->getSubExpr(), MaxWidth
);
2299 IntRange OutputTypeRange
= IntRange::forValueOfType(C
, CE
->getType());
2301 bool isIntegerCast
= (CE
->getCastKind() == CK_IntegralCast
);
2303 // Assume that non-integer casts can span the full range of the type.
2305 return OutputTypeRange
;
2308 = GetExprRange(C
, CE
->getSubExpr(),
2309 std::min(MaxWidth
, OutputTypeRange
.Width
));
2311 // Bail out if the subexpr's range is as wide as the cast type.
2312 if (SubRange
.Width
>= OutputTypeRange
.Width
)
2313 return OutputTypeRange
;
2315 // Otherwise, we take the smaller width, and we're non-negative if
2316 // either the output type or the subexpr is.
2317 return IntRange(SubRange
.Width
,
2318 SubRange
.NonNegative
|| OutputTypeRange
.NonNegative
);
2321 if (ConditionalOperator
*CO
= dyn_cast
<ConditionalOperator
>(E
)) {
2322 // If we can fold the condition, just take that operand.
2324 if (CO
->getCond()->EvaluateAsBooleanCondition(CondResult
, C
))
2325 return GetExprRange(C
, CondResult
? CO
->getTrueExpr()
2326 : CO
->getFalseExpr(),
2329 // Otherwise, conservatively merge.
2330 IntRange L
= GetExprRange(C
, CO
->getTrueExpr(), MaxWidth
);
2331 IntRange R
= GetExprRange(C
, CO
->getFalseExpr(), MaxWidth
);
2332 return IntRange::join(L
, R
);
2335 if (BinaryOperator
*BO
= dyn_cast
<BinaryOperator
>(E
)) {
2336 switch (BO
->getOpcode()) {
2338 // Boolean-valued operations are single-bit and positive.
2347 return IntRange::forBoolType();
2349 // The type of these compound assignments is the type of the LHS,
2350 // so the RHS is not necessarily an integer.
2356 return IntRange::forValueOfType(C
, E
->getType());
2358 // Operations with opaque sources are black-listed.
2361 return IntRange::forValueOfType(C
, E
->getType());
2363 // Bitwise-and uses the *infinum* of the two source ranges.
2366 return IntRange::meet(GetExprRange(C
, BO
->getLHS(), MaxWidth
),
2367 GetExprRange(C
, BO
->getRHS(), MaxWidth
));
2369 // Left shift gets black-listed based on a judgement call.
2371 // ...except that we want to treat '1 << (blah)' as logically
2372 // positive. It's an important idiom.
2373 if (IntegerLiteral
*I
2374 = dyn_cast
<IntegerLiteral
>(BO
->getLHS()->IgnoreParenCasts())) {
2375 if (I
->getValue() == 1) {
2376 IntRange R
= IntRange::forValueOfType(C
, E
->getType());
2377 return IntRange(R
.Width
, /*NonNegative*/ true);
2383 return IntRange::forValueOfType(C
, E
->getType());
2385 // Right shift by a constant can narrow its left argument.
2387 case BO_ShrAssign
: {
2388 IntRange L
= GetExprRange(C
, BO
->getLHS(), MaxWidth
);
2390 // If the shift amount is a positive constant, drop the width by
2393 if (BO
->getRHS()->isIntegerConstantExpr(shift
, C
) &&
2394 shift
.isNonNegative()) {
2395 unsigned zext
= shift
.getZExtValue();
2396 if (zext
>= L
.Width
)
2397 L
.Width
= (L
.NonNegative
? 0 : 1);
2405 // Comma acts as its right operand.
2407 return GetExprRange(C
, BO
->getRHS(), MaxWidth
);
2409 // Black-list pointer subtractions.
2411 if (BO
->getLHS()->getType()->isPointerType())
2412 return IntRange::forValueOfType(C
, E
->getType());
2419 // Treat every other operator as if it were closed on the
2420 // narrowest type that encompasses both operands.
2421 IntRange L
= GetExprRange(C
, BO
->getLHS(), MaxWidth
);
2422 IntRange R
= GetExprRange(C
, BO
->getRHS(), MaxWidth
);
2423 return IntRange::join(L
, R
);
2426 if (UnaryOperator
*UO
= dyn_cast
<UnaryOperator
>(E
)) {
2427 switch (UO
->getOpcode()) {
2428 // Boolean-valued operations are white-listed.
2430 return IntRange::forBoolType();
2432 // Operations with opaque sources are black-listed.
2434 case UO_AddrOf
: // should be impossible
2435 return IntRange::forValueOfType(C
, E
->getType());
2438 return GetExprRange(C
, UO
->getSubExpr(), MaxWidth
);
2442 if (dyn_cast
<OffsetOfExpr
>(E
)) {
2443 IntRange::forValueOfType(C
, E
->getType());
2446 FieldDecl
*BitField
= E
->getBitField();
2448 llvm::APSInt BitWidthAP
= BitField
->getBitWidth()->EvaluateAsInt(C
);
2449 unsigned BitWidth
= BitWidthAP
.getZExtValue();
2451 return IntRange(BitWidth
, BitField
->getType()->isUnsignedIntegerType());
2454 return IntRange::forValueOfType(C
, E
->getType());
2457 IntRange
GetExprRange(ASTContext
&C
, Expr
*E
) {
2458 return GetExprRange(C
, E
, C
.getIntWidth(E
->getType()));
2461 /// Checks whether the given value, which currently has the given
2462 /// source semantics, has the same value when coerced through the
2463 /// target semantics.
2464 bool IsSameFloatAfterCast(const llvm::APFloat
&value
,
2465 const llvm::fltSemantics
&Src
,
2466 const llvm::fltSemantics
&Tgt
) {
2467 llvm::APFloat truncated
= value
;
2470 truncated
.convert(Src
, llvm::APFloat::rmNearestTiesToEven
, &ignored
);
2471 truncated
.convert(Tgt
, llvm::APFloat::rmNearestTiesToEven
, &ignored
);
2473 return truncated
.bitwiseIsEqual(value
);
2476 /// Checks whether the given value, which currently has the given
2477 /// source semantics, has the same value when coerced through the
2478 /// target semantics.
2480 /// The value might be a vector of floats (or a complex number).
2481 bool IsSameFloatAfterCast(const APValue
&value
,
2482 const llvm::fltSemantics
&Src
,
2483 const llvm::fltSemantics
&Tgt
) {
2484 if (value
.isFloat())
2485 return IsSameFloatAfterCast(value
.getFloat(), Src
, Tgt
);
2487 if (value
.isVector()) {
2488 for (unsigned i
= 0, e
= value
.getVectorLength(); i
!= e
; ++i
)
2489 if (!IsSameFloatAfterCast(value
.getVectorElt(i
), Src
, Tgt
))
2494 assert(value
.isComplexFloat());
2495 return (IsSameFloatAfterCast(value
.getComplexFloatReal(), Src
, Tgt
) &&
2496 IsSameFloatAfterCast(value
.getComplexFloatImag(), Src
, Tgt
));
2499 void AnalyzeImplicitConversions(Sema
&S
, Expr
*E
, SourceLocation CC
);
2501 static bool IsZero(Sema
&S
, Expr
*E
) {
2502 // Suppress cases where we are comparing against an enum constant.
2503 if (const DeclRefExpr
*DR
=
2504 dyn_cast
<DeclRefExpr
>(E
->IgnoreParenImpCasts()))
2505 if (isa
<EnumConstantDecl
>(DR
->getDecl()))
2508 // Suppress cases where the '0' value is expanded from a macro.
2509 if (E
->getLocStart().isMacroID())
2513 return E
->isIntegerConstantExpr(Value
, S
.Context
) && Value
== 0;
2516 static bool HasEnumType(Expr
*E
) {
2517 // Strip off implicit integral promotions.
2518 while (ImplicitCastExpr
*ICE
= dyn_cast
<ImplicitCastExpr
>(E
)) {
2519 if (ICE
->getCastKind() != CK_IntegralCast
&&
2520 ICE
->getCastKind() != CK_NoOp
)
2522 E
= ICE
->getSubExpr();
2525 return E
->getType()->isEnumeralType();
2528 void CheckTrivialUnsignedComparison(Sema
&S
, BinaryOperator
*E
) {
2529 BinaryOperatorKind op
= E
->getOpcode();
2530 if (op
== BO_LT
&& IsZero(S
, E
->getRHS())) {
2531 S
.Diag(E
->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison
)
2532 << "< 0" << "false" << HasEnumType(E
->getLHS())
2533 << E
->getLHS()->getSourceRange() << E
->getRHS()->getSourceRange();
2534 } else if (op
== BO_GE
&& IsZero(S
, E
->getRHS())) {
2535 S
.Diag(E
->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison
)
2536 << ">= 0" << "true" << HasEnumType(E
->getLHS())
2537 << E
->getLHS()->getSourceRange() << E
->getRHS()->getSourceRange();
2538 } else if (op
== BO_GT
&& IsZero(S
, E
->getLHS())) {
2539 S
.Diag(E
->getOperatorLoc(), diag::warn_runsigned_always_true_comparison
)
2540 << "0 >" << "false" << HasEnumType(E
->getRHS())
2541 << E
->getLHS()->getSourceRange() << E
->getRHS()->getSourceRange();
2542 } else if (op
== BO_LE
&& IsZero(S
, E
->getLHS())) {
2543 S
.Diag(E
->getOperatorLoc(), diag::warn_runsigned_always_true_comparison
)
2544 << "0 <=" << "true" << HasEnumType(E
->getRHS())
2545 << E
->getLHS()->getSourceRange() << E
->getRHS()->getSourceRange();
2549 /// Analyze the operands of the given comparison. Implements the
2550 /// fallback case from AnalyzeComparison.
2551 void AnalyzeImpConvsInComparison(Sema
&S
, BinaryOperator
*E
) {
2552 AnalyzeImplicitConversions(S
, E
->getLHS(), E
->getOperatorLoc());
2553 AnalyzeImplicitConversions(S
, E
->getRHS(), E
->getOperatorLoc());
2556 /// \brief Implements -Wsign-compare.
2558 /// \param lex the left-hand expression
2559 /// \param rex the right-hand expression
2560 /// \param OpLoc the location of the joining operator
2561 /// \param BinOpc binary opcode or 0
2562 void AnalyzeComparison(Sema
&S
, BinaryOperator
*E
) {
2563 // The type the comparison is being performed in.
2564 QualType T
= E
->getLHS()->getType();
2565 assert(S
.Context
.hasSameUnqualifiedType(T
, E
->getRHS()->getType())
2566 && "comparison with mismatched types");
2568 // We don't do anything special if this isn't an unsigned integral
2569 // comparison: we're only interested in integral comparisons, and
2570 // signed comparisons only happen in cases we don't care to warn about.
2571 if (!T
->hasUnsignedIntegerRepresentation())
2572 return AnalyzeImpConvsInComparison(S
, E
);
2574 Expr
*lex
= E
->getLHS()->IgnoreParenImpCasts();
2575 Expr
*rex
= E
->getRHS()->IgnoreParenImpCasts();
2577 // Check to see if one of the (unmodified) operands is of different
2579 Expr
*signedOperand
, *unsignedOperand
;
2580 if (lex
->getType()->hasSignedIntegerRepresentation()) {
2581 assert(!rex
->getType()->hasSignedIntegerRepresentation() &&
2582 "unsigned comparison between two signed integer expressions?");
2583 signedOperand
= lex
;
2584 unsignedOperand
= rex
;
2585 } else if (rex
->getType()->hasSignedIntegerRepresentation()) {
2586 signedOperand
= rex
;
2587 unsignedOperand
= lex
;
2589 CheckTrivialUnsignedComparison(S
, E
);
2590 return AnalyzeImpConvsInComparison(S
, E
);
2593 // Otherwise, calculate the effective range of the signed operand.
2594 IntRange signedRange
= GetExprRange(S
.Context
, signedOperand
);
2596 // Go ahead and analyze implicit conversions in the operands. Note
2597 // that we skip the implicit conversions on both sides.
2598 AnalyzeImplicitConversions(S
, lex
, E
->getOperatorLoc());
2599 AnalyzeImplicitConversions(S
, rex
, E
->getOperatorLoc());
2601 // If the signed range is non-negative, -Wsign-compare won't fire,
2602 // but we should still check for comparisons which are always true
2604 if (signedRange
.NonNegative
)
2605 return CheckTrivialUnsignedComparison(S
, E
);
2607 // For (in)equality comparisons, if the unsigned operand is a
2608 // constant which cannot collide with a overflowed signed operand,
2609 // then reinterpreting the signed operand as unsigned will not
2610 // change the result of the comparison.
2611 if (E
->isEqualityOp()) {
2612 unsigned comparisonWidth
= S
.Context
.getIntWidth(T
);
2613 IntRange unsignedRange
= GetExprRange(S
.Context
, unsignedOperand
);
2615 // We should never be unable to prove that the unsigned operand is
2617 assert(unsignedRange
.NonNegative
&& "unsigned range includes negative?");
2619 if (unsignedRange
.Width
< comparisonWidth
)
2623 S
.Diag(E
->getOperatorLoc(), diag::warn_mixed_sign_comparison
)
2624 << lex
->getType() << rex
->getType()
2625 << lex
->getSourceRange() << rex
->getSourceRange();
2628 /// Analyzes an attempt to assign the given value to a bitfield.
2630 /// Returns true if there was something fishy about the attempt.
2631 bool AnalyzeBitFieldAssignment(Sema
&S
, FieldDecl
*Bitfield
, Expr
*Init
,
2632 SourceLocation InitLoc
) {
2633 assert(Bitfield
->isBitField());
2634 if (Bitfield
->isInvalidDecl())
2637 // White-list bool bitfields.
2638 if (Bitfield
->getType()->isBooleanType())
2641 Expr
*OriginalInit
= Init
->IgnoreParenImpCasts();
2643 llvm::APSInt
Width(32);
2644 Expr::EvalResult InitValue
;
2645 if (!Bitfield
->getBitWidth()->isIntegerConstantExpr(Width
, S
.Context
) ||
2646 !OriginalInit
->Evaluate(InitValue
, S
.Context
) ||
2647 !InitValue
.Val
.isInt())
2650 const llvm::APSInt
&Value
= InitValue
.Val
.getInt();
2651 unsigned OriginalWidth
= Value
.getBitWidth();
2652 unsigned FieldWidth
= Width
.getZExtValue();
2654 if (OriginalWidth
<= FieldWidth
)
2657 llvm::APSInt TruncatedValue
= Value
.trunc(FieldWidth
);
2659 // It's fairly common to write values into signed bitfields
2660 // that, if sign-extended, would end up becoming a different
2661 // value. We don't want to warn about that.
2662 if (Value
.isSigned() && Value
.isNegative())
2663 TruncatedValue
= TruncatedValue
.sext(OriginalWidth
);
2665 TruncatedValue
= TruncatedValue
.zext(OriginalWidth
);
2667 if (Value
== TruncatedValue
)
2670 std::string PrettyValue
= Value
.toString(10);
2671 std::string PrettyTrunc
= TruncatedValue
.toString(10);
2673 S
.Diag(InitLoc
, diag::warn_impcast_bitfield_precision_constant
)
2674 << PrettyValue
<< PrettyTrunc
<< OriginalInit
->getType()
2675 << Init
->getSourceRange();
2680 /// Analyze the given simple or compound assignment for warning-worthy
2682 void AnalyzeAssignment(Sema
&S
, BinaryOperator
*E
) {
2683 // Just recurse on the LHS.
2684 AnalyzeImplicitConversions(S
, E
->getLHS(), E
->getOperatorLoc());
2686 // We want to recurse on the RHS as normal unless we're assigning to
2688 if (FieldDecl
*Bitfield
= E
->getLHS()->getBitField()) {
2689 if (AnalyzeBitFieldAssignment(S
, Bitfield
, E
->getRHS(),
2690 E
->getOperatorLoc())) {
2691 // Recurse, ignoring any implicit conversions on the RHS.
2692 return AnalyzeImplicitConversions(S
, E
->getRHS()->IgnoreParenImpCasts(),
2693 E
->getOperatorLoc());
2697 AnalyzeImplicitConversions(S
, E
->getRHS(), E
->getOperatorLoc());
2700 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
2701 void DiagnoseImpCast(Sema
&S
, Expr
*E
, QualType T
, SourceLocation CContext
,
2703 S
.Diag(E
->getExprLoc(), diag
)
2704 << E
->getType() << T
<< E
->getSourceRange() << SourceRange(CContext
);
2707 std::string
PrettyPrintInRange(const llvm::APSInt
&Value
, IntRange Range
) {
2708 if (!Range
.Width
) return "0";
2710 llvm::APSInt ValueInRange
= Value
;
2711 ValueInRange
.setIsSigned(!Range
.NonNegative
);
2712 ValueInRange
= ValueInRange
.trunc(Range
.Width
);
2713 return ValueInRange
.toString(10);
2716 void CheckImplicitConversion(Sema
&S
, Expr
*E
, QualType T
,
2717 SourceLocation CC
, bool *ICContext
= 0) {
2718 if (E
->isTypeDependent() || E
->isValueDependent()) return;
2720 const Type
*Source
= S
.Context
.getCanonicalType(E
->getType()).getTypePtr();
2721 const Type
*Target
= S
.Context
.getCanonicalType(T
).getTypePtr();
2722 if (Source
== Target
) return;
2723 if (Target
->isDependentType()) return;
2725 // If the conversion context location is invalid or instantiated
2726 // from a system macro, don't complain.
2727 if (CC
.isInvalid() ||
2728 (CC
.isMacroID() && S
.Context
.getSourceManager().isInSystemHeader(
2729 S
.Context
.getSourceManager().getSpellingLoc(CC
))))
2732 // Never diagnose implicit casts to bool.
2733 if (Target
->isSpecificBuiltinType(BuiltinType::Bool
))
2736 // Strip vector types.
2737 if (isa
<VectorType
>(Source
)) {
2738 if (!isa
<VectorType
>(Target
))
2739 return DiagnoseImpCast(S
, E
, T
, CC
, diag::warn_impcast_vector_scalar
);
2741 Source
= cast
<VectorType
>(Source
)->getElementType().getTypePtr();
2742 Target
= cast
<VectorType
>(Target
)->getElementType().getTypePtr();
2745 // Strip complex types.
2746 if (isa
<ComplexType
>(Source
)) {
2747 if (!isa
<ComplexType
>(Target
))
2748 return DiagnoseImpCast(S
, E
, T
, CC
, diag::warn_impcast_complex_scalar
);
2750 Source
= cast
<ComplexType
>(Source
)->getElementType().getTypePtr();
2751 Target
= cast
<ComplexType
>(Target
)->getElementType().getTypePtr();
2754 const BuiltinType
*SourceBT
= dyn_cast
<BuiltinType
>(Source
);
2755 const BuiltinType
*TargetBT
= dyn_cast
<BuiltinType
>(Target
);
2757 // If the source is floating point...
2758 if (SourceBT
&& SourceBT
->isFloatingPoint()) {
2759 // ...and the target is floating point...
2760 if (TargetBT
&& TargetBT
->isFloatingPoint()) {
2761 // ...then warn if we're dropping FP rank.
2763 // Builtin FP kinds are ordered by increasing FP rank.
2764 if (SourceBT
->getKind() > TargetBT
->getKind()) {
2765 // Don't warn about float constants that are precisely
2766 // representable in the target type.
2767 Expr::EvalResult result
;
2768 if (E
->Evaluate(result
, S
.Context
)) {
2769 // Value might be a float, a float vector, or a float complex.
2770 if (IsSameFloatAfterCast(result
.Val
,
2771 S
.Context
.getFloatTypeSemantics(QualType(TargetBT
, 0)),
2772 S
.Context
.getFloatTypeSemantics(QualType(SourceBT
, 0))))
2776 DiagnoseImpCast(S
, E
, T
, CC
, diag::warn_impcast_float_precision
);
2781 // If the target is integral, always warn.
2782 if ((TargetBT
&& TargetBT
->isInteger()))
2783 // TODO: don't warn for integer values?
2784 DiagnoseImpCast(S
, E
, T
, CC
, diag::warn_impcast_float_integer
);
2789 if (!Source
->isIntegerType() || !Target
->isIntegerType())
2792 IntRange SourceRange
= GetExprRange(S
.Context
, E
);
2793 IntRange TargetRange
= IntRange::forTargetOfCanonicalType(S
.Context
, Target
);
2795 if (SourceRange
.Width
> TargetRange
.Width
) {
2796 // If the source is a constant, use a default-on diagnostic.
2797 // TODO: this should happen for bitfield stores, too.
2798 llvm::APSInt
Value(32);
2799 if (E
->isIntegerConstantExpr(Value
, S
.Context
)) {
2800 std::string PrettySourceValue
= Value
.toString(10);
2801 std::string PrettyTargetValue
= PrettyPrintInRange(Value
, TargetRange
);
2803 S
.Diag(E
->getExprLoc(), diag::warn_impcast_integer_precision_constant
)
2804 << PrettySourceValue
<< PrettyTargetValue
2805 << E
->getType() << T
<< E
->getSourceRange() << clang::SourceRange(CC
);
2809 // People want to build with -Wshorten-64-to-32 and not -Wconversion
2810 // and by god we'll let them.
2811 if (SourceRange
.Width
== 64 && TargetRange
.Width
== 32)
2812 return DiagnoseImpCast(S
, E
, T
, CC
, diag::warn_impcast_integer_64_32
);
2813 return DiagnoseImpCast(S
, E
, T
, CC
, diag::warn_impcast_integer_precision
);
2816 if ((TargetRange
.NonNegative
&& !SourceRange
.NonNegative
) ||
2817 (!TargetRange
.NonNegative
&& SourceRange
.NonNegative
&&
2818 SourceRange
.Width
== TargetRange
.Width
)) {
2819 unsigned DiagID
= diag::warn_impcast_integer_sign
;
2821 // Traditionally, gcc has warned about this under -Wsign-compare.
2822 // We also want to warn about it in -Wconversion.
2823 // So if -Wconversion is off, use a completely identical diagnostic
2824 // in the sign-compare group.
2825 // The conditional-checking code will
2827 DiagID
= diag::warn_impcast_integer_sign_conditional
;
2831 return DiagnoseImpCast(S
, E
, T
, CC
, DiagID
);
2837 void CheckConditionalOperator(Sema
&S
, ConditionalOperator
*E
, QualType T
);
2839 void CheckConditionalOperand(Sema
&S
, Expr
*E
, QualType T
,
2840 SourceLocation CC
, bool &ICContext
) {
2841 E
= E
->IgnoreParenImpCasts();
2843 if (isa
<ConditionalOperator
>(E
))
2844 return CheckConditionalOperator(S
, cast
<ConditionalOperator
>(E
), T
);
2846 AnalyzeImplicitConversions(S
, E
, CC
);
2847 if (E
->getType() != T
)
2848 return CheckImplicitConversion(S
, E
, T
, CC
, &ICContext
);
2852 void CheckConditionalOperator(Sema
&S
, ConditionalOperator
*E
, QualType T
) {
2853 SourceLocation CC
= E
->getQuestionLoc();
2855 AnalyzeImplicitConversions(S
, E
->getCond(), CC
);
2857 bool Suspicious
= false;
2858 CheckConditionalOperand(S
, E
->getTrueExpr(), T
, CC
, Suspicious
);
2859 CheckConditionalOperand(S
, E
->getFalseExpr(), T
, CC
, Suspicious
);
2861 // If -Wconversion would have warned about either of the candidates
2862 // for a signedness conversion to the context type...
2863 if (!Suspicious
) return;
2865 // ...but it's currently ignored...
2866 if (S
.Diags
.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional
))
2869 // ...and -Wsign-compare isn't...
2870 if (!S
.Diags
.getDiagnosticLevel(diag::warn_mixed_sign_conditional
))
2873 // ...then check whether it would have warned about either of the
2874 // candidates for a signedness conversion to the condition type.
2875 if (E
->getType() != T
) {
2877 CheckImplicitConversion(S
, E
->getTrueExpr()->IgnoreParenImpCasts(),
2878 E
->getType(), CC
, &Suspicious
);
2880 CheckImplicitConversion(S
, E
->getFalseExpr()->IgnoreParenImpCasts(),
2881 E
->getType(), CC
, &Suspicious
);
2886 // If so, emit a diagnostic under -Wsign-compare.
2887 Expr
*lex
= E
->getTrueExpr()->IgnoreParenImpCasts();
2888 Expr
*rex
= E
->getFalseExpr()->IgnoreParenImpCasts();
2889 S
.Diag(E
->getQuestionLoc(), diag::warn_mixed_sign_conditional
)
2890 << lex
->getType() << rex
->getType()
2891 << lex
->getSourceRange() << rex
->getSourceRange();
2894 /// AnalyzeImplicitConversions - Find and report any interesting
2895 /// implicit conversions in the given expression. There are a couple
2896 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
2897 void AnalyzeImplicitConversions(Sema
&S
, Expr
*OrigE
, SourceLocation CC
) {
2898 QualType T
= OrigE
->getType();
2899 Expr
*E
= OrigE
->IgnoreParenImpCasts();
2901 // For conditional operators, we analyze the arguments as if they
2902 // were being fed directly into the output.
2903 if (isa
<ConditionalOperator
>(E
)) {
2904 ConditionalOperator
*CO
= cast
<ConditionalOperator
>(E
);
2905 CheckConditionalOperator(S
, CO
, T
);
2909 // Go ahead and check any implicit conversions we might have skipped.
2910 // The non-canonical typecheck is just an optimization;
2911 // CheckImplicitConversion will filter out dead implicit conversions.
2912 if (E
->getType() != T
)
2913 CheckImplicitConversion(S
, E
, T
, CC
);
2915 // Now continue drilling into this expression.
2917 // Skip past explicit casts.
2918 if (isa
<ExplicitCastExpr
>(E
)) {
2919 E
= cast
<ExplicitCastExpr
>(E
)->getSubExpr()->IgnoreParenImpCasts();
2920 return AnalyzeImplicitConversions(S
, E
, CC
);
2923 if (BinaryOperator
*BO
= dyn_cast
<BinaryOperator
>(E
)) {
2924 // Do a somewhat different check with comparison operators.
2925 if (BO
->isComparisonOp())
2926 return AnalyzeComparison(S
, BO
);
2928 // And with assignments and compound assignments.
2929 if (BO
->isAssignmentOp())
2930 return AnalyzeAssignment(S
, BO
);
2933 // These break the otherwise-useful invariant below. Fortunately,
2934 // we don't really need to recurse into them, because any internal
2935 // expressions should have been analyzed already when they were
2936 // built into statements.
2937 if (isa
<StmtExpr
>(E
)) return;
2939 // Don't descend into unevaluated contexts.
2940 if (isa
<SizeOfAlignOfExpr
>(E
)) return;
2942 // Now just recurse over the expression's children.
2943 CC
= E
->getExprLoc();
2944 for (Stmt::child_iterator I
= E
->child_begin(), IE
= E
->child_end();
2946 AnalyzeImplicitConversions(S
, cast
<Expr
>(*I
), CC
);
2949 } // end anonymous namespace
2951 /// Diagnoses "dangerous" implicit conversions within the given
2952 /// expression (which is a full expression). Implements -Wconversion
2953 /// and -Wsign-compare.
2955 /// \param CC the "context" location of the implicit conversion, i.e.
2956 /// the most location of the syntactic entity requiring the implicit
2958 void Sema::CheckImplicitConversions(Expr
*E
, SourceLocation CC
) {
2959 // Don't diagnose in unevaluated contexts.
2960 if (ExprEvalContexts
.back().Context
== Sema::Unevaluated
)
2963 // Don't diagnose for value- or type-dependent expressions.
2964 if (E
->isTypeDependent() || E
->isValueDependent())
2967 // This is not the right CC for (e.g.) a variable initialization.
2968 AnalyzeImplicitConversions(*this, E
, CC
);
2971 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc
,
2972 FieldDecl
*BitField
,
2974 (void) AnalyzeBitFieldAssignment(*this, BitField
, Init
, InitLoc
);
2977 /// CheckParmsForFunctionDef - Check that the parameters of the given
2978 /// function are appropriate for the definition of a function. This
2979 /// takes care of any checks that cannot be performed on the
2980 /// declaration itself, e.g., that the types of each of the function
2981 /// parameters are complete.
2982 bool Sema::CheckParmsForFunctionDef(ParmVarDecl
**P
, ParmVarDecl
**PEnd
,
2983 bool CheckParameterNames
) {
2984 bool HasInvalidParm
= false;
2985 for (; P
!= PEnd
; ++P
) {
2986 ParmVarDecl
*Param
= *P
;
2988 // C99 6.7.5.3p4: the parameters in a parameter type list in a
2989 // function declarator that is part of a function definition of
2990 // that function shall not have incomplete type.
2992 // This is also C++ [dcl.fct]p6.
2993 if (!Param
->isInvalidDecl() &&
2994 RequireCompleteType(Param
->getLocation(), Param
->getType(),
2995 diag::err_typecheck_decl_incomplete_type
)) {
2996 Param
->setInvalidDecl();
2997 HasInvalidParm
= true;
3000 // C99 6.9.1p5: If the declarator includes a parameter type list, the
3001 // declaration of each parameter shall include an identifier.
3002 if (CheckParameterNames
&&
3003 Param
->getIdentifier() == 0 &&
3004 !Param
->isImplicit() &&
3005 !getLangOptions().CPlusPlus
)
3006 Diag(Param
->getLocation(), diag::err_parameter_name_omitted
);
3009 // If the function declarator is not part of a definition of that
3010 // function, parameters may have incomplete type and may use the [*]
3011 // notation in their sequences of declarator specifiers to specify
3012 // variable length array types.
3013 QualType PType
= Param
->getOriginalType();
3014 if (const ArrayType
*AT
= Context
.getAsArrayType(PType
)) {
3015 if (AT
->getSizeModifier() == ArrayType::Star
) {
3016 // FIXME: This diagnosic should point the the '[*]' if source-location
3017 // information is added for it.
3018 Diag(Param
->getLocation(), diag::err_array_star_in_function_definition
);
3023 return HasInvalidParm
;
3026 /// CheckCastAlign - Implements -Wcast-align, which warns when a
3027 /// pointer cast increases the alignment requirements.
3028 void Sema::CheckCastAlign(Expr
*Op
, QualType T
, SourceRange TRange
) {
3029 // This is actually a lot of work to potentially be doing on every
3030 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
3031 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align
)
3032 == Diagnostic::Ignored
)
3035 // Ignore dependent types.
3036 if (T
->isDependentType() || Op
->getType()->isDependentType())
3039 // Require that the destination be a pointer type.
3040 const PointerType
*DestPtr
= T
->getAs
<PointerType
>();
3041 if (!DestPtr
) return;
3043 // If the destination has alignment 1, we're done.
3044 QualType DestPointee
= DestPtr
->getPointeeType();
3045 if (DestPointee
->isIncompleteType()) return;
3046 CharUnits DestAlign
= Context
.getTypeAlignInChars(DestPointee
);
3047 if (DestAlign
.isOne()) return;
3049 // Require that the source be a pointer type.
3050 const PointerType
*SrcPtr
= Op
->getType()->getAs
<PointerType
>();
3051 if (!SrcPtr
) return;
3052 QualType SrcPointee
= SrcPtr
->getPointeeType();
3054 // Whitelist casts from cv void*. We already implicitly
3055 // whitelisted casts to cv void*, since they have alignment 1.
3056 // Also whitelist casts involving incomplete types, which implicitly
3058 if (SrcPointee
->isIncompleteType()) return;
3060 CharUnits SrcAlign
= Context
.getTypeAlignInChars(SrcPointee
);
3061 if (SrcAlign
>= DestAlign
) return;
3063 Diag(TRange
.getBegin(), diag::warn_cast_align
)
3064 << Op
->getType() << T
3065 << static_cast<unsigned>(SrcAlign
.getQuantity())
3066 << static_cast<unsigned>(DestAlign
.getQuantity())
3067 << TRange
<< Op
->getSourceRange();