blob: 1a7a203171e646e8f4daa450d27f7a5935aba798 [file] [log] [blame]
Chris Lattner59907c42007-08-10 20:18:51 +00001//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner59907c42007-08-10 20:18:51 +00007//
8//===----------------------------------------------------------------------===//
9//
Mike Stump1eb44332009-09-09 15:08:12 +000010// This file implements extra semantic analysis beyond what is enforced
Chris Lattner59907c42007-08-10 20:18:51 +000011// by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
15#include "Sema.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000016#include "clang/Analysis/CFG.h"
Ted Kremenek1309f9a2010-01-25 04:41:41 +000017#include "clang/Analysis/AnalysisContext.h"
Ted Kremeneke0e53132010-01-28 23:39:18 +000018#include "clang/Analysis/Analyses/PrintfFormatString.h"
Chris Lattner59907c42007-08-10 20:18:51 +000019#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000020#include "clang/AST/CharUnits.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000021#include "clang/AST/DeclObjC.h"
Ted Kremenek23245122007-08-20 16:18:38 +000022#include "clang/AST/ExprCXX.h"
Ted Kremenek7ff22b22008-06-16 18:00:42 +000023#include "clang/AST/ExprObjC.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000024#include "clang/AST/DeclObjC.h"
25#include "clang/AST/StmtCXX.h"
26#include "clang/AST/StmtObjC.h"
Chris Lattner719e6152009-02-18 19:21:10 +000027#include "clang/Lex/LiteralSupport.h"
Chris Lattner59907c42007-08-10 20:18:51 +000028#include "clang/Lex/Preprocessor.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000029#include "llvm/ADT/BitVector.h"
30#include "llvm/ADT/STLExtras.h"
Zhongxing Xua1f3dba2009-05-20 01:55:10 +000031#include <limits>
Mike Stumpf8c49212010-01-21 03:59:47 +000032#include <queue>
Chris Lattner59907c42007-08-10 20:18:51 +000033using namespace clang;
34
Chris Lattner60800082009-02-18 17:49:48 +000035/// getLocationOfStringLiteralByte - Return a source location that points to the
36/// specified byte of the specified string literal.
37///
38/// Strings are amazingly complex. They can be formed from multiple tokens and
39/// can have escape sequences in them in addition to the usual trigraph and
40/// escaped newline business. This routine handles this complexity.
41///
42SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
43 unsigned ByteNo) const {
44 assert(!SL->isWide() && "This doesn't work for wide strings yet");
Mike Stump1eb44332009-09-09 15:08:12 +000045
Chris Lattner60800082009-02-18 17:49:48 +000046 // Loop over all of the tokens in this string until we find the one that
47 // contains the byte we're looking for.
48 unsigned TokNo = 0;
49 while (1) {
50 assert(TokNo < SL->getNumConcatenated() && "Invalid byte number!");
51 SourceLocation StrTokLoc = SL->getStrTokenLoc(TokNo);
Mike Stump1eb44332009-09-09 15:08:12 +000052
Chris Lattner60800082009-02-18 17:49:48 +000053 // Get the spelling of the string so that we can get the data that makes up
54 // the string literal, not the identifier for the macro it is potentially
55 // expanded through.
56 SourceLocation StrTokSpellingLoc = SourceMgr.getSpellingLoc(StrTokLoc);
57
58 // Re-lex the token to get its length and original spelling.
59 std::pair<FileID, unsigned> LocInfo =
60 SourceMgr.getDecomposedLoc(StrTokSpellingLoc);
61 std::pair<const char *,const char *> Buffer =
62 SourceMgr.getBufferData(LocInfo.first);
63 const char *StrData = Buffer.first+LocInfo.second;
Mike Stump1eb44332009-09-09 15:08:12 +000064
Chris Lattner60800082009-02-18 17:49:48 +000065 // Create a langops struct and enable trigraphs. This is sufficient for
66 // relexing tokens.
67 LangOptions LangOpts;
68 LangOpts.Trigraphs = true;
Mike Stump1eb44332009-09-09 15:08:12 +000069
Chris Lattner60800082009-02-18 17:49:48 +000070 // Create a lexer starting at the beginning of this token.
71 Lexer TheLexer(StrTokSpellingLoc, LangOpts, Buffer.first, StrData,
72 Buffer.second);
73 Token TheTok;
74 TheLexer.LexFromRawLexer(TheTok);
Mike Stump1eb44332009-09-09 15:08:12 +000075
Chris Lattner443e53c2009-02-18 19:26:42 +000076 // Use the StringLiteralParser to compute the length of the string in bytes.
77 StringLiteralParser SLP(&TheTok, 1, PP);
78 unsigned TokNumBytes = SLP.GetStringLength();
Mike Stump1eb44332009-09-09 15:08:12 +000079
Chris Lattner2197c962009-02-18 18:52:52 +000080 // If the byte is in this token, return the location of the byte.
Chris Lattner60800082009-02-18 17:49:48 +000081 if (ByteNo < TokNumBytes ||
82 (ByteNo == TokNumBytes && TokNo == SL->getNumConcatenated())) {
Mike Stump1eb44332009-09-09 15:08:12 +000083 unsigned Offset =
Chris Lattner719e6152009-02-18 19:21:10 +000084 StringLiteralParser::getOffsetOfStringByte(TheTok, ByteNo, PP);
Mike Stump1eb44332009-09-09 15:08:12 +000085
Chris Lattner719e6152009-02-18 19:21:10 +000086 // Now that we know the offset of the token in the spelling, use the
87 // preprocessor to get the offset in the original source.
88 return PP.AdvanceToTokenCharacter(StrTokLoc, Offset);
Chris Lattner60800082009-02-18 17:49:48 +000089 }
Mike Stump1eb44332009-09-09 15:08:12 +000090
Chris Lattner60800082009-02-18 17:49:48 +000091 // Move to the next string token.
92 ++TokNo;
93 ByteNo -= TokNumBytes;
94 }
95}
96
Ryan Flynn4403a5e2009-08-06 03:00:50 +000097/// CheckablePrintfAttr - does a function call have a "printf" attribute
98/// and arguments that merit checking?
99bool Sema::CheckablePrintfAttr(const FormatAttr *Format, CallExpr *TheCall) {
100 if (Format->getType() == "printf") return true;
101 if (Format->getType() == "printf0") {
102 // printf0 allows null "format" string; if so don't check format/args
103 unsigned format_idx = Format->getFormatIdx() - 1;
Sebastian Redl4a2614e2009-11-17 18:02:24 +0000104 // Does the index refer to the implicit object argument?
105 if (isa<CXXMemberCallExpr>(TheCall)) {
106 if (format_idx == 0)
107 return false;
108 --format_idx;
109 }
Ryan Flynn4403a5e2009-08-06 03:00:50 +0000110 if (format_idx < TheCall->getNumArgs()) {
111 Expr *Format = TheCall->getArg(format_idx)->IgnoreParenCasts();
Douglas Gregorce940492009-09-25 04:25:58 +0000112 if (!Format->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
Ryan Flynn4403a5e2009-08-06 03:00:50 +0000113 return true;
114 }
115 }
116 return false;
117}
Chris Lattner60800082009-02-18 17:49:48 +0000118
Sebastian Redl0eb23302009-01-19 00:08:26 +0000119Action::OwningExprResult
Anders Carlssond406bf02009-08-16 01:56:34 +0000120Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Sebastian Redl0eb23302009-01-19 00:08:26 +0000121 OwningExprResult TheCallResult(Owned(TheCall));
Douglas Gregor2def4832008-11-17 20:34:05 +0000122
Anders Carlssond406bf02009-08-16 01:56:34 +0000123 switch (BuiltinID) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000124 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +0000125 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +0000126 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner69039812009-02-18 06:01:06 +0000127 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000128 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000129 break;
Ted Kremenek49ff7a12008-07-09 17:58:53 +0000130 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +0000131 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000132 if (SemaBuiltinVAStart(TheCall))
133 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000134 break;
Chris Lattner1b9a0792007-12-20 00:26:33 +0000135 case Builtin::BI__builtin_isgreater:
136 case Builtin::BI__builtin_isgreaterequal:
137 case Builtin::BI__builtin_isless:
138 case Builtin::BI__builtin_islessequal:
139 case Builtin::BI__builtin_islessgreater:
140 case Builtin::BI__builtin_isunordered:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000141 if (SemaBuiltinUnorderedCompare(TheCall))
142 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000143 break;
Eli Friedman9ac6f622009-08-31 20:06:00 +0000144 case Builtin::BI__builtin_isfinite:
145 case Builtin::BI__builtin_isinf:
146 case Builtin::BI__builtin_isinf_sign:
147 case Builtin::BI__builtin_isnan:
148 case Builtin::BI__builtin_isnormal:
149 if (SemaBuiltinUnaryFP(TheCall))
150 return ExprError();
151 break;
Eli Friedman6cfda232008-05-20 08:23:37 +0000152 case Builtin::BI__builtin_return_address:
153 case Builtin::BI__builtin_frame_address:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000154 if (SemaBuiltinStackAddress(TheCall))
155 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000156 break;
Chris Lattner21fb98e2009-09-23 06:06:36 +0000157 case Builtin::BI__builtin_eh_return_data_regno:
158 if (SemaBuiltinEHReturnDataRegNo(TheCall))
159 return ExprError();
160 break;
Eli Friedmand38617c2008-05-14 19:38:39 +0000161 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000162 return SemaBuiltinShuffleVector(TheCall);
163 // TheCall will be freed by the smart pointer here, but that's fine, since
164 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000165 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000166 if (SemaBuiltinPrefetch(TheCall))
167 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000168 break;
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000169 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000170 if (SemaBuiltinObjectSize(TheCall))
171 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000172 break;
Eli Friedmand875fed2009-05-03 04:46:36 +0000173 case Builtin::BI__builtin_longjmp:
174 if (SemaBuiltinLongjmp(TheCall))
175 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000176 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000177 case Builtin::BI__sync_fetch_and_add:
178 case Builtin::BI__sync_fetch_and_sub:
179 case Builtin::BI__sync_fetch_and_or:
180 case Builtin::BI__sync_fetch_and_and:
181 case Builtin::BI__sync_fetch_and_xor:
Chris Lattnereebd9d22009-05-13 04:37:52 +0000182 case Builtin::BI__sync_fetch_and_nand:
Chris Lattner5caa3702009-05-08 06:58:22 +0000183 case Builtin::BI__sync_add_and_fetch:
184 case Builtin::BI__sync_sub_and_fetch:
185 case Builtin::BI__sync_and_and_fetch:
186 case Builtin::BI__sync_or_and_fetch:
187 case Builtin::BI__sync_xor_and_fetch:
Chris Lattnereebd9d22009-05-13 04:37:52 +0000188 case Builtin::BI__sync_nand_and_fetch:
Chris Lattner5caa3702009-05-08 06:58:22 +0000189 case Builtin::BI__sync_val_compare_and_swap:
190 case Builtin::BI__sync_bool_compare_and_swap:
191 case Builtin::BI__sync_lock_test_and_set:
192 case Builtin::BI__sync_lock_release:
193 if (SemaBuiltinAtomicOverloaded(TheCall))
194 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000195 break;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000196 }
Mike Stump1eb44332009-09-09 15:08:12 +0000197
Anders Carlssond406bf02009-08-16 01:56:34 +0000198 return move(TheCallResult);
199}
Daniel Dunbarde454282008-10-02 18:44:07 +0000200
Anders Carlssond406bf02009-08-16 01:56:34 +0000201/// CheckFunctionCall - Check a direct function call for various correctness
202/// and safety properties not strictly enforced by the C type system.
203bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
204 // Get the IdentifierInfo* for the called function.
205 IdentifierInfo *FnInfo = FDecl->getIdentifier();
206
207 // None of the checks below are needed for functions that don't have
208 // simple names (e.g., C++ conversion functions).
209 if (!FnInfo)
210 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000211
Daniel Dunbarde454282008-10-02 18:44:07 +0000212 // FIXME: This mechanism should be abstracted to be less fragile and
213 // more efficient. For example, just map function ids to custom
214 // handlers.
215
Chris Lattner59907c42007-08-10 20:18:51 +0000216 // Printf checking.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000217 if (const FormatAttr *Format = FDecl->getAttr<FormatAttr>()) {
Ryan Flynn4403a5e2009-08-06 03:00:50 +0000218 if (CheckablePrintfAttr(Format, TheCall)) {
Ted Kremenek3d692df2009-02-27 17:58:43 +0000219 bool HasVAListArg = Format->getFirstArg() == 0;
220 if (!HasVAListArg) {
Mike Stump1eb44332009-09-09 15:08:12 +0000221 if (const FunctionProtoType *Proto
John McCall183700f2009-09-21 23:43:11 +0000222 = FDecl->getType()->getAs<FunctionProtoType>())
Sebastian Redl4a2614e2009-11-17 18:02:24 +0000223 HasVAListArg = !Proto->isVariadic();
Ted Kremenek3d692df2009-02-27 17:58:43 +0000224 }
Douglas Gregor3c385e52009-02-14 18:57:46 +0000225 CheckPrintfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
Ted Kremenek3d692df2009-02-27 17:58:43 +0000226 HasVAListArg ? 0 : Format->getFirstArg() - 1);
Douglas Gregor3c385e52009-02-14 18:57:46 +0000227 }
Chris Lattner59907c42007-08-10 20:18:51 +0000228 }
Mike Stump1eb44332009-09-09 15:08:12 +0000229
230 for (const NonNullAttr *NonNull = FDecl->getAttr<NonNullAttr>(); NonNull;
Anders Carlssond406bf02009-08-16 01:56:34 +0000231 NonNull = NonNull->getNext<NonNullAttr>())
232 CheckNonNullArguments(NonNull, TheCall);
Sebastian Redl0eb23302009-01-19 00:08:26 +0000233
Anders Carlssond406bf02009-08-16 01:56:34 +0000234 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000235}
236
Anders Carlssond406bf02009-08-16 01:56:34 +0000237bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000238 // Printf checking.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000239 const FormatAttr *Format = NDecl->getAttr<FormatAttr>();
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000240 if (!Format)
Anders Carlssond406bf02009-08-16 01:56:34 +0000241 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000242
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000243 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
244 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000245 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000246
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000247 QualType Ty = V->getType();
248 if (!Ty->isBlockPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000249 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000250
Anders Carlssond406bf02009-08-16 01:56:34 +0000251 if (!CheckablePrintfAttr(Format, TheCall))
252 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000253
Anders Carlssond406bf02009-08-16 01:56:34 +0000254 bool HasVAListArg = Format->getFirstArg() == 0;
255 if (!HasVAListArg) {
Mike Stump1eb44332009-09-09 15:08:12 +0000256 const FunctionType *FT =
John McCall183700f2009-09-21 23:43:11 +0000257 Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Anders Carlssond406bf02009-08-16 01:56:34 +0000258 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT))
259 HasVAListArg = !Proto->isVariadic();
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000260 }
Anders Carlssond406bf02009-08-16 01:56:34 +0000261 CheckPrintfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
262 HasVAListArg ? 0 : Format->getFirstArg() - 1);
263
264 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000265}
266
Chris Lattner5caa3702009-05-08 06:58:22 +0000267/// SemaBuiltinAtomicOverloaded - We have a call to a function like
268/// __sync_fetch_and_add, which is an overloaded function based on the pointer
269/// type of its first argument. The main ActOnCallExpr routines have already
270/// promoted the types of arguments because all of these calls are prototyped as
271/// void(...).
272///
273/// This function goes through and does final semantic checking for these
274/// builtins,
275bool Sema::SemaBuiltinAtomicOverloaded(CallExpr *TheCall) {
276 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
277 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
278
279 // Ensure that we have at least one argument to do type inference from.
280 if (TheCall->getNumArgs() < 1)
281 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
282 << 0 << TheCall->getCallee()->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000283
Chris Lattner5caa3702009-05-08 06:58:22 +0000284 // Inspect the first argument of the atomic builtin. This should always be
285 // a pointer type, whose element is an integral scalar or pointer type.
286 // Because it is a pointer type, we don't have to worry about any implicit
287 // casts here.
288 Expr *FirstArg = TheCall->getArg(0);
289 if (!FirstArg->getType()->isPointerType())
290 return Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
291 << FirstArg->getType() << FirstArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000292
Ted Kremenek6217b802009-07-29 21:53:49 +0000293 QualType ValType = FirstArg->getType()->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +0000294 if (!ValType->isIntegerType() && !ValType->isPointerType() &&
Chris Lattner5caa3702009-05-08 06:58:22 +0000295 !ValType->isBlockPointerType())
296 return Diag(DRE->getLocStart(),
297 diag::err_atomic_builtin_must_be_pointer_intptr)
298 << FirstArg->getType() << FirstArg->getSourceRange();
299
300 // We need to figure out which concrete builtin this maps onto. For example,
301 // __sync_fetch_and_add with a 2 byte object turns into
302 // __sync_fetch_and_add_2.
303#define BUILTIN_ROW(x) \
304 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
305 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +0000306
Chris Lattner5caa3702009-05-08 06:58:22 +0000307 static const unsigned BuiltinIndices[][5] = {
308 BUILTIN_ROW(__sync_fetch_and_add),
309 BUILTIN_ROW(__sync_fetch_and_sub),
310 BUILTIN_ROW(__sync_fetch_and_or),
311 BUILTIN_ROW(__sync_fetch_and_and),
312 BUILTIN_ROW(__sync_fetch_and_xor),
Chris Lattnereebd9d22009-05-13 04:37:52 +0000313 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump1eb44332009-09-09 15:08:12 +0000314
Chris Lattner5caa3702009-05-08 06:58:22 +0000315 BUILTIN_ROW(__sync_add_and_fetch),
316 BUILTIN_ROW(__sync_sub_and_fetch),
317 BUILTIN_ROW(__sync_and_and_fetch),
318 BUILTIN_ROW(__sync_or_and_fetch),
319 BUILTIN_ROW(__sync_xor_and_fetch),
Chris Lattnereebd9d22009-05-13 04:37:52 +0000320 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +0000321
Chris Lattner5caa3702009-05-08 06:58:22 +0000322 BUILTIN_ROW(__sync_val_compare_and_swap),
323 BUILTIN_ROW(__sync_bool_compare_and_swap),
324 BUILTIN_ROW(__sync_lock_test_and_set),
325 BUILTIN_ROW(__sync_lock_release)
326 };
Mike Stump1eb44332009-09-09 15:08:12 +0000327#undef BUILTIN_ROW
328
Chris Lattner5caa3702009-05-08 06:58:22 +0000329 // Determine the index of the size.
330 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +0000331 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +0000332 case 1: SizeIndex = 0; break;
333 case 2: SizeIndex = 1; break;
334 case 4: SizeIndex = 2; break;
335 case 8: SizeIndex = 3; break;
336 case 16: SizeIndex = 4; break;
337 default:
338 return Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
339 << FirstArg->getType() << FirstArg->getSourceRange();
340 }
Mike Stump1eb44332009-09-09 15:08:12 +0000341
Chris Lattner5caa3702009-05-08 06:58:22 +0000342 // Each of these builtins has one pointer argument, followed by some number of
343 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
344 // that we ignore. Find out which row of BuiltinIndices to read from as well
345 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +0000346 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +0000347 unsigned BuiltinIndex, NumFixed = 1;
348 switch (BuiltinID) {
349 default: assert(0 && "Unknown overloaded atomic builtin!");
350 case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break;
351 case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break;
352 case Builtin::BI__sync_fetch_and_or: BuiltinIndex = 2; break;
353 case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break;
354 case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break;
Chris Lattnereebd9d22009-05-13 04:37:52 +0000355 case Builtin::BI__sync_fetch_and_nand:BuiltinIndex = 5; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000356
Chris Lattnereebd9d22009-05-13 04:37:52 +0000357 case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 6; break;
358 case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 7; break;
359 case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 8; break;
360 case Builtin::BI__sync_or_and_fetch: BuiltinIndex = 9; break;
361 case Builtin::BI__sync_xor_and_fetch: BuiltinIndex =10; break;
362 case Builtin::BI__sync_nand_and_fetch:BuiltinIndex =11; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000363
Chris Lattner5caa3702009-05-08 06:58:22 +0000364 case Builtin::BI__sync_val_compare_and_swap:
Chris Lattnereebd9d22009-05-13 04:37:52 +0000365 BuiltinIndex = 12;
Chris Lattner5caa3702009-05-08 06:58:22 +0000366 NumFixed = 2;
367 break;
368 case Builtin::BI__sync_bool_compare_and_swap:
Chris Lattnereebd9d22009-05-13 04:37:52 +0000369 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +0000370 NumFixed = 2;
371 break;
Chris Lattnereebd9d22009-05-13 04:37:52 +0000372 case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 14; break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000373 case Builtin::BI__sync_lock_release:
Chris Lattnereebd9d22009-05-13 04:37:52 +0000374 BuiltinIndex = 15;
Chris Lattner5caa3702009-05-08 06:58:22 +0000375 NumFixed = 0;
376 break;
377 }
Mike Stump1eb44332009-09-09 15:08:12 +0000378
Chris Lattner5caa3702009-05-08 06:58:22 +0000379 // Now that we know how many fixed arguments we expect, first check that we
380 // have at least that many.
381 if (TheCall->getNumArgs() < 1+NumFixed)
382 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
383 << 0 << TheCall->getCallee()->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000384
385
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000386 // Get the decl for the concrete builtin from this, we can tell what the
387 // concrete integer type we should convert to is.
388 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
389 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
390 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
Mike Stump1eb44332009-09-09 15:08:12 +0000391 FunctionDecl *NewBuiltinDecl =
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000392 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
393 TUScope, false, DRE->getLocStart()));
394 const FunctionProtoType *BuiltinFT =
John McCall183700f2009-09-21 23:43:11 +0000395 NewBuiltinDecl->getType()->getAs<FunctionProtoType>();
Ted Kremenek6217b802009-07-29 21:53:49 +0000396 ValType = BuiltinFT->getArgType(0)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +0000397
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000398 // If the first type needs to be converted (e.g. void** -> int*), do it now.
399 if (BuiltinFT->getArgType(0) != FirstArg->getType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +0000400 ImpCastExprToType(FirstArg, BuiltinFT->getArgType(0), CastExpr::CK_BitCast);
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000401 TheCall->setArg(0, FirstArg);
402 }
Mike Stump1eb44332009-09-09 15:08:12 +0000403
Chris Lattner5caa3702009-05-08 06:58:22 +0000404 // Next, walk the valid ones promoting to the right type.
405 for (unsigned i = 0; i != NumFixed; ++i) {
406 Expr *Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +0000407
Chris Lattner5caa3702009-05-08 06:58:22 +0000408 // If the argument is an implicit cast, then there was a promotion due to
409 // "...", just remove it now.
410 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
411 Arg = ICE->getSubExpr();
412 ICE->setSubExpr(0);
413 ICE->Destroy(Context);
414 TheCall->setArg(i+1, Arg);
415 }
Mike Stump1eb44332009-09-09 15:08:12 +0000416
Chris Lattner5caa3702009-05-08 06:58:22 +0000417 // GCC does an implicit conversion to the pointer or integer ValType. This
418 // can fail in some cases (1i -> int**), check for this error case now.
Anders Carlssoncdb61972009-08-07 22:21:05 +0000419 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Fariborz Jahaniane9f42082009-08-26 18:55:36 +0000420 CXXMethodDecl *ConversionDecl = 0;
421 if (CheckCastTypes(Arg->getSourceRange(), ValType, Arg, Kind,
422 ConversionDecl))
Chris Lattner5caa3702009-05-08 06:58:22 +0000423 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000424
Chris Lattner5caa3702009-05-08 06:58:22 +0000425 // Okay, we have something that *can* be converted to the right type. Check
426 // to see if there is a potentially weird extension going on here. This can
427 // happen when you do an atomic operation on something like an char* and
428 // pass in 42. The 42 gets converted to char. This is even more strange
429 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +0000430 // FIXME: Do this check.
Anders Carlssoncdb61972009-08-07 22:21:05 +0000431 ImpCastExprToType(Arg, ValType, Kind, /*isLvalue=*/false);
Chris Lattner5caa3702009-05-08 06:58:22 +0000432 TheCall->setArg(i+1, Arg);
433 }
Mike Stump1eb44332009-09-09 15:08:12 +0000434
Chris Lattner5caa3702009-05-08 06:58:22 +0000435 // Switch the DeclRefExpr to refer to the new decl.
436 DRE->setDecl(NewBuiltinDecl);
437 DRE->setType(NewBuiltinDecl->getType());
Mike Stump1eb44332009-09-09 15:08:12 +0000438
Chris Lattner5caa3702009-05-08 06:58:22 +0000439 // Set the callee in the CallExpr.
440 // FIXME: This leaks the original parens and implicit casts.
441 Expr *PromotedCall = DRE;
442 UsualUnaryConversions(PromotedCall);
443 TheCall->setCallee(PromotedCall);
Mike Stump1eb44332009-09-09 15:08:12 +0000444
Chris Lattner5caa3702009-05-08 06:58:22 +0000445
446 // Change the result type of the call to match the result type of the decl.
447 TheCall->setType(NewBuiltinDecl->getResultType());
448 return false;
449}
450
451
Chris Lattner69039812009-02-18 06:01:06 +0000452/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +0000453/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +0000454/// FIXME: GCC currently emits the following warning:
Mike Stump1eb44332009-09-09 15:08:12 +0000455/// "warning: input conversion stopped due to an input byte that does not
Steve Narofffd942622009-04-13 20:26:29 +0000456/// belong to the input codeset UTF-8"
457/// Note: It might also make sense to do the UTF-16 conversion here (would
458/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +0000459bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +0000460 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000461 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
462
463 if (!Literal || Literal->isWide()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000464 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
465 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000466 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000467 }
Mike Stump1eb44332009-09-09 15:08:12 +0000468
Daniel Dunbarf015b032009-09-22 10:03:52 +0000469 const char *Data = Literal->getStrData();
470 unsigned Length = Literal->getByteLength();
Mike Stump1eb44332009-09-09 15:08:12 +0000471
Daniel Dunbarf015b032009-09-22 10:03:52 +0000472 for (unsigned i = 0; i < Length; ++i) {
473 if (!Data[i]) {
474 Diag(getLocationOfStringLiteralByte(Literal, i),
475 diag::warn_cfstring_literal_contains_nul_character)
476 << Arg->getSourceRange();
477 break;
478 }
479 }
Mike Stump1eb44332009-09-09 15:08:12 +0000480
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000481 return false;
Chris Lattner59907c42007-08-10 20:18:51 +0000482}
483
Chris Lattnerc27c6652007-12-20 00:05:45 +0000484/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
485/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +0000486bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
487 Expr *Fn = TheCall->getCallee();
488 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +0000489 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000490 diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000491 << 0 /*function call*/ << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +0000492 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000493 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +0000494 return true;
495 }
Eli Friedman56f20ae2008-12-15 22:05:35 +0000496
497 if (TheCall->getNumArgs() < 2) {
498 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
499 << 0 /*function call*/;
500 }
501
Chris Lattnerc27c6652007-12-20 00:05:45 +0000502 // Determine whether the current function is variadic or not.
503 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000504 if (CurBlock)
505 isVariadic = CurBlock->isVariadic;
506 else if (getCurFunctionDecl()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000507 if (FunctionProtoType* FTP =
508 dyn_cast<FunctionProtoType>(getCurFunctionDecl()->getType()))
Eli Friedman56f20ae2008-12-15 22:05:35 +0000509 isVariadic = FTP->isVariadic();
510 else
511 isVariadic = false;
512 } else {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000513 isVariadic = getCurMethodDecl()->isVariadic();
Eli Friedman56f20ae2008-12-15 22:05:35 +0000514 }
Mike Stump1eb44332009-09-09 15:08:12 +0000515
Chris Lattnerc27c6652007-12-20 00:05:45 +0000516 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000517 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
518 return true;
519 }
Mike Stump1eb44332009-09-09 15:08:12 +0000520
Chris Lattner30ce3442007-12-19 23:59:04 +0000521 // Verify that the second argument to the builtin is the last argument of the
522 // current function or method.
523 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +0000524 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +0000525
Anders Carlsson88cf2262008-02-11 04:20:54 +0000526 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
527 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000528 // FIXME: This isn't correct for methods (results in bogus warning).
529 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +0000530 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000531 if (CurBlock)
532 LastArg = *(CurBlock->TheDecl->param_end()-1);
533 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +0000534 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000535 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000536 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000537 SecondArgIsLastNamedArgument = PV == LastArg;
538 }
539 }
Mike Stump1eb44332009-09-09 15:08:12 +0000540
Chris Lattner30ce3442007-12-19 23:59:04 +0000541 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +0000542 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +0000543 diag::warn_second_parameter_of_va_start_not_last_named_argument);
544 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +0000545}
Chris Lattner30ce3442007-12-19 23:59:04 +0000546
Chris Lattner1b9a0792007-12-20 00:26:33 +0000547/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
548/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +0000549bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
550 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +0000551 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
552 << 0 /*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +0000553 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +0000554 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000555 diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000556 << 0 /*function call*/
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000557 << SourceRange(TheCall->getArg(2)->getLocStart(),
558 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000559
Chris Lattner925e60d2007-12-28 05:29:59 +0000560 Expr *OrigArg0 = TheCall->getArg(0);
561 Expr *OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +0000562
Chris Lattner1b9a0792007-12-20 00:26:33 +0000563 // Do standard promotions between the two arguments, returning their common
564 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +0000565 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
Daniel Dunbar403bc2b2009-02-19 19:28:43 +0000566
567 // Make sure any conversions are pushed back into the call; this is
568 // type safe since unordered compare builtins are declared as "_Bool
569 // foo(...)".
570 TheCall->setArg(0, OrigArg0);
571 TheCall->setArg(1, OrigArg1);
Mike Stump1eb44332009-09-09 15:08:12 +0000572
Douglas Gregorcde01732009-05-19 22:10:17 +0000573 if (OrigArg0->isTypeDependent() || OrigArg1->isTypeDependent())
574 return false;
575
Chris Lattner1b9a0792007-12-20 00:26:33 +0000576 // If the common type isn't a real floating type, then the arguments were
577 // invalid for this operation.
578 if (!Res->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +0000579 return Diag(OrigArg0->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000580 diag::err_typecheck_call_invalid_ordered_compare)
Chris Lattnerd1625842008-11-24 06:25:27 +0000581 << OrigArg0->getType() << OrigArg1->getType()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000582 << SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000583
Chris Lattner1b9a0792007-12-20 00:26:33 +0000584 return false;
585}
586
Eli Friedman9ac6f622009-08-31 20:06:00 +0000587/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isnan and
588/// friends. This is declared to take (...), so we have to check everything.
589bool Sema::SemaBuiltinUnaryFP(CallExpr *TheCall) {
590 if (TheCall->getNumArgs() < 1)
591 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
592 << 0 /*function call*/;
593 if (TheCall->getNumArgs() > 1)
Mike Stump1eb44332009-09-09 15:08:12 +0000594 return Diag(TheCall->getArg(1)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000595 diag::err_typecheck_call_too_many_args)
596 << 0 /*function call*/
597 << SourceRange(TheCall->getArg(1)->getLocStart(),
598 (*(TheCall->arg_end()-1))->getLocEnd());
599
600 Expr *OrigArg = TheCall->getArg(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000601
Eli Friedman9ac6f622009-08-31 20:06:00 +0000602 if (OrigArg->isTypeDependent())
603 return false;
604
605 // This operation requires a floating-point number
606 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +0000607 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000608 diag::err_typecheck_call_invalid_unary_fp)
609 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000610
Eli Friedman9ac6f622009-08-31 20:06:00 +0000611 return false;
612}
613
Eli Friedman6cfda232008-05-20 08:23:37 +0000614bool Sema::SemaBuiltinStackAddress(CallExpr *TheCall) {
615 // The signature for these builtins is exact; the only thing we need
616 // to check is that the argument is a constant.
617 SourceLocation Loc;
Douglas Gregorcde01732009-05-19 22:10:17 +0000618 if (!TheCall->getArg(0)->isTypeDependent() &&
619 !TheCall->getArg(0)->isValueDependent() &&
620 !TheCall->getArg(0)->isIntegerConstantExpr(Context, &Loc))
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000621 return Diag(Loc, diag::err_stack_const_level) << TheCall->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000622
Eli Friedman6cfda232008-05-20 08:23:37 +0000623 return false;
624}
625
Eli Friedmand38617c2008-05-14 19:38:39 +0000626/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
627// This is declared to take (...), so we have to check everything.
Sebastian Redl0eb23302009-01-19 00:08:26 +0000628Action::OwningExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000629 if (TheCall->getNumArgs() < 3)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000630 return ExprError(Diag(TheCall->getLocEnd(),
631 diag::err_typecheck_call_too_few_args)
632 << 0 /*function call*/ << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000633
Douglas Gregorcde01732009-05-19 22:10:17 +0000634 unsigned numElements = std::numeric_limits<unsigned>::max();
635 if (!TheCall->getArg(0)->isTypeDependent() &&
636 !TheCall->getArg(1)->isTypeDependent()) {
637 QualType FAType = TheCall->getArg(0)->getType();
638 QualType SAType = TheCall->getArg(1)->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000639
Douglas Gregorcde01732009-05-19 22:10:17 +0000640 if (!FAType->isVectorType() || !SAType->isVectorType()) {
641 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +0000642 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000643 TheCall->getArg(1)->getLocEnd());
644 return ExprError();
645 }
Mike Stump1eb44332009-09-09 15:08:12 +0000646
Douglas Gregora4923eb2009-11-16 21:35:15 +0000647 if (!Context.hasSameUnqualifiedType(FAType, SAType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000648 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +0000649 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000650 TheCall->getArg(1)->getLocEnd());
651 return ExprError();
652 }
Eli Friedmand38617c2008-05-14 19:38:39 +0000653
John McCall183700f2009-09-21 23:43:11 +0000654 numElements = FAType->getAs<VectorType>()->getNumElements();
Douglas Gregorcde01732009-05-19 22:10:17 +0000655 if (TheCall->getNumArgs() != numElements+2) {
656 if (TheCall->getNumArgs() < numElements+2)
657 return ExprError(Diag(TheCall->getLocEnd(),
658 diag::err_typecheck_call_too_few_args)
659 << 0 /*function call*/ << TheCall->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +0000660 return ExprError(Diag(TheCall->getLocEnd(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000661 diag::err_typecheck_call_too_many_args)
662 << 0 /*function call*/ << TheCall->getSourceRange());
663 }
Eli Friedmand38617c2008-05-14 19:38:39 +0000664 }
665
666 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000667 if (TheCall->getArg(i)->isTypeDependent() ||
668 TheCall->getArg(i)->isValueDependent())
669 continue;
670
Eli Friedmand38617c2008-05-14 19:38:39 +0000671 llvm::APSInt Result(32);
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000672 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000673 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000674 diag::err_shufflevector_nonconstant_argument)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000675 << TheCall->getArg(i)->getSourceRange());
676
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000677 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000678 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000679 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000680 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000681 }
682
683 llvm::SmallVector<Expr*, 32> exprs;
684
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000685 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000686 exprs.push_back(TheCall->getArg(i));
687 TheCall->setArg(i, 0);
688 }
689
Nate Begemana88dc302009-08-12 02:10:25 +0000690 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
691 exprs.size(), exprs[0]->getType(),
Ted Kremenek8189cde2009-02-07 01:47:29 +0000692 TheCall->getCallee()->getLocStart(),
693 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +0000694}
Chris Lattner30ce3442007-12-19 23:59:04 +0000695
Daniel Dunbar4493f792008-07-21 22:59:13 +0000696/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
697// This is declared to take (const void*, ...) and can take two
698// optional constant int args.
699bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000700 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000701
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000702 if (NumArgs > 3)
703 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000704 << 0 /*function call*/ << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000705
706 // Argument 0 is checked for us and the remaining arguments must be
707 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000708 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +0000709 Expr *Arg = TheCall->getArg(i);
Douglas Gregorcde01732009-05-19 22:10:17 +0000710 if (Arg->isTypeDependent())
711 continue;
712
Eli Friedman9aef7262009-12-04 00:30:06 +0000713 if (!Arg->getType()->isIntegralType())
714 return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_arg_type)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000715 << Arg->getSourceRange();
Douglas Gregorcde01732009-05-19 22:10:17 +0000716
Eli Friedman9aef7262009-12-04 00:30:06 +0000717 ImpCastExprToType(Arg, Context.IntTy, CastExpr::CK_IntegralCast);
718 TheCall->setArg(i, Arg);
719
Douglas Gregorcde01732009-05-19 22:10:17 +0000720 if (Arg->isValueDependent())
721 continue;
722
Eli Friedman9aef7262009-12-04 00:30:06 +0000723 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +0000724 if (!Arg->isIntegerConstantExpr(Result, Context))
Eli Friedman9aef7262009-12-04 00:30:06 +0000725 return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_arg_ice)
Douglas Gregorcde01732009-05-19 22:10:17 +0000726 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000727
Daniel Dunbar4493f792008-07-21 22:59:13 +0000728 // FIXME: gcc issues a warning and rewrites these to 0. These
729 // seems especially odd for the third argument since the default
730 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000731 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +0000732 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000733 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000734 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000735 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +0000736 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000737 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000738 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000739 }
740 }
741
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000742 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +0000743}
744
Chris Lattner21fb98e2009-09-23 06:06:36 +0000745/// SemaBuiltinEHReturnDataRegNo - Handle __builtin_eh_return_data_regno, the
746/// operand must be an integer constant.
747bool Sema::SemaBuiltinEHReturnDataRegNo(CallExpr *TheCall) {
748 llvm::APSInt Result;
749 if (!TheCall->getArg(0)->isIntegerConstantExpr(Result, Context))
750 return Diag(TheCall->getLocStart(), diag::err_expr_not_ice)
751 << TheCall->getArg(0)->getSourceRange();
752
753 return false;
754}
755
756
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000757/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
758/// int type). This simply type checks that type is one of the defined
759/// constants (0-3).
Eric Christopherfee667f2009-12-23 03:49:37 +0000760// For compatability check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000761bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
762 Expr *Arg = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +0000763 if (Arg->isTypeDependent())
764 return false;
765
Mike Stump1eb44332009-09-09 15:08:12 +0000766 QualType ArgType = Arg->getType();
John McCall183700f2009-09-21 23:43:11 +0000767 const BuiltinType *BT = ArgType->getAs<BuiltinType>();
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000768 llvm::APSInt Result(32);
Douglas Gregorcde01732009-05-19 22:10:17 +0000769 if (!BT || BT->getKind() != BuiltinType::Int)
770 return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument)
771 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
772
773 if (Arg->isValueDependent())
774 return false;
775
776 if (!Arg->isIntegerConstantExpr(Result, Context)) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000777 return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument)
778 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000779 }
780
781 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000782 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
783 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000784 }
785
786 return false;
787}
788
Eli Friedman586d6a82009-05-03 06:04:26 +0000789/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +0000790/// This checks that val is a constant 1.
791bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
792 Expr *Arg = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +0000793 if (Arg->isTypeDependent() || Arg->isValueDependent())
794 return false;
795
Eli Friedmand875fed2009-05-03 04:46:36 +0000796 llvm::APSInt Result(32);
797 if (!Arg->isIntegerConstantExpr(Result, Context) || Result != 1)
798 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
799 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
800
801 return false;
802}
803
Ted Kremenekd30ef872009-01-12 23:09:09 +0000804// Handle i > 1 ? "x" : "y", recursivelly
Ted Kremenek082d9362009-03-20 21:35:28 +0000805bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
806 bool HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000807 unsigned format_idx, unsigned firstDataArg) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000808 if (E->isTypeDependent() || E->isValueDependent())
809 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000810
811 switch (E->getStmtClass()) {
812 case Stmt::ConditionalOperatorClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +0000813 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Chris Lattner813b70d2009-12-22 06:00:13 +0000814 return SemaCheckStringLiteral(C->getTrueExpr(), TheCall,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000815 HasVAListArg, format_idx, firstDataArg)
Ted Kremenekd30ef872009-01-12 23:09:09 +0000816 && SemaCheckStringLiteral(C->getRHS(), TheCall,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000817 HasVAListArg, format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000818 }
819
820 case Stmt::ImplicitCastExprClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +0000821 const ImplicitCastExpr *Expr = cast<ImplicitCastExpr>(E);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000822 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000823 format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000824 }
825
826 case Stmt::ParenExprClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +0000827 const ParenExpr *Expr = cast<ParenExpr>(E);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000828 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000829 format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000830 }
Mike Stump1eb44332009-09-09 15:08:12 +0000831
Ted Kremenek082d9362009-03-20 21:35:28 +0000832 case Stmt::DeclRefExprClass: {
833 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +0000834
Ted Kremenek082d9362009-03-20 21:35:28 +0000835 // As an exception, do not flag errors for variables binding to
836 // const string literals.
837 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
838 bool isConstant = false;
839 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +0000840
Ted Kremenek082d9362009-03-20 21:35:28 +0000841 if (const ArrayType *AT = Context.getAsArrayType(T)) {
842 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000843 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000844 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +0000845 PT->getPointeeType().isConstant(Context);
846 }
Mike Stump1eb44332009-09-09 15:08:12 +0000847
Ted Kremenek082d9362009-03-20 21:35:28 +0000848 if (isConstant) {
849 const VarDecl *Def = 0;
850 if (const Expr *Init = VD->getDefinition(Def))
851 return SemaCheckStringLiteral(Init, TheCall,
852 HasVAListArg, format_idx, firstDataArg);
853 }
Mike Stump1eb44332009-09-09 15:08:12 +0000854
Anders Carlssond966a552009-06-28 19:55:58 +0000855 // For vprintf* functions (i.e., HasVAListArg==true), we add a
856 // special check to see if the format string is a function parameter
857 // of the function calling the printf function. If the function
858 // has an attribute indicating it is a printf-like function, then we
859 // should suppress warnings concerning non-literals being used in a call
860 // to a vprintf function. For example:
861 //
862 // void
863 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
864 // va_list ap;
865 // va_start(ap, fmt);
866 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
867 // ...
868 //
869 //
870 // FIXME: We don't have full attribute support yet, so just check to see
871 // if the argument is a DeclRefExpr that references a parameter. We'll
872 // add proper support for checking the attribute later.
873 if (HasVAListArg)
874 if (isa<ParmVarDecl>(VD))
875 return true;
Ted Kremenek082d9362009-03-20 21:35:28 +0000876 }
Mike Stump1eb44332009-09-09 15:08:12 +0000877
Ted Kremenek082d9362009-03-20 21:35:28 +0000878 return false;
879 }
Ted Kremenekd30ef872009-01-12 23:09:09 +0000880
Anders Carlsson8f031b32009-06-27 04:05:33 +0000881 case Stmt::CallExprClass: {
882 const CallExpr *CE = cast<CallExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +0000883 if (const ImplicitCastExpr *ICE
Anders Carlsson8f031b32009-06-27 04:05:33 +0000884 = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
885 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
886 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000887 if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
Anders Carlsson8f031b32009-06-27 04:05:33 +0000888 unsigned ArgIndex = FA->getFormatIdx();
889 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +0000890
891 return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg,
Anders Carlsson8f031b32009-06-27 04:05:33 +0000892 format_idx, firstDataArg);
893 }
894 }
895 }
896 }
Mike Stump1eb44332009-09-09 15:08:12 +0000897
Anders Carlsson8f031b32009-06-27 04:05:33 +0000898 return false;
899 }
Ted Kremenek082d9362009-03-20 21:35:28 +0000900 case Stmt::ObjCStringLiteralClass:
901 case Stmt::StringLiteralClass: {
902 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +0000903
Ted Kremenek082d9362009-03-20 21:35:28 +0000904 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +0000905 StrE = ObjCFExpr->getString();
906 else
Ted Kremenek082d9362009-03-20 21:35:28 +0000907 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +0000908
Ted Kremenekd30ef872009-01-12 23:09:09 +0000909 if (StrE) {
Mike Stump1eb44332009-09-09 15:08:12 +0000910 CheckPrintfString(StrE, E, TheCall, HasVAListArg, format_idx,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000911 firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000912 return true;
913 }
Mike Stump1eb44332009-09-09 15:08:12 +0000914
Ted Kremenekd30ef872009-01-12 23:09:09 +0000915 return false;
916 }
Mike Stump1eb44332009-09-09 15:08:12 +0000917
Ted Kremenek082d9362009-03-20 21:35:28 +0000918 default:
919 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000920 }
921}
922
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +0000923void
Mike Stump1eb44332009-09-09 15:08:12 +0000924Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
925 const CallExpr *TheCall) {
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +0000926 for (NonNullAttr::iterator i = NonNull->begin(), e = NonNull->end();
927 i != e; ++i) {
Chris Lattner12b97ff2009-05-25 18:23:36 +0000928 const Expr *ArgExpr = TheCall->getArg(*i);
Douglas Gregorce940492009-09-25 04:25:58 +0000929 if (ArgExpr->isNullPointerConstant(Context,
930 Expr::NPC_ValueDependentIsNotNull))
Chris Lattner12b97ff2009-05-25 18:23:36 +0000931 Diag(TheCall->getCallee()->getLocStart(), diag::warn_null_arg)
932 << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +0000933 }
934}
Ted Kremenekd30ef872009-01-12 23:09:09 +0000935
Chris Lattner59907c42007-08-10 20:18:51 +0000936/// CheckPrintfArguments - Check calls to printf (and similar functions) for
Mike Stump1eb44332009-09-09 15:08:12 +0000937/// correct use of format strings.
Ted Kremenek71895b92007-08-14 17:39:48 +0000938///
939/// HasVAListArg - A predicate indicating whether the printf-like
940/// function is passed an explicit va_arg argument (e.g., vprintf)
941///
942/// format_idx - The index into Args for the format string.
943///
944/// Improper format strings to functions in the printf family can be
945/// the source of bizarre bugs and very serious security holes. A
946/// good source of information is available in the following paper
947/// (which includes additional references):
Chris Lattner59907c42007-08-10 20:18:51 +0000948///
949/// FormatGuard: Automatic Protection From printf Format String
950/// Vulnerabilities, Proceedings of the 10th USENIX Security Symposium, 2001.
Ted Kremenek71895b92007-08-14 17:39:48 +0000951///
952/// Functionality implemented:
953///
954/// We can statically check the following properties for string
955/// literal format strings for non v.*printf functions (where the
956/// arguments are passed directly):
957//
958/// (1) Are the number of format conversions equal to the number of
959/// data arguments?
960///
961/// (2) Does each format conversion correctly match the type of the
962/// corresponding data argument? (TODO)
963///
964/// Moreover, for all printf functions we can:
965///
966/// (3) Check for a missing format string (when not caught by type checking).
967///
968/// (4) Check for no-operation flags; e.g. using "#" with format
969/// conversion 'c' (TODO)
970///
971/// (5) Check the use of '%n', a major source of security holes.
972///
973/// (6) Check for malformed format conversions that don't specify anything.
974///
975/// (7) Check for empty format strings. e.g: printf("");
976///
977/// (8) Check that the format string is a wide literal.
978///
979/// All of these checks can be done by parsing the format string.
980///
981/// For now, we ONLY do (1), (3), (5), (6), (7), and (8).
Chris Lattner59907c42007-08-10 20:18:51 +0000982void
Mike Stump1eb44332009-09-09 15:08:12 +0000983Sema::CheckPrintfArguments(const CallExpr *TheCall, bool HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000984 unsigned format_idx, unsigned firstDataArg) {
Ted Kremenek082d9362009-03-20 21:35:28 +0000985 const Expr *Fn = TheCall->getCallee();
Chris Lattner925e60d2007-12-28 05:29:59 +0000986
Sebastian Redl4a2614e2009-11-17 18:02:24 +0000987 // The way the format attribute works in GCC, the implicit this argument
988 // of member functions is counted. However, it doesn't appear in our own
989 // lists, so decrement format_idx in that case.
990 if (isa<CXXMemberCallExpr>(TheCall)) {
991 // Catch a format attribute mistakenly referring to the object argument.
992 if (format_idx == 0)
993 return;
994 --format_idx;
995 if(firstDataArg != 0)
996 --firstDataArg;
997 }
998
Mike Stump1eb44332009-09-09 15:08:12 +0000999 // CHECK: printf-like function is called with no format string.
Chris Lattner925e60d2007-12-28 05:29:59 +00001000 if (format_idx >= TheCall->getNumArgs()) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001001 Diag(TheCall->getRParenLoc(), diag::warn_printf_missing_format_string)
1002 << Fn->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001003 return;
1004 }
Mike Stump1eb44332009-09-09 15:08:12 +00001005
Ted Kremenek082d9362009-03-20 21:35:28 +00001006 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001007
Chris Lattner59907c42007-08-10 20:18:51 +00001008 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001009 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001010 // Dynamically generated format strings are difficult to
1011 // automatically vet at compile time. Requiring that format strings
1012 // are string literals: (1) permits the checking of format strings by
1013 // the compiler and thereby (2) can practically remove the source of
1014 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001015
Mike Stump1eb44332009-09-09 15:08:12 +00001016 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001017 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001018 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001019 // the same format string checking logic for both ObjC and C strings.
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001020 if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
1021 firstDataArg))
1022 return; // Literal format string found, check done!
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001023
Chris Lattner655f1412009-04-29 04:59:47 +00001024 // If there are no arguments specified, warn with -Wformat-security, otherwise
1025 // warn only with -Wformat-nonliteral.
1026 if (TheCall->getNumArgs() == format_idx+1)
Mike Stump1eb44332009-09-09 15:08:12 +00001027 Diag(TheCall->getArg(format_idx)->getLocStart(),
Chris Lattner655f1412009-04-29 04:59:47 +00001028 diag::warn_printf_nonliteral_noargs)
1029 << OrigFormatExpr->getSourceRange();
1030 else
Mike Stump1eb44332009-09-09 15:08:12 +00001031 Diag(TheCall->getArg(format_idx)->getLocStart(),
Chris Lattner655f1412009-04-29 04:59:47 +00001032 diag::warn_printf_nonliteral)
1033 << OrigFormatExpr->getSourceRange();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001034}
Ted Kremenek71895b92007-08-14 17:39:48 +00001035
Ted Kremenek082d9362009-03-20 21:35:28 +00001036void Sema::CheckPrintfString(const StringLiteral *FExpr,
1037 const Expr *OrigFormatExpr,
1038 const CallExpr *TheCall, bool HasVAListArg,
1039 unsigned format_idx, unsigned firstDataArg) {
Ted Kremenekce7024e2010-01-28 01:18:22 +00001040
1041 static bool UseAlternatePrintfChecking = false;
1042 if (UseAlternatePrintfChecking) {
1043 AlternateCheckPrintfString(FExpr, OrigFormatExpr, TheCall,
1044 HasVAListArg, format_idx, firstDataArg);
1045 return;
1046 }
1047
Ted Kremenekd30ef872009-01-12 23:09:09 +00001048
Ted Kremenek082d9362009-03-20 21:35:28 +00001049 const ObjCStringLiteral *ObjCFExpr =
1050 dyn_cast<ObjCStringLiteral>(OrigFormatExpr);
1051
Ted Kremenek71895b92007-08-14 17:39:48 +00001052 // CHECK: is the format string a wide literal?
1053 if (FExpr->isWide()) {
Chris Lattner925e60d2007-12-28 05:29:59 +00001054 Diag(FExpr->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001055 diag::warn_printf_format_string_is_wide_literal)
1056 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001057 return;
1058 }
1059
1060 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattnerb9fc8562009-04-29 04:12:34 +00001061 const char *Str = FExpr->getStrData();
Ted Kremenek71895b92007-08-14 17:39:48 +00001062
1063 // CHECK: empty format string?
Chris Lattnerb9fc8562009-04-29 04:12:34 +00001064 unsigned StrLen = FExpr->getByteLength();
Mike Stump1eb44332009-09-09 15:08:12 +00001065
Ted Kremenek71895b92007-08-14 17:39:48 +00001066 if (StrLen == 0) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001067 Diag(FExpr->getLocStart(), diag::warn_printf_empty_format_string)
1068 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001069 return;
1070 }
Ted Kremenekce7024e2010-01-28 01:18:22 +00001071
Ted Kremenek71895b92007-08-14 17:39:48 +00001072 // We process the format string using a binary state machine. The
1073 // current state is stored in CurrentState.
1074 enum {
1075 state_OrdChr,
1076 state_Conversion
1077 } CurrentState = state_OrdChr;
Mike Stump1eb44332009-09-09 15:08:12 +00001078
Ted Kremenek71895b92007-08-14 17:39:48 +00001079 // numConversions - The number of conversions seen so far. This is
1080 // incremented as we traverse the format string.
1081 unsigned numConversions = 0;
1082
1083 // numDataArgs - The number of data arguments after the format
1084 // string. This can only be determined for non vprintf-like
1085 // functions. For those functions, this value is 1 (the sole
1086 // va_arg argument).
Douglas Gregor3c385e52009-02-14 18:57:46 +00001087 unsigned numDataArgs = TheCall->getNumArgs()-firstDataArg;
Ted Kremenek71895b92007-08-14 17:39:48 +00001088
1089 // Inspect the format string.
1090 unsigned StrIdx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001091
Ted Kremenek71895b92007-08-14 17:39:48 +00001092 // LastConversionIdx - Index within the format string where we last saw
1093 // a '%' character that starts a new format conversion.
1094 unsigned LastConversionIdx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001095
Chris Lattner925e60d2007-12-28 05:29:59 +00001096 for (; StrIdx < StrLen; ++StrIdx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001097
Ted Kremenek71895b92007-08-14 17:39:48 +00001098 // Is the number of detected conversion conversions greater than
1099 // the number of matching data arguments? If so, stop.
1100 if (!HasVAListArg && numConversions > numDataArgs) break;
Mike Stump1eb44332009-09-09 15:08:12 +00001101
Ted Kremenek71895b92007-08-14 17:39:48 +00001102 // Handle "\0"
Chris Lattner925e60d2007-12-28 05:29:59 +00001103 if (Str[StrIdx] == '\0') {
Ted Kremenek71895b92007-08-14 17:39:48 +00001104 // The string returned by getStrData() is not null-terminated,
1105 // so the presence of a null character is likely an error.
Chris Lattner60800082009-02-18 17:49:48 +00001106 Diag(getLocationOfStringLiteralByte(FExpr, StrIdx),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001107 diag::warn_printf_format_string_contains_null_char)
1108 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001109 return;
1110 }
Mike Stump1eb44332009-09-09 15:08:12 +00001111
Ted Kremenek71895b92007-08-14 17:39:48 +00001112 // Ordinary characters (not processing a format conversion).
1113 if (CurrentState == state_OrdChr) {
1114 if (Str[StrIdx] == '%') {
1115 CurrentState = state_Conversion;
1116 LastConversionIdx = StrIdx;
1117 }
1118 continue;
1119 }
1120
1121 // Seen '%'. Now processing a format conversion.
1122 switch (Str[StrIdx]) {
Mike Stump1eb44332009-09-09 15:08:12 +00001123 // Handle dynamic precision or width specifier.
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001124 case '*': {
1125 ++numConversions;
Mike Stump1eb44332009-09-09 15:08:12 +00001126
Ted Kremenek42ae3e82009-05-13 16:06:05 +00001127 if (!HasVAListArg) {
1128 if (numConversions > numDataArgs) {
1129 SourceLocation Loc = getLocationOfStringLiteralByte(FExpr, StrIdx);
Ted Kremenek580b6642007-10-12 20:51:52 +00001130
Ted Kremenek42ae3e82009-05-13 16:06:05 +00001131 if (Str[StrIdx-1] == '.')
1132 Diag(Loc, diag::warn_printf_asterisk_precision_missing_arg)
1133 << OrigFormatExpr->getSourceRange();
1134 else
1135 Diag(Loc, diag::warn_printf_asterisk_width_missing_arg)
1136 << OrigFormatExpr->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001137
Ted Kremenek42ae3e82009-05-13 16:06:05 +00001138 // Don't do any more checking. We'll just emit spurious errors.
1139 return;
1140 }
Mike Stump1eb44332009-09-09 15:08:12 +00001141
Ted Kremenek42ae3e82009-05-13 16:06:05 +00001142 // Perform type checking on width/precision specifier.
1143 const Expr *E = TheCall->getArg(format_idx+numConversions);
John McCall183700f2009-09-21 23:43:11 +00001144 if (const BuiltinType *BT = E->getType()->getAs<BuiltinType>())
Ted Kremenek42ae3e82009-05-13 16:06:05 +00001145 if (BT->getKind() == BuiltinType::Int)
1146 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001147
Ted Kremenek42ae3e82009-05-13 16:06:05 +00001148 SourceLocation Loc = getLocationOfStringLiteralByte(FExpr, StrIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00001149
Ted Kremenek42ae3e82009-05-13 16:06:05 +00001150 if (Str[StrIdx-1] == '.')
1151 Diag(Loc, diag::warn_printf_asterisk_precision_wrong_type)
1152 << E->getType() << E->getSourceRange();
1153 else
1154 Diag(Loc, diag::warn_printf_asterisk_width_wrong_type)
1155 << E->getType() << E->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001156
1157 break;
Ted Kremenek580b6642007-10-12 20:51:52 +00001158 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001159 }
Mike Stump1eb44332009-09-09 15:08:12 +00001160
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001161 // Characters which can terminate a format conversion
1162 // (e.g. "%d"). Characters that specify length modifiers or
1163 // other flags are handled by the default case below.
1164 //
Mike Stump1eb44332009-09-09 15:08:12 +00001165 // FIXME: additional checks will go into the following cases.
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001166 case 'i':
1167 case 'd':
Mike Stump1eb44332009-09-09 15:08:12 +00001168 case 'o':
1169 case 'u':
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001170 case 'x':
1171 case 'X':
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001172 case 'e':
1173 case 'E':
1174 case 'f':
1175 case 'F':
1176 case 'g':
1177 case 'G':
1178 case 'a':
1179 case 'A':
1180 case 'c':
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001181 case 's':
Mike Stump1eb44332009-09-09 15:08:12 +00001182 case 'p':
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001183 ++numConversions;
1184 CurrentState = state_OrdChr;
1185 break;
1186
Eli Friedmanb92abb42009-06-02 08:36:19 +00001187 case 'm':
1188 // FIXME: Warn in situations where this isn't supported!
1189 CurrentState = state_OrdChr;
1190 break;
1191
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001192 // CHECK: Are we using "%n"? Issue a warning.
1193 case 'n': {
1194 ++numConversions;
1195 CurrentState = state_OrdChr;
Chris Lattner60800082009-02-18 17:49:48 +00001196 SourceLocation Loc = getLocationOfStringLiteralByte(FExpr,
1197 LastConversionIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00001198
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001199 Diag(Loc, diag::warn_printf_write_back)<<OrigFormatExpr->getSourceRange();
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001200 break;
1201 }
Mike Stump1eb44332009-09-09 15:08:12 +00001202
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001203 // Handle "%@"
1204 case '@':
1205 // %@ is allowed in ObjC format strings only.
Mike Stump1eb44332009-09-09 15:08:12 +00001206 if (ObjCFExpr != NULL)
1207 CurrentState = state_OrdChr;
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001208 else {
1209 // Issue a warning: invalid format conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00001210 SourceLocation Loc =
Chris Lattner60800082009-02-18 17:49:48 +00001211 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00001212
Chris Lattnerd3a94e22008-11-20 06:06:08 +00001213 Diag(Loc, diag::warn_printf_invalid_conversion)
1214 << std::string(Str+LastConversionIdx,
1215 Str+std::min(LastConversionIdx+2, StrLen))
1216 << OrigFormatExpr->getSourceRange();
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001217 }
1218 ++numConversions;
1219 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001220
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001221 // Handle "%%"
1222 case '%':
1223 // Sanity check: Was the first "%" character the previous one?
1224 // If not, we will assume that we have a malformed format
1225 // conversion, and that the current "%" character is the start
1226 // of a new conversion.
1227 if (StrIdx - LastConversionIdx == 1)
Mike Stump1eb44332009-09-09 15:08:12 +00001228 CurrentState = state_OrdChr;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001229 else {
1230 // Issue a warning: invalid format conversion.
Chris Lattner60800082009-02-18 17:49:48 +00001231 SourceLocation Loc =
1232 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00001233
Chris Lattnerd3a94e22008-11-20 06:06:08 +00001234 Diag(Loc, diag::warn_printf_invalid_conversion)
1235 << std::string(Str+LastConversionIdx, Str+StrIdx)
1236 << OrigFormatExpr->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001237
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001238 // This conversion is broken. Advance to the next format
1239 // conversion.
1240 LastConversionIdx = StrIdx;
1241 ++numConversions;
Ted Kremenek71895b92007-08-14 17:39:48 +00001242 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001243 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001244
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001245 default:
1246 // This case catches all other characters: flags, widths, etc.
1247 // We should eventually process those as well.
1248 break;
Ted Kremenek71895b92007-08-14 17:39:48 +00001249 }
1250 }
1251
1252 if (CurrentState == state_Conversion) {
1253 // Issue a warning: invalid format conversion.
Chris Lattner60800082009-02-18 17:49:48 +00001254 SourceLocation Loc =
1255 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00001256
Chris Lattnerd3a94e22008-11-20 06:06:08 +00001257 Diag(Loc, diag::warn_printf_invalid_conversion)
1258 << std::string(Str+LastConversionIdx,
1259 Str+std::min(LastConversionIdx+2, StrLen))
1260 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001261 return;
1262 }
Mike Stump1eb44332009-09-09 15:08:12 +00001263
Ted Kremenek71895b92007-08-14 17:39:48 +00001264 if (!HasVAListArg) {
1265 // CHECK: Does the number of format conversions exceed the number
1266 // of data arguments?
1267 if (numConversions > numDataArgs) {
Chris Lattner60800082009-02-18 17:49:48 +00001268 SourceLocation Loc =
1269 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00001270
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001271 Diag(Loc, diag::warn_printf_insufficient_data_args)
1272 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001273 }
1274 // CHECK: Does the number of data arguments exceed the number of
1275 // format conversions in the format string?
1276 else if (numConversions < numDataArgs)
Chris Lattner925e60d2007-12-28 05:29:59 +00001277 Diag(TheCall->getArg(format_idx+numConversions+1)->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001278 diag::warn_printf_too_many_data_args)
1279 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001280 }
1281}
Ted Kremenek06de2762007-08-17 16:46:58 +00001282
Ted Kremeneke0e53132010-01-28 23:39:18 +00001283
1284namespace {
Ted Kremenek808015a2010-01-29 03:16:21 +00001285class CheckPrintfHandler : public FormatStringHandler {
Ted Kremeneke0e53132010-01-28 23:39:18 +00001286 Sema &S;
1287 const StringLiteral *FExpr;
1288 const Expr *OrigFormatExpr;
1289 unsigned NumConversions;
1290 const unsigned NumDataArgs;
1291 const bool IsObjCLiteral;
1292 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00001293 const bool HasVAListArg;
1294 const CallExpr *TheCall;
1295 unsigned FormatIdx;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001296public:
1297 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
1298 const Expr *origFormatExpr,
1299 unsigned numDataArgs, bool isObjCLiteral,
Ted Kremenek0d277352010-01-29 01:06:55 +00001300 const char *beg, bool hasVAListArg,
1301 const CallExpr *theCall, unsigned formatIdx)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001302 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
1303 NumConversions(0), NumDataArgs(numDataArgs),
Ted Kremenek0d277352010-01-29 01:06:55 +00001304 IsObjCLiteral(isObjCLiteral), Beg(beg),
1305 HasVAListArg(hasVAListArg),
1306 TheCall(theCall), FormatIdx(formatIdx) {}
Ted Kremenek07d161f2010-01-29 01:50:07 +00001307
1308 void DoneProcessing();
Ted Kremenek808015a2010-01-29 03:16:21 +00001309
1310 void HandleIncompleteFormatSpecifier(const char *startSpecifier,
1311 unsigned specifierLen);
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001312
1313 void HandleInvalidConversionSpecifier(const analyze_printf::FormatSpecifier &FS,
1314 const char *startSpecifier,
1315 unsigned specifierLen);
1316
Ted Kremeneke0e53132010-01-28 23:39:18 +00001317 void HandleNullChar(const char *nullCharacter);
1318
1319 bool HandleFormatSpecifier(const analyze_printf::FormatSpecifier &FS,
1320 const char *startSpecifier,
1321 unsigned specifierLen);
1322private:
1323 SourceRange getFormatRange();
1324 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek0d277352010-01-29 01:06:55 +00001325
1326 bool HandleAmount(const analyze_printf::OptionalAmount &Amt,
1327 unsigned MissingArgDiag, unsigned BadTypeDiag);
1328
1329 const Expr *getDataArg(unsigned i) const;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001330};
1331}
1332
1333SourceRange CheckPrintfHandler::getFormatRange() {
1334 return OrigFormatExpr->getSourceRange();
1335}
1336
1337SourceLocation CheckPrintfHandler::getLocationOfByte(const char *x) {
1338 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
1339}
1340
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001341void CheckPrintfHandler::
Ted Kremenek808015a2010-01-29 03:16:21 +00001342HandleIncompleteFormatSpecifier(const char *startSpecifier,
1343 unsigned specifierLen) {
1344 SourceLocation Loc = getLocationOfByte(startSpecifier);
1345 S.Diag(Loc, diag::warn_printf_incomplete_specifier)
1346 << llvm::StringRef(startSpecifier, specifierLen)
1347 << getFormatRange();
1348}
1349
1350void CheckPrintfHandler::
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001351HandleInvalidConversionSpecifier(const analyze_printf::FormatSpecifier &FS,
1352 const char *startSpecifier,
1353 unsigned specifierLen) {
1354
1355 ++NumConversions;
Ted Kremenek808015a2010-01-29 03:16:21 +00001356 const analyze_printf::ConversionSpecifier &CS =
1357 FS.getConversionSpecifier();
1358 SourceLocation Loc = getLocationOfByte(CS.getStart());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001359 S.Diag(Loc, diag::warn_printf_invalid_conversion)
Ted Kremenek808015a2010-01-29 03:16:21 +00001360 << llvm::StringRef(CS.getStart(), CS.getLength())
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001361 << getFormatRange();
1362}
1363
Ted Kremeneke0e53132010-01-28 23:39:18 +00001364void CheckPrintfHandler::HandleNullChar(const char *nullCharacter) {
1365 // The presence of a null character is likely an error.
1366 S.Diag(getLocationOfByte(nullCharacter),
1367 diag::warn_printf_format_string_contains_null_char)
1368 << getFormatRange();
1369}
1370
Ted Kremenek0d277352010-01-29 01:06:55 +00001371const Expr *CheckPrintfHandler::getDataArg(unsigned i) const {
1372 return TheCall->getArg(FormatIdx + i);
1373}
1374
1375bool
1376CheckPrintfHandler::HandleAmount(const analyze_printf::OptionalAmount &Amt,
1377 unsigned MissingArgDiag,
1378 unsigned BadTypeDiag) {
1379
1380 if (Amt.hasDataArgument()) {
1381 ++NumConversions;
1382 if (!HasVAListArg) {
1383 if (NumConversions > NumDataArgs) {
1384 S.Diag(getLocationOfByte(Amt.getStart()), MissingArgDiag)
1385 << getFormatRange();
1386 // Don't do any more checking. We will just emit
1387 // spurious errors.
1388 return false;
1389 }
1390
1391 // Type check the data argument. It should be an 'int'.
1392 const Expr *Arg = getDataArg(NumConversions);
1393 QualType T = Arg->getType();
1394 const BuiltinType *BT = T->getAs<BuiltinType>();
1395 if (!BT || BT->getKind() != BuiltinType::Int) {
1396 S.Diag(getLocationOfByte(Amt.getStart()), BadTypeDiag)
1397 << T << getFormatRange() << Arg->getSourceRange();
1398 // Don't do any more checking. We will just emit
1399 // spurious errors.
1400 return false;
1401 }
1402 }
1403 }
1404 return true;
1405}
Ted Kremenek0d277352010-01-29 01:06:55 +00001406
Ted Kremeneke0e53132010-01-28 23:39:18 +00001407bool
1408CheckPrintfHandler::HandleFormatSpecifier(const analyze_printf::FormatSpecifier &FS,
1409 const char *startSpecifier,
1410 unsigned specifierLen) {
1411
1412 using namespace analyze_printf;
1413 const ConversionSpecifier &CS = FS.getConversionSpecifier();
1414
Ted Kremenek0d277352010-01-29 01:06:55 +00001415 // First check if the field width, precision, and conversion specifier
1416 // have matching data arguments.
1417 if (!HandleAmount(FS.getFieldWidth(),
1418 diag::warn_printf_asterisk_width_missing_arg,
1419 diag::warn_printf_asterisk_width_wrong_type)) {
1420 return false;
1421 }
1422
1423 if (!HandleAmount(FS.getPrecision(),
1424 diag::warn_printf_asterisk_precision_missing_arg,
1425 diag::warn_printf_asterisk_precision_wrong_type)) {
1426 return false;
1427 }
1428
Ted Kremeneke0e53132010-01-28 23:39:18 +00001429 // Check for using an Objective-C specific conversion specifier
1430 // in a non-ObjC literal.
1431 if (!IsObjCLiteral && CS.isObjCArg()) {
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001432 HandleInvalidConversionSpecifier(FS, startSpecifier, specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001433
1434 // Continue checking the other format specifiers.
1435 return true;
1436 }
Ted Kremeneke82d8042010-01-29 01:35:25 +00001437
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001438 ++NumConversions;
1439
Ted Kremeneke82d8042010-01-29 01:35:25 +00001440 // Are we using '%n'? Issue a warning about this being
1441 // a possible security issue.
1442 if (CS.getKind() == ConversionSpecifier::OutIntPtrArg) {
1443 S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_write_back)
1444 << getFormatRange();
1445 // Continue checking the other format specifiers.
1446 return true;
1447 }
1448
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001449
1450 // The remaining checks depend on the data arguments.
1451 if (HasVAListArg)
1452 return true;
1453
1454 if (NumConversions > NumDataArgs) {
1455 S.Diag(getLocationOfByte(CS.getStart()),
1456 diag::warn_printf_insufficient_data_args)
1457 << getFormatRange();
1458 // Don't do any more checking.
1459 return false;
1460 }
Ted Kremeneke0e53132010-01-28 23:39:18 +00001461
1462 return true;
1463}
1464
Ted Kremenek07d161f2010-01-29 01:50:07 +00001465void CheckPrintfHandler::DoneProcessing() {
1466 // Does the number of data arguments exceed the number of
1467 // format conversions in the format string?
1468 if (!HasVAListArg && NumConversions < NumDataArgs)
1469 S.Diag(getDataArg(NumConversions+1)->getLocStart(),
1470 diag::warn_printf_too_many_data_args)
1471 << getFormatRange();
1472}
Ted Kremeneke0e53132010-01-28 23:39:18 +00001473
Ted Kremenekce7024e2010-01-28 01:18:22 +00001474void
1475Sema::AlternateCheckPrintfString(const StringLiteral *FExpr,
1476 const Expr *OrigFormatExpr,
1477 const CallExpr *TheCall, bool HasVAListArg,
1478 unsigned format_idx, unsigned firstDataArg) {
1479
Ted Kremeneke0e53132010-01-28 23:39:18 +00001480 // CHECK: is the format string a wide literal?
1481 if (FExpr->isWide()) {
1482 Diag(FExpr->getLocStart(),
1483 diag::warn_printf_format_string_is_wide_literal)
1484 << OrigFormatExpr->getSourceRange();
1485 return;
1486 }
Ted Kremenekce7024e2010-01-28 01:18:22 +00001487
Ted Kremeneke0e53132010-01-28 23:39:18 +00001488 // Str - The format string. NOTE: this is NOT null-terminated!
1489 const char *Str = FExpr->getStrData();
1490
1491 // CHECK: empty format string?
1492 unsigned StrLen = FExpr->getByteLength();
1493
1494 if (StrLen == 0) {
1495 Diag(FExpr->getLocStart(), diag::warn_printf_empty_format_string)
1496 << OrigFormatExpr->getSourceRange();
1497 return;
1498 }
1499
1500 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr,
1501 TheCall->getNumArgs() - firstDataArg,
Ted Kremenek0d277352010-01-29 01:06:55 +00001502 isa<ObjCStringLiteral>(OrigFormatExpr), Str,
1503 HasVAListArg, TheCall, format_idx);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001504
Ted Kremenek808015a2010-01-29 03:16:21 +00001505 if (!ParseFormatString(H, Str, Str + StrLen))
1506 H.DoneProcessing();
Ted Kremenekce7024e2010-01-28 01:18:22 +00001507}
1508
Ted Kremenek06de2762007-08-17 16:46:58 +00001509//===--- CHECK: Return Address of Stack Variable --------------------------===//
1510
1511static DeclRefExpr* EvalVal(Expr *E);
1512static DeclRefExpr* EvalAddr(Expr* E);
1513
1514/// CheckReturnStackAddr - Check if a return statement returns the address
1515/// of a stack variable.
1516void
1517Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
1518 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00001519
Ted Kremenek06de2762007-08-17 16:46:58 +00001520 // Perform checking for returned stack addresses.
Steve Naroffdd972f22008-09-05 22:11:13 +00001521 if (lhsType->isPointerType() || lhsType->isBlockPointerType()) {
Ted Kremenek06de2762007-08-17 16:46:58 +00001522 if (DeclRefExpr *DR = EvalAddr(RetValExp))
Chris Lattner3c73c412008-11-19 08:23:25 +00001523 Diag(DR->getLocStart(), diag::warn_ret_stack_addr)
Chris Lattner08631c52008-11-23 21:45:46 +00001524 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001525
Steve Naroffc50a4a52008-09-16 22:25:10 +00001526 // Skip over implicit cast expressions when checking for block expressions.
Chris Lattner4ca606e2009-09-08 00:36:37 +00001527 RetValExp = RetValExp->IgnoreParenCasts();
Steve Naroffc50a4a52008-09-16 22:25:10 +00001528
Chris Lattner9e6b37a2009-10-30 04:01:58 +00001529 if (BlockExpr *C = dyn_cast<BlockExpr>(RetValExp))
Mike Stump397195b2009-04-17 00:09:41 +00001530 if (C->hasBlockDeclRefExprs())
1531 Diag(C->getLocStart(), diag::err_ret_local_block)
1532 << C->getSourceRange();
Chris Lattner9e6b37a2009-10-30 04:01:58 +00001533
1534 if (AddrLabelExpr *ALE = dyn_cast<AddrLabelExpr>(RetValExp))
1535 Diag(ALE->getLocStart(), diag::warn_ret_addr_label)
1536 << ALE->getSourceRange();
1537
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001538 } else if (lhsType->isReferenceType()) {
1539 // Perform checking for stack values returned by reference.
Douglas Gregor49badde2008-10-27 19:41:14 +00001540 // Check for a reference to the stack
1541 if (DeclRefExpr *DR = EvalVal(RetValExp))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001542 Diag(DR->getLocStart(), diag::warn_ret_stack_ref)
Chris Lattner08631c52008-11-23 21:45:46 +00001543 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Ted Kremenek06de2762007-08-17 16:46:58 +00001544 }
1545}
1546
1547/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
1548/// check if the expression in a return statement evaluates to an address
1549/// to a location on the stack. The recursion is used to traverse the
1550/// AST of the return expression, with recursion backtracking when we
1551/// encounter a subexpression that (1) clearly does not lead to the address
1552/// of a stack variable or (2) is something we cannot determine leads to
1553/// the address of a stack variable based on such local checking.
1554///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00001555/// EvalAddr processes expressions that are pointers that are used as
1556/// references (and not L-values). EvalVal handles all other values.
Mike Stump1eb44332009-09-09 15:08:12 +00001557/// At the base case of the recursion is a check for a DeclRefExpr* in
Ted Kremenek06de2762007-08-17 16:46:58 +00001558/// the refers to a stack variable.
1559///
1560/// This implementation handles:
1561///
1562/// * pointer-to-pointer casts
1563/// * implicit conversions from array references to pointers
1564/// * taking the address of fields
1565/// * arbitrary interplay between "&" and "*" operators
1566/// * pointer arithmetic from an address of a stack variable
1567/// * taking the address of an array element where the array is on the stack
1568static DeclRefExpr* EvalAddr(Expr *E) {
Ted Kremenek06de2762007-08-17 16:46:58 +00001569 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00001570 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00001571 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001572 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001573 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00001574
Ted Kremenek06de2762007-08-17 16:46:58 +00001575 // Our "symbolic interpreter" is just a dispatch off the currently
1576 // viewed AST node. We then recursively traverse the AST by calling
1577 // EvalAddr and EvalVal appropriately.
1578 switch (E->getStmtClass()) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001579 case Stmt::ParenExprClass:
1580 // Ignore parentheses.
1581 return EvalAddr(cast<ParenExpr>(E)->getSubExpr());
Ted Kremenek06de2762007-08-17 16:46:58 +00001582
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001583 case Stmt::UnaryOperatorClass: {
1584 // The only unary operator that make sense to handle here
1585 // is AddrOf. All others don't make sense as pointers.
1586 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001587
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001588 if (U->getOpcode() == UnaryOperator::AddrOf)
1589 return EvalVal(U->getSubExpr());
1590 else
Ted Kremenek06de2762007-08-17 16:46:58 +00001591 return NULL;
1592 }
Mike Stump1eb44332009-09-09 15:08:12 +00001593
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001594 case Stmt::BinaryOperatorClass: {
1595 // Handle pointer arithmetic. All other binary operators are not valid
1596 // in this context.
1597 BinaryOperator *B = cast<BinaryOperator>(E);
1598 BinaryOperator::Opcode op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00001599
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001600 if (op != BinaryOperator::Add && op != BinaryOperator::Sub)
1601 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001602
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001603 Expr *Base = B->getLHS();
1604
1605 // Determine which argument is the real pointer base. It could be
1606 // the RHS argument instead of the LHS.
1607 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00001608
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001609 assert (Base->getType()->isPointerType());
1610 return EvalAddr(Base);
1611 }
Steve Naroff61f40a22008-09-10 19:17:48 +00001612
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001613 // For conditional operators we need to see if either the LHS or RHS are
1614 // valid DeclRefExpr*s. If one of them is valid, we return it.
1615 case Stmt::ConditionalOperatorClass: {
1616 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001617
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001618 // Handle the GNU extension for missing LHS.
1619 if (Expr *lhsExpr = C->getLHS())
1620 if (DeclRefExpr* LHS = EvalAddr(lhsExpr))
1621 return LHS;
1622
1623 return EvalAddr(C->getRHS());
1624 }
Mike Stump1eb44332009-09-09 15:08:12 +00001625
Ted Kremenek54b52742008-08-07 00:49:01 +00001626 // For casts, we need to handle conversions from arrays to
1627 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00001628 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001629 case Stmt::CStyleCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00001630 case Stmt::CXXFunctionalCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001631 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenek54b52742008-08-07 00:49:01 +00001632 QualType T = SubExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001633
Steve Naroffdd972f22008-09-05 22:11:13 +00001634 if (SubExpr->getType()->isPointerType() ||
1635 SubExpr->getType()->isBlockPointerType() ||
1636 SubExpr->getType()->isObjCQualifiedIdType())
Ted Kremenek54b52742008-08-07 00:49:01 +00001637 return EvalAddr(SubExpr);
1638 else if (T->isArrayType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001639 return EvalVal(SubExpr);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001640 else
Ted Kremenek54b52742008-08-07 00:49:01 +00001641 return 0;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001642 }
Mike Stump1eb44332009-09-09 15:08:12 +00001643
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001644 // C++ casts. For dynamic casts, static casts, and const casts, we
1645 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor49badde2008-10-27 19:41:14 +00001646 // through the cast. In the case the dynamic cast doesn't fail (and
1647 // return NULL), we take the conservative route and report cases
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001648 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor49badde2008-10-27 19:41:14 +00001649 // FIXME: The comment about is wrong; we're not always converting
1650 // from pointer to pointer. I'm guessing that this code should also
Mike Stump1eb44332009-09-09 15:08:12 +00001651 // handle references to objects.
1652 case Stmt::CXXStaticCastExprClass:
1653 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00001654 case Stmt::CXXConstCastExprClass:
1655 case Stmt::CXXReinterpretCastExprClass: {
1656 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffdd972f22008-09-05 22:11:13 +00001657 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001658 return EvalAddr(S);
1659 else
1660 return NULL;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001661 }
Mike Stump1eb44332009-09-09 15:08:12 +00001662
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001663 // Everything else: we simply don't reason about them.
1664 default:
1665 return NULL;
1666 }
Ted Kremenek06de2762007-08-17 16:46:58 +00001667}
Mike Stump1eb44332009-09-09 15:08:12 +00001668
Ted Kremenek06de2762007-08-17 16:46:58 +00001669
1670/// EvalVal - This function is complements EvalAddr in the mutual recursion.
1671/// See the comments for EvalAddr for more details.
1672static DeclRefExpr* EvalVal(Expr *E) {
Mike Stump1eb44332009-09-09 15:08:12 +00001673
Ted Kremeneke8c600f2007-08-28 17:02:55 +00001674 // We should only be called for evaluating non-pointer expressions, or
1675 // expressions with a pointer type that are not used as references but instead
1676 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00001677
Ted Kremenek06de2762007-08-17 16:46:58 +00001678 // Our "symbolic interpreter" is just a dispatch off the currently
1679 // viewed AST node. We then recursively traverse the AST by calling
1680 // EvalAddr and EvalVal appropriately.
1681 switch (E->getStmtClass()) {
Douglas Gregora2813ce2009-10-23 18:54:35 +00001682 case Stmt::DeclRefExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00001683 // DeclRefExpr: the base case. When we hit a DeclRefExpr we are looking
1684 // at code that refers to a variable's name. We check if it has local
1685 // storage within the function, and if so, return the expression.
1686 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001687
Ted Kremenek06de2762007-08-17 16:46:58 +00001688 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Mike Stump1eb44332009-09-09 15:08:12 +00001689 if (V->hasLocalStorage() && !V->getType()->isReferenceType()) return DR;
1690
Ted Kremenek06de2762007-08-17 16:46:58 +00001691 return NULL;
1692 }
Mike Stump1eb44332009-09-09 15:08:12 +00001693
Ted Kremenek06de2762007-08-17 16:46:58 +00001694 case Stmt::ParenExprClass:
1695 // Ignore parentheses.
1696 return EvalVal(cast<ParenExpr>(E)->getSubExpr());
Mike Stump1eb44332009-09-09 15:08:12 +00001697
Ted Kremenek06de2762007-08-17 16:46:58 +00001698 case Stmt::UnaryOperatorClass: {
1699 // The only unary operator that make sense to handle here
1700 // is Deref. All others don't resolve to a "name." This includes
1701 // handling all sorts of rvalues passed to a unary operator.
1702 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001703
Ted Kremenek06de2762007-08-17 16:46:58 +00001704 if (U->getOpcode() == UnaryOperator::Deref)
1705 return EvalAddr(U->getSubExpr());
1706
1707 return NULL;
1708 }
Mike Stump1eb44332009-09-09 15:08:12 +00001709
Ted Kremenek06de2762007-08-17 16:46:58 +00001710 case Stmt::ArraySubscriptExprClass: {
1711 // Array subscripts are potential references to data on the stack. We
1712 // retrieve the DeclRefExpr* for the array variable if it indeed
1713 // has local storage.
Ted Kremenek23245122007-08-20 16:18:38 +00001714 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase());
Ted Kremenek06de2762007-08-17 16:46:58 +00001715 }
Mike Stump1eb44332009-09-09 15:08:12 +00001716
Ted Kremenek06de2762007-08-17 16:46:58 +00001717 case Stmt::ConditionalOperatorClass: {
1718 // For conditional operators we need to see if either the LHS or RHS are
1719 // non-NULL DeclRefExpr's. If one is non-NULL, we return it.
1720 ConditionalOperator *C = cast<ConditionalOperator>(E);
1721
Anders Carlsson39073232007-11-30 19:04:31 +00001722 // Handle the GNU extension for missing LHS.
1723 if (Expr *lhsExpr = C->getLHS())
1724 if (DeclRefExpr *LHS = EvalVal(lhsExpr))
1725 return LHS;
1726
1727 return EvalVal(C->getRHS());
Ted Kremenek06de2762007-08-17 16:46:58 +00001728 }
Mike Stump1eb44332009-09-09 15:08:12 +00001729
Ted Kremenek06de2762007-08-17 16:46:58 +00001730 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00001731 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00001732 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001733
Ted Kremenek06de2762007-08-17 16:46:58 +00001734 // Check for indirect access. We only want direct field accesses.
1735 if (!M->isArrow())
1736 return EvalVal(M->getBase());
1737 else
1738 return NULL;
1739 }
Mike Stump1eb44332009-09-09 15:08:12 +00001740
Ted Kremenek06de2762007-08-17 16:46:58 +00001741 // Everything else: we simply don't reason about them.
1742 default:
1743 return NULL;
1744 }
1745}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001746
1747//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
1748
1749/// Check for comparisons of floating point operands using != and ==.
1750/// Issue a warning if these are no self-comparisons, as they are not likely
1751/// to do what the programmer intended.
1752void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
1753 bool EmitWarning = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001754
Ted Kremenek4e99a5f2008-01-17 16:57:34 +00001755 Expr* LeftExprSansParen = lex->IgnoreParens();
Ted Kremenek32e97b62008-01-17 17:55:13 +00001756 Expr* RightExprSansParen = rex->IgnoreParens();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001757
1758 // Special case: check for x == x (which is OK).
1759 // Do not emit warnings for such cases.
1760 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
1761 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
1762 if (DRL->getDecl() == DRR->getDecl())
1763 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001764
1765
Ted Kremenek1b500bb2007-11-29 00:59:04 +00001766 // Special case: check for comparisons against literals that can be exactly
1767 // represented by APFloat. In such cases, do not emit a warning. This
1768 // is a heuristic: often comparison against such literals are used to
1769 // detect if a value in a variable has not changed. This clearly can
1770 // lead to false negatives.
1771 if (EmitWarning) {
1772 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
1773 if (FLL->isExact())
1774 EmitWarning = false;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001775 } else
Ted Kremenek1b500bb2007-11-29 00:59:04 +00001776 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
1777 if (FLR->isExact())
1778 EmitWarning = false;
1779 }
1780 }
Mike Stump1eb44332009-09-09 15:08:12 +00001781
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001782 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001783 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001784 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00001785 if (CL->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001786 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001787
Sebastian Redl0eb23302009-01-19 00:08:26 +00001788 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001789 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00001790 if (CR->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001791 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001792
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001793 // Emit the diagnostic.
1794 if (EmitWarning)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001795 Diag(loc, diag::warn_floatingpoint_eq)
1796 << lex->getSourceRange() << rex->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001797}
John McCallba26e582010-01-04 23:21:16 +00001798
John McCallf2370c92010-01-06 05:24:50 +00001799//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
1800//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00001801
John McCallf2370c92010-01-06 05:24:50 +00001802namespace {
John McCallba26e582010-01-04 23:21:16 +00001803
John McCallf2370c92010-01-06 05:24:50 +00001804/// Structure recording the 'active' range of an integer-valued
1805/// expression.
1806struct IntRange {
1807 /// The number of bits active in the int.
1808 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00001809
John McCallf2370c92010-01-06 05:24:50 +00001810 /// True if the int is known not to have negative values.
1811 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00001812
John McCallf2370c92010-01-06 05:24:50 +00001813 IntRange() {}
1814 IntRange(unsigned Width, bool NonNegative)
1815 : Width(Width), NonNegative(NonNegative)
1816 {}
John McCallba26e582010-01-04 23:21:16 +00001817
John McCallf2370c92010-01-06 05:24:50 +00001818 // Returns the range of the bool type.
1819 static IntRange forBoolType() {
1820 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00001821 }
1822
John McCallf2370c92010-01-06 05:24:50 +00001823 // Returns the range of an integral type.
1824 static IntRange forType(ASTContext &C, QualType T) {
1825 return forCanonicalType(C, T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00001826 }
1827
John McCallf2370c92010-01-06 05:24:50 +00001828 // Returns the range of an integeral type based on its canonical
1829 // representation.
1830 static IntRange forCanonicalType(ASTContext &C, const Type *T) {
1831 assert(T->isCanonicalUnqualified());
1832
1833 if (const VectorType *VT = dyn_cast<VectorType>(T))
1834 T = VT->getElementType().getTypePtr();
1835 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
1836 T = CT->getElementType().getTypePtr();
1837 if (const EnumType *ET = dyn_cast<EnumType>(T))
1838 T = ET->getDecl()->getIntegerType().getTypePtr();
1839
1840 const BuiltinType *BT = cast<BuiltinType>(T);
1841 assert(BT->isInteger());
1842
1843 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
1844 }
1845
1846 // Returns the supremum of two ranges: i.e. their conservative merge.
1847 static IntRange join(const IntRange &L, const IntRange &R) {
1848 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00001849 L.NonNegative && R.NonNegative);
1850 }
1851
1852 // Returns the infinum of two ranges: i.e. their aggressive merge.
1853 static IntRange meet(const IntRange &L, const IntRange &R) {
1854 return IntRange(std::min(L.Width, R.Width),
1855 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00001856 }
1857};
1858
1859IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
1860 if (value.isSigned() && value.isNegative())
1861 return IntRange(value.getMinSignedBits(), false);
1862
1863 if (value.getBitWidth() > MaxWidth)
1864 value.trunc(MaxWidth);
1865
1866 // isNonNegative() just checks the sign bit without considering
1867 // signedness.
1868 return IntRange(value.getActiveBits(), true);
1869}
1870
John McCall0acc3112010-01-06 22:57:21 +00001871IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
John McCallf2370c92010-01-06 05:24:50 +00001872 unsigned MaxWidth) {
1873 if (result.isInt())
1874 return GetValueRange(C, result.getInt(), MaxWidth);
1875
1876 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00001877 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
1878 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
1879 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
1880 R = IntRange::join(R, El);
1881 }
John McCallf2370c92010-01-06 05:24:50 +00001882 return R;
1883 }
1884
1885 if (result.isComplexInt()) {
1886 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
1887 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
1888 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00001889 }
1890
1891 // This can happen with lossless casts to intptr_t of "based" lvalues.
1892 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00001893 // FIXME: The only reason we need to pass the type in here is to get
1894 // the sign right on this one case. It would be nice if APValue
1895 // preserved this.
John McCallf2370c92010-01-06 05:24:50 +00001896 assert(result.isLValue());
John McCall0acc3112010-01-06 22:57:21 +00001897 return IntRange(MaxWidth, Ty->isUnsignedIntegerType());
John McCall51313c32010-01-04 23:31:57 +00001898}
John McCallf2370c92010-01-06 05:24:50 +00001899
1900/// Pseudo-evaluate the given integer expression, estimating the
1901/// range of values it might take.
1902///
1903/// \param MaxWidth - the width to which the value will be truncated
1904IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
1905 E = E->IgnoreParens();
1906
1907 // Try a full evaluation first.
1908 Expr::EvalResult result;
1909 if (E->Evaluate(result, C))
John McCall0acc3112010-01-06 22:57:21 +00001910 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00001911
1912 // I think we only want to look through implicit casts here; if the
1913 // user has an explicit widening cast, we should treat the value as
1914 // being of the new, wider type.
1915 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
1916 if (CE->getCastKind() == CastExpr::CK_NoOp)
1917 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
1918
1919 IntRange OutputTypeRange = IntRange::forType(C, CE->getType());
1920
John McCall60fad452010-01-06 22:07:33 +00001921 bool isIntegerCast = (CE->getCastKind() == CastExpr::CK_IntegralCast);
1922 if (!isIntegerCast && CE->getCastKind() == CastExpr::CK_Unknown)
1923 isIntegerCast = CE->getSubExpr()->getType()->isIntegerType();
1924
John McCallf2370c92010-01-06 05:24:50 +00001925 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00001926 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00001927 return OutputTypeRange;
1928
1929 IntRange SubRange
1930 = GetExprRange(C, CE->getSubExpr(),
1931 std::min(MaxWidth, OutputTypeRange.Width));
1932
1933 // Bail out if the subexpr's range is as wide as the cast type.
1934 if (SubRange.Width >= OutputTypeRange.Width)
1935 return OutputTypeRange;
1936
1937 // Otherwise, we take the smaller width, and we're non-negative if
1938 // either the output type or the subexpr is.
1939 return IntRange(SubRange.Width,
1940 SubRange.NonNegative || OutputTypeRange.NonNegative);
1941 }
1942
1943 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1944 // If we can fold the condition, just take that operand.
1945 bool CondResult;
1946 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
1947 return GetExprRange(C, CondResult ? CO->getTrueExpr()
1948 : CO->getFalseExpr(),
1949 MaxWidth);
1950
1951 // Otherwise, conservatively merge.
1952 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
1953 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
1954 return IntRange::join(L, R);
1955 }
1956
1957 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
1958 switch (BO->getOpcode()) {
1959
1960 // Boolean-valued operations are single-bit and positive.
1961 case BinaryOperator::LAnd:
1962 case BinaryOperator::LOr:
1963 case BinaryOperator::LT:
1964 case BinaryOperator::GT:
1965 case BinaryOperator::LE:
1966 case BinaryOperator::GE:
1967 case BinaryOperator::EQ:
1968 case BinaryOperator::NE:
1969 return IntRange::forBoolType();
1970
1971 // Operations with opaque sources are black-listed.
1972 case BinaryOperator::PtrMemD:
1973 case BinaryOperator::PtrMemI:
1974 return IntRange::forType(C, E->getType());
1975
John McCall60fad452010-01-06 22:07:33 +00001976 // Bitwise-and uses the *infinum* of the two source ranges.
1977 case BinaryOperator::And:
1978 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
1979 GetExprRange(C, BO->getRHS(), MaxWidth));
1980
John McCallf2370c92010-01-06 05:24:50 +00001981 // Left shift gets black-listed based on a judgement call.
1982 case BinaryOperator::Shl:
1983 return IntRange::forType(C, E->getType());
1984
John McCall60fad452010-01-06 22:07:33 +00001985 // Right shift by a constant can narrow its left argument.
1986 case BinaryOperator::Shr: {
1987 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
1988
1989 // If the shift amount is a positive constant, drop the width by
1990 // that much.
1991 llvm::APSInt shift;
1992 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
1993 shift.isNonNegative()) {
1994 unsigned zext = shift.getZExtValue();
1995 if (zext >= L.Width)
1996 L.Width = (L.NonNegative ? 0 : 1);
1997 else
1998 L.Width -= zext;
1999 }
2000
2001 return L;
2002 }
2003
2004 // Comma acts as its right operand.
John McCallf2370c92010-01-06 05:24:50 +00002005 case BinaryOperator::Comma:
2006 return GetExprRange(C, BO->getRHS(), MaxWidth);
2007
John McCall60fad452010-01-06 22:07:33 +00002008 // Black-list pointer subtractions.
John McCallf2370c92010-01-06 05:24:50 +00002009 case BinaryOperator::Sub:
2010 if (BO->getLHS()->getType()->isPointerType())
2011 return IntRange::forType(C, E->getType());
2012 // fallthrough
2013
2014 default:
2015 break;
2016 }
2017
2018 // Treat every other operator as if it were closed on the
2019 // narrowest type that encompasses both operands.
2020 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
2021 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
2022 return IntRange::join(L, R);
2023 }
2024
2025 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
2026 switch (UO->getOpcode()) {
2027 // Boolean-valued operations are white-listed.
2028 case UnaryOperator::LNot:
2029 return IntRange::forBoolType();
2030
2031 // Operations with opaque sources are black-listed.
2032 case UnaryOperator::Deref:
2033 case UnaryOperator::AddrOf: // should be impossible
2034 case UnaryOperator::OffsetOf:
2035 return IntRange::forType(C, E->getType());
2036
2037 default:
2038 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
2039 }
2040 }
2041
2042 FieldDecl *BitField = E->getBitField();
2043 if (BitField) {
2044 llvm::APSInt BitWidthAP = BitField->getBitWidth()->EvaluateAsInt(C);
2045 unsigned BitWidth = BitWidthAP.getZExtValue();
2046
2047 return IntRange(BitWidth, BitField->getType()->isUnsignedIntegerType());
2048 }
2049
2050 return IntRange::forType(C, E->getType());
2051}
John McCall51313c32010-01-04 23:31:57 +00002052
2053/// Checks whether the given value, which currently has the given
2054/// source semantics, has the same value when coerced through the
2055/// target semantics.
John McCallf2370c92010-01-06 05:24:50 +00002056bool IsSameFloatAfterCast(const llvm::APFloat &value,
2057 const llvm::fltSemantics &Src,
2058 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00002059 llvm::APFloat truncated = value;
2060
2061 bool ignored;
2062 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
2063 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
2064
2065 return truncated.bitwiseIsEqual(value);
2066}
2067
2068/// Checks whether the given value, which currently has the given
2069/// source semantics, has the same value when coerced through the
2070/// target semantics.
2071///
2072/// The value might be a vector of floats (or a complex number).
John McCallf2370c92010-01-06 05:24:50 +00002073bool IsSameFloatAfterCast(const APValue &value,
2074 const llvm::fltSemantics &Src,
2075 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00002076 if (value.isFloat())
2077 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
2078
2079 if (value.isVector()) {
2080 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
2081 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
2082 return false;
2083 return true;
2084 }
2085
2086 assert(value.isComplexFloat());
2087 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
2088 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
2089}
2090
John McCallf2370c92010-01-06 05:24:50 +00002091} // end anonymous namespace
John McCall51313c32010-01-04 23:31:57 +00002092
John McCallba26e582010-01-04 23:21:16 +00002093/// \brief Implements -Wsign-compare.
2094///
2095/// \param lex the left-hand expression
2096/// \param rex the right-hand expression
2097/// \param OpLoc the location of the joining operator
2098/// \param Equality whether this is an "equality-like" join, which
2099/// suppresses the warning in some cases
2100void Sema::CheckSignCompare(Expr *lex, Expr *rex, SourceLocation OpLoc,
2101 const PartialDiagnostic &PD, bool Equality) {
2102 // Don't warn if we're in an unevaluated context.
2103 if (ExprEvalContexts.back().Context == Unevaluated)
2104 return;
2105
John McCallf2370c92010-01-06 05:24:50 +00002106 // If either expression is value-dependent, don't warn. We'll get another
2107 // chance at instantiation time.
2108 if (lex->isValueDependent() || rex->isValueDependent())
2109 return;
2110
John McCallba26e582010-01-04 23:21:16 +00002111 QualType lt = lex->getType(), rt = rex->getType();
2112
2113 // Only warn if both operands are integral.
2114 if (!lt->isIntegerType() || !rt->isIntegerType())
2115 return;
2116
John McCallf2370c92010-01-06 05:24:50 +00002117 // In C, the width of a bitfield determines its type, and the
2118 // declared type only contributes the signedness. This duplicates
2119 // the work that will later be done by UsualUnaryConversions.
2120 // Eventually, this check will be reorganized in a way that avoids
2121 // this duplication.
2122 if (!getLangOptions().CPlusPlus) {
2123 QualType tmp;
2124 tmp = Context.isPromotableBitField(lex);
2125 if (!tmp.isNull()) lt = tmp;
2126 tmp = Context.isPromotableBitField(rex);
2127 if (!tmp.isNull()) rt = tmp;
2128 }
John McCallba26e582010-01-04 23:21:16 +00002129
2130 // The rule is that the signed operand becomes unsigned, so isolate the
2131 // signed operand.
John McCallf2370c92010-01-06 05:24:50 +00002132 Expr *signedOperand = lex, *unsignedOperand = rex;
2133 QualType signedType = lt, unsignedType = rt;
John McCallba26e582010-01-04 23:21:16 +00002134 if (lt->isSignedIntegerType()) {
2135 if (rt->isSignedIntegerType()) return;
John McCallba26e582010-01-04 23:21:16 +00002136 } else {
2137 if (!rt->isSignedIntegerType()) return;
John McCallf2370c92010-01-06 05:24:50 +00002138 std::swap(signedOperand, unsignedOperand);
2139 std::swap(signedType, unsignedType);
John McCallba26e582010-01-04 23:21:16 +00002140 }
2141
John McCallf2370c92010-01-06 05:24:50 +00002142 unsigned unsignedWidth = Context.getIntWidth(unsignedType);
2143 unsigned signedWidth = Context.getIntWidth(signedType);
2144
John McCallba26e582010-01-04 23:21:16 +00002145 // If the unsigned type is strictly smaller than the signed type,
2146 // then (1) the result type will be signed and (2) the unsigned
2147 // value will fit fully within the signed type, and thus the result
2148 // of the comparison will be exact.
John McCallf2370c92010-01-06 05:24:50 +00002149 if (signedWidth > unsignedWidth)
John McCallba26e582010-01-04 23:21:16 +00002150 return;
2151
John McCallf2370c92010-01-06 05:24:50 +00002152 // Otherwise, calculate the effective ranges.
2153 IntRange signedRange = GetExprRange(Context, signedOperand, signedWidth);
2154 IntRange unsignedRange = GetExprRange(Context, unsignedOperand, unsignedWidth);
2155
2156 // We should never be unable to prove that the unsigned operand is
2157 // non-negative.
2158 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
2159
2160 // If the signed operand is non-negative, then the signed->unsigned
2161 // conversion won't change it.
2162 if (signedRange.NonNegative)
John McCallba26e582010-01-04 23:21:16 +00002163 return;
2164
2165 // For (in)equality comparisons, if the unsigned operand is a
2166 // constant which cannot collide with a overflowed signed operand,
2167 // then reinterpreting the signed operand as unsigned will not
2168 // change the result of the comparison.
John McCallf2370c92010-01-06 05:24:50 +00002169 if (Equality && unsignedRange.Width < unsignedWidth)
John McCallba26e582010-01-04 23:21:16 +00002170 return;
2171
2172 Diag(OpLoc, PD)
John McCallf2370c92010-01-06 05:24:50 +00002173 << lt << rt << lex->getSourceRange() << rex->getSourceRange();
John McCallba26e582010-01-04 23:21:16 +00002174}
2175
John McCall51313c32010-01-04 23:31:57 +00002176/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
2177static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, unsigned diag) {
2178 S.Diag(E->getExprLoc(), diag) << E->getType() << T << E->getSourceRange();
2179}
2180
2181/// Implements -Wconversion.
2182void Sema::CheckImplicitConversion(Expr *E, QualType T) {
2183 // Don't diagnose in unevaluated contexts.
2184 if (ExprEvalContexts.back().Context == Sema::Unevaluated)
2185 return;
2186
2187 // Don't diagnose for value-dependent expressions.
2188 if (E->isValueDependent())
2189 return;
2190
2191 const Type *Source = Context.getCanonicalType(E->getType()).getTypePtr();
2192 const Type *Target = Context.getCanonicalType(T).getTypePtr();
2193
2194 // Never diagnose implicit casts to bool.
2195 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
2196 return;
2197
2198 // Strip vector types.
2199 if (isa<VectorType>(Source)) {
2200 if (!isa<VectorType>(Target))
2201 return DiagnoseImpCast(*this, E, T, diag::warn_impcast_vector_scalar);
2202
2203 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
2204 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
2205 }
2206
2207 // Strip complex types.
2208 if (isa<ComplexType>(Source)) {
2209 if (!isa<ComplexType>(Target))
2210 return DiagnoseImpCast(*this, E, T, diag::warn_impcast_complex_scalar);
2211
2212 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
2213 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
2214 }
2215
2216 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
2217 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
2218
2219 // If the source is floating point...
2220 if (SourceBT && SourceBT->isFloatingPoint()) {
2221 // ...and the target is floating point...
2222 if (TargetBT && TargetBT->isFloatingPoint()) {
2223 // ...then warn if we're dropping FP rank.
2224
2225 // Builtin FP kinds are ordered by increasing FP rank.
2226 if (SourceBT->getKind() > TargetBT->getKind()) {
2227 // Don't warn about float constants that are precisely
2228 // representable in the target type.
2229 Expr::EvalResult result;
2230 if (E->Evaluate(result, Context)) {
2231 // Value might be a float, a float vector, or a float complex.
2232 if (IsSameFloatAfterCast(result.Val,
2233 Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
2234 Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
2235 return;
2236 }
2237
2238 DiagnoseImpCast(*this, E, T, diag::warn_impcast_float_precision);
2239 }
2240 return;
2241 }
2242
2243 // If the target is integral, always warn.
2244 if ((TargetBT && TargetBT->isInteger()))
2245 // TODO: don't warn for integer values?
2246 return DiagnoseImpCast(*this, E, T, diag::warn_impcast_float_integer);
2247
2248 return;
2249 }
2250
John McCallf2370c92010-01-06 05:24:50 +00002251 if (!Source->isIntegerType() || !Target->isIntegerType())
John McCall51313c32010-01-04 23:31:57 +00002252 return;
2253
John McCallf2370c92010-01-06 05:24:50 +00002254 IntRange SourceRange = GetExprRange(Context, E, Context.getIntWidth(E->getType()));
2255 IntRange TargetRange = IntRange::forCanonicalType(Context, Target);
John McCall51313c32010-01-04 23:31:57 +00002256
John McCallf2370c92010-01-06 05:24:50 +00002257 // FIXME: also signed<->unsigned?
2258
2259 if (SourceRange.Width > TargetRange.Width) {
John McCall51313c32010-01-04 23:31:57 +00002260 // People want to build with -Wshorten-64-to-32 and not -Wconversion
2261 // and by god we'll let them.
John McCallf2370c92010-01-06 05:24:50 +00002262 if (SourceRange.Width == 64 && TargetRange.Width == 32)
John McCall51313c32010-01-04 23:31:57 +00002263 return DiagnoseImpCast(*this, E, T, diag::warn_impcast_integer_64_32);
2264 return DiagnoseImpCast(*this, E, T, diag::warn_impcast_integer_precision);
2265 }
2266
2267 return;
2268}
2269
Mike Stumpf8c49212010-01-21 03:59:47 +00002270// MarkLive - Mark all the blocks reachable from e as live. Returns the total
2271// number of blocks just marked live.
2272static unsigned MarkLive(CFGBlock *e, llvm::BitVector &live) {
2273 unsigned count = 0;
2274 std::queue<CFGBlock*> workq;
2275 // Prep work queue
2276 live.set(e->getBlockID());
2277 ++count;
2278 workq.push(e);
2279 // Solve
2280 while (!workq.empty()) {
2281 CFGBlock *item = workq.front();
2282 workq.pop();
2283 for (CFGBlock::succ_iterator I=item->succ_begin(),
2284 E=item->succ_end();
2285 I != E;
2286 ++I) {
2287 if ((*I) && !live[(*I)->getBlockID()]) {
2288 live.set((*I)->getBlockID());
2289 ++count;
2290 workq.push(*I);
2291 }
2292 }
2293 }
2294 return count;
2295}
2296
Mike Stump55f988e2010-01-21 17:21:23 +00002297static SourceLocation GetUnreachableLoc(CFGBlock &b, SourceRange &R1,
2298 SourceRange &R2) {
Mike Stumpf8c49212010-01-21 03:59:47 +00002299 Stmt *S;
Mike Stumpe5fba702010-01-21 19:44:04 +00002300 unsigned sn = 0;
2301 R1 = R2 = SourceRange();
2302
2303 top:
2304 if (sn < b.size())
2305 S = b[sn].getStmt();
Mike Stumpf8c49212010-01-21 03:59:47 +00002306 else if (b.getTerminator())
2307 S = b.getTerminator();
2308 else
2309 return SourceLocation();
2310
2311 switch (S->getStmtClass()) {
2312 case Expr::BinaryOperatorClass: {
Mike Stump55f988e2010-01-21 17:21:23 +00002313 BinaryOperator *BO = cast<BinaryOperator>(S);
2314 if (BO->getOpcode() == BinaryOperator::Comma) {
Mike Stumpe5fba702010-01-21 19:44:04 +00002315 if (sn+1 < b.size())
2316 return b[sn+1].getStmt()->getLocStart();
Mike Stumpf8c49212010-01-21 03:59:47 +00002317 CFGBlock *n = &b;
2318 while (1) {
2319 if (n->getTerminator())
2320 return n->getTerminator()->getLocStart();
2321 if (n->succ_size() != 1)
2322 return SourceLocation();
2323 n = n[0].succ_begin()[0];
2324 if (n->pred_size() != 1)
2325 return SourceLocation();
2326 if (!n->empty())
2327 return n[0][0].getStmt()->getLocStart();
2328 }
2329 }
Mike Stump55f988e2010-01-21 17:21:23 +00002330 R1 = BO->getLHS()->getSourceRange();
2331 R2 = BO->getRHS()->getSourceRange();
2332 return BO->getOperatorLoc();
2333 }
2334 case Expr::UnaryOperatorClass: {
2335 const UnaryOperator *UO = cast<UnaryOperator>(S);
2336 R1 = UO->getSubExpr()->getSourceRange();
2337 return UO->getOperatorLoc();
Mike Stumpf8c49212010-01-21 03:59:47 +00002338 }
Mike Stump45db90d2010-01-21 17:31:41 +00002339 case Expr::CompoundAssignOperatorClass: {
2340 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(S);
2341 R1 = CAO->getLHS()->getSourceRange();
2342 R2 = CAO->getRHS()->getSourceRange();
2343 return CAO->getOperatorLoc();
2344 }
Mike Stumpe5fba702010-01-21 19:44:04 +00002345 case Expr::ConditionalOperatorClass: {
2346 const ConditionalOperator *CO = cast<ConditionalOperator>(S);
2347 return CO->getQuestionLoc();
2348 }
Mike Stumpb5c77552010-01-21 23:15:53 +00002349 case Expr::MemberExprClass: {
2350 const MemberExpr *ME = cast<MemberExpr>(S);
2351 R1 = ME->getSourceRange();
2352 return ME->getMemberLoc();
2353 }
2354 case Expr::ArraySubscriptExprClass: {
2355 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(S);
2356 R1 = ASE->getLHS()->getSourceRange();
2357 R2 = ASE->getRHS()->getSourceRange();
2358 return ASE->getRBracketLoc();
2359 }
Mike Stump44582302010-01-21 19:51:34 +00002360 case Expr::CStyleCastExprClass: {
2361 const CStyleCastExpr *CSC = cast<CStyleCastExpr>(S);
2362 R1 = CSC->getSubExpr()->getSourceRange();
2363 return CSC->getLParenLoc();
2364 }
Mike Stump2d6ceab2010-01-21 22:12:18 +00002365 case Expr::CXXFunctionalCastExprClass: {
2366 const CXXFunctionalCastExpr *CE = cast <CXXFunctionalCastExpr>(S);
2367 R1 = CE->getSubExpr()->getSourceRange();
2368 return CE->getTypeBeginLoc();
2369 }
Mike Stumpe5fba702010-01-21 19:44:04 +00002370 case Expr::ImplicitCastExprClass:
2371 ++sn;
2372 goto top;
Mike Stump4c45aa12010-01-21 15:20:48 +00002373 case Stmt::CXXTryStmtClass: {
2374 return cast<CXXTryStmt>(S)->getHandler(0)->getCatchLoc();
2375 }
Mike Stumpf8c49212010-01-21 03:59:47 +00002376 default: ;
2377 }
Mike Stumpb5c77552010-01-21 23:15:53 +00002378 R1 = S->getSourceRange();
Mike Stumpf8c49212010-01-21 03:59:47 +00002379 return S->getLocStart();
2380}
2381
2382static SourceLocation MarkLiveTop(CFGBlock *e, llvm::BitVector &live,
2383 SourceManager &SM) {
2384 std::queue<CFGBlock*> workq;
2385 // Prep work queue
2386 workq.push(e);
Mike Stump55f988e2010-01-21 17:21:23 +00002387 SourceRange R1, R2;
2388 SourceLocation top = GetUnreachableLoc(*e, R1, R2);
Mike Stumpf8c49212010-01-21 03:59:47 +00002389 bool FromMainFile = false;
2390 bool FromSystemHeader = false;
2391 bool TopValid = false;
2392 if (top.isValid()) {
2393 FromMainFile = SM.isFromMainFile(top);
2394 FromSystemHeader = SM.isInSystemHeader(top);
2395 TopValid = true;
2396 }
2397 // Solve
2398 while (!workq.empty()) {
2399 CFGBlock *item = workq.front();
2400 workq.pop();
Mike Stump55f988e2010-01-21 17:21:23 +00002401 SourceLocation c = GetUnreachableLoc(*item, R1, R2);
Mike Stumpf8c49212010-01-21 03:59:47 +00002402 if (c.isValid()
2403 && (!TopValid
2404 || (SM.isFromMainFile(c) && !FromMainFile)
2405 || (FromSystemHeader && !SM.isInSystemHeader(c))
2406 || SM.isBeforeInTranslationUnit(c, top))) {
2407 top = c;
2408 FromMainFile = SM.isFromMainFile(top);
2409 FromSystemHeader = SM.isInSystemHeader(top);
2410 }
2411 live.set(item->getBlockID());
2412 for (CFGBlock::succ_iterator I=item->succ_begin(),
2413 E=item->succ_end();
2414 I != E;
2415 ++I) {
2416 if ((*I) && !live[(*I)->getBlockID()]) {
2417 live.set((*I)->getBlockID());
2418 workq.push(*I);
2419 }
2420 }
2421 }
2422 return top;
2423}
2424
2425static int LineCmp(const void *p1, const void *p2) {
2426 SourceLocation *Line1 = (SourceLocation *)p1;
2427 SourceLocation *Line2 = (SourceLocation *)p2;
2428 return !(*Line1 < *Line2);
2429}
2430
Mike Stump4a415672010-01-21 23:49:01 +00002431namespace {
2432 struct ErrLoc {
2433 SourceLocation Loc;
2434 SourceRange R1;
2435 SourceRange R2;
2436 ErrLoc(SourceLocation l, SourceRange r1, SourceRange r2)
2437 : Loc(l), R1(r1), R2(r2) { }
2438 };
2439}
2440
Mike Stumpf8c49212010-01-21 03:59:47 +00002441/// CheckUnreachable - Check for unreachable code.
2442void Sema::CheckUnreachable(AnalysisContext &AC) {
2443 unsigned count;
2444 // We avoid checking when there are errors, as the CFG won't faithfully match
2445 // the user's code.
2446 if (getDiagnostics().hasErrorOccurred())
2447 return;
2448 if (Diags.getDiagnosticLevel(diag::warn_unreachable) == Diagnostic::Ignored)
2449 return;
2450
2451 CFG *cfg = AC.getCFG();
2452 if (cfg == 0)
2453 return;
2454
2455 llvm::BitVector live(cfg->getNumBlockIDs());
2456 // Mark all live things first.
2457 count = MarkLive(&cfg->getEntry(), live);
2458
2459 if (count == cfg->getNumBlockIDs())
2460 // If there are no dead blocks, we're done.
2461 return;
2462
Mike Stump55f988e2010-01-21 17:21:23 +00002463 SourceRange R1, R2;
2464
Mike Stump4a415672010-01-21 23:49:01 +00002465 llvm::SmallVector<ErrLoc, 24> lines;
Mike Stump4c45aa12010-01-21 15:20:48 +00002466 bool AddEHEdges = AC.getAddEHEdges();
Mike Stumpf8c49212010-01-21 03:59:47 +00002467 // First, give warnings for blocks with no predecessors, as they
2468 // can't be part of a loop.
2469 for (CFG::iterator I = cfg->begin(), E = cfg->end(); I != E; ++I) {
2470 CFGBlock &b = **I;
2471 if (!live[b.getBlockID()]) {
2472 if (b.pred_begin() == b.pred_end()) {
Mike Stump4c45aa12010-01-21 15:20:48 +00002473 if (!AddEHEdges && b.getTerminator()
2474 && isa<CXXTryStmt>(b.getTerminator())) {
2475 // When not adding EH edges from calls, catch clauses
2476 // can otherwise seem dead. Avoid noting them as dead.
2477 count += MarkLive(&b, live);
2478 continue;
2479 }
Mike Stump55f988e2010-01-21 17:21:23 +00002480 SourceLocation c = GetUnreachableLoc(b, R1, R2);
Mike Stumpf8c49212010-01-21 03:59:47 +00002481 if (!c.isValid()) {
2482 // Blocks without a location can't produce a warning, so don't mark
2483 // reachable blocks from here as live.
2484 live.set(b.getBlockID());
2485 ++count;
2486 continue;
2487 }
Mike Stump4a415672010-01-21 23:49:01 +00002488 lines.push_back(ErrLoc(c, R1, R2));
Mike Stumpf8c49212010-01-21 03:59:47 +00002489 // Avoid excessive errors by marking everything reachable from here
2490 count += MarkLive(&b, live);
2491 }
2492 }
2493 }
2494
2495 if (count < cfg->getNumBlockIDs()) {
2496 // And then give warnings for the tops of loops.
2497 for (CFG::iterator I = cfg->begin(), E = cfg->end(); I != E; ++I) {
2498 CFGBlock &b = **I;
2499 if (!live[b.getBlockID()])
2500 // Avoid excessive errors by marking everything reachable from here
Ted Kremenek8acc9f62010-01-28 01:04:48 +00002501 lines.push_back(ErrLoc(MarkLiveTop(&b, live,
2502 Context.getSourceManager()),
2503 SourceRange(), SourceRange()));
Mike Stumpf8c49212010-01-21 03:59:47 +00002504 }
2505 }
2506
2507 llvm::array_pod_sort(lines.begin(), lines.end(), LineCmp);
Mike Stump4a415672010-01-21 23:49:01 +00002508 for (llvm::SmallVector<ErrLoc, 24>::iterator I = lines.begin(),
Mike Stumpf8c49212010-01-21 03:59:47 +00002509 E = lines.end();
2510 I != E;
2511 ++I)
Mike Stump4a415672010-01-21 23:49:01 +00002512 if (I->Loc.isValid())
2513 Diag(I->Loc, diag::warn_unreachable) << I->R1 << I->R2;
Mike Stumpf8c49212010-01-21 03:59:47 +00002514}
2515
2516/// CheckFallThrough - Check that we don't fall off the end of a
2517/// Statement that should return a value.
2518///
2519/// \returns AlwaysFallThrough iff we always fall off the end of the statement,
2520/// MaybeFallThrough iff we might or might not fall off the end,
2521/// NeverFallThroughOrReturn iff we never fall off the end of the statement or
2522/// return. We assume NeverFallThrough iff we never fall off the end of the
2523/// statement but we may return. We assume that functions not marked noreturn
2524/// will return.
2525Sema::ControlFlowKind Sema::CheckFallThrough(AnalysisContext &AC) {
2526 CFG *cfg = AC.getCFG();
2527 if (cfg == 0)
2528 // FIXME: This should be NeverFallThrough
2529 return NeverFallThroughOrReturn;
2530
Mike Stump4c45aa12010-01-21 15:20:48 +00002531 // The CFG leaves in dead things, and we don't want the dead code paths to
Mike Stumpf8c49212010-01-21 03:59:47 +00002532 // confuse us, so we mark all live things first.
2533 std::queue<CFGBlock*> workq;
2534 llvm::BitVector live(cfg->getNumBlockIDs());
Mike Stump4c45aa12010-01-21 15:20:48 +00002535 unsigned count = MarkLive(&cfg->getEntry(), live);
2536
2537 bool AddEHEdges = AC.getAddEHEdges();
2538 if (!AddEHEdges && count != cfg->getNumBlockIDs())
2539 // When there are things remaining dead, and we didn't add EH edges
2540 // from CallExprs to the catch clauses, we have to go back and
2541 // mark them as live.
2542 for (CFG::iterator I = cfg->begin(), E = cfg->end(); I != E; ++I) {
2543 CFGBlock &b = **I;
2544 if (!live[b.getBlockID()]) {
2545 if (b.pred_begin() == b.pred_end()) {
2546 if (b.getTerminator() && isa<CXXTryStmt>(b.getTerminator()))
2547 // When not adding EH edges from calls, catch clauses
2548 // can otherwise seem dead. Avoid noting them as dead.
2549 count += MarkLive(&b, live);
2550 continue;
2551 }
2552 }
2553 }
Mike Stumpf8c49212010-01-21 03:59:47 +00002554
2555 // Now we know what is live, we check the live precessors of the exit block
2556 // and look for fall through paths, being careful to ignore normal returns,
2557 // and exceptional paths.
2558 bool HasLiveReturn = false;
2559 bool HasFakeEdge = false;
2560 bool HasPlainEdge = false;
2561 bool HasAbnormalEdge = false;
2562 for (CFGBlock::pred_iterator I=cfg->getExit().pred_begin(),
2563 E = cfg->getExit().pred_end();
2564 I != E;
2565 ++I) {
2566 CFGBlock& B = **I;
2567 if (!live[B.getBlockID()])
2568 continue;
2569 if (B.size() == 0) {
Mike Stump4c45aa12010-01-21 15:20:48 +00002570 if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
2571 HasAbnormalEdge = true;
2572 continue;
2573 }
2574
Mike Stumpf8c49212010-01-21 03:59:47 +00002575 // A labeled empty statement, or the entry block...
2576 HasPlainEdge = true;
2577 continue;
2578 }
2579 Stmt *S = B[B.size()-1];
2580 if (isa<ReturnStmt>(S)) {
2581 HasLiveReturn = true;
2582 continue;
2583 }
2584 if (isa<ObjCAtThrowStmt>(S)) {
2585 HasFakeEdge = true;
2586 continue;
2587 }
2588 if (isa<CXXThrowExpr>(S)) {
2589 HasFakeEdge = true;
2590 continue;
2591 }
2592 if (const AsmStmt *AS = dyn_cast<AsmStmt>(S)) {
2593 if (AS->isMSAsm()) {
2594 HasFakeEdge = true;
2595 HasLiveReturn = true;
2596 continue;
2597 }
2598 }
2599 if (isa<CXXTryStmt>(S)) {
2600 HasAbnormalEdge = true;
2601 continue;
2602 }
2603
2604 bool NoReturnEdge = false;
2605 if (CallExpr *C = dyn_cast<CallExpr>(S)) {
2606 if (B.succ_begin()[0] != &cfg->getExit()) {
2607 HasAbnormalEdge = true;
2608 continue;
2609 }
2610 Expr *CEE = C->getCallee()->IgnoreParenCasts();
2611 if (CEE->getType().getNoReturnAttr()) {
2612 NoReturnEdge = true;
2613 HasFakeEdge = true;
2614 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE)) {
2615 ValueDecl *VD = DRE->getDecl();
2616 if (VD->hasAttr<NoReturnAttr>()) {
2617 NoReturnEdge = true;
2618 HasFakeEdge = true;
2619 }
2620 }
2621 }
2622 // FIXME: Add noreturn message sends.
2623 if (NoReturnEdge == false)
2624 HasPlainEdge = true;
2625 }
2626 if (!HasPlainEdge) {
2627 if (HasLiveReturn)
2628 return NeverFallThrough;
2629 return NeverFallThroughOrReturn;
2630 }
2631 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
2632 return MaybeFallThrough;
2633 // This says AlwaysFallThrough for calls to functions that are not marked
2634 // noreturn, that don't return. If people would like this warning to be more
2635 // accurate, such functions should be marked as noreturn.
2636 return AlwaysFallThrough;
2637}
2638
2639/// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
2640/// function that should return a value. Check that we don't fall off the end
2641/// of a noreturn function. We assume that functions and blocks not marked
2642/// noreturn will return.
2643void Sema::CheckFallThroughForFunctionDef(Decl *D, Stmt *Body,
2644 AnalysisContext &AC) {
2645 // FIXME: Would be nice if we had a better way to control cascading errors,
2646 // but for now, avoid them. The problem is that when Parse sees:
2647 // int foo() { return a; }
2648 // The return is eaten and the Sema code sees just:
2649 // int foo() { }
2650 // which this code would then warn about.
2651 if (getDiagnostics().hasErrorOccurred())
2652 return;
2653
2654 bool ReturnsVoid = false;
2655 bool HasNoReturn = false;
2656 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2657 // If the result type of the function is a dependent type, we don't know
2658 // whether it will be void or not, so don't
2659 if (FD->getResultType()->isDependentType())
2660 return;
2661 if (FD->getResultType()->isVoidType())
2662 ReturnsVoid = true;
2663 if (FD->hasAttr<NoReturnAttr>())
2664 HasNoReturn = true;
2665 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2666 if (MD->getResultType()->isVoidType())
2667 ReturnsVoid = true;
2668 if (MD->hasAttr<NoReturnAttr>())
2669 HasNoReturn = true;
2670 }
2671
2672 // Short circuit for compilation speed.
2673 if ((Diags.getDiagnosticLevel(diag::warn_maybe_falloff_nonvoid_function)
2674 == Diagnostic::Ignored || ReturnsVoid)
2675 && (Diags.getDiagnosticLevel(diag::warn_noreturn_function_has_return_expr)
2676 == Diagnostic::Ignored || !HasNoReturn)
2677 && (Diags.getDiagnosticLevel(diag::warn_suggest_noreturn_block)
2678 == Diagnostic::Ignored || !ReturnsVoid))
2679 return;
2680 // FIXME: Function try block
2681 if (CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) {
2682 switch (CheckFallThrough(AC)) {
2683 case MaybeFallThrough:
2684 if (HasNoReturn)
2685 Diag(Compound->getRBracLoc(), diag::warn_falloff_noreturn_function);
2686 else if (!ReturnsVoid)
2687 Diag(Compound->getRBracLoc(),diag::warn_maybe_falloff_nonvoid_function);
2688 break;
2689 case AlwaysFallThrough:
2690 if (HasNoReturn)
2691 Diag(Compound->getRBracLoc(), diag::warn_falloff_noreturn_function);
2692 else if (!ReturnsVoid)
2693 Diag(Compound->getRBracLoc(), diag::warn_falloff_nonvoid_function);
2694 break;
2695 case NeverFallThroughOrReturn:
2696 if (ReturnsVoid && !HasNoReturn)
2697 Diag(Compound->getLBracLoc(), diag::warn_suggest_noreturn_function);
2698 break;
2699 case NeverFallThrough:
2700 break;
2701 }
2702 }
2703}
2704
2705/// CheckFallThroughForBlock - Check that we don't fall off the end of a block
2706/// that should return a value. Check that we don't fall off the end of a
2707/// noreturn block. We assume that functions and blocks not marked noreturn
2708/// will return.
2709void Sema::CheckFallThroughForBlock(QualType BlockTy, Stmt *Body,
2710 AnalysisContext &AC) {
2711 // FIXME: Would be nice if we had a better way to control cascading errors,
2712 // but for now, avoid them. The problem is that when Parse sees:
2713 // int foo() { return a; }
2714 // The return is eaten and the Sema code sees just:
2715 // int foo() { }
2716 // which this code would then warn about.
2717 if (getDiagnostics().hasErrorOccurred())
2718 return;
2719 bool ReturnsVoid = false;
2720 bool HasNoReturn = false;
2721 if (const FunctionType *FT =BlockTy->getPointeeType()->getAs<FunctionType>()){
2722 if (FT->getResultType()->isVoidType())
2723 ReturnsVoid = true;
2724 if (FT->getNoReturnAttr())
2725 HasNoReturn = true;
2726 }
2727
2728 // Short circuit for compilation speed.
2729 if (ReturnsVoid
2730 && !HasNoReturn
2731 && (Diags.getDiagnosticLevel(diag::warn_suggest_noreturn_block)
2732 == Diagnostic::Ignored || !ReturnsVoid))
2733 return;
2734 // FIXME: Funtion try block
2735 if (CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) {
2736 switch (CheckFallThrough(AC)) {
2737 case MaybeFallThrough:
2738 if (HasNoReturn)
2739 Diag(Compound->getRBracLoc(), diag::err_noreturn_block_has_return_expr);
2740 else if (!ReturnsVoid)
2741 Diag(Compound->getRBracLoc(), diag::err_maybe_falloff_nonvoid_block);
2742 break;
2743 case AlwaysFallThrough:
2744 if (HasNoReturn)
2745 Diag(Compound->getRBracLoc(), diag::err_noreturn_block_has_return_expr);
2746 else if (!ReturnsVoid)
2747 Diag(Compound->getRBracLoc(), diag::err_falloff_nonvoid_block);
2748 break;
2749 case NeverFallThroughOrReturn:
2750 if (ReturnsVoid)
2751 Diag(Compound->getLBracLoc(), diag::warn_suggest_noreturn_block);
2752 break;
2753 case NeverFallThrough:
2754 break;
2755 }
2756 }
2757}
2758
2759/// CheckParmsForFunctionDef - Check that the parameters of the given
2760/// function are appropriate for the definition of a function. This
2761/// takes care of any checks that cannot be performed on the
2762/// declaration itself, e.g., that the types of each of the function
2763/// parameters are complete.
2764bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
2765 bool HasInvalidParm = false;
2766 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2767 ParmVarDecl *Param = FD->getParamDecl(p);
2768
2769 // C99 6.7.5.3p4: the parameters in a parameter type list in a
2770 // function declarator that is part of a function definition of
2771 // that function shall not have incomplete type.
2772 //
2773 // This is also C++ [dcl.fct]p6.
2774 if (!Param->isInvalidDecl() &&
2775 RequireCompleteType(Param->getLocation(), Param->getType(),
2776 diag::err_typecheck_decl_incomplete_type)) {
2777 Param->setInvalidDecl();
2778 HasInvalidParm = true;
2779 }
2780
2781 // C99 6.9.1p5: If the declarator includes a parameter type list, the
2782 // declaration of each parameter shall include an identifier.
2783 if (Param->getIdentifier() == 0 &&
2784 !Param->isImplicit() &&
2785 !getLangOptions().CPlusPlus)
2786 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
2787 }
2788
2789 return HasInvalidParm;
2790}