blob: d6095fc2ae5bb3b26ca0d10c1dc8c0200416c1bc [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//
10// This file implements extra semantic analysis beyond what is enforced
11// by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
15#include "Sema.h"
16#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000017#include "clang/AST/DeclObjC.h"
Ted Kremenek23245122007-08-20 16:18:38 +000018#include "clang/AST/ExprCXX.h"
Ted Kremenek7ff22b22008-06-16 18:00:42 +000019#include "clang/AST/ExprObjC.h"
Chris Lattner719e6152009-02-18 19:21:10 +000020#include "clang/Lex/LiteralSupport.h"
Chris Lattner59907c42007-08-10 20:18:51 +000021#include "clang/Lex/Preprocessor.h"
Zhongxing Xua1f3dba2009-05-20 01:55:10 +000022#include <limits>
Chris Lattner59907c42007-08-10 20:18:51 +000023using namespace clang;
24
Chris Lattner60800082009-02-18 17:49:48 +000025/// getLocationOfStringLiteralByte - Return a source location that points to the
26/// specified byte of the specified string literal.
27///
28/// Strings are amazingly complex. They can be formed from multiple tokens and
29/// can have escape sequences in them in addition to the usual trigraph and
30/// escaped newline business. This routine handles this complexity.
31///
32SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
33 unsigned ByteNo) const {
34 assert(!SL->isWide() && "This doesn't work for wide strings yet");
35
36 // Loop over all of the tokens in this string until we find the one that
37 // contains the byte we're looking for.
38 unsigned TokNo = 0;
39 while (1) {
40 assert(TokNo < SL->getNumConcatenated() && "Invalid byte number!");
41 SourceLocation StrTokLoc = SL->getStrTokenLoc(TokNo);
42
43 // Get the spelling of the string so that we can get the data that makes up
44 // the string literal, not the identifier for the macro it is potentially
45 // expanded through.
46 SourceLocation StrTokSpellingLoc = SourceMgr.getSpellingLoc(StrTokLoc);
47
48 // Re-lex the token to get its length and original spelling.
49 std::pair<FileID, unsigned> LocInfo =
50 SourceMgr.getDecomposedLoc(StrTokSpellingLoc);
51 std::pair<const char *,const char *> Buffer =
52 SourceMgr.getBufferData(LocInfo.first);
53 const char *StrData = Buffer.first+LocInfo.second;
54
55 // Create a langops struct and enable trigraphs. This is sufficient for
56 // relexing tokens.
57 LangOptions LangOpts;
58 LangOpts.Trigraphs = true;
59
60 // Create a lexer starting at the beginning of this token.
61 Lexer TheLexer(StrTokSpellingLoc, LangOpts, Buffer.first, StrData,
62 Buffer.second);
63 Token TheTok;
64 TheLexer.LexFromRawLexer(TheTok);
65
Chris Lattner443e53c2009-02-18 19:26:42 +000066 // Use the StringLiteralParser to compute the length of the string in bytes.
67 StringLiteralParser SLP(&TheTok, 1, PP);
68 unsigned TokNumBytes = SLP.GetStringLength();
Chris Lattnerd0d082f2009-02-18 18:34:12 +000069
Chris Lattner2197c962009-02-18 18:52:52 +000070 // If the byte is in this token, return the location of the byte.
Chris Lattner60800082009-02-18 17:49:48 +000071 if (ByteNo < TokNumBytes ||
72 (ByteNo == TokNumBytes && TokNo == SL->getNumConcatenated())) {
Chris Lattner719e6152009-02-18 19:21:10 +000073 unsigned Offset =
74 StringLiteralParser::getOffsetOfStringByte(TheTok, ByteNo, PP);
75
76 // Now that we know the offset of the token in the spelling, use the
77 // preprocessor to get the offset in the original source.
78 return PP.AdvanceToTokenCharacter(StrTokLoc, Offset);
Chris Lattner60800082009-02-18 17:49:48 +000079 }
80
81 // Move to the next string token.
82 ++TokNo;
83 ByteNo -= TokNumBytes;
84 }
85}
86
87
Chris Lattner59907c42007-08-10 20:18:51 +000088/// CheckFunctionCall - Check a direct function call for various correctness
89/// and safety properties not strictly enforced by the C type system.
Sebastian Redl0eb23302009-01-19 00:08:26 +000090Action::OwningExprResult
91Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
92 OwningExprResult TheCallResult(Owned(TheCall));
Chris Lattner59907c42007-08-10 20:18:51 +000093 // Get the IdentifierInfo* for the called function.
94 IdentifierInfo *FnInfo = FDecl->getIdentifier();
Douglas Gregor2def4832008-11-17 20:34:05 +000095
96 // None of the checks below are needed for functions that don't have
97 // simple names (e.g., C++ conversion functions).
98 if (!FnInfo)
Sebastian Redl0eb23302009-01-19 00:08:26 +000099 return move(TheCallResult);
Douglas Gregor2def4832008-11-17 20:34:05 +0000100
Douglas Gregor3c385e52009-02-14 18:57:46 +0000101 switch (FDecl->getBuiltinID(Context)) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000102 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +0000103 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +0000104 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner69039812009-02-18 06:01:06 +0000105 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000106 return ExprError();
107 return move(TheCallResult);
Ted Kremenek49ff7a12008-07-09 17:58:53 +0000108 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +0000109 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000110 if (SemaBuiltinVAStart(TheCall))
111 return ExprError();
112 return move(TheCallResult);
Chris Lattner1b9a0792007-12-20 00:26:33 +0000113 case Builtin::BI__builtin_isgreater:
114 case Builtin::BI__builtin_isgreaterequal:
115 case Builtin::BI__builtin_isless:
116 case Builtin::BI__builtin_islessequal:
117 case Builtin::BI__builtin_islessgreater:
118 case Builtin::BI__builtin_isunordered:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000119 if (SemaBuiltinUnorderedCompare(TheCall))
120 return ExprError();
121 return move(TheCallResult);
Eli Friedman6cfda232008-05-20 08:23:37 +0000122 case Builtin::BI__builtin_return_address:
123 case Builtin::BI__builtin_frame_address:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000124 if (SemaBuiltinStackAddress(TheCall))
125 return ExprError();
126 return move(TheCallResult);
Eli Friedmand38617c2008-05-14 19:38:39 +0000127 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000128 return SemaBuiltinShuffleVector(TheCall);
129 // TheCall will be freed by the smart pointer here, but that's fine, since
130 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000131 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000132 if (SemaBuiltinPrefetch(TheCall))
133 return ExprError();
134 return move(TheCallResult);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000135 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000136 if (SemaBuiltinObjectSize(TheCall))
137 return ExprError();
Eli Friedman586d6a82009-05-03 06:04:26 +0000138 return move(TheCallResult);
Eli Friedmand875fed2009-05-03 04:46:36 +0000139 case Builtin::BI__builtin_longjmp:
140 if (SemaBuiltinLongjmp(TheCall))
141 return ExprError();
Eli Friedman586d6a82009-05-03 06:04:26 +0000142 return move(TheCallResult);
Chris Lattner5caa3702009-05-08 06:58:22 +0000143 case Builtin::BI__sync_fetch_and_add:
144 case Builtin::BI__sync_fetch_and_sub:
145 case Builtin::BI__sync_fetch_and_or:
146 case Builtin::BI__sync_fetch_and_and:
147 case Builtin::BI__sync_fetch_and_xor:
Chris Lattnereebd9d22009-05-13 04:37:52 +0000148 case Builtin::BI__sync_fetch_and_nand:
Chris Lattner5caa3702009-05-08 06:58:22 +0000149 case Builtin::BI__sync_add_and_fetch:
150 case Builtin::BI__sync_sub_and_fetch:
151 case Builtin::BI__sync_and_and_fetch:
152 case Builtin::BI__sync_or_and_fetch:
153 case Builtin::BI__sync_xor_and_fetch:
Chris Lattnereebd9d22009-05-13 04:37:52 +0000154 case Builtin::BI__sync_nand_and_fetch:
Chris Lattner5caa3702009-05-08 06:58:22 +0000155 case Builtin::BI__sync_val_compare_and_swap:
156 case Builtin::BI__sync_bool_compare_and_swap:
157 case Builtin::BI__sync_lock_test_and_set:
158 case Builtin::BI__sync_lock_release:
159 if (SemaBuiltinAtomicOverloaded(TheCall))
160 return ExprError();
161 return move(TheCallResult);
Anders Carlsson71993dd2007-08-17 05:31:46 +0000162 }
Daniel Dunbarde454282008-10-02 18:44:07 +0000163
164 // FIXME: This mechanism should be abstracted to be less fragile and
165 // more efficient. For example, just map function ids to custom
166 // handlers.
167
Chris Lattner59907c42007-08-10 20:18:51 +0000168 // Printf checking.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000169 if (const FormatAttr *Format = FDecl->getAttr<FormatAttr>()) {
Douglas Gregor3c385e52009-02-14 18:57:46 +0000170 if (Format->getType() == "printf") {
Ted Kremenek3d692df2009-02-27 17:58:43 +0000171 bool HasVAListArg = Format->getFirstArg() == 0;
172 if (!HasVAListArg) {
173 if (const FunctionProtoType *Proto
174 = FDecl->getType()->getAsFunctionProtoType())
Douglas Gregor3c385e52009-02-14 18:57:46 +0000175 HasVAListArg = !Proto->isVariadic();
Ted Kremenek3d692df2009-02-27 17:58:43 +0000176 }
Douglas Gregor3c385e52009-02-14 18:57:46 +0000177 CheckPrintfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
Ted Kremenek3d692df2009-02-27 17:58:43 +0000178 HasVAListArg ? 0 : Format->getFirstArg() - 1);
Douglas Gregor3c385e52009-02-14 18:57:46 +0000179 }
Chris Lattner59907c42007-08-10 20:18:51 +0000180 }
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000181 for (const Attr *attr = FDecl->getAttrs();
Douglas Gregor68584ed2009-06-18 16:11:24 +0000182 attr; attr = attr->getNext()) {
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +0000183 if (const NonNullAttr *NonNull = dyn_cast<NonNullAttr>(attr))
184 CheckNonNullArguments(NonNull, TheCall);
185 }
Sebastian Redl0eb23302009-01-19 00:08:26 +0000186
187 return move(TheCallResult);
Anders Carlsson71993dd2007-08-17 05:31:46 +0000188}
189
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000190Action::OwningExprResult
191Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
192
193 OwningExprResult TheCallResult(Owned(TheCall));
194 // Printf checking.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000195 const FormatAttr *Format = NDecl->getAttr<FormatAttr>();
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000196 if (!Format)
197 return move(TheCallResult);
198 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
199 if (!V)
200 return move(TheCallResult);
201 QualType Ty = V->getType();
202 if (!Ty->isBlockPointerType())
203 return move(TheCallResult);
204 if (Format->getType() == "printf") {
205 bool HasVAListArg = Format->getFirstArg() == 0;
206 if (!HasVAListArg) {
207 const FunctionType *FT =
Ted Kremenek6217b802009-07-29 21:53:49 +0000208 Ty->getAs<BlockPointerType>()->getPointeeType()->getAsFunctionType();
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000209 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT))
210 HasVAListArg = !Proto->isVariadic();
211 }
212 CheckPrintfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
213 HasVAListArg ? 0 : Format->getFirstArg() - 1);
214 }
215 return move(TheCallResult);
216}
217
Chris Lattner5caa3702009-05-08 06:58:22 +0000218/// SemaBuiltinAtomicOverloaded - We have a call to a function like
219/// __sync_fetch_and_add, which is an overloaded function based on the pointer
220/// type of its first argument. The main ActOnCallExpr routines have already
221/// promoted the types of arguments because all of these calls are prototyped as
222/// void(...).
223///
224/// This function goes through and does final semantic checking for these
225/// builtins,
226bool Sema::SemaBuiltinAtomicOverloaded(CallExpr *TheCall) {
227 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
228 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
229
230 // Ensure that we have at least one argument to do type inference from.
231 if (TheCall->getNumArgs() < 1)
232 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
233 << 0 << TheCall->getCallee()->getSourceRange();
234
235 // Inspect the first argument of the atomic builtin. This should always be
236 // a pointer type, whose element is an integral scalar or pointer type.
237 // Because it is a pointer type, we don't have to worry about any implicit
238 // casts here.
239 Expr *FirstArg = TheCall->getArg(0);
240 if (!FirstArg->getType()->isPointerType())
241 return Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
242 << FirstArg->getType() << FirstArg->getSourceRange();
243
Ted Kremenek6217b802009-07-29 21:53:49 +0000244 QualType ValType = FirstArg->getType()->getAs<PointerType>()->getPointeeType();
Chris Lattner5caa3702009-05-08 06:58:22 +0000245 if (!ValType->isIntegerType() && !ValType->isPointerType() &&
246 !ValType->isBlockPointerType())
247 return Diag(DRE->getLocStart(),
248 diag::err_atomic_builtin_must_be_pointer_intptr)
249 << FirstArg->getType() << FirstArg->getSourceRange();
250
251 // We need to figure out which concrete builtin this maps onto. For example,
252 // __sync_fetch_and_add with a 2 byte object turns into
253 // __sync_fetch_and_add_2.
254#define BUILTIN_ROW(x) \
255 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
256 Builtin::BI##x##_8, Builtin::BI##x##_16 }
257
258 static const unsigned BuiltinIndices[][5] = {
259 BUILTIN_ROW(__sync_fetch_and_add),
260 BUILTIN_ROW(__sync_fetch_and_sub),
261 BUILTIN_ROW(__sync_fetch_and_or),
262 BUILTIN_ROW(__sync_fetch_and_and),
263 BUILTIN_ROW(__sync_fetch_and_xor),
Chris Lattnereebd9d22009-05-13 04:37:52 +0000264 BUILTIN_ROW(__sync_fetch_and_nand),
Chris Lattner5caa3702009-05-08 06:58:22 +0000265
266 BUILTIN_ROW(__sync_add_and_fetch),
267 BUILTIN_ROW(__sync_sub_and_fetch),
268 BUILTIN_ROW(__sync_and_and_fetch),
269 BUILTIN_ROW(__sync_or_and_fetch),
270 BUILTIN_ROW(__sync_xor_and_fetch),
Chris Lattnereebd9d22009-05-13 04:37:52 +0000271 BUILTIN_ROW(__sync_nand_and_fetch),
Chris Lattner5caa3702009-05-08 06:58:22 +0000272
273 BUILTIN_ROW(__sync_val_compare_and_swap),
274 BUILTIN_ROW(__sync_bool_compare_and_swap),
275 BUILTIN_ROW(__sync_lock_test_and_set),
276 BUILTIN_ROW(__sync_lock_release)
277 };
278#undef BUILTIN_ROW
279
280 // Determine the index of the size.
281 unsigned SizeIndex;
282 switch (Context.getTypeSize(ValType)/8) {
283 case 1: SizeIndex = 0; break;
284 case 2: SizeIndex = 1; break;
285 case 4: SizeIndex = 2; break;
286 case 8: SizeIndex = 3; break;
287 case 16: SizeIndex = 4; break;
288 default:
289 return Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
290 << FirstArg->getType() << FirstArg->getSourceRange();
291 }
292
293 // Each of these builtins has one pointer argument, followed by some number of
294 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
295 // that we ignore. Find out which row of BuiltinIndices to read from as well
296 // as the number of fixed args.
297 unsigned BuiltinID = FDecl->getBuiltinID(Context);
298 unsigned BuiltinIndex, NumFixed = 1;
299 switch (BuiltinID) {
300 default: assert(0 && "Unknown overloaded atomic builtin!");
301 case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break;
302 case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break;
303 case Builtin::BI__sync_fetch_and_or: BuiltinIndex = 2; break;
304 case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break;
305 case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break;
Chris Lattnereebd9d22009-05-13 04:37:52 +0000306 case Builtin::BI__sync_fetch_and_nand:BuiltinIndex = 5; break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000307
Chris Lattnereebd9d22009-05-13 04:37:52 +0000308 case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 6; break;
309 case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 7; break;
310 case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 8; break;
311 case Builtin::BI__sync_or_and_fetch: BuiltinIndex = 9; break;
312 case Builtin::BI__sync_xor_and_fetch: BuiltinIndex =10; break;
313 case Builtin::BI__sync_nand_and_fetch:BuiltinIndex =11; break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000314
315 case Builtin::BI__sync_val_compare_and_swap:
Chris Lattnereebd9d22009-05-13 04:37:52 +0000316 BuiltinIndex = 12;
Chris Lattner5caa3702009-05-08 06:58:22 +0000317 NumFixed = 2;
318 break;
319 case Builtin::BI__sync_bool_compare_and_swap:
Chris Lattnereebd9d22009-05-13 04:37:52 +0000320 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +0000321 NumFixed = 2;
322 break;
Chris Lattnereebd9d22009-05-13 04:37:52 +0000323 case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 14; break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000324 case Builtin::BI__sync_lock_release:
Chris Lattnereebd9d22009-05-13 04:37:52 +0000325 BuiltinIndex = 15;
Chris Lattner5caa3702009-05-08 06:58:22 +0000326 NumFixed = 0;
327 break;
328 }
329
330 // Now that we know how many fixed arguments we expect, first check that we
331 // have at least that many.
332 if (TheCall->getNumArgs() < 1+NumFixed)
333 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
334 << 0 << TheCall->getCallee()->getSourceRange();
335
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000336
337 // Get the decl for the concrete builtin from this, we can tell what the
338 // concrete integer type we should convert to is.
339 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
340 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
341 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
342 FunctionDecl *NewBuiltinDecl =
343 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
344 TUScope, false, DRE->getLocStart()));
345 const FunctionProtoType *BuiltinFT =
346 NewBuiltinDecl->getType()->getAsFunctionProtoType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000347 ValType = BuiltinFT->getArgType(0)->getAs<PointerType>()->getPointeeType();
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000348
349 // If the first type needs to be converted (e.g. void** -> int*), do it now.
350 if (BuiltinFT->getArgType(0) != FirstArg->getType()) {
Anders Carlsson3503d042009-07-31 01:23:52 +0000351 ImpCastExprToType(FirstArg, BuiltinFT->getArgType(0), CastExpr::CK_Unknown,
352 /*isLvalue=*/false);
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000353 TheCall->setArg(0, FirstArg);
354 }
355
Chris Lattner5caa3702009-05-08 06:58:22 +0000356 // Next, walk the valid ones promoting to the right type.
357 for (unsigned i = 0; i != NumFixed; ++i) {
358 Expr *Arg = TheCall->getArg(i+1);
359
360 // If the argument is an implicit cast, then there was a promotion due to
361 // "...", just remove it now.
362 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
363 Arg = ICE->getSubExpr();
364 ICE->setSubExpr(0);
365 ICE->Destroy(Context);
366 TheCall->setArg(i+1, Arg);
367 }
368
369 // GCC does an implicit conversion to the pointer or integer ValType. This
370 // can fail in some cases (1i -> int**), check for this error case now.
371 if (CheckCastTypes(Arg->getSourceRange(), ValType, Arg))
372 return true;
373
374 // Okay, we have something that *can* be converted to the right type. Check
375 // to see if there is a potentially weird extension going on here. This can
376 // happen when you do an atomic operation on something like an char* and
377 // pass in 42. The 42 gets converted to char. This is even more strange
378 // for things like 45.123 -> char, etc.
379 // FIXME: Do this check.
Anders Carlsson3503d042009-07-31 01:23:52 +0000380 ImpCastExprToType(Arg, ValType, CastExpr::CK_Unknown,
381 /*isLvalue=*/false);
Chris Lattner5caa3702009-05-08 06:58:22 +0000382 TheCall->setArg(i+1, Arg);
383 }
384
Chris Lattner5caa3702009-05-08 06:58:22 +0000385 // Switch the DeclRefExpr to refer to the new decl.
386 DRE->setDecl(NewBuiltinDecl);
387 DRE->setType(NewBuiltinDecl->getType());
388
389 // Set the callee in the CallExpr.
390 // FIXME: This leaks the original parens and implicit casts.
391 Expr *PromotedCall = DRE;
392 UsualUnaryConversions(PromotedCall);
393 TheCall->setCallee(PromotedCall);
394
395
396 // Change the result type of the call to match the result type of the decl.
397 TheCall->setType(NewBuiltinDecl->getResultType());
398 return false;
399}
400
401
Chris Lattner69039812009-02-18 06:01:06 +0000402/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +0000403/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +0000404/// FIXME: GCC currently emits the following warning:
405/// "warning: input conversion stopped due to an input byte that does not
406/// belong to the input codeset UTF-8"
407/// Note: It might also make sense to do the UTF-16 conversion here (would
408/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +0000409bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +0000410 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000411 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
412
413 if (!Literal || Literal->isWide()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000414 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
415 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000416 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000417 }
418
419 const char *Data = Literal->getStrData();
420 unsigned Length = Literal->getByteLength();
421
422 for (unsigned i = 0; i < Length; ++i) {
Anders Carlsson71993dd2007-08-17 05:31:46 +0000423 if (!Data[i]) {
Chris Lattner60800082009-02-18 17:49:48 +0000424 Diag(getLocationOfStringLiteralByte(Literal, i),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000425 diag::warn_cfstring_literal_contains_nul_character)
426 << Arg->getSourceRange();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000427 break;
428 }
429 }
430
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000431 return false;
Chris Lattner59907c42007-08-10 20:18:51 +0000432}
433
Chris Lattnerc27c6652007-12-20 00:05:45 +0000434/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
435/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +0000436bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
437 Expr *Fn = TheCall->getCallee();
438 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +0000439 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000440 diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000441 << 0 /*function call*/ << Fn->getSourceRange()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000442 << SourceRange(TheCall->getArg(2)->getLocStart(),
443 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +0000444 return true;
445 }
Eli Friedman56f20ae2008-12-15 22:05:35 +0000446
447 if (TheCall->getNumArgs() < 2) {
448 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
449 << 0 /*function call*/;
450 }
451
Chris Lattnerc27c6652007-12-20 00:05:45 +0000452 // Determine whether the current function is variadic or not.
453 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000454 if (CurBlock)
455 isVariadic = CurBlock->isVariadic;
456 else if (getCurFunctionDecl()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000457 if (FunctionProtoType* FTP =
458 dyn_cast<FunctionProtoType>(getCurFunctionDecl()->getType()))
Eli Friedman56f20ae2008-12-15 22:05:35 +0000459 isVariadic = FTP->isVariadic();
460 else
461 isVariadic = false;
462 } else {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000463 isVariadic = getCurMethodDecl()->isVariadic();
Eli Friedman56f20ae2008-12-15 22:05:35 +0000464 }
Chris Lattner30ce3442007-12-19 23:59:04 +0000465
Chris Lattnerc27c6652007-12-20 00:05:45 +0000466 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000467 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
468 return true;
469 }
470
471 // Verify that the second argument to the builtin is the last argument of the
472 // current function or method.
473 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +0000474 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Anders Carlsson88cf2262008-02-11 04:20:54 +0000475
476 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
477 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000478 // FIXME: This isn't correct for methods (results in bogus warning).
479 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +0000480 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000481 if (CurBlock)
482 LastArg = *(CurBlock->TheDecl->param_end()-1);
483 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +0000484 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000485 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000486 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000487 SecondArgIsLastNamedArgument = PV == LastArg;
488 }
489 }
490
491 if (!SecondArgIsLastNamedArgument)
Chris Lattner925e60d2007-12-28 05:29:59 +0000492 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +0000493 diag::warn_second_parameter_of_va_start_not_last_named_argument);
494 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +0000495}
Chris Lattner30ce3442007-12-19 23:59:04 +0000496
Chris Lattner1b9a0792007-12-20 00:26:33 +0000497/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
498/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +0000499bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
500 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +0000501 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
502 << 0 /*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +0000503 if (TheCall->getNumArgs() > 2)
504 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000505 diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000506 << 0 /*function call*/
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000507 << SourceRange(TheCall->getArg(2)->getLocStart(),
508 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner1b9a0792007-12-20 00:26:33 +0000509
Chris Lattner925e60d2007-12-28 05:29:59 +0000510 Expr *OrigArg0 = TheCall->getArg(0);
511 Expr *OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +0000512
Chris Lattner1b9a0792007-12-20 00:26:33 +0000513 // Do standard promotions between the two arguments, returning their common
514 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +0000515 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
Daniel Dunbar403bc2b2009-02-19 19:28:43 +0000516
517 // Make sure any conversions are pushed back into the call; this is
518 // type safe since unordered compare builtins are declared as "_Bool
519 // foo(...)".
520 TheCall->setArg(0, OrigArg0);
521 TheCall->setArg(1, OrigArg1);
Chris Lattner1b9a0792007-12-20 00:26:33 +0000522
Douglas Gregorcde01732009-05-19 22:10:17 +0000523 if (OrigArg0->isTypeDependent() || OrigArg1->isTypeDependent())
524 return false;
525
Chris Lattner1b9a0792007-12-20 00:26:33 +0000526 // If the common type isn't a real floating type, then the arguments were
527 // invalid for this operation.
528 if (!Res->isRealFloatingType())
Chris Lattner925e60d2007-12-28 05:29:59 +0000529 return Diag(OrigArg0->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000530 diag::err_typecheck_call_invalid_ordered_compare)
Chris Lattnerd1625842008-11-24 06:25:27 +0000531 << OrigArg0->getType() << OrigArg1->getType()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000532 << SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd());
Chris Lattner1b9a0792007-12-20 00:26:33 +0000533
534 return false;
535}
536
Eli Friedman6cfda232008-05-20 08:23:37 +0000537bool Sema::SemaBuiltinStackAddress(CallExpr *TheCall) {
538 // The signature for these builtins is exact; the only thing we need
539 // to check is that the argument is a constant.
540 SourceLocation Loc;
Douglas Gregorcde01732009-05-19 22:10:17 +0000541 if (!TheCall->getArg(0)->isTypeDependent() &&
542 !TheCall->getArg(0)->isValueDependent() &&
543 !TheCall->getArg(0)->isIntegerConstantExpr(Context, &Loc))
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000544 return Diag(Loc, diag::err_stack_const_level) << TheCall->getSourceRange();
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000545
Eli Friedman6cfda232008-05-20 08:23:37 +0000546 return false;
547}
548
Eli Friedmand38617c2008-05-14 19:38:39 +0000549/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
550// This is declared to take (...), so we have to check everything.
Sebastian Redl0eb23302009-01-19 00:08:26 +0000551Action::OwningExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000552 if (TheCall->getNumArgs() < 3)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000553 return ExprError(Diag(TheCall->getLocEnd(),
554 diag::err_typecheck_call_too_few_args)
555 << 0 /*function call*/ << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000556
Douglas Gregorcde01732009-05-19 22:10:17 +0000557 unsigned numElements = std::numeric_limits<unsigned>::max();
558 if (!TheCall->getArg(0)->isTypeDependent() &&
559 !TheCall->getArg(1)->isTypeDependent()) {
560 QualType FAType = TheCall->getArg(0)->getType();
561 QualType SAType = TheCall->getArg(1)->getType();
562
563 if (!FAType->isVectorType() || !SAType->isVectorType()) {
564 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
565 << SourceRange(TheCall->getArg(0)->getLocStart(),
566 TheCall->getArg(1)->getLocEnd());
567 return ExprError();
568 }
569
570 if (Context.getCanonicalType(FAType).getUnqualifiedType() !=
571 Context.getCanonicalType(SAType).getUnqualifiedType()) {
572 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
573 << SourceRange(TheCall->getArg(0)->getLocStart(),
574 TheCall->getArg(1)->getLocEnd());
575 return ExprError();
576 }
Eli Friedmand38617c2008-05-14 19:38:39 +0000577
Douglas Gregorcde01732009-05-19 22:10:17 +0000578 numElements = FAType->getAsVectorType()->getNumElements();
579 if (TheCall->getNumArgs() != numElements+2) {
580 if (TheCall->getNumArgs() < numElements+2)
581 return ExprError(Diag(TheCall->getLocEnd(),
582 diag::err_typecheck_call_too_few_args)
583 << 0 /*function call*/ << TheCall->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +0000584 return ExprError(Diag(TheCall->getLocEnd(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000585 diag::err_typecheck_call_too_many_args)
586 << 0 /*function call*/ << TheCall->getSourceRange());
587 }
Eli Friedmand38617c2008-05-14 19:38:39 +0000588 }
589
590 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000591 if (TheCall->getArg(i)->isTypeDependent() ||
592 TheCall->getArg(i)->isValueDependent())
593 continue;
594
Eli Friedmand38617c2008-05-14 19:38:39 +0000595 llvm::APSInt Result(32);
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000596 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000597 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000598 diag::err_shufflevector_nonconstant_argument)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000599 << TheCall->getArg(i)->getSourceRange());
600
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000601 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000602 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000603 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000604 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000605 }
606
607 llvm::SmallVector<Expr*, 32> exprs;
608
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000609 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000610 exprs.push_back(TheCall->getArg(i));
611 TheCall->setArg(i, 0);
612 }
613
Douglas Gregorcde01732009-05-19 22:10:17 +0000614 return Owned(new (Context) ShuffleVectorExpr(exprs.begin(), exprs.size(),
615 exprs[0]->getType(),
Ted Kremenek8189cde2009-02-07 01:47:29 +0000616 TheCall->getCallee()->getLocStart(),
617 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +0000618}
Chris Lattner30ce3442007-12-19 23:59:04 +0000619
Daniel Dunbar4493f792008-07-21 22:59:13 +0000620/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
621// This is declared to take (const void*, ...) and can take two
622// optional constant int args.
623bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000624 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000625
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000626 if (NumArgs > 3)
627 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000628 << 0 /*function call*/ << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000629
630 // Argument 0 is checked for us and the remaining arguments must be
631 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000632 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +0000633 Expr *Arg = TheCall->getArg(i);
Douglas Gregorcde01732009-05-19 22:10:17 +0000634 if (Arg->isTypeDependent())
635 continue;
636
Daniel Dunbar4493f792008-07-21 22:59:13 +0000637 QualType RWType = Arg->getType();
638
639 const BuiltinType *BT = RWType->getAsBuiltinType();
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000640 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +0000641 if (!BT || BT->getKind() != BuiltinType::Int)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000642 return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_argument)
643 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Douglas Gregorcde01732009-05-19 22:10:17 +0000644
645 if (Arg->isValueDependent())
646 continue;
647
648 if (!Arg->isIntegerConstantExpr(Result, Context))
649 return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_argument)
650 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar4493f792008-07-21 22:59:13 +0000651
652 // FIXME: gcc issues a warning and rewrites these to 0. These
653 // seems especially odd for the third argument since the default
654 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000655 if (i == 1) {
Daniel Dunbar4493f792008-07-21 22:59:13 +0000656 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000657 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
658 << "0" << "1" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar4493f792008-07-21 22:59:13 +0000659 } else {
660 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000661 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
662 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar4493f792008-07-21 22:59:13 +0000663 }
664 }
665
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000666 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +0000667}
668
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000669/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
670/// int type). This simply type checks that type is one of the defined
671/// constants (0-3).
672bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
673 Expr *Arg = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +0000674 if (Arg->isTypeDependent())
675 return false;
676
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000677 QualType ArgType = Arg->getType();
678 const BuiltinType *BT = ArgType->getAsBuiltinType();
679 llvm::APSInt Result(32);
Douglas Gregorcde01732009-05-19 22:10:17 +0000680 if (!BT || BT->getKind() != BuiltinType::Int)
681 return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument)
682 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
683
684 if (Arg->isValueDependent())
685 return false;
686
687 if (!Arg->isIntegerConstantExpr(Result, Context)) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000688 return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument)
689 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000690 }
691
692 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000693 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
694 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000695 }
696
697 return false;
698}
699
Eli Friedman586d6a82009-05-03 06:04:26 +0000700/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +0000701/// This checks that val is a constant 1.
702bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
703 Expr *Arg = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +0000704 if (Arg->isTypeDependent() || Arg->isValueDependent())
705 return false;
706
Eli Friedmand875fed2009-05-03 04:46:36 +0000707 llvm::APSInt Result(32);
708 if (!Arg->isIntegerConstantExpr(Result, Context) || Result != 1)
709 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
710 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
711
712 return false;
713}
714
Ted Kremenekd30ef872009-01-12 23:09:09 +0000715// Handle i > 1 ? "x" : "y", recursivelly
Ted Kremenek082d9362009-03-20 21:35:28 +0000716bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
717 bool HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000718 unsigned format_idx, unsigned firstDataArg) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000719 if (E->isTypeDependent() || E->isValueDependent())
720 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000721
722 switch (E->getStmtClass()) {
723 case Stmt::ConditionalOperatorClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +0000724 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000725 return SemaCheckStringLiteral(C->getLHS(), TheCall,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000726 HasVAListArg, format_idx, firstDataArg)
Ted Kremenekd30ef872009-01-12 23:09:09 +0000727 && SemaCheckStringLiteral(C->getRHS(), TheCall,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000728 HasVAListArg, format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000729 }
730
731 case Stmt::ImplicitCastExprClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +0000732 const ImplicitCastExpr *Expr = cast<ImplicitCastExpr>(E);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000733 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000734 format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000735 }
736
737 case Stmt::ParenExprClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +0000738 const ParenExpr *Expr = cast<ParenExpr>(E);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000739 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000740 format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000741 }
Ted Kremenek082d9362009-03-20 21:35:28 +0000742
743 case Stmt::DeclRefExprClass: {
744 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
745
746 // As an exception, do not flag errors for variables binding to
747 // const string literals.
748 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
749 bool isConstant = false;
750 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +0000751
Ted Kremenek082d9362009-03-20 21:35:28 +0000752 if (const ArrayType *AT = Context.getAsArrayType(T)) {
753 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000754 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Ted Kremenek082d9362009-03-20 21:35:28 +0000755 isConstant = T.isConstant(Context) &&
756 PT->getPointeeType().isConstant(Context);
757 }
758
759 if (isConstant) {
760 const VarDecl *Def = 0;
761 if (const Expr *Init = VD->getDefinition(Def))
762 return SemaCheckStringLiteral(Init, TheCall,
763 HasVAListArg, format_idx, firstDataArg);
764 }
Anders Carlssond966a552009-06-28 19:55:58 +0000765
766 // For vprintf* functions (i.e., HasVAListArg==true), we add a
767 // special check to see if the format string is a function parameter
768 // of the function calling the printf function. If the function
769 // has an attribute indicating it is a printf-like function, then we
770 // should suppress warnings concerning non-literals being used in a call
771 // to a vprintf function. For example:
772 //
773 // void
774 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
775 // va_list ap;
776 // va_start(ap, fmt);
777 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
778 // ...
779 //
780 //
781 // FIXME: We don't have full attribute support yet, so just check to see
782 // if the argument is a DeclRefExpr that references a parameter. We'll
783 // add proper support for checking the attribute later.
784 if (HasVAListArg)
785 if (isa<ParmVarDecl>(VD))
786 return true;
Ted Kremenek082d9362009-03-20 21:35:28 +0000787 }
788
789 return false;
790 }
Ted Kremenekd30ef872009-01-12 23:09:09 +0000791
Anders Carlsson8f031b32009-06-27 04:05:33 +0000792 case Stmt::CallExprClass: {
793 const CallExpr *CE = cast<CallExpr>(E);
794 if (const ImplicitCastExpr *ICE
795 = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
796 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
797 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000798 if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
Anders Carlsson8f031b32009-06-27 04:05:33 +0000799 unsigned ArgIndex = FA->getFormatIdx();
800 const Expr *Arg = CE->getArg(ArgIndex - 1);
801
802 return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg,
803 format_idx, firstDataArg);
804 }
805 }
806 }
807 }
808
809 return false;
810 }
Ted Kremenek082d9362009-03-20 21:35:28 +0000811 case Stmt::ObjCStringLiteralClass:
812 case Stmt::StringLiteralClass: {
813 const StringLiteral *StrE = NULL;
814
815 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +0000816 StrE = ObjCFExpr->getString();
817 else
Ted Kremenek082d9362009-03-20 21:35:28 +0000818 StrE = cast<StringLiteral>(E);
819
Ted Kremenekd30ef872009-01-12 23:09:09 +0000820 if (StrE) {
Douglas Gregor3c385e52009-02-14 18:57:46 +0000821 CheckPrintfString(StrE, E, TheCall, HasVAListArg, format_idx,
822 firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000823 return true;
824 }
825
826 return false;
827 }
Ted Kremenek082d9362009-03-20 21:35:28 +0000828
829 default:
830 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000831 }
832}
833
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +0000834void
835Sema::CheckNonNullArguments(const NonNullAttr *NonNull, const CallExpr *TheCall)
836{
837 for (NonNullAttr::iterator i = NonNull->begin(), e = NonNull->end();
838 i != e; ++i) {
Chris Lattner12b97ff2009-05-25 18:23:36 +0000839 const Expr *ArgExpr = TheCall->getArg(*i);
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +0000840 if (ArgExpr->isNullPointerConstant(Context))
Chris Lattner12b97ff2009-05-25 18:23:36 +0000841 Diag(TheCall->getCallee()->getLocStart(), diag::warn_null_arg)
842 << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +0000843 }
844}
Ted Kremenekd30ef872009-01-12 23:09:09 +0000845
Chris Lattner59907c42007-08-10 20:18:51 +0000846/// CheckPrintfArguments - Check calls to printf (and similar functions) for
Ted Kremenek71895b92007-08-14 17:39:48 +0000847/// correct use of format strings.
848///
849/// HasVAListArg - A predicate indicating whether the printf-like
850/// function is passed an explicit va_arg argument (e.g., vprintf)
851///
852/// format_idx - The index into Args for the format string.
853///
854/// Improper format strings to functions in the printf family can be
855/// the source of bizarre bugs and very serious security holes. A
856/// good source of information is available in the following paper
857/// (which includes additional references):
Chris Lattner59907c42007-08-10 20:18:51 +0000858///
859/// FormatGuard: Automatic Protection From printf Format String
860/// Vulnerabilities, Proceedings of the 10th USENIX Security Symposium, 2001.
Ted Kremenek71895b92007-08-14 17:39:48 +0000861///
862/// Functionality implemented:
863///
864/// We can statically check the following properties for string
865/// literal format strings for non v.*printf functions (where the
866/// arguments are passed directly):
867//
868/// (1) Are the number of format conversions equal to the number of
869/// data arguments?
870///
871/// (2) Does each format conversion correctly match the type of the
872/// corresponding data argument? (TODO)
873///
874/// Moreover, for all printf functions we can:
875///
876/// (3) Check for a missing format string (when not caught by type checking).
877///
878/// (4) Check for no-operation flags; e.g. using "#" with format
879/// conversion 'c' (TODO)
880///
881/// (5) Check the use of '%n', a major source of security holes.
882///
883/// (6) Check for malformed format conversions that don't specify anything.
884///
885/// (7) Check for empty format strings. e.g: printf("");
886///
887/// (8) Check that the format string is a wide literal.
888///
Ted Kremenek6d439592008-03-03 16:50:00 +0000889/// (9) Also check the arguments of functions with the __format__ attribute.
890/// (TODO).
891///
Ted Kremenek71895b92007-08-14 17:39:48 +0000892/// All of these checks can be done by parsing the format string.
893///
894/// For now, we ONLY do (1), (3), (5), (6), (7), and (8).
Chris Lattner59907c42007-08-10 20:18:51 +0000895void
Ted Kremenek082d9362009-03-20 21:35:28 +0000896Sema::CheckPrintfArguments(const CallExpr *TheCall, bool HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000897 unsigned format_idx, unsigned firstDataArg) {
Ted Kremenek082d9362009-03-20 21:35:28 +0000898 const Expr *Fn = TheCall->getCallee();
Chris Lattner925e60d2007-12-28 05:29:59 +0000899
Ted Kremenek71895b92007-08-14 17:39:48 +0000900 // CHECK: printf-like function is called with no format string.
Chris Lattner925e60d2007-12-28 05:29:59 +0000901 if (format_idx >= TheCall->getNumArgs()) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000902 Diag(TheCall->getRParenLoc(), diag::warn_printf_missing_format_string)
903 << Fn->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000904 return;
905 }
906
Ted Kremenek082d9362009-03-20 21:35:28 +0000907 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Chris Lattner459e8482007-08-25 05:36:18 +0000908
Chris Lattner59907c42007-08-10 20:18:51 +0000909 // CHECK: format string is not a string literal.
910 //
Ted Kremenek71895b92007-08-14 17:39:48 +0000911 // Dynamically generated format strings are difficult to
912 // automatically vet at compile time. Requiring that format strings
913 // are string literals: (1) permits the checking of format strings by
914 // the compiler and thereby (2) can practically remove the source of
915 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000916
917 // Format string can be either ObjC string (e.g. @"%d") or
918 // C string (e.g. "%d")
919 // ObjC string uses the same format specifiers as C string, so we can use
920 // the same format string checking logic for both ObjC and C strings.
Chris Lattner1cd3e1f2009-04-29 04:49:34 +0000921 if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
922 firstDataArg))
923 return; // Literal format string found, check done!
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000924
Chris Lattner655f1412009-04-29 04:59:47 +0000925 // If there are no arguments specified, warn with -Wformat-security, otherwise
926 // warn only with -Wformat-nonliteral.
927 if (TheCall->getNumArgs() == format_idx+1)
928 Diag(TheCall->getArg(format_idx)->getLocStart(),
929 diag::warn_printf_nonliteral_noargs)
930 << OrigFormatExpr->getSourceRange();
931 else
932 Diag(TheCall->getArg(format_idx)->getLocStart(),
933 diag::warn_printf_nonliteral)
934 << OrigFormatExpr->getSourceRange();
Ted Kremenekd30ef872009-01-12 23:09:09 +0000935}
Ted Kremenek71895b92007-08-14 17:39:48 +0000936
Ted Kremenek082d9362009-03-20 21:35:28 +0000937void Sema::CheckPrintfString(const StringLiteral *FExpr,
938 const Expr *OrigFormatExpr,
939 const CallExpr *TheCall, bool HasVAListArg,
940 unsigned format_idx, unsigned firstDataArg) {
Ted Kremenekd30ef872009-01-12 23:09:09 +0000941
Ted Kremenek082d9362009-03-20 21:35:28 +0000942 const ObjCStringLiteral *ObjCFExpr =
943 dyn_cast<ObjCStringLiteral>(OrigFormatExpr);
944
Ted Kremenek71895b92007-08-14 17:39:48 +0000945 // CHECK: is the format string a wide literal?
946 if (FExpr->isWide()) {
Chris Lattner925e60d2007-12-28 05:29:59 +0000947 Diag(FExpr->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000948 diag::warn_printf_format_string_is_wide_literal)
949 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000950 return;
951 }
952
953 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattnerb9fc8562009-04-29 04:12:34 +0000954 const char *Str = FExpr->getStrData();
Ted Kremenek71895b92007-08-14 17:39:48 +0000955
956 // CHECK: empty format string?
Chris Lattnerb9fc8562009-04-29 04:12:34 +0000957 unsigned StrLen = FExpr->getByteLength();
Ted Kremenek71895b92007-08-14 17:39:48 +0000958
959 if (StrLen == 0) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000960 Diag(FExpr->getLocStart(), diag::warn_printf_empty_format_string)
961 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000962 return;
963 }
964
965 // We process the format string using a binary state machine. The
966 // current state is stored in CurrentState.
967 enum {
968 state_OrdChr,
969 state_Conversion
970 } CurrentState = state_OrdChr;
971
972 // numConversions - The number of conversions seen so far. This is
973 // incremented as we traverse the format string.
974 unsigned numConversions = 0;
975
976 // numDataArgs - The number of data arguments after the format
977 // string. This can only be determined for non vprintf-like
978 // functions. For those functions, this value is 1 (the sole
979 // va_arg argument).
Douglas Gregor3c385e52009-02-14 18:57:46 +0000980 unsigned numDataArgs = TheCall->getNumArgs()-firstDataArg;
Ted Kremenek71895b92007-08-14 17:39:48 +0000981
982 // Inspect the format string.
983 unsigned StrIdx = 0;
984
985 // LastConversionIdx - Index within the format string where we last saw
986 // a '%' character that starts a new format conversion.
987 unsigned LastConversionIdx = 0;
988
Chris Lattner925e60d2007-12-28 05:29:59 +0000989 for (; StrIdx < StrLen; ++StrIdx) {
Chris Lattner998568f2007-12-28 05:38:24 +0000990
Ted Kremenek71895b92007-08-14 17:39:48 +0000991 // Is the number of detected conversion conversions greater than
992 // the number of matching data arguments? If so, stop.
993 if (!HasVAListArg && numConversions > numDataArgs) break;
994
995 // Handle "\0"
Chris Lattner925e60d2007-12-28 05:29:59 +0000996 if (Str[StrIdx] == '\0') {
Ted Kremenek71895b92007-08-14 17:39:48 +0000997 // The string returned by getStrData() is not null-terminated,
998 // so the presence of a null character is likely an error.
Chris Lattner60800082009-02-18 17:49:48 +0000999 Diag(getLocationOfStringLiteralByte(FExpr, StrIdx),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001000 diag::warn_printf_format_string_contains_null_char)
1001 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001002 return;
1003 }
1004
1005 // Ordinary characters (not processing a format conversion).
1006 if (CurrentState == state_OrdChr) {
1007 if (Str[StrIdx] == '%') {
1008 CurrentState = state_Conversion;
1009 LastConversionIdx = StrIdx;
1010 }
1011 continue;
1012 }
1013
1014 // Seen '%'. Now processing a format conversion.
1015 switch (Str[StrIdx]) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001016 // Handle dynamic precision or width specifier.
1017 case '*': {
1018 ++numConversions;
1019
Ted Kremenek42ae3e82009-05-13 16:06:05 +00001020 if (!HasVAListArg) {
1021 if (numConversions > numDataArgs) {
1022 SourceLocation Loc = getLocationOfStringLiteralByte(FExpr, StrIdx);
Ted Kremenek580b6642007-10-12 20:51:52 +00001023
Ted Kremenek42ae3e82009-05-13 16:06:05 +00001024 if (Str[StrIdx-1] == '.')
1025 Diag(Loc, diag::warn_printf_asterisk_precision_missing_arg)
1026 << OrigFormatExpr->getSourceRange();
1027 else
1028 Diag(Loc, diag::warn_printf_asterisk_width_missing_arg)
1029 << OrigFormatExpr->getSourceRange();
1030
1031 // Don't do any more checking. We'll just emit spurious errors.
1032 return;
1033 }
1034
1035 // Perform type checking on width/precision specifier.
1036 const Expr *E = TheCall->getArg(format_idx+numConversions);
1037 if (const BuiltinType *BT = E->getType()->getAsBuiltinType())
1038 if (BT->getKind() == BuiltinType::Int)
1039 break;
Ted Kremenek580b6642007-10-12 20:51:52 +00001040
Ted Kremenek42ae3e82009-05-13 16:06:05 +00001041 SourceLocation Loc = getLocationOfStringLiteralByte(FExpr, StrIdx);
1042
1043 if (Str[StrIdx-1] == '.')
1044 Diag(Loc, diag::warn_printf_asterisk_precision_wrong_type)
1045 << E->getType() << E->getSourceRange();
1046 else
1047 Diag(Loc, diag::warn_printf_asterisk_width_wrong_type)
1048 << E->getType() << E->getSourceRange();
1049
1050 break;
Ted Kremenek580b6642007-10-12 20:51:52 +00001051 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001052 }
1053
1054 // Characters which can terminate a format conversion
1055 // (e.g. "%d"). Characters that specify length modifiers or
1056 // other flags are handled by the default case below.
1057 //
1058 // FIXME: additional checks will go into the following cases.
1059 case 'i':
1060 case 'd':
1061 case 'o':
1062 case 'u':
1063 case 'x':
1064 case 'X':
1065 case 'D':
1066 case 'O':
1067 case 'U':
1068 case 'e':
1069 case 'E':
1070 case 'f':
1071 case 'F':
1072 case 'g':
1073 case 'G':
1074 case 'a':
1075 case 'A':
1076 case 'c':
1077 case 'C':
1078 case 'S':
1079 case 's':
1080 case 'p':
1081 ++numConversions;
1082 CurrentState = state_OrdChr;
1083 break;
1084
Eli Friedmanb92abb42009-06-02 08:36:19 +00001085 case 'm':
1086 // FIXME: Warn in situations where this isn't supported!
1087 CurrentState = state_OrdChr;
1088 break;
1089
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001090 // CHECK: Are we using "%n"? Issue a warning.
1091 case 'n': {
1092 ++numConversions;
1093 CurrentState = state_OrdChr;
Chris Lattner60800082009-02-18 17:49:48 +00001094 SourceLocation Loc = getLocationOfStringLiteralByte(FExpr,
1095 LastConversionIdx);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001096
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001097 Diag(Loc, diag::warn_printf_write_back)<<OrigFormatExpr->getSourceRange();
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001098 break;
1099 }
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001100
1101 // Handle "%@"
1102 case '@':
1103 // %@ is allowed in ObjC format strings only.
1104 if(ObjCFExpr != NULL)
1105 CurrentState = state_OrdChr;
1106 else {
1107 // Issue a warning: invalid format conversion.
Chris Lattner60800082009-02-18 17:49:48 +00001108 SourceLocation Loc =
1109 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001110
Chris Lattnerd3a94e22008-11-20 06:06:08 +00001111 Diag(Loc, diag::warn_printf_invalid_conversion)
1112 << std::string(Str+LastConversionIdx,
1113 Str+std::min(LastConversionIdx+2, StrLen))
1114 << OrigFormatExpr->getSourceRange();
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001115 }
1116 ++numConversions;
1117 break;
1118
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001119 // Handle "%%"
1120 case '%':
1121 // Sanity check: Was the first "%" character the previous one?
1122 // If not, we will assume that we have a malformed format
1123 // conversion, and that the current "%" character is the start
1124 // of a new conversion.
1125 if (StrIdx - LastConversionIdx == 1)
1126 CurrentState = state_OrdChr;
1127 else {
1128 // Issue a warning: invalid format conversion.
Chris Lattner60800082009-02-18 17:49:48 +00001129 SourceLocation Loc =
1130 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001131
Chris Lattnerd3a94e22008-11-20 06:06:08 +00001132 Diag(Loc, diag::warn_printf_invalid_conversion)
1133 << std::string(Str+LastConversionIdx, Str+StrIdx)
1134 << OrigFormatExpr->getSourceRange();
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001135
1136 // This conversion is broken. Advance to the next format
1137 // conversion.
1138 LastConversionIdx = StrIdx;
1139 ++numConversions;
Ted Kremenek71895b92007-08-14 17:39:48 +00001140 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001141 break;
Ted Kremenek71895b92007-08-14 17:39:48 +00001142
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001143 default:
1144 // This case catches all other characters: flags, widths, etc.
1145 // We should eventually process those as well.
1146 break;
Ted Kremenek71895b92007-08-14 17:39:48 +00001147 }
1148 }
1149
1150 if (CurrentState == state_Conversion) {
1151 // Issue a warning: invalid format conversion.
Chris Lattner60800082009-02-18 17:49:48 +00001152 SourceLocation Loc =
1153 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Ted Kremenek71895b92007-08-14 17:39:48 +00001154
Chris Lattnerd3a94e22008-11-20 06:06:08 +00001155 Diag(Loc, diag::warn_printf_invalid_conversion)
1156 << std::string(Str+LastConversionIdx,
1157 Str+std::min(LastConversionIdx+2, StrLen))
1158 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001159 return;
1160 }
1161
1162 if (!HasVAListArg) {
1163 // CHECK: Does the number of format conversions exceed the number
1164 // of data arguments?
1165 if (numConversions > numDataArgs) {
Chris Lattner60800082009-02-18 17:49:48 +00001166 SourceLocation Loc =
1167 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Ted Kremenek71895b92007-08-14 17:39:48 +00001168
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001169 Diag(Loc, diag::warn_printf_insufficient_data_args)
1170 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001171 }
1172 // CHECK: Does the number of data arguments exceed the number of
1173 // format conversions in the format string?
1174 else if (numConversions < numDataArgs)
Chris Lattner925e60d2007-12-28 05:29:59 +00001175 Diag(TheCall->getArg(format_idx+numConversions+1)->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001176 diag::warn_printf_too_many_data_args)
1177 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001178 }
1179}
Ted Kremenek06de2762007-08-17 16:46:58 +00001180
1181//===--- CHECK: Return Address of Stack Variable --------------------------===//
1182
1183static DeclRefExpr* EvalVal(Expr *E);
1184static DeclRefExpr* EvalAddr(Expr* E);
1185
1186/// CheckReturnStackAddr - Check if a return statement returns the address
1187/// of a stack variable.
1188void
1189Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
1190 SourceLocation ReturnLoc) {
Chris Lattner56f34942008-02-13 01:02:39 +00001191
Ted Kremenek06de2762007-08-17 16:46:58 +00001192 // Perform checking for returned stack addresses.
Steve Naroffdd972f22008-09-05 22:11:13 +00001193 if (lhsType->isPointerType() || lhsType->isBlockPointerType()) {
Ted Kremenek06de2762007-08-17 16:46:58 +00001194 if (DeclRefExpr *DR = EvalAddr(RetValExp))
Chris Lattner3c73c412008-11-19 08:23:25 +00001195 Diag(DR->getLocStart(), diag::warn_ret_stack_addr)
Chris Lattner08631c52008-11-23 21:45:46 +00001196 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Steve Naroffc50a4a52008-09-16 22:25:10 +00001197
1198 // Skip over implicit cast expressions when checking for block expressions.
1199 if (ImplicitCastExpr *IcExpr =
1200 dyn_cast_or_null<ImplicitCastExpr>(RetValExp))
1201 RetValExp = IcExpr->getSubExpr();
1202
Steve Naroff61f40a22008-09-10 19:17:48 +00001203 if (BlockExpr *C = dyn_cast_or_null<BlockExpr>(RetValExp))
Mike Stump397195b2009-04-17 00:09:41 +00001204 if (C->hasBlockDeclRefExprs())
1205 Diag(C->getLocStart(), diag::err_ret_local_block)
1206 << C->getSourceRange();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001207 } else if (lhsType->isReferenceType()) {
1208 // Perform checking for stack values returned by reference.
Douglas Gregor49badde2008-10-27 19:41:14 +00001209 // Check for a reference to the stack
1210 if (DeclRefExpr *DR = EvalVal(RetValExp))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001211 Diag(DR->getLocStart(), diag::warn_ret_stack_ref)
Chris Lattner08631c52008-11-23 21:45:46 +00001212 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Ted Kremenek06de2762007-08-17 16:46:58 +00001213 }
1214}
1215
1216/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
1217/// check if the expression in a return statement evaluates to an address
1218/// to a location on the stack. The recursion is used to traverse the
1219/// AST of the return expression, with recursion backtracking when we
1220/// encounter a subexpression that (1) clearly does not lead to the address
1221/// of a stack variable or (2) is something we cannot determine leads to
1222/// the address of a stack variable based on such local checking.
1223///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00001224/// EvalAddr processes expressions that are pointers that are used as
1225/// references (and not L-values). EvalVal handles all other values.
Ted Kremenek06de2762007-08-17 16:46:58 +00001226/// At the base case of the recursion is a check for a DeclRefExpr* in
1227/// the refers to a stack variable.
1228///
1229/// This implementation handles:
1230///
1231/// * pointer-to-pointer casts
1232/// * implicit conversions from array references to pointers
1233/// * taking the address of fields
1234/// * arbitrary interplay between "&" and "*" operators
1235/// * pointer arithmetic from an address of a stack variable
1236/// * taking the address of an array element where the array is on the stack
1237static DeclRefExpr* EvalAddr(Expr *E) {
Ted Kremenek06de2762007-08-17 16:46:58 +00001238 // We should only be called for evaluating pointer expressions.
Steve Naroffdd972f22008-09-05 22:11:13 +00001239 assert((E->getType()->isPointerType() ||
1240 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001241 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001242 "EvalAddr only works on pointers");
Ted Kremenek06de2762007-08-17 16:46:58 +00001243
1244 // Our "symbolic interpreter" is just a dispatch off the currently
1245 // viewed AST node. We then recursively traverse the AST by calling
1246 // EvalAddr and EvalVal appropriately.
1247 switch (E->getStmtClass()) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001248 case Stmt::ParenExprClass:
1249 // Ignore parentheses.
1250 return EvalAddr(cast<ParenExpr>(E)->getSubExpr());
Ted Kremenek06de2762007-08-17 16:46:58 +00001251
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001252 case Stmt::UnaryOperatorClass: {
1253 // The only unary operator that make sense to handle here
1254 // is AddrOf. All others don't make sense as pointers.
1255 UnaryOperator *U = cast<UnaryOperator>(E);
Ted Kremenek06de2762007-08-17 16:46:58 +00001256
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001257 if (U->getOpcode() == UnaryOperator::AddrOf)
1258 return EvalVal(U->getSubExpr());
1259 else
Ted Kremenek06de2762007-08-17 16:46:58 +00001260 return NULL;
1261 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001262
1263 case Stmt::BinaryOperatorClass: {
1264 // Handle pointer arithmetic. All other binary operators are not valid
1265 // in this context.
1266 BinaryOperator *B = cast<BinaryOperator>(E);
1267 BinaryOperator::Opcode op = B->getOpcode();
1268
1269 if (op != BinaryOperator::Add && op != BinaryOperator::Sub)
1270 return NULL;
1271
1272 Expr *Base = B->getLHS();
1273
1274 // Determine which argument is the real pointer base. It could be
1275 // the RHS argument instead of the LHS.
1276 if (!Base->getType()->isPointerType()) Base = B->getRHS();
1277
1278 assert (Base->getType()->isPointerType());
1279 return EvalAddr(Base);
1280 }
Steve Naroff61f40a22008-09-10 19:17:48 +00001281
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001282 // For conditional operators we need to see if either the LHS or RHS are
1283 // valid DeclRefExpr*s. If one of them is valid, we return it.
1284 case Stmt::ConditionalOperatorClass: {
1285 ConditionalOperator *C = cast<ConditionalOperator>(E);
1286
1287 // Handle the GNU extension for missing LHS.
1288 if (Expr *lhsExpr = C->getLHS())
1289 if (DeclRefExpr* LHS = EvalAddr(lhsExpr))
1290 return LHS;
1291
1292 return EvalAddr(C->getRHS());
1293 }
1294
Ted Kremenek54b52742008-08-07 00:49:01 +00001295 // For casts, we need to handle conversions from arrays to
1296 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00001297 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001298 case Stmt::CStyleCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00001299 case Stmt::CXXFunctionalCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001300 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenek54b52742008-08-07 00:49:01 +00001301 QualType T = SubExpr->getType();
1302
Steve Naroffdd972f22008-09-05 22:11:13 +00001303 if (SubExpr->getType()->isPointerType() ||
1304 SubExpr->getType()->isBlockPointerType() ||
1305 SubExpr->getType()->isObjCQualifiedIdType())
Ted Kremenek54b52742008-08-07 00:49:01 +00001306 return EvalAddr(SubExpr);
1307 else if (T->isArrayType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001308 return EvalVal(SubExpr);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001309 else
Ted Kremenek54b52742008-08-07 00:49:01 +00001310 return 0;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001311 }
1312
1313 // C++ casts. For dynamic casts, static casts, and const casts, we
1314 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor49badde2008-10-27 19:41:14 +00001315 // through the cast. In the case the dynamic cast doesn't fail (and
1316 // return NULL), we take the conservative route and report cases
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001317 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor49badde2008-10-27 19:41:14 +00001318 // FIXME: The comment about is wrong; we're not always converting
1319 // from pointer to pointer. I'm guessing that this code should also
1320 // handle references to objects.
1321 case Stmt::CXXStaticCastExprClass:
1322 case Stmt::CXXDynamicCastExprClass:
1323 case Stmt::CXXConstCastExprClass:
1324 case Stmt::CXXReinterpretCastExprClass: {
1325 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffdd972f22008-09-05 22:11:13 +00001326 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001327 return EvalAddr(S);
1328 else
1329 return NULL;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001330 }
1331
1332 // Everything else: we simply don't reason about them.
1333 default:
1334 return NULL;
1335 }
Ted Kremenek06de2762007-08-17 16:46:58 +00001336}
1337
1338
1339/// EvalVal - This function is complements EvalAddr in the mutual recursion.
1340/// See the comments for EvalAddr for more details.
1341static DeclRefExpr* EvalVal(Expr *E) {
1342
Ted Kremeneke8c600f2007-08-28 17:02:55 +00001343 // We should only be called for evaluating non-pointer expressions, or
1344 // expressions with a pointer type that are not used as references but instead
1345 // are l-values (e.g., DeclRefExpr with a pointer type).
1346
Ted Kremenek06de2762007-08-17 16:46:58 +00001347 // Our "symbolic interpreter" is just a dispatch off the currently
1348 // viewed AST node. We then recursively traverse the AST by calling
1349 // EvalAddr and EvalVal appropriately.
1350 switch (E->getStmtClass()) {
Douglas Gregor1a49af92009-01-06 05:10:23 +00001351 case Stmt::DeclRefExprClass:
1352 case Stmt::QualifiedDeclRefExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00001353 // DeclRefExpr: the base case. When we hit a DeclRefExpr we are looking
1354 // at code that refers to a variable's name. We check if it has local
1355 // storage within the function, and if so, return the expression.
1356 DeclRefExpr *DR = cast<DeclRefExpr>(E);
1357
1358 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001359 if(V->hasLocalStorage() && !V->getType()->isReferenceType()) return DR;
Ted Kremenek06de2762007-08-17 16:46:58 +00001360
1361 return NULL;
1362 }
1363
1364 case Stmt::ParenExprClass:
1365 // Ignore parentheses.
1366 return EvalVal(cast<ParenExpr>(E)->getSubExpr());
1367
1368 case Stmt::UnaryOperatorClass: {
1369 // The only unary operator that make sense to handle here
1370 // is Deref. All others don't resolve to a "name." This includes
1371 // handling all sorts of rvalues passed to a unary operator.
1372 UnaryOperator *U = cast<UnaryOperator>(E);
1373
1374 if (U->getOpcode() == UnaryOperator::Deref)
1375 return EvalAddr(U->getSubExpr());
1376
1377 return NULL;
1378 }
1379
1380 case Stmt::ArraySubscriptExprClass: {
1381 // Array subscripts are potential references to data on the stack. We
1382 // retrieve the DeclRefExpr* for the array variable if it indeed
1383 // has local storage.
Ted Kremenek23245122007-08-20 16:18:38 +00001384 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase());
Ted Kremenek06de2762007-08-17 16:46:58 +00001385 }
1386
1387 case Stmt::ConditionalOperatorClass: {
1388 // For conditional operators we need to see if either the LHS or RHS are
1389 // non-NULL DeclRefExpr's. If one is non-NULL, we return it.
1390 ConditionalOperator *C = cast<ConditionalOperator>(E);
1391
Anders Carlsson39073232007-11-30 19:04:31 +00001392 // Handle the GNU extension for missing LHS.
1393 if (Expr *lhsExpr = C->getLHS())
1394 if (DeclRefExpr *LHS = EvalVal(lhsExpr))
1395 return LHS;
1396
1397 return EvalVal(C->getRHS());
Ted Kremenek06de2762007-08-17 16:46:58 +00001398 }
1399
1400 // Accesses to members are potential references to data on the stack.
1401 case Stmt::MemberExprClass: {
1402 MemberExpr *M = cast<MemberExpr>(E);
1403
1404 // Check for indirect access. We only want direct field accesses.
1405 if (!M->isArrow())
1406 return EvalVal(M->getBase());
1407 else
1408 return NULL;
1409 }
1410
1411 // Everything else: we simply don't reason about them.
1412 default:
1413 return NULL;
1414 }
1415}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001416
1417//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
1418
1419/// Check for comparisons of floating point operands using != and ==.
1420/// Issue a warning if these are no self-comparisons, as they are not likely
1421/// to do what the programmer intended.
1422void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
1423 bool EmitWarning = true;
1424
Ted Kremenek4e99a5f2008-01-17 16:57:34 +00001425 Expr* LeftExprSansParen = lex->IgnoreParens();
Ted Kremenek32e97b62008-01-17 17:55:13 +00001426 Expr* RightExprSansParen = rex->IgnoreParens();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001427
1428 // Special case: check for x == x (which is OK).
1429 // Do not emit warnings for such cases.
1430 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
1431 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
1432 if (DRL->getDecl() == DRR->getDecl())
1433 EmitWarning = false;
1434
Ted Kremenek1b500bb2007-11-29 00:59:04 +00001435
1436 // Special case: check for comparisons against literals that can be exactly
1437 // represented by APFloat. In such cases, do not emit a warning. This
1438 // is a heuristic: often comparison against such literals are used to
1439 // detect if a value in a variable has not changed. This clearly can
1440 // lead to false negatives.
1441 if (EmitWarning) {
1442 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
1443 if (FLL->isExact())
1444 EmitWarning = false;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001445 } else
Ted Kremenek1b500bb2007-11-29 00:59:04 +00001446 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
1447 if (FLR->isExact())
1448 EmitWarning = false;
1449 }
1450 }
1451
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001452 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001453 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001454 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00001455 if (CL->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001456 EmitWarning = false;
1457
Sebastian Redl0eb23302009-01-19 00:08:26 +00001458 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001459 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00001460 if (CR->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001461 EmitWarning = false;
1462
1463 // Emit the diagnostic.
1464 if (EmitWarning)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001465 Diag(loc, diag::warn_floatingpoint_eq)
1466 << lex->getSourceRange() << rex->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001467}