blob: 2f71c778ecf86521c5c83906b22d9c4611eeff83 [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"
Ted Kremenek1309f9a2010-01-25 04:41:41 +000016#include "clang/Analysis/AnalysisContext.h"
Ted Kremenek3d2eed82010-02-23 02:39:16 +000017#include "clang/Analysis/CFG.h"
18#include "clang/Analysis/Analyses/ReachableCode.h"
Ted Kremeneke0e53132010-01-28 23:39:18 +000019#include "clang/Analysis/Analyses/PrintfFormatString.h"
Chris Lattner59907c42007-08-10 20:18:51 +000020#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000021#include "clang/AST/CharUnits.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000022#include "clang/AST/DeclObjC.h"
Ted Kremenek23245122007-08-20 16:18:38 +000023#include "clang/AST/ExprCXX.h"
Ted Kremenek7ff22b22008-06-16 18:00:42 +000024#include "clang/AST/ExprObjC.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000025#include "clang/AST/DeclObjC.h"
26#include "clang/AST/StmtCXX.h"
27#include "clang/AST/StmtObjC.h"
Chris Lattner719e6152009-02-18 19:21:10 +000028#include "clang/Lex/LiteralSupport.h"
Chris Lattner59907c42007-08-10 20:18:51 +000029#include "clang/Lex/Preprocessor.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000030#include "llvm/ADT/BitVector.h"
31#include "llvm/ADT/STLExtras.h"
Zhongxing Xua1f3dba2009-05-20 01:55:10 +000032#include <limits>
Mike Stumpf8c49212010-01-21 03:59:47 +000033#include <queue>
Chris Lattner59907c42007-08-10 20:18:51 +000034using namespace clang;
35
Chris Lattner60800082009-02-18 17:49:48 +000036/// getLocationOfStringLiteralByte - Return a source location that points to the
37/// specified byte of the specified string literal.
38///
39/// Strings are amazingly complex. They can be formed from multiple tokens and
40/// can have escape sequences in them in addition to the usual trigraph and
41/// escaped newline business. This routine handles this complexity.
42///
43SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
44 unsigned ByteNo) const {
45 assert(!SL->isWide() && "This doesn't work for wide strings yet");
Mike Stump1eb44332009-09-09 15:08:12 +000046
Chris Lattner60800082009-02-18 17:49:48 +000047 // Loop over all of the tokens in this string until we find the one that
48 // contains the byte we're looking for.
49 unsigned TokNo = 0;
50 while (1) {
51 assert(TokNo < SL->getNumConcatenated() && "Invalid byte number!");
52 SourceLocation StrTokLoc = SL->getStrTokenLoc(TokNo);
Mike Stump1eb44332009-09-09 15:08:12 +000053
Chris Lattner60800082009-02-18 17:49:48 +000054 // Get the spelling of the string so that we can get the data that makes up
55 // the string literal, not the identifier for the macro it is potentially
56 // expanded through.
57 SourceLocation StrTokSpellingLoc = SourceMgr.getSpellingLoc(StrTokLoc);
58
59 // Re-lex the token to get its length and original spelling.
60 std::pair<FileID, unsigned> LocInfo =
61 SourceMgr.getDecomposedLoc(StrTokSpellingLoc);
62 std::pair<const char *,const char *> Buffer =
63 SourceMgr.getBufferData(LocInfo.first);
64 const char *StrData = Buffer.first+LocInfo.second;
Mike Stump1eb44332009-09-09 15:08:12 +000065
Chris Lattner60800082009-02-18 17:49:48 +000066 // Create a langops struct and enable trigraphs. This is sufficient for
67 // relexing tokens.
68 LangOptions LangOpts;
69 LangOpts.Trigraphs = true;
Mike Stump1eb44332009-09-09 15:08:12 +000070
Chris Lattner60800082009-02-18 17:49:48 +000071 // Create a lexer starting at the beginning of this token.
72 Lexer TheLexer(StrTokSpellingLoc, LangOpts, Buffer.first, StrData,
73 Buffer.second);
74 Token TheTok;
75 TheLexer.LexFromRawLexer(TheTok);
Mike Stump1eb44332009-09-09 15:08:12 +000076
Chris Lattner443e53c2009-02-18 19:26:42 +000077 // Use the StringLiteralParser to compute the length of the string in bytes.
78 StringLiteralParser SLP(&TheTok, 1, PP);
79 unsigned TokNumBytes = SLP.GetStringLength();
Mike Stump1eb44332009-09-09 15:08:12 +000080
Chris Lattner2197c962009-02-18 18:52:52 +000081 // If the byte is in this token, return the location of the byte.
Chris Lattner60800082009-02-18 17:49:48 +000082 if (ByteNo < TokNumBytes ||
83 (ByteNo == TokNumBytes && TokNo == SL->getNumConcatenated())) {
Mike Stump1eb44332009-09-09 15:08:12 +000084 unsigned Offset =
Chris Lattner719e6152009-02-18 19:21:10 +000085 StringLiteralParser::getOffsetOfStringByte(TheTok, ByteNo, PP);
Mike Stump1eb44332009-09-09 15:08:12 +000086
Chris Lattner719e6152009-02-18 19:21:10 +000087 // Now that we know the offset of the token in the spelling, use the
88 // preprocessor to get the offset in the original source.
89 return PP.AdvanceToTokenCharacter(StrTokLoc, Offset);
Chris Lattner60800082009-02-18 17:49:48 +000090 }
Mike Stump1eb44332009-09-09 15:08:12 +000091
Chris Lattner60800082009-02-18 17:49:48 +000092 // Move to the next string token.
93 ++TokNo;
94 ByteNo -= TokNumBytes;
95 }
96}
97
Ryan Flynn4403a5e2009-08-06 03:00:50 +000098/// CheckablePrintfAttr - does a function call have a "printf" attribute
99/// and arguments that merit checking?
100bool Sema::CheckablePrintfAttr(const FormatAttr *Format, CallExpr *TheCall) {
101 if (Format->getType() == "printf") return true;
102 if (Format->getType() == "printf0") {
103 // printf0 allows null "format" string; if so don't check format/args
104 unsigned format_idx = Format->getFormatIdx() - 1;
Sebastian Redl4a2614e2009-11-17 18:02:24 +0000105 // Does the index refer to the implicit object argument?
106 if (isa<CXXMemberCallExpr>(TheCall)) {
107 if (format_idx == 0)
108 return false;
109 --format_idx;
110 }
Ryan Flynn4403a5e2009-08-06 03:00:50 +0000111 if (format_idx < TheCall->getNumArgs()) {
112 Expr *Format = TheCall->getArg(format_idx)->IgnoreParenCasts();
Douglas Gregorce940492009-09-25 04:25:58 +0000113 if (!Format->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
Ryan Flynn4403a5e2009-08-06 03:00:50 +0000114 return true;
115 }
116 }
117 return false;
118}
Chris Lattner60800082009-02-18 17:49:48 +0000119
Sebastian Redl0eb23302009-01-19 00:08:26 +0000120Action::OwningExprResult
Anders Carlssond406bf02009-08-16 01:56:34 +0000121Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Sebastian Redl0eb23302009-01-19 00:08:26 +0000122 OwningExprResult TheCallResult(Owned(TheCall));
Douglas Gregor2def4832008-11-17 20:34:05 +0000123
Anders Carlssond406bf02009-08-16 01:56:34 +0000124 switch (BuiltinID) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000125 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +0000126 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +0000127 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner69039812009-02-18 06:01:06 +0000128 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000129 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000130 break;
Ted Kremenek49ff7a12008-07-09 17:58:53 +0000131 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +0000132 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000133 if (SemaBuiltinVAStart(TheCall))
134 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000135 break;
Chris Lattner1b9a0792007-12-20 00:26:33 +0000136 case Builtin::BI__builtin_isgreater:
137 case Builtin::BI__builtin_isgreaterequal:
138 case Builtin::BI__builtin_isless:
139 case Builtin::BI__builtin_islessequal:
140 case Builtin::BI__builtin_islessgreater:
141 case Builtin::BI__builtin_isunordered:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000142 if (SemaBuiltinUnorderedCompare(TheCall))
143 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000144 break;
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000145 case Builtin::BI__builtin_fpclassify:
146 if (SemaBuiltinFPClassification(TheCall, 6))
147 return ExprError();
148 break;
Eli Friedman9ac6f622009-08-31 20:06:00 +0000149 case Builtin::BI__builtin_isfinite:
150 case Builtin::BI__builtin_isinf:
151 case Builtin::BI__builtin_isinf_sign:
152 case Builtin::BI__builtin_isnan:
153 case Builtin::BI__builtin_isnormal:
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000154 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman9ac6f622009-08-31 20:06:00 +0000155 return ExprError();
156 break;
Eli Friedman6cfda232008-05-20 08:23:37 +0000157 case Builtin::BI__builtin_return_address:
158 case Builtin::BI__builtin_frame_address:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000159 if (SemaBuiltinStackAddress(TheCall))
160 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000161 break;
Chris Lattner21fb98e2009-09-23 06:06:36 +0000162 case Builtin::BI__builtin_eh_return_data_regno:
163 if (SemaBuiltinEHReturnDataRegNo(TheCall))
164 return ExprError();
165 break;
Eli Friedmand38617c2008-05-14 19:38:39 +0000166 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000167 return SemaBuiltinShuffleVector(TheCall);
168 // TheCall will be freed by the smart pointer here, but that's fine, since
169 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000170 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000171 if (SemaBuiltinPrefetch(TheCall))
172 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000173 break;
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000174 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000175 if (SemaBuiltinObjectSize(TheCall))
176 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000177 break;
Eli Friedmand875fed2009-05-03 04:46:36 +0000178 case Builtin::BI__builtin_longjmp:
179 if (SemaBuiltinLongjmp(TheCall))
180 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000181 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000182 case Builtin::BI__sync_fetch_and_add:
183 case Builtin::BI__sync_fetch_and_sub:
184 case Builtin::BI__sync_fetch_and_or:
185 case Builtin::BI__sync_fetch_and_and:
186 case Builtin::BI__sync_fetch_and_xor:
Chris Lattnereebd9d22009-05-13 04:37:52 +0000187 case Builtin::BI__sync_fetch_and_nand:
Chris Lattner5caa3702009-05-08 06:58:22 +0000188 case Builtin::BI__sync_add_and_fetch:
189 case Builtin::BI__sync_sub_and_fetch:
190 case Builtin::BI__sync_and_and_fetch:
191 case Builtin::BI__sync_or_and_fetch:
192 case Builtin::BI__sync_xor_and_fetch:
Chris Lattnereebd9d22009-05-13 04:37:52 +0000193 case Builtin::BI__sync_nand_and_fetch:
Chris Lattner5caa3702009-05-08 06:58:22 +0000194 case Builtin::BI__sync_val_compare_and_swap:
195 case Builtin::BI__sync_bool_compare_and_swap:
196 case Builtin::BI__sync_lock_test_and_set:
197 case Builtin::BI__sync_lock_release:
198 if (SemaBuiltinAtomicOverloaded(TheCall))
199 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000200 break;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000201 }
Mike Stump1eb44332009-09-09 15:08:12 +0000202
Anders Carlssond406bf02009-08-16 01:56:34 +0000203 return move(TheCallResult);
204}
Daniel Dunbarde454282008-10-02 18:44:07 +0000205
Anders Carlssond406bf02009-08-16 01:56:34 +0000206/// CheckFunctionCall - Check a direct function call for various correctness
207/// and safety properties not strictly enforced by the C type system.
208bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
209 // Get the IdentifierInfo* for the called function.
210 IdentifierInfo *FnInfo = FDecl->getIdentifier();
211
212 // None of the checks below are needed for functions that don't have
213 // simple names (e.g., C++ conversion functions).
214 if (!FnInfo)
215 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000216
Daniel Dunbarde454282008-10-02 18:44:07 +0000217 // FIXME: This mechanism should be abstracted to be less fragile and
218 // more efficient. For example, just map function ids to custom
219 // handlers.
220
Chris Lattner59907c42007-08-10 20:18:51 +0000221 // Printf checking.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000222 if (const FormatAttr *Format = FDecl->getAttr<FormatAttr>()) {
Ryan Flynn4403a5e2009-08-06 03:00:50 +0000223 if (CheckablePrintfAttr(Format, TheCall)) {
Ted Kremenek3d692df2009-02-27 17:58:43 +0000224 bool HasVAListArg = Format->getFirstArg() == 0;
225 if (!HasVAListArg) {
Mike Stump1eb44332009-09-09 15:08:12 +0000226 if (const FunctionProtoType *Proto
John McCall183700f2009-09-21 23:43:11 +0000227 = FDecl->getType()->getAs<FunctionProtoType>())
Sebastian Redl4a2614e2009-11-17 18:02:24 +0000228 HasVAListArg = !Proto->isVariadic();
Ted Kremenek3d692df2009-02-27 17:58:43 +0000229 }
Douglas Gregor3c385e52009-02-14 18:57:46 +0000230 CheckPrintfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
Ted Kremenek3d692df2009-02-27 17:58:43 +0000231 HasVAListArg ? 0 : Format->getFirstArg() - 1);
Douglas Gregor3c385e52009-02-14 18:57:46 +0000232 }
Chris Lattner59907c42007-08-10 20:18:51 +0000233 }
Mike Stump1eb44332009-09-09 15:08:12 +0000234
235 for (const NonNullAttr *NonNull = FDecl->getAttr<NonNullAttr>(); NonNull;
Anders Carlssond406bf02009-08-16 01:56:34 +0000236 NonNull = NonNull->getNext<NonNullAttr>())
237 CheckNonNullArguments(NonNull, TheCall);
Sebastian Redl0eb23302009-01-19 00:08:26 +0000238
Anders Carlssond406bf02009-08-16 01:56:34 +0000239 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000240}
241
Anders Carlssond406bf02009-08-16 01:56:34 +0000242bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000243 // Printf checking.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000244 const FormatAttr *Format = NDecl->getAttr<FormatAttr>();
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000245 if (!Format)
Anders Carlssond406bf02009-08-16 01:56:34 +0000246 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000247
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000248 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
249 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000250 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000251
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000252 QualType Ty = V->getType();
253 if (!Ty->isBlockPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000254 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000255
Anders Carlssond406bf02009-08-16 01:56:34 +0000256 if (!CheckablePrintfAttr(Format, TheCall))
257 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000258
Anders Carlssond406bf02009-08-16 01:56:34 +0000259 bool HasVAListArg = Format->getFirstArg() == 0;
260 if (!HasVAListArg) {
Mike Stump1eb44332009-09-09 15:08:12 +0000261 const FunctionType *FT =
John McCall183700f2009-09-21 23:43:11 +0000262 Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Anders Carlssond406bf02009-08-16 01:56:34 +0000263 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT))
264 HasVAListArg = !Proto->isVariadic();
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000265 }
Anders Carlssond406bf02009-08-16 01:56:34 +0000266 CheckPrintfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
267 HasVAListArg ? 0 : Format->getFirstArg() - 1);
268
269 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000270}
271
Chris Lattner5caa3702009-05-08 06:58:22 +0000272/// SemaBuiltinAtomicOverloaded - We have a call to a function like
273/// __sync_fetch_and_add, which is an overloaded function based on the pointer
274/// type of its first argument. The main ActOnCallExpr routines have already
275/// promoted the types of arguments because all of these calls are prototyped as
276/// void(...).
277///
278/// This function goes through and does final semantic checking for these
279/// builtins,
280bool Sema::SemaBuiltinAtomicOverloaded(CallExpr *TheCall) {
281 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
282 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
283
284 // Ensure that we have at least one argument to do type inference from.
285 if (TheCall->getNumArgs() < 1)
286 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
287 << 0 << TheCall->getCallee()->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000288
Chris Lattner5caa3702009-05-08 06:58:22 +0000289 // Inspect the first argument of the atomic builtin. This should always be
290 // a pointer type, whose element is an integral scalar or pointer type.
291 // Because it is a pointer type, we don't have to worry about any implicit
292 // casts here.
293 Expr *FirstArg = TheCall->getArg(0);
294 if (!FirstArg->getType()->isPointerType())
295 return Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
296 << FirstArg->getType() << FirstArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000297
Ted Kremenek6217b802009-07-29 21:53:49 +0000298 QualType ValType = FirstArg->getType()->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +0000299 if (!ValType->isIntegerType() && !ValType->isPointerType() &&
Chris Lattner5caa3702009-05-08 06:58:22 +0000300 !ValType->isBlockPointerType())
301 return Diag(DRE->getLocStart(),
302 diag::err_atomic_builtin_must_be_pointer_intptr)
303 << FirstArg->getType() << FirstArg->getSourceRange();
304
305 // We need to figure out which concrete builtin this maps onto. For example,
306 // __sync_fetch_and_add with a 2 byte object turns into
307 // __sync_fetch_and_add_2.
308#define BUILTIN_ROW(x) \
309 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
310 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +0000311
Chris Lattner5caa3702009-05-08 06:58:22 +0000312 static const unsigned BuiltinIndices[][5] = {
313 BUILTIN_ROW(__sync_fetch_and_add),
314 BUILTIN_ROW(__sync_fetch_and_sub),
315 BUILTIN_ROW(__sync_fetch_and_or),
316 BUILTIN_ROW(__sync_fetch_and_and),
317 BUILTIN_ROW(__sync_fetch_and_xor),
Chris Lattnereebd9d22009-05-13 04:37:52 +0000318 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump1eb44332009-09-09 15:08:12 +0000319
Chris Lattner5caa3702009-05-08 06:58:22 +0000320 BUILTIN_ROW(__sync_add_and_fetch),
321 BUILTIN_ROW(__sync_sub_and_fetch),
322 BUILTIN_ROW(__sync_and_and_fetch),
323 BUILTIN_ROW(__sync_or_and_fetch),
324 BUILTIN_ROW(__sync_xor_and_fetch),
Chris Lattnereebd9d22009-05-13 04:37:52 +0000325 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +0000326
Chris Lattner5caa3702009-05-08 06:58:22 +0000327 BUILTIN_ROW(__sync_val_compare_and_swap),
328 BUILTIN_ROW(__sync_bool_compare_and_swap),
329 BUILTIN_ROW(__sync_lock_test_and_set),
330 BUILTIN_ROW(__sync_lock_release)
331 };
Mike Stump1eb44332009-09-09 15:08:12 +0000332#undef BUILTIN_ROW
333
Chris Lattner5caa3702009-05-08 06:58:22 +0000334 // Determine the index of the size.
335 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +0000336 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +0000337 case 1: SizeIndex = 0; break;
338 case 2: SizeIndex = 1; break;
339 case 4: SizeIndex = 2; break;
340 case 8: SizeIndex = 3; break;
341 case 16: SizeIndex = 4; break;
342 default:
343 return Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
344 << FirstArg->getType() << FirstArg->getSourceRange();
345 }
Mike Stump1eb44332009-09-09 15:08:12 +0000346
Chris Lattner5caa3702009-05-08 06:58:22 +0000347 // Each of these builtins has one pointer argument, followed by some number of
348 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
349 // that we ignore. Find out which row of BuiltinIndices to read from as well
350 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +0000351 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +0000352 unsigned BuiltinIndex, NumFixed = 1;
353 switch (BuiltinID) {
354 default: assert(0 && "Unknown overloaded atomic builtin!");
355 case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break;
356 case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break;
357 case Builtin::BI__sync_fetch_and_or: BuiltinIndex = 2; break;
358 case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break;
359 case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break;
Chris Lattnereebd9d22009-05-13 04:37:52 +0000360 case Builtin::BI__sync_fetch_and_nand:BuiltinIndex = 5; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000361
Chris Lattnereebd9d22009-05-13 04:37:52 +0000362 case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 6; break;
363 case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 7; break;
364 case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 8; break;
365 case Builtin::BI__sync_or_and_fetch: BuiltinIndex = 9; break;
366 case Builtin::BI__sync_xor_and_fetch: BuiltinIndex =10; break;
367 case Builtin::BI__sync_nand_and_fetch:BuiltinIndex =11; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000368
Chris Lattner5caa3702009-05-08 06:58:22 +0000369 case Builtin::BI__sync_val_compare_and_swap:
Chris Lattnereebd9d22009-05-13 04:37:52 +0000370 BuiltinIndex = 12;
Chris Lattner5caa3702009-05-08 06:58:22 +0000371 NumFixed = 2;
372 break;
373 case Builtin::BI__sync_bool_compare_and_swap:
Chris Lattnereebd9d22009-05-13 04:37:52 +0000374 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +0000375 NumFixed = 2;
376 break;
Chris Lattnereebd9d22009-05-13 04:37:52 +0000377 case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 14; break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000378 case Builtin::BI__sync_lock_release:
Chris Lattnereebd9d22009-05-13 04:37:52 +0000379 BuiltinIndex = 15;
Chris Lattner5caa3702009-05-08 06:58:22 +0000380 NumFixed = 0;
381 break;
382 }
Mike Stump1eb44332009-09-09 15:08:12 +0000383
Chris Lattner5caa3702009-05-08 06:58:22 +0000384 // Now that we know how many fixed arguments we expect, first check that we
385 // have at least that many.
386 if (TheCall->getNumArgs() < 1+NumFixed)
387 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
388 << 0 << TheCall->getCallee()->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000389
390
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000391 // Get the decl for the concrete builtin from this, we can tell what the
392 // concrete integer type we should convert to is.
393 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
394 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
395 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
Mike Stump1eb44332009-09-09 15:08:12 +0000396 FunctionDecl *NewBuiltinDecl =
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000397 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
398 TUScope, false, DRE->getLocStart()));
399 const FunctionProtoType *BuiltinFT =
John McCall183700f2009-09-21 23:43:11 +0000400 NewBuiltinDecl->getType()->getAs<FunctionProtoType>();
Ted Kremenek6217b802009-07-29 21:53:49 +0000401 ValType = BuiltinFT->getArgType(0)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +0000402
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000403 // If the first type needs to be converted (e.g. void** -> int*), do it now.
404 if (BuiltinFT->getArgType(0) != FirstArg->getType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +0000405 ImpCastExprToType(FirstArg, BuiltinFT->getArgType(0), CastExpr::CK_BitCast);
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000406 TheCall->setArg(0, FirstArg);
407 }
Mike Stump1eb44332009-09-09 15:08:12 +0000408
Chris Lattner5caa3702009-05-08 06:58:22 +0000409 // Next, walk the valid ones promoting to the right type.
410 for (unsigned i = 0; i != NumFixed; ++i) {
411 Expr *Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +0000412
Chris Lattner5caa3702009-05-08 06:58:22 +0000413 // If the argument is an implicit cast, then there was a promotion due to
414 // "...", just remove it now.
415 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
416 Arg = ICE->getSubExpr();
417 ICE->setSubExpr(0);
418 ICE->Destroy(Context);
419 TheCall->setArg(i+1, Arg);
420 }
Mike Stump1eb44332009-09-09 15:08:12 +0000421
Chris Lattner5caa3702009-05-08 06:58:22 +0000422 // GCC does an implicit conversion to the pointer or integer ValType. This
423 // can fail in some cases (1i -> int**), check for this error case now.
Anders Carlssoncdb61972009-08-07 22:21:05 +0000424 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Fariborz Jahaniane9f42082009-08-26 18:55:36 +0000425 CXXMethodDecl *ConversionDecl = 0;
426 if (CheckCastTypes(Arg->getSourceRange(), ValType, Arg, Kind,
427 ConversionDecl))
Chris Lattner5caa3702009-05-08 06:58:22 +0000428 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000429
Chris Lattner5caa3702009-05-08 06:58:22 +0000430 // Okay, we have something that *can* be converted to the right type. Check
431 // to see if there is a potentially weird extension going on here. This can
432 // happen when you do an atomic operation on something like an char* and
433 // pass in 42. The 42 gets converted to char. This is even more strange
434 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +0000435 // FIXME: Do this check.
Anders Carlssoncdb61972009-08-07 22:21:05 +0000436 ImpCastExprToType(Arg, ValType, Kind, /*isLvalue=*/false);
Chris Lattner5caa3702009-05-08 06:58:22 +0000437 TheCall->setArg(i+1, Arg);
438 }
Mike Stump1eb44332009-09-09 15:08:12 +0000439
Chris Lattner5caa3702009-05-08 06:58:22 +0000440 // Switch the DeclRefExpr to refer to the new decl.
441 DRE->setDecl(NewBuiltinDecl);
442 DRE->setType(NewBuiltinDecl->getType());
Mike Stump1eb44332009-09-09 15:08:12 +0000443
Chris Lattner5caa3702009-05-08 06:58:22 +0000444 // Set the callee in the CallExpr.
445 // FIXME: This leaks the original parens and implicit casts.
446 Expr *PromotedCall = DRE;
447 UsualUnaryConversions(PromotedCall);
448 TheCall->setCallee(PromotedCall);
Mike Stump1eb44332009-09-09 15:08:12 +0000449
Chris Lattner5caa3702009-05-08 06:58:22 +0000450
451 // Change the result type of the call to match the result type of the decl.
452 TheCall->setType(NewBuiltinDecl->getResultType());
453 return false;
454}
455
456
Chris Lattner69039812009-02-18 06:01:06 +0000457/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +0000458/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +0000459/// FIXME: GCC currently emits the following warning:
Mike Stump1eb44332009-09-09 15:08:12 +0000460/// "warning: input conversion stopped due to an input byte that does not
Steve Narofffd942622009-04-13 20:26:29 +0000461/// belong to the input codeset UTF-8"
462/// Note: It might also make sense to do the UTF-16 conversion here (would
463/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +0000464bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +0000465 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000466 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
467
468 if (!Literal || Literal->isWide()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000469 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
470 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000471 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000472 }
Mike Stump1eb44332009-09-09 15:08:12 +0000473
Daniel Dunbarf015b032009-09-22 10:03:52 +0000474 const char *Data = Literal->getStrData();
475 unsigned Length = Literal->getByteLength();
Mike Stump1eb44332009-09-09 15:08:12 +0000476
Daniel Dunbarf015b032009-09-22 10:03:52 +0000477 for (unsigned i = 0; i < Length; ++i) {
478 if (!Data[i]) {
479 Diag(getLocationOfStringLiteralByte(Literal, i),
480 diag::warn_cfstring_literal_contains_nul_character)
481 << Arg->getSourceRange();
482 break;
483 }
484 }
Mike Stump1eb44332009-09-09 15:08:12 +0000485
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000486 return false;
Chris Lattner59907c42007-08-10 20:18:51 +0000487}
488
Chris Lattnerc27c6652007-12-20 00:05:45 +0000489/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
490/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +0000491bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
492 Expr *Fn = TheCall->getCallee();
493 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +0000494 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000495 diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000496 << 0 /*function call*/ << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +0000497 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000498 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +0000499 return true;
500 }
Eli Friedman56f20ae2008-12-15 22:05:35 +0000501
502 if (TheCall->getNumArgs() < 2) {
503 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
504 << 0 /*function call*/;
505 }
506
Chris Lattnerc27c6652007-12-20 00:05:45 +0000507 // Determine whether the current function is variadic or not.
508 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000509 if (CurBlock)
510 isVariadic = CurBlock->isVariadic;
511 else if (getCurFunctionDecl()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000512 if (FunctionProtoType* FTP =
513 dyn_cast<FunctionProtoType>(getCurFunctionDecl()->getType()))
Eli Friedman56f20ae2008-12-15 22:05:35 +0000514 isVariadic = FTP->isVariadic();
515 else
516 isVariadic = false;
517 } else {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000518 isVariadic = getCurMethodDecl()->isVariadic();
Eli Friedman56f20ae2008-12-15 22:05:35 +0000519 }
Mike Stump1eb44332009-09-09 15:08:12 +0000520
Chris Lattnerc27c6652007-12-20 00:05:45 +0000521 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000522 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
523 return true;
524 }
Mike Stump1eb44332009-09-09 15:08:12 +0000525
Chris Lattner30ce3442007-12-19 23:59:04 +0000526 // Verify that the second argument to the builtin is the last argument of the
527 // current function or method.
528 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +0000529 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +0000530
Anders Carlsson88cf2262008-02-11 04:20:54 +0000531 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
532 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000533 // FIXME: This isn't correct for methods (results in bogus warning).
534 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +0000535 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000536 if (CurBlock)
537 LastArg = *(CurBlock->TheDecl->param_end()-1);
538 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +0000539 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000540 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000541 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000542 SecondArgIsLastNamedArgument = PV == LastArg;
543 }
544 }
Mike Stump1eb44332009-09-09 15:08:12 +0000545
Chris Lattner30ce3442007-12-19 23:59:04 +0000546 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +0000547 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +0000548 diag::warn_second_parameter_of_va_start_not_last_named_argument);
549 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +0000550}
Chris Lattner30ce3442007-12-19 23:59:04 +0000551
Chris Lattner1b9a0792007-12-20 00:26:33 +0000552/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
553/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +0000554bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
555 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +0000556 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
557 << 0 /*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +0000558 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +0000559 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000560 diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000561 << 0 /*function call*/
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000562 << SourceRange(TheCall->getArg(2)->getLocStart(),
563 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000564
Chris Lattner925e60d2007-12-28 05:29:59 +0000565 Expr *OrigArg0 = TheCall->getArg(0);
566 Expr *OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +0000567
Chris Lattner1b9a0792007-12-20 00:26:33 +0000568 // Do standard promotions between the two arguments, returning their common
569 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +0000570 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
Daniel Dunbar403bc2b2009-02-19 19:28:43 +0000571
572 // Make sure any conversions are pushed back into the call; this is
573 // type safe since unordered compare builtins are declared as "_Bool
574 // foo(...)".
575 TheCall->setArg(0, OrigArg0);
576 TheCall->setArg(1, OrigArg1);
Mike Stump1eb44332009-09-09 15:08:12 +0000577
Douglas Gregorcde01732009-05-19 22:10:17 +0000578 if (OrigArg0->isTypeDependent() || OrigArg1->isTypeDependent())
579 return false;
580
Chris Lattner1b9a0792007-12-20 00:26:33 +0000581 // If the common type isn't a real floating type, then the arguments were
582 // invalid for this operation.
583 if (!Res->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +0000584 return Diag(OrigArg0->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000585 diag::err_typecheck_call_invalid_ordered_compare)
Chris Lattnerd1625842008-11-24 06:25:27 +0000586 << OrigArg0->getType() << OrigArg1->getType()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000587 << SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000588
Chris Lattner1b9a0792007-12-20 00:26:33 +0000589 return false;
590}
591
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000592/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
593/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000594/// to check everything. We expect the last argument to be a floating point
595/// value.
596bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
597 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +0000598 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
599 << 0 /*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000600 if (TheCall->getNumArgs() > NumArgs)
601 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000602 diag::err_typecheck_call_too_many_args)
603 << 0 /*function call*/
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000604 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000605 (*(TheCall->arg_end()-1))->getLocEnd());
606
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000607 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +0000608
Eli Friedman9ac6f622009-08-31 20:06:00 +0000609 if (OrigArg->isTypeDependent())
610 return false;
611
612 // This operation requires a floating-point number
613 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +0000614 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000615 diag::err_typecheck_call_invalid_unary_fp)
616 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000617
Eli Friedman9ac6f622009-08-31 20:06:00 +0000618 return false;
619}
620
Eli Friedman6cfda232008-05-20 08:23:37 +0000621bool Sema::SemaBuiltinStackAddress(CallExpr *TheCall) {
622 // The signature for these builtins is exact; the only thing we need
623 // to check is that the argument is a constant.
624 SourceLocation Loc;
Douglas Gregorcde01732009-05-19 22:10:17 +0000625 if (!TheCall->getArg(0)->isTypeDependent() &&
626 !TheCall->getArg(0)->isValueDependent() &&
627 !TheCall->getArg(0)->isIntegerConstantExpr(Context, &Loc))
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000628 return Diag(Loc, diag::err_stack_const_level) << TheCall->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000629
Eli Friedman6cfda232008-05-20 08:23:37 +0000630 return false;
631}
632
Eli Friedmand38617c2008-05-14 19:38:39 +0000633/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
634// This is declared to take (...), so we have to check everything.
Sebastian Redl0eb23302009-01-19 00:08:26 +0000635Action::OwningExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000636 if (TheCall->getNumArgs() < 3)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000637 return ExprError(Diag(TheCall->getLocEnd(),
638 diag::err_typecheck_call_too_few_args)
639 << 0 /*function call*/ << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000640
Douglas Gregorcde01732009-05-19 22:10:17 +0000641 unsigned numElements = std::numeric_limits<unsigned>::max();
642 if (!TheCall->getArg(0)->isTypeDependent() &&
643 !TheCall->getArg(1)->isTypeDependent()) {
644 QualType FAType = TheCall->getArg(0)->getType();
645 QualType SAType = TheCall->getArg(1)->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000646
Douglas Gregorcde01732009-05-19 22:10:17 +0000647 if (!FAType->isVectorType() || !SAType->isVectorType()) {
648 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_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 }
Mike Stump1eb44332009-09-09 15:08:12 +0000653
Douglas Gregora4923eb2009-11-16 21:35:15 +0000654 if (!Context.hasSameUnqualifiedType(FAType, SAType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000655 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +0000656 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000657 TheCall->getArg(1)->getLocEnd());
658 return ExprError();
659 }
Eli Friedmand38617c2008-05-14 19:38:39 +0000660
John McCall183700f2009-09-21 23:43:11 +0000661 numElements = FAType->getAs<VectorType>()->getNumElements();
Douglas Gregorcde01732009-05-19 22:10:17 +0000662 if (TheCall->getNumArgs() != numElements+2) {
663 if (TheCall->getNumArgs() < numElements+2)
664 return ExprError(Diag(TheCall->getLocEnd(),
665 diag::err_typecheck_call_too_few_args)
666 << 0 /*function call*/ << TheCall->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +0000667 return ExprError(Diag(TheCall->getLocEnd(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000668 diag::err_typecheck_call_too_many_args)
669 << 0 /*function call*/ << TheCall->getSourceRange());
670 }
Eli Friedmand38617c2008-05-14 19:38:39 +0000671 }
672
673 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000674 if (TheCall->getArg(i)->isTypeDependent() ||
675 TheCall->getArg(i)->isValueDependent())
676 continue;
677
Eli Friedmand38617c2008-05-14 19:38:39 +0000678 llvm::APSInt Result(32);
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000679 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000680 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000681 diag::err_shufflevector_nonconstant_argument)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000682 << TheCall->getArg(i)->getSourceRange());
683
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000684 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000685 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000686 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000687 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000688 }
689
690 llvm::SmallVector<Expr*, 32> exprs;
691
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000692 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000693 exprs.push_back(TheCall->getArg(i));
694 TheCall->setArg(i, 0);
695 }
696
Nate Begemana88dc302009-08-12 02:10:25 +0000697 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
698 exprs.size(), exprs[0]->getType(),
Ted Kremenek8189cde2009-02-07 01:47:29 +0000699 TheCall->getCallee()->getLocStart(),
700 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +0000701}
Chris Lattner30ce3442007-12-19 23:59:04 +0000702
Daniel Dunbar4493f792008-07-21 22:59:13 +0000703/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
704// This is declared to take (const void*, ...) and can take two
705// optional constant int args.
706bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000707 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000708
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000709 if (NumArgs > 3)
710 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000711 << 0 /*function call*/ << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000712
713 // Argument 0 is checked for us and the remaining arguments must be
714 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000715 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +0000716 Expr *Arg = TheCall->getArg(i);
Douglas Gregorcde01732009-05-19 22:10:17 +0000717 if (Arg->isTypeDependent())
718 continue;
719
Eli Friedman9aef7262009-12-04 00:30:06 +0000720 if (!Arg->getType()->isIntegralType())
721 return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_arg_type)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000722 << Arg->getSourceRange();
Douglas Gregorcde01732009-05-19 22:10:17 +0000723
Eli Friedman9aef7262009-12-04 00:30:06 +0000724 ImpCastExprToType(Arg, Context.IntTy, CastExpr::CK_IntegralCast);
725 TheCall->setArg(i, Arg);
726
Douglas Gregorcde01732009-05-19 22:10:17 +0000727 if (Arg->isValueDependent())
728 continue;
729
Eli Friedman9aef7262009-12-04 00:30:06 +0000730 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +0000731 if (!Arg->isIntegerConstantExpr(Result, Context))
Eli Friedman9aef7262009-12-04 00:30:06 +0000732 return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_arg_ice)
Douglas Gregorcde01732009-05-19 22:10:17 +0000733 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000734
Daniel Dunbar4493f792008-07-21 22:59:13 +0000735 // FIXME: gcc issues a warning and rewrites these to 0. These
736 // seems especially odd for the third argument since the default
737 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000738 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +0000739 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000740 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000741 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000742 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +0000743 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000744 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000745 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000746 }
747 }
748
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000749 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +0000750}
751
Chris Lattner21fb98e2009-09-23 06:06:36 +0000752/// SemaBuiltinEHReturnDataRegNo - Handle __builtin_eh_return_data_regno, the
753/// operand must be an integer constant.
754bool Sema::SemaBuiltinEHReturnDataRegNo(CallExpr *TheCall) {
755 llvm::APSInt Result;
756 if (!TheCall->getArg(0)->isIntegerConstantExpr(Result, Context))
757 return Diag(TheCall->getLocStart(), diag::err_expr_not_ice)
758 << TheCall->getArg(0)->getSourceRange();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +0000759
Chris Lattner21fb98e2009-09-23 06:06:36 +0000760 return false;
761}
762
763
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000764/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
765/// int type). This simply type checks that type is one of the defined
766/// constants (0-3).
Eric Christopherfee667f2009-12-23 03:49:37 +0000767// For compatability check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000768bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
769 Expr *Arg = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +0000770 if (Arg->isTypeDependent())
771 return false;
772
Mike Stump1eb44332009-09-09 15:08:12 +0000773 QualType ArgType = Arg->getType();
John McCall183700f2009-09-21 23:43:11 +0000774 const BuiltinType *BT = ArgType->getAs<BuiltinType>();
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000775 llvm::APSInt Result(32);
Douglas Gregorcde01732009-05-19 22:10:17 +0000776 if (!BT || BT->getKind() != BuiltinType::Int)
777 return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument)
778 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
779
780 if (Arg->isValueDependent())
781 return false;
782
783 if (!Arg->isIntegerConstantExpr(Result, Context)) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000784 return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument)
785 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000786 }
787
788 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000789 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
790 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000791 }
792
793 return false;
794}
795
Eli Friedman586d6a82009-05-03 06:04:26 +0000796/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +0000797/// This checks that val is a constant 1.
798bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
799 Expr *Arg = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +0000800 if (Arg->isTypeDependent() || Arg->isValueDependent())
801 return false;
802
Eli Friedmand875fed2009-05-03 04:46:36 +0000803 llvm::APSInt Result(32);
804 if (!Arg->isIntegerConstantExpr(Result, Context) || Result != 1)
805 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
806 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
807
808 return false;
809}
810
Ted Kremenekd30ef872009-01-12 23:09:09 +0000811// Handle i > 1 ? "x" : "y", recursivelly
Ted Kremenek082d9362009-03-20 21:35:28 +0000812bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
813 bool HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000814 unsigned format_idx, unsigned firstDataArg) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000815 if (E->isTypeDependent() || E->isValueDependent())
816 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000817
818 switch (E->getStmtClass()) {
819 case Stmt::ConditionalOperatorClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +0000820 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Chris Lattner813b70d2009-12-22 06:00:13 +0000821 return SemaCheckStringLiteral(C->getTrueExpr(), TheCall,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000822 HasVAListArg, format_idx, firstDataArg)
Ted Kremenekd30ef872009-01-12 23:09:09 +0000823 && SemaCheckStringLiteral(C->getRHS(), TheCall,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000824 HasVAListArg, format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000825 }
826
827 case Stmt::ImplicitCastExprClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +0000828 const ImplicitCastExpr *Expr = cast<ImplicitCastExpr>(E);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000829 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000830 format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000831 }
832
833 case Stmt::ParenExprClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +0000834 const ParenExpr *Expr = cast<ParenExpr>(E);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000835 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000836 format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000837 }
Mike Stump1eb44332009-09-09 15:08:12 +0000838
Ted Kremenek082d9362009-03-20 21:35:28 +0000839 case Stmt::DeclRefExprClass: {
840 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +0000841
Ted Kremenek082d9362009-03-20 21:35:28 +0000842 // As an exception, do not flag errors for variables binding to
843 // const string literals.
844 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
845 bool isConstant = false;
846 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +0000847
Ted Kremenek082d9362009-03-20 21:35:28 +0000848 if (const ArrayType *AT = Context.getAsArrayType(T)) {
849 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000850 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000851 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +0000852 PT->getPointeeType().isConstant(Context);
853 }
Mike Stump1eb44332009-09-09 15:08:12 +0000854
Ted Kremenek082d9362009-03-20 21:35:28 +0000855 if (isConstant) {
Sebastian Redl31310a22010-02-01 20:16:42 +0000856 if (const Expr *Init = VD->getAnyInitializer())
Ted Kremenek082d9362009-03-20 21:35:28 +0000857 return SemaCheckStringLiteral(Init, TheCall,
858 HasVAListArg, format_idx, firstDataArg);
859 }
Mike Stump1eb44332009-09-09 15:08:12 +0000860
Anders Carlssond966a552009-06-28 19:55:58 +0000861 // For vprintf* functions (i.e., HasVAListArg==true), we add a
862 // special check to see if the format string is a function parameter
863 // of the function calling the printf function. If the function
864 // has an attribute indicating it is a printf-like function, then we
865 // should suppress warnings concerning non-literals being used in a call
866 // to a vprintf function. For example:
867 //
868 // void
869 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
870 // va_list ap;
871 // va_start(ap, fmt);
872 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
873 // ...
874 //
875 //
876 // FIXME: We don't have full attribute support yet, so just check to see
877 // if the argument is a DeclRefExpr that references a parameter. We'll
878 // add proper support for checking the attribute later.
879 if (HasVAListArg)
880 if (isa<ParmVarDecl>(VD))
881 return true;
Ted Kremenek082d9362009-03-20 21:35:28 +0000882 }
Mike Stump1eb44332009-09-09 15:08:12 +0000883
Ted Kremenek082d9362009-03-20 21:35:28 +0000884 return false;
885 }
Ted Kremenekd30ef872009-01-12 23:09:09 +0000886
Anders Carlsson8f031b32009-06-27 04:05:33 +0000887 case Stmt::CallExprClass: {
888 const CallExpr *CE = cast<CallExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +0000889 if (const ImplicitCastExpr *ICE
Anders Carlsson8f031b32009-06-27 04:05:33 +0000890 = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
891 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
892 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000893 if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
Anders Carlsson8f031b32009-06-27 04:05:33 +0000894 unsigned ArgIndex = FA->getFormatIdx();
895 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +0000896
897 return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg,
Anders Carlsson8f031b32009-06-27 04:05:33 +0000898 format_idx, firstDataArg);
899 }
900 }
901 }
902 }
Mike Stump1eb44332009-09-09 15:08:12 +0000903
Anders Carlsson8f031b32009-06-27 04:05:33 +0000904 return false;
905 }
Ted Kremenek082d9362009-03-20 21:35:28 +0000906 case Stmt::ObjCStringLiteralClass:
907 case Stmt::StringLiteralClass: {
908 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +0000909
Ted Kremenek082d9362009-03-20 21:35:28 +0000910 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +0000911 StrE = ObjCFExpr->getString();
912 else
Ted Kremenek082d9362009-03-20 21:35:28 +0000913 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +0000914
Ted Kremenekd30ef872009-01-12 23:09:09 +0000915 if (StrE) {
Mike Stump1eb44332009-09-09 15:08:12 +0000916 CheckPrintfString(StrE, E, TheCall, HasVAListArg, format_idx,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000917 firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000918 return true;
919 }
Mike Stump1eb44332009-09-09 15:08:12 +0000920
Ted Kremenekd30ef872009-01-12 23:09:09 +0000921 return false;
922 }
Mike Stump1eb44332009-09-09 15:08:12 +0000923
Ted Kremenek082d9362009-03-20 21:35:28 +0000924 default:
925 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000926 }
927}
928
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +0000929void
Mike Stump1eb44332009-09-09 15:08:12 +0000930Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
931 const CallExpr *TheCall) {
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +0000932 for (NonNullAttr::iterator i = NonNull->begin(), e = NonNull->end();
933 i != e; ++i) {
Chris Lattner12b97ff2009-05-25 18:23:36 +0000934 const Expr *ArgExpr = TheCall->getArg(*i);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +0000935 if (ArgExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +0000936 Expr::NPC_ValueDependentIsNotNull))
Chris Lattner12b97ff2009-05-25 18:23:36 +0000937 Diag(TheCall->getCallee()->getLocStart(), diag::warn_null_arg)
938 << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +0000939 }
940}
Ted Kremenekd30ef872009-01-12 23:09:09 +0000941
Chris Lattner59907c42007-08-10 20:18:51 +0000942/// CheckPrintfArguments - Check calls to printf (and similar functions) for
Mike Stump1eb44332009-09-09 15:08:12 +0000943/// correct use of format strings.
Ted Kremenek71895b92007-08-14 17:39:48 +0000944///
945/// HasVAListArg - A predicate indicating whether the printf-like
946/// function is passed an explicit va_arg argument (e.g., vprintf)
947///
948/// format_idx - The index into Args for the format string.
949///
950/// Improper format strings to functions in the printf family can be
951/// the source of bizarre bugs and very serious security holes. A
952/// good source of information is available in the following paper
953/// (which includes additional references):
Chris Lattner59907c42007-08-10 20:18:51 +0000954///
955/// FormatGuard: Automatic Protection From printf Format String
956/// Vulnerabilities, Proceedings of the 10th USENIX Security Symposium, 2001.
Ted Kremenek71895b92007-08-14 17:39:48 +0000957///
Ted Kremenek7f70dc82010-02-26 19:18:41 +0000958/// TODO:
Ted Kremenek71895b92007-08-14 17:39:48 +0000959/// Functionality implemented:
960///
961/// We can statically check the following properties for string
962/// literal format strings for non v.*printf functions (where the
963/// arguments are passed directly):
964//
965/// (1) Are the number of format conversions equal to the number of
966/// data arguments?
967///
968/// (2) Does each format conversion correctly match the type of the
Ted Kremenek7f70dc82010-02-26 19:18:41 +0000969/// corresponding data argument?
Ted Kremenek71895b92007-08-14 17:39:48 +0000970///
971/// Moreover, for all printf functions we can:
972///
973/// (3) Check for a missing format string (when not caught by type checking).
974///
975/// (4) Check for no-operation flags; e.g. using "#" with format
976/// conversion 'c' (TODO)
977///
978/// (5) Check the use of '%n', a major source of security holes.
979///
980/// (6) Check for malformed format conversions that don't specify anything.
981///
982/// (7) Check for empty format strings. e.g: printf("");
983///
984/// (8) Check that the format string is a wide literal.
985///
986/// All of these checks can be done by parsing the format string.
987///
Chris Lattner59907c42007-08-10 20:18:51 +0000988void
Mike Stump1eb44332009-09-09 15:08:12 +0000989Sema::CheckPrintfArguments(const CallExpr *TheCall, bool HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000990 unsigned format_idx, unsigned firstDataArg) {
Ted Kremenek082d9362009-03-20 21:35:28 +0000991 const Expr *Fn = TheCall->getCallee();
Chris Lattner925e60d2007-12-28 05:29:59 +0000992
Sebastian Redl4a2614e2009-11-17 18:02:24 +0000993 // The way the format attribute works in GCC, the implicit this argument
994 // of member functions is counted. However, it doesn't appear in our own
995 // lists, so decrement format_idx in that case.
996 if (isa<CXXMemberCallExpr>(TheCall)) {
997 // Catch a format attribute mistakenly referring to the object argument.
998 if (format_idx == 0)
999 return;
1000 --format_idx;
1001 if(firstDataArg != 0)
1002 --firstDataArg;
1003 }
1004
Mike Stump1eb44332009-09-09 15:08:12 +00001005 // CHECK: printf-like function is called with no format string.
Chris Lattner925e60d2007-12-28 05:29:59 +00001006 if (format_idx >= TheCall->getNumArgs()) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001007 Diag(TheCall->getRParenLoc(), diag::warn_printf_missing_format_string)
1008 << Fn->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001009 return;
1010 }
Mike Stump1eb44332009-09-09 15:08:12 +00001011
Ted Kremenek082d9362009-03-20 21:35:28 +00001012 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001013
Chris Lattner59907c42007-08-10 20:18:51 +00001014 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001015 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001016 // Dynamically generated format strings are difficult to
1017 // automatically vet at compile time. Requiring that format strings
1018 // are string literals: (1) permits the checking of format strings by
1019 // the compiler and thereby (2) can practically remove the source of
1020 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001021
Mike Stump1eb44332009-09-09 15:08:12 +00001022 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001023 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001024 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001025 // the same format string checking logic for both ObjC and C strings.
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001026 if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
1027 firstDataArg))
1028 return; // Literal format string found, check done!
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001029
Chris Lattner655f1412009-04-29 04:59:47 +00001030 // If there are no arguments specified, warn with -Wformat-security, otherwise
1031 // warn only with -Wformat-nonliteral.
1032 if (TheCall->getNumArgs() == format_idx+1)
Mike Stump1eb44332009-09-09 15:08:12 +00001033 Diag(TheCall->getArg(format_idx)->getLocStart(),
Chris Lattner655f1412009-04-29 04:59:47 +00001034 diag::warn_printf_nonliteral_noargs)
1035 << OrigFormatExpr->getSourceRange();
1036 else
Mike Stump1eb44332009-09-09 15:08:12 +00001037 Diag(TheCall->getArg(format_idx)->getLocStart(),
Chris Lattner655f1412009-04-29 04:59:47 +00001038 diag::warn_printf_nonliteral)
1039 << OrigFormatExpr->getSourceRange();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001040}
Ted Kremenek71895b92007-08-14 17:39:48 +00001041
Ted Kremeneke0e53132010-01-28 23:39:18 +00001042namespace {
Ted Kremenek74d56a12010-02-04 20:46:58 +00001043class CheckPrintfHandler : public analyze_printf::FormatStringHandler {
Ted Kremeneke0e53132010-01-28 23:39:18 +00001044 Sema &S;
1045 const StringLiteral *FExpr;
1046 const Expr *OrigFormatExpr;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001047 const unsigned NumDataArgs;
1048 const bool IsObjCLiteral;
1049 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00001050 const bool HasVAListArg;
1051 const CallExpr *TheCall;
1052 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001053 llvm::BitVector CoveredArgs;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001054public:
Ted Kremeneke0e53132010-01-28 23:39:18 +00001055 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
1056 const Expr *origFormatExpr,
1057 unsigned numDataArgs, bool isObjCLiteral,
Ted Kremenek0d277352010-01-29 01:06:55 +00001058 const char *beg, bool hasVAListArg,
1059 const CallExpr *theCall, unsigned formatIdx)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001060 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001061 NumDataArgs(numDataArgs),
Ted Kremenek0d277352010-01-29 01:06:55 +00001062 IsObjCLiteral(isObjCLiteral), Beg(beg),
1063 HasVAListArg(hasVAListArg),
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001064 TheCall(theCall), FormatIdx(formatIdx) {
1065 CoveredArgs.resize(numDataArgs);
1066 CoveredArgs.reset();
1067 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001068
Ted Kremenek07d161f2010-01-29 01:50:07 +00001069 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001070
Ted Kremenek808015a2010-01-29 03:16:21 +00001071 void HandleIncompleteFormatSpecifier(const char *startSpecifier,
1072 unsigned specifierLen);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001073
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001074 bool
Ted Kremenek74d56a12010-02-04 20:46:58 +00001075 HandleInvalidConversionSpecifier(const analyze_printf::FormatSpecifier &FS,
1076 const char *startSpecifier,
1077 unsigned specifierLen);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001078
Ted Kremeneke0e53132010-01-28 23:39:18 +00001079 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001080
Ted Kremeneke0e53132010-01-28 23:39:18 +00001081 bool HandleFormatSpecifier(const analyze_printf::FormatSpecifier &FS,
1082 const char *startSpecifier,
1083 unsigned specifierLen);
1084private:
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001085 SourceRange getFormatStringRange();
1086 SourceRange getFormatSpecifierRange(const char *startSpecifier,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001087 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001088 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001089
Ted Kremenek0d277352010-01-29 01:06:55 +00001090 bool HandleAmount(const analyze_printf::OptionalAmount &Amt,
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001091 unsigned MissingArgDiag, unsigned BadTypeDiag,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001092 const char *startSpecifier, unsigned specifierLen);
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001093 void HandleFlags(const analyze_printf::FormatSpecifier &FS,
1094 llvm::StringRef flag, llvm::StringRef cspec,
1095 const char *startSpecifier, unsigned specifierLen);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001096
Ted Kremenek0d277352010-01-29 01:06:55 +00001097 const Expr *getDataArg(unsigned i) const;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001098};
1099}
1100
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001101SourceRange CheckPrintfHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00001102 return OrigFormatExpr->getSourceRange();
1103}
1104
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001105SourceRange CheckPrintfHandler::
1106getFormatSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
1107 return SourceRange(getLocationOfByte(startSpecifier),
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001108 getLocationOfByte(startSpecifier+specifierLen-1));
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001109}
1110
Ted Kremeneke0e53132010-01-28 23:39:18 +00001111SourceLocation CheckPrintfHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001112 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001113}
1114
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001115void CheckPrintfHandler::
Ted Kremenek808015a2010-01-29 03:16:21 +00001116HandleIncompleteFormatSpecifier(const char *startSpecifier,
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001117 unsigned specifierLen) {
Ted Kremenek808015a2010-01-29 03:16:21 +00001118 SourceLocation Loc = getLocationOfByte(startSpecifier);
1119 S.Diag(Loc, diag::warn_printf_incomplete_specifier)
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001120 << getFormatSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek808015a2010-01-29 03:16:21 +00001121}
1122
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001123bool CheckPrintfHandler::
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001124HandleInvalidConversionSpecifier(const analyze_printf::FormatSpecifier &FS,
1125 const char *startSpecifier,
1126 unsigned specifierLen) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001127
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001128 unsigned argIndex = FS.getArgIndex();
1129 bool keepGoing = true;
1130 if (argIndex < NumDataArgs) {
1131 // Consider the argument coverered, even though the specifier doesn't
1132 // make sense.
1133 CoveredArgs.set(argIndex);
1134 }
1135 else {
1136 // If argIndex exceeds the number of data arguments we
1137 // don't issue a warning because that is just a cascade of warnings (and
1138 // they may have intended '%%' anyway). We don't want to continue processing
1139 // the format string after this point, however, as we will like just get
1140 // gibberish when trying to match arguments.
1141 keepGoing = false;
1142 }
1143
Ted Kremenek808015a2010-01-29 03:16:21 +00001144 const analyze_printf::ConversionSpecifier &CS =
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001145 FS.getConversionSpecifier();
Ted Kremenek808015a2010-01-29 03:16:21 +00001146 SourceLocation Loc = getLocationOfByte(CS.getStart());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001147 S.Diag(Loc, diag::warn_printf_invalid_conversion)
Ted Kremenek808015a2010-01-29 03:16:21 +00001148 << llvm::StringRef(CS.getStart(), CS.getLength())
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001149 << getFormatSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001150
1151 return keepGoing;
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001152}
1153
Ted Kremeneke0e53132010-01-28 23:39:18 +00001154void CheckPrintfHandler::HandleNullChar(const char *nullCharacter) {
1155 // The presence of a null character is likely an error.
1156 S.Diag(getLocationOfByte(nullCharacter),
1157 diag::warn_printf_format_string_contains_null_char)
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001158 << getFormatStringRange();
Ted Kremeneke0e53132010-01-28 23:39:18 +00001159}
1160
Ted Kremenek0d277352010-01-29 01:06:55 +00001161const Expr *CheckPrintfHandler::getDataArg(unsigned i) const {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001162 return TheCall->getArg(FormatIdx + i + 1);
Ted Kremenek0d277352010-01-29 01:06:55 +00001163}
1164
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001165
Ted Kremenekd635c5f2010-01-30 00:49:51 +00001166
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001167void CheckPrintfHandler::HandleFlags(const analyze_printf::FormatSpecifier &FS,
1168 llvm::StringRef flag,
1169 llvm::StringRef cspec,
1170 const char *startSpecifier,
1171 unsigned specifierLen) {
1172 const analyze_printf::ConversionSpecifier &CS = FS.getConversionSpecifier();
1173 S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_nonsensical_flag)
1174 << flag << cspec << getFormatSpecifierRange(startSpecifier, specifierLen);
1175}
1176
Ted Kremenek0d277352010-01-29 01:06:55 +00001177bool
1178CheckPrintfHandler::HandleAmount(const analyze_printf::OptionalAmount &Amt,
1179 unsigned MissingArgDiag,
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001180 unsigned BadTypeDiag,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001181 const char *startSpecifier,
1182 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001183
1184 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001185 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001186 unsigned argIndex = Amt.getArgIndex();
1187 if (argIndex >= NumDataArgs) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001188 S.Diag(getLocationOfByte(Amt.getStart()), MissingArgDiag)
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001189 << getFormatSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek0d277352010-01-29 01:06:55 +00001190 // Don't do any more checking. We will just emit
1191 // spurious errors.
1192 return false;
1193 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001194
Ted Kremenek0d277352010-01-29 01:06:55 +00001195 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00001196 // Although not in conformance with C99, we also allow the argument to be
1197 // an 'unsigned int' as that is a reasonably safe case. GCC also
1198 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001199 CoveredArgs.set(argIndex);
1200 const Expr *Arg = getDataArg(argIndex);
Ted Kremenek0d277352010-01-29 01:06:55 +00001201 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001202
1203 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
1204 assert(ATR.isValid());
1205
1206 if (!ATR.matchesType(S.Context, T)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001207 S.Diag(getLocationOfByte(Amt.getStart()), BadTypeDiag)
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001208 << ATR.getRepresentativeType(S.Context) << T
Ted Kremenekd635c5f2010-01-30 00:49:51 +00001209 << getFormatSpecifierRange(startSpecifier, specifierLen)
1210 << Arg->getSourceRange();
Ted Kremenek0d277352010-01-29 01:06:55 +00001211 // Don't do any more checking. We will just emit
1212 // spurious errors.
1213 return false;
1214 }
1215 }
1216 }
1217 return true;
1218}
Ted Kremenek0d277352010-01-29 01:06:55 +00001219
Ted Kremeneke0e53132010-01-28 23:39:18 +00001220bool
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001221CheckPrintfHandler::HandleFormatSpecifier(const analyze_printf::FormatSpecifier
1222 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001223 const char *startSpecifier,
1224 unsigned specifierLen) {
1225
1226 using namespace analyze_printf;
1227 const ConversionSpecifier &CS = FS.getConversionSpecifier();
1228
Ted Kremenek0d277352010-01-29 01:06:55 +00001229 // First check if the field width, precision, and conversion specifier
1230 // have matching data arguments.
1231 if (!HandleAmount(FS.getFieldWidth(),
1232 diag::warn_printf_asterisk_width_missing_arg,
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001233 diag::warn_printf_asterisk_width_wrong_type,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001234 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001235 return false;
1236 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001237
Ted Kremenek0d277352010-01-29 01:06:55 +00001238 if (!HandleAmount(FS.getPrecision(),
1239 diag::warn_printf_asterisk_precision_missing_arg,
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001240 diag::warn_printf_asterisk_precision_wrong_type,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001241 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001242 return false;
1243 }
1244
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001245 if (!CS.consumesDataArgument()) {
1246 // FIXME: Technically specifying a precision or field width here
1247 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001248 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001249 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001250
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001251 // Consume the argument.
1252 unsigned argIndex = FS.getArgIndex();
1253 CoveredArgs.set(argIndex);
1254
1255 // Check for using an Objective-C specific conversion specifier
1256 // in a non-ObjC literal.
1257 if (!IsObjCLiteral && CS.isObjCArg()) {
1258 return HandleInvalidConversionSpecifier(FS, startSpecifier, specifierLen);
1259 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001260
Ted Kremeneke82d8042010-01-29 01:35:25 +00001261 // Are we using '%n'? Issue a warning about this being
1262 // a possible security issue.
1263 if (CS.getKind() == ConversionSpecifier::OutIntPtrArg) {
1264 S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_write_back)
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001265 << getFormatSpecifierRange(startSpecifier, specifierLen);
Ted Kremeneke82d8042010-01-29 01:35:25 +00001266 // Continue checking the other format specifiers.
1267 return true;
1268 }
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001269
1270 if (CS.getKind() == ConversionSpecifier::VoidPtrArg) {
1271 if (FS.getPrecision().getHowSpecified() != OptionalAmount::NotSpecified)
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001272 S.Diag(getLocationOfByte(CS.getStart()),
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001273 diag::warn_printf_nonsensical_precision)
1274 << CS.getCharacters()
1275 << getFormatSpecifierRange(startSpecifier, specifierLen);
1276 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001277 if (CS.getKind() == ConversionSpecifier::VoidPtrArg ||
1278 CS.getKind() == ConversionSpecifier::CStrArg) {
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001279 // FIXME: Instead of using "0", "+", etc., eventually get them from
1280 // the FormatSpecifier.
1281 if (FS.hasLeadingZeros())
1282 HandleFlags(FS, "0", CS.getCharacters(), startSpecifier, specifierLen);
1283 if (FS.hasPlusPrefix())
1284 HandleFlags(FS, "+", CS.getCharacters(), startSpecifier, specifierLen);
1285 if (FS.hasSpacePrefix())
1286 HandleFlags(FS, " ", CS.getCharacters(), startSpecifier, specifierLen);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001287 }
1288
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001289 // The remaining checks depend on the data arguments.
1290 if (HasVAListArg)
1291 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001292
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001293 if (argIndex >= NumDataArgs) {
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001294 S.Diag(getLocationOfByte(CS.getStart()),
1295 diag::warn_printf_insufficient_data_args)
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001296 << getFormatSpecifierRange(startSpecifier, specifierLen);
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001297 // Don't do any more checking.
1298 return false;
1299 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001300
Ted Kremenekd635c5f2010-01-30 00:49:51 +00001301 // Now type check the data expression that matches the
1302 // format specifier.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001303 const Expr *Ex = getDataArg(argIndex);
Ted Kremenekd635c5f2010-01-30 00:49:51 +00001304 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001305 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
1306 // Check if we didn't match because of an implicit cast from a 'char'
1307 // or 'short' to an 'int'. This is done because printf is a varargs
1308 // function.
1309 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
1310 if (ICE->getType() == S.Context.IntTy)
1311 if (ATR.matchesType(S.Context, ICE->getSubExpr()->getType()))
1312 return true;
Ted Kremenek105d41c2010-02-01 19:38:10 +00001313
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001314 S.Diag(getLocationOfByte(CS.getStart()),
1315 diag::warn_printf_conversion_argument_type_mismatch)
1316 << ATR.getRepresentativeType(S.Context) << Ex->getType()
Ted Kremenek1497bff2010-02-11 19:37:25 +00001317 << getFormatSpecifierRange(startSpecifier, specifierLen)
1318 << Ex->getSourceRange();
Ted Kremenekd635c5f2010-01-30 00:49:51 +00001319 }
Ted Kremeneke0e53132010-01-28 23:39:18 +00001320
1321 return true;
1322}
1323
Ted Kremenek07d161f2010-01-29 01:50:07 +00001324void CheckPrintfHandler::DoneProcessing() {
1325 // Does the number of data arguments exceed the number of
1326 // format conversions in the format string?
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001327 if (!HasVAListArg) {
1328 // Find any arguments that weren't covered.
1329 CoveredArgs.flip();
1330 signed notCoveredArg = CoveredArgs.find_first();
1331 if (notCoveredArg >= 0) {
1332 assert((unsigned)notCoveredArg < NumDataArgs);
1333 S.Diag(getDataArg((unsigned) notCoveredArg)->getLocStart(),
1334 diag::warn_printf_data_arg_not_used)
1335 << getFormatStringRange();
1336 }
1337 }
Ted Kremenek07d161f2010-01-29 01:50:07 +00001338}
Ted Kremeneke0e53132010-01-28 23:39:18 +00001339
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001340void Sema::CheckPrintfString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001341 const Expr *OrigFormatExpr,
1342 const CallExpr *TheCall, bool HasVAListArg,
1343 unsigned format_idx, unsigned firstDataArg) {
1344
Ted Kremeneke0e53132010-01-28 23:39:18 +00001345 // CHECK: is the format string a wide literal?
1346 if (FExpr->isWide()) {
1347 Diag(FExpr->getLocStart(),
1348 diag::warn_printf_format_string_is_wide_literal)
1349 << OrigFormatExpr->getSourceRange();
1350 return;
1351 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001352
Ted Kremeneke0e53132010-01-28 23:39:18 +00001353 // Str - The format string. NOTE: this is NOT null-terminated!
1354 const char *Str = FExpr->getStrData();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001355
Ted Kremeneke0e53132010-01-28 23:39:18 +00001356 // CHECK: empty format string?
1357 unsigned StrLen = FExpr->getByteLength();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001358
Ted Kremeneke0e53132010-01-28 23:39:18 +00001359 if (StrLen == 0) {
1360 Diag(FExpr->getLocStart(), diag::warn_printf_empty_format_string)
1361 << OrigFormatExpr->getSourceRange();
1362 return;
1363 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001364
Ted Kremeneke0e53132010-01-28 23:39:18 +00001365 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr,
1366 TheCall->getNumArgs() - firstDataArg,
Ted Kremenek0d277352010-01-29 01:06:55 +00001367 isa<ObjCStringLiteral>(OrigFormatExpr), Str,
1368 HasVAListArg, TheCall, format_idx);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001369
Ted Kremenek74d56a12010-02-04 20:46:58 +00001370 if (!analyze_printf::ParseFormatString(H, Str, Str + StrLen))
Ted Kremenek808015a2010-01-29 03:16:21 +00001371 H.DoneProcessing();
Ted Kremenekce7024e2010-01-28 01:18:22 +00001372}
1373
Ted Kremenek06de2762007-08-17 16:46:58 +00001374//===--- CHECK: Return Address of Stack Variable --------------------------===//
1375
1376static DeclRefExpr* EvalVal(Expr *E);
1377static DeclRefExpr* EvalAddr(Expr* E);
1378
1379/// CheckReturnStackAddr - Check if a return statement returns the address
1380/// of a stack variable.
1381void
1382Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
1383 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00001384
Ted Kremenek06de2762007-08-17 16:46:58 +00001385 // Perform checking for returned stack addresses.
Steve Naroffdd972f22008-09-05 22:11:13 +00001386 if (lhsType->isPointerType() || lhsType->isBlockPointerType()) {
Ted Kremenek06de2762007-08-17 16:46:58 +00001387 if (DeclRefExpr *DR = EvalAddr(RetValExp))
Chris Lattner3c73c412008-11-19 08:23:25 +00001388 Diag(DR->getLocStart(), diag::warn_ret_stack_addr)
Chris Lattner08631c52008-11-23 21:45:46 +00001389 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001390
Steve Naroffc50a4a52008-09-16 22:25:10 +00001391 // Skip over implicit cast expressions when checking for block expressions.
Chris Lattner4ca606e2009-09-08 00:36:37 +00001392 RetValExp = RetValExp->IgnoreParenCasts();
Steve Naroffc50a4a52008-09-16 22:25:10 +00001393
Chris Lattner9e6b37a2009-10-30 04:01:58 +00001394 if (BlockExpr *C = dyn_cast<BlockExpr>(RetValExp))
Mike Stump397195b2009-04-17 00:09:41 +00001395 if (C->hasBlockDeclRefExprs())
1396 Diag(C->getLocStart(), diag::err_ret_local_block)
1397 << C->getSourceRange();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001398
Chris Lattner9e6b37a2009-10-30 04:01:58 +00001399 if (AddrLabelExpr *ALE = dyn_cast<AddrLabelExpr>(RetValExp))
1400 Diag(ALE->getLocStart(), diag::warn_ret_addr_label)
1401 << ALE->getSourceRange();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001402
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001403 } else if (lhsType->isReferenceType()) {
1404 // Perform checking for stack values returned by reference.
Douglas Gregor49badde2008-10-27 19:41:14 +00001405 // Check for a reference to the stack
1406 if (DeclRefExpr *DR = EvalVal(RetValExp))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001407 Diag(DR->getLocStart(), diag::warn_ret_stack_ref)
Chris Lattner08631c52008-11-23 21:45:46 +00001408 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Ted Kremenek06de2762007-08-17 16:46:58 +00001409 }
1410}
1411
1412/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
1413/// check if the expression in a return statement evaluates to an address
1414/// to a location on the stack. The recursion is used to traverse the
1415/// AST of the return expression, with recursion backtracking when we
1416/// encounter a subexpression that (1) clearly does not lead to the address
1417/// of a stack variable or (2) is something we cannot determine leads to
1418/// the address of a stack variable based on such local checking.
1419///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00001420/// EvalAddr processes expressions that are pointers that are used as
1421/// references (and not L-values). EvalVal handles all other values.
Mike Stump1eb44332009-09-09 15:08:12 +00001422/// At the base case of the recursion is a check for a DeclRefExpr* in
Ted Kremenek06de2762007-08-17 16:46:58 +00001423/// the refers to a stack variable.
1424///
1425/// This implementation handles:
1426///
1427/// * pointer-to-pointer casts
1428/// * implicit conversions from array references to pointers
1429/// * taking the address of fields
1430/// * arbitrary interplay between "&" and "*" operators
1431/// * pointer arithmetic from an address of a stack variable
1432/// * taking the address of an array element where the array is on the stack
1433static DeclRefExpr* EvalAddr(Expr *E) {
Ted Kremenek06de2762007-08-17 16:46:58 +00001434 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00001435 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00001436 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001437 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001438 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00001439
Ted Kremenek06de2762007-08-17 16:46:58 +00001440 // Our "symbolic interpreter" is just a dispatch off the currently
1441 // viewed AST node. We then recursively traverse the AST by calling
1442 // EvalAddr and EvalVal appropriately.
1443 switch (E->getStmtClass()) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001444 case Stmt::ParenExprClass:
1445 // Ignore parentheses.
1446 return EvalAddr(cast<ParenExpr>(E)->getSubExpr());
Ted Kremenek06de2762007-08-17 16:46:58 +00001447
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001448 case Stmt::UnaryOperatorClass: {
1449 // The only unary operator that make sense to handle here
1450 // is AddrOf. All others don't make sense as pointers.
1451 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001452
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001453 if (U->getOpcode() == UnaryOperator::AddrOf)
1454 return EvalVal(U->getSubExpr());
1455 else
Ted Kremenek06de2762007-08-17 16:46:58 +00001456 return NULL;
1457 }
Mike Stump1eb44332009-09-09 15:08:12 +00001458
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001459 case Stmt::BinaryOperatorClass: {
1460 // Handle pointer arithmetic. All other binary operators are not valid
1461 // in this context.
1462 BinaryOperator *B = cast<BinaryOperator>(E);
1463 BinaryOperator::Opcode op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00001464
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001465 if (op != BinaryOperator::Add && op != BinaryOperator::Sub)
1466 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001467
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001468 Expr *Base = B->getLHS();
1469
1470 // Determine which argument is the real pointer base. It could be
1471 // the RHS argument instead of the LHS.
1472 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00001473
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001474 assert (Base->getType()->isPointerType());
1475 return EvalAddr(Base);
1476 }
Steve Naroff61f40a22008-09-10 19:17:48 +00001477
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001478 // For conditional operators we need to see if either the LHS or RHS are
1479 // valid DeclRefExpr*s. If one of them is valid, we return it.
1480 case Stmt::ConditionalOperatorClass: {
1481 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001482
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001483 // Handle the GNU extension for missing LHS.
1484 if (Expr *lhsExpr = C->getLHS())
1485 if (DeclRefExpr* LHS = EvalAddr(lhsExpr))
1486 return LHS;
1487
1488 return EvalAddr(C->getRHS());
1489 }
Mike Stump1eb44332009-09-09 15:08:12 +00001490
Ted Kremenek54b52742008-08-07 00:49:01 +00001491 // For casts, we need to handle conversions from arrays to
1492 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00001493 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001494 case Stmt::CStyleCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00001495 case Stmt::CXXFunctionalCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001496 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenek54b52742008-08-07 00:49:01 +00001497 QualType T = SubExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001498
Steve Naroffdd972f22008-09-05 22:11:13 +00001499 if (SubExpr->getType()->isPointerType() ||
1500 SubExpr->getType()->isBlockPointerType() ||
1501 SubExpr->getType()->isObjCQualifiedIdType())
Ted Kremenek54b52742008-08-07 00:49:01 +00001502 return EvalAddr(SubExpr);
1503 else if (T->isArrayType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001504 return EvalVal(SubExpr);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001505 else
Ted Kremenek54b52742008-08-07 00:49:01 +00001506 return 0;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001507 }
Mike Stump1eb44332009-09-09 15:08:12 +00001508
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001509 // C++ casts. For dynamic casts, static casts, and const casts, we
1510 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor49badde2008-10-27 19:41:14 +00001511 // through the cast. In the case the dynamic cast doesn't fail (and
1512 // return NULL), we take the conservative route and report cases
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001513 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor49badde2008-10-27 19:41:14 +00001514 // FIXME: The comment about is wrong; we're not always converting
1515 // from pointer to pointer. I'm guessing that this code should also
Mike Stump1eb44332009-09-09 15:08:12 +00001516 // handle references to objects.
1517 case Stmt::CXXStaticCastExprClass:
1518 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00001519 case Stmt::CXXConstCastExprClass:
1520 case Stmt::CXXReinterpretCastExprClass: {
1521 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffdd972f22008-09-05 22:11:13 +00001522 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001523 return EvalAddr(S);
1524 else
1525 return NULL;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001526 }
Mike Stump1eb44332009-09-09 15:08:12 +00001527
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001528 // Everything else: we simply don't reason about them.
1529 default:
1530 return NULL;
1531 }
Ted Kremenek06de2762007-08-17 16:46:58 +00001532}
Mike Stump1eb44332009-09-09 15:08:12 +00001533
Ted Kremenek06de2762007-08-17 16:46:58 +00001534
1535/// EvalVal - This function is complements EvalAddr in the mutual recursion.
1536/// See the comments for EvalAddr for more details.
1537static DeclRefExpr* EvalVal(Expr *E) {
Mike Stump1eb44332009-09-09 15:08:12 +00001538
Ted Kremeneke8c600f2007-08-28 17:02:55 +00001539 // We should only be called for evaluating non-pointer expressions, or
1540 // expressions with a pointer type that are not used as references but instead
1541 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00001542
Ted Kremenek06de2762007-08-17 16:46:58 +00001543 // Our "symbolic interpreter" is just a dispatch off the currently
1544 // viewed AST node. We then recursively traverse the AST by calling
1545 // EvalAddr and EvalVal appropriately.
1546 switch (E->getStmtClass()) {
Douglas Gregora2813ce2009-10-23 18:54:35 +00001547 case Stmt::DeclRefExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00001548 // DeclRefExpr: the base case. When we hit a DeclRefExpr we are looking
1549 // at code that refers to a variable's name. We check if it has local
1550 // storage within the function, and if so, return the expression.
1551 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001552
Ted Kremenek06de2762007-08-17 16:46:58 +00001553 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Mike Stump1eb44332009-09-09 15:08:12 +00001554 if (V->hasLocalStorage() && !V->getType()->isReferenceType()) return DR;
1555
Ted Kremenek06de2762007-08-17 16:46:58 +00001556 return NULL;
1557 }
Mike Stump1eb44332009-09-09 15:08:12 +00001558
Ted Kremenek06de2762007-08-17 16:46:58 +00001559 case Stmt::ParenExprClass:
1560 // Ignore parentheses.
1561 return EvalVal(cast<ParenExpr>(E)->getSubExpr());
Mike Stump1eb44332009-09-09 15:08:12 +00001562
Ted Kremenek06de2762007-08-17 16:46:58 +00001563 case Stmt::UnaryOperatorClass: {
1564 // The only unary operator that make sense to handle here
1565 // is Deref. All others don't resolve to a "name." This includes
1566 // handling all sorts of rvalues passed to a unary operator.
1567 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001568
Ted Kremenek06de2762007-08-17 16:46:58 +00001569 if (U->getOpcode() == UnaryOperator::Deref)
1570 return EvalAddr(U->getSubExpr());
1571
1572 return NULL;
1573 }
Mike Stump1eb44332009-09-09 15:08:12 +00001574
Ted Kremenek06de2762007-08-17 16:46:58 +00001575 case Stmt::ArraySubscriptExprClass: {
1576 // Array subscripts are potential references to data on the stack. We
1577 // retrieve the DeclRefExpr* for the array variable if it indeed
1578 // has local storage.
Ted Kremenek23245122007-08-20 16:18:38 +00001579 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase());
Ted Kremenek06de2762007-08-17 16:46:58 +00001580 }
Mike Stump1eb44332009-09-09 15:08:12 +00001581
Ted Kremenek06de2762007-08-17 16:46:58 +00001582 case Stmt::ConditionalOperatorClass: {
1583 // For conditional operators we need to see if either the LHS or RHS are
1584 // non-NULL DeclRefExpr's. If one is non-NULL, we return it.
1585 ConditionalOperator *C = cast<ConditionalOperator>(E);
1586
Anders Carlsson39073232007-11-30 19:04:31 +00001587 // Handle the GNU extension for missing LHS.
1588 if (Expr *lhsExpr = C->getLHS())
1589 if (DeclRefExpr *LHS = EvalVal(lhsExpr))
1590 return LHS;
1591
1592 return EvalVal(C->getRHS());
Ted Kremenek06de2762007-08-17 16:46:58 +00001593 }
Mike Stump1eb44332009-09-09 15:08:12 +00001594
Ted Kremenek06de2762007-08-17 16:46:58 +00001595 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00001596 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00001597 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001598
Ted Kremenek06de2762007-08-17 16:46:58 +00001599 // Check for indirect access. We only want direct field accesses.
1600 if (!M->isArrow())
1601 return EvalVal(M->getBase());
1602 else
1603 return NULL;
1604 }
Mike Stump1eb44332009-09-09 15:08:12 +00001605
Ted Kremenek06de2762007-08-17 16:46:58 +00001606 // Everything else: we simply don't reason about them.
1607 default:
1608 return NULL;
1609 }
1610}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001611
1612//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
1613
1614/// Check for comparisons of floating point operands using != and ==.
1615/// Issue a warning if these are no self-comparisons, as they are not likely
1616/// to do what the programmer intended.
1617void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
1618 bool EmitWarning = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001619
Ted Kremenek4e99a5f2008-01-17 16:57:34 +00001620 Expr* LeftExprSansParen = lex->IgnoreParens();
Ted Kremenek32e97b62008-01-17 17:55:13 +00001621 Expr* RightExprSansParen = rex->IgnoreParens();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001622
1623 // Special case: check for x == x (which is OK).
1624 // Do not emit warnings for such cases.
1625 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
1626 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
1627 if (DRL->getDecl() == DRR->getDecl())
1628 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001629
1630
Ted Kremenek1b500bb2007-11-29 00:59:04 +00001631 // Special case: check for comparisons against literals that can be exactly
1632 // represented by APFloat. In such cases, do not emit a warning. This
1633 // is a heuristic: often comparison against such literals are used to
1634 // detect if a value in a variable has not changed. This clearly can
1635 // lead to false negatives.
1636 if (EmitWarning) {
1637 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
1638 if (FLL->isExact())
1639 EmitWarning = false;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001640 } else
Ted Kremenek1b500bb2007-11-29 00:59:04 +00001641 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
1642 if (FLR->isExact())
1643 EmitWarning = false;
1644 }
1645 }
Mike Stump1eb44332009-09-09 15:08:12 +00001646
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001647 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001648 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001649 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00001650 if (CL->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001651 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001652
Sebastian Redl0eb23302009-01-19 00:08:26 +00001653 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001654 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00001655 if (CR->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001656 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001657
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001658 // Emit the diagnostic.
1659 if (EmitWarning)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001660 Diag(loc, diag::warn_floatingpoint_eq)
1661 << lex->getSourceRange() << rex->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001662}
John McCallba26e582010-01-04 23:21:16 +00001663
John McCallf2370c92010-01-06 05:24:50 +00001664//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
1665//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00001666
John McCallf2370c92010-01-06 05:24:50 +00001667namespace {
John McCallba26e582010-01-04 23:21:16 +00001668
John McCallf2370c92010-01-06 05:24:50 +00001669/// Structure recording the 'active' range of an integer-valued
1670/// expression.
1671struct IntRange {
1672 /// The number of bits active in the int.
1673 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00001674
John McCallf2370c92010-01-06 05:24:50 +00001675 /// True if the int is known not to have negative values.
1676 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00001677
John McCallf2370c92010-01-06 05:24:50 +00001678 IntRange() {}
1679 IntRange(unsigned Width, bool NonNegative)
1680 : Width(Width), NonNegative(NonNegative)
1681 {}
John McCallba26e582010-01-04 23:21:16 +00001682
John McCallf2370c92010-01-06 05:24:50 +00001683 // Returns the range of the bool type.
1684 static IntRange forBoolType() {
1685 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00001686 }
1687
John McCallf2370c92010-01-06 05:24:50 +00001688 // Returns the range of an integral type.
1689 static IntRange forType(ASTContext &C, QualType T) {
1690 return forCanonicalType(C, T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00001691 }
1692
John McCallf2370c92010-01-06 05:24:50 +00001693 // Returns the range of an integeral type based on its canonical
1694 // representation.
1695 static IntRange forCanonicalType(ASTContext &C, const Type *T) {
1696 assert(T->isCanonicalUnqualified());
1697
1698 if (const VectorType *VT = dyn_cast<VectorType>(T))
1699 T = VT->getElementType().getTypePtr();
1700 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
1701 T = CT->getElementType().getTypePtr();
1702 if (const EnumType *ET = dyn_cast<EnumType>(T))
1703 T = ET->getDecl()->getIntegerType().getTypePtr();
1704
1705 const BuiltinType *BT = cast<BuiltinType>(T);
1706 assert(BT->isInteger());
1707
1708 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
1709 }
1710
1711 // Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00001712 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00001713 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00001714 L.NonNegative && R.NonNegative);
1715 }
1716
1717 // Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00001718 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00001719 return IntRange(std::min(L.Width, R.Width),
1720 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00001721 }
1722};
1723
1724IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
1725 if (value.isSigned() && value.isNegative())
1726 return IntRange(value.getMinSignedBits(), false);
1727
1728 if (value.getBitWidth() > MaxWidth)
1729 value.trunc(MaxWidth);
1730
1731 // isNonNegative() just checks the sign bit without considering
1732 // signedness.
1733 return IntRange(value.getActiveBits(), true);
1734}
1735
John McCall0acc3112010-01-06 22:57:21 +00001736IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
John McCallf2370c92010-01-06 05:24:50 +00001737 unsigned MaxWidth) {
1738 if (result.isInt())
1739 return GetValueRange(C, result.getInt(), MaxWidth);
1740
1741 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00001742 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
1743 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
1744 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
1745 R = IntRange::join(R, El);
1746 }
John McCallf2370c92010-01-06 05:24:50 +00001747 return R;
1748 }
1749
1750 if (result.isComplexInt()) {
1751 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
1752 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
1753 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00001754 }
1755
1756 // This can happen with lossless casts to intptr_t of "based" lvalues.
1757 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00001758 // FIXME: The only reason we need to pass the type in here is to get
1759 // the sign right on this one case. It would be nice if APValue
1760 // preserved this.
John McCallf2370c92010-01-06 05:24:50 +00001761 assert(result.isLValue());
John McCall0acc3112010-01-06 22:57:21 +00001762 return IntRange(MaxWidth, Ty->isUnsignedIntegerType());
John McCall51313c32010-01-04 23:31:57 +00001763}
John McCallf2370c92010-01-06 05:24:50 +00001764
1765/// Pseudo-evaluate the given integer expression, estimating the
1766/// range of values it might take.
1767///
1768/// \param MaxWidth - the width to which the value will be truncated
1769IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
1770 E = E->IgnoreParens();
1771
1772 // Try a full evaluation first.
1773 Expr::EvalResult result;
1774 if (E->Evaluate(result, C))
John McCall0acc3112010-01-06 22:57:21 +00001775 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00001776
1777 // I think we only want to look through implicit casts here; if the
1778 // user has an explicit widening cast, we should treat the value as
1779 // being of the new, wider type.
1780 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
1781 if (CE->getCastKind() == CastExpr::CK_NoOp)
1782 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
1783
1784 IntRange OutputTypeRange = IntRange::forType(C, CE->getType());
1785
John McCall60fad452010-01-06 22:07:33 +00001786 bool isIntegerCast = (CE->getCastKind() == CastExpr::CK_IntegralCast);
1787 if (!isIntegerCast && CE->getCastKind() == CastExpr::CK_Unknown)
1788 isIntegerCast = CE->getSubExpr()->getType()->isIntegerType();
1789
John McCallf2370c92010-01-06 05:24:50 +00001790 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00001791 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00001792 return OutputTypeRange;
1793
1794 IntRange SubRange
1795 = GetExprRange(C, CE->getSubExpr(),
1796 std::min(MaxWidth, OutputTypeRange.Width));
1797
1798 // Bail out if the subexpr's range is as wide as the cast type.
1799 if (SubRange.Width >= OutputTypeRange.Width)
1800 return OutputTypeRange;
1801
1802 // Otherwise, we take the smaller width, and we're non-negative if
1803 // either the output type or the subexpr is.
1804 return IntRange(SubRange.Width,
1805 SubRange.NonNegative || OutputTypeRange.NonNegative);
1806 }
1807
1808 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1809 // If we can fold the condition, just take that operand.
1810 bool CondResult;
1811 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
1812 return GetExprRange(C, CondResult ? CO->getTrueExpr()
1813 : CO->getFalseExpr(),
1814 MaxWidth);
1815
1816 // Otherwise, conservatively merge.
1817 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
1818 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
1819 return IntRange::join(L, R);
1820 }
1821
1822 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
1823 switch (BO->getOpcode()) {
1824
1825 // Boolean-valued operations are single-bit and positive.
1826 case BinaryOperator::LAnd:
1827 case BinaryOperator::LOr:
1828 case BinaryOperator::LT:
1829 case BinaryOperator::GT:
1830 case BinaryOperator::LE:
1831 case BinaryOperator::GE:
1832 case BinaryOperator::EQ:
1833 case BinaryOperator::NE:
1834 return IntRange::forBoolType();
1835
John McCallc0cd21d2010-02-23 19:22:29 +00001836 // The type of these compound assignments is the type of the LHS,
1837 // so the RHS is not necessarily an integer.
1838 case BinaryOperator::MulAssign:
1839 case BinaryOperator::DivAssign:
1840 case BinaryOperator::RemAssign:
1841 case BinaryOperator::AddAssign:
1842 case BinaryOperator::SubAssign:
1843 return IntRange::forType(C, E->getType());
1844
John McCallf2370c92010-01-06 05:24:50 +00001845 // Operations with opaque sources are black-listed.
1846 case BinaryOperator::PtrMemD:
1847 case BinaryOperator::PtrMemI:
1848 return IntRange::forType(C, E->getType());
1849
John McCall60fad452010-01-06 22:07:33 +00001850 // Bitwise-and uses the *infinum* of the two source ranges.
1851 case BinaryOperator::And:
John McCallc0cd21d2010-02-23 19:22:29 +00001852 case BinaryOperator::AndAssign:
John McCall60fad452010-01-06 22:07:33 +00001853 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
1854 GetExprRange(C, BO->getRHS(), MaxWidth));
1855
John McCallf2370c92010-01-06 05:24:50 +00001856 // Left shift gets black-listed based on a judgement call.
1857 case BinaryOperator::Shl:
John McCallc0cd21d2010-02-23 19:22:29 +00001858 case BinaryOperator::ShlAssign:
John McCallf2370c92010-01-06 05:24:50 +00001859 return IntRange::forType(C, E->getType());
1860
John McCall60fad452010-01-06 22:07:33 +00001861 // Right shift by a constant can narrow its left argument.
John McCallc0cd21d2010-02-23 19:22:29 +00001862 case BinaryOperator::Shr:
1863 case BinaryOperator::ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00001864 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
1865
1866 // If the shift amount is a positive constant, drop the width by
1867 // that much.
1868 llvm::APSInt shift;
1869 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
1870 shift.isNonNegative()) {
1871 unsigned zext = shift.getZExtValue();
1872 if (zext >= L.Width)
1873 L.Width = (L.NonNegative ? 0 : 1);
1874 else
1875 L.Width -= zext;
1876 }
1877
1878 return L;
1879 }
1880
1881 // Comma acts as its right operand.
John McCallf2370c92010-01-06 05:24:50 +00001882 case BinaryOperator::Comma:
1883 return GetExprRange(C, BO->getRHS(), MaxWidth);
1884
John McCall60fad452010-01-06 22:07:33 +00001885 // Black-list pointer subtractions.
John McCallf2370c92010-01-06 05:24:50 +00001886 case BinaryOperator::Sub:
1887 if (BO->getLHS()->getType()->isPointerType())
1888 return IntRange::forType(C, E->getType());
1889 // fallthrough
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001890
John McCallf2370c92010-01-06 05:24:50 +00001891 default:
1892 break;
1893 }
1894
1895 // Treat every other operator as if it were closed on the
1896 // narrowest type that encompasses both operands.
1897 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
1898 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
1899 return IntRange::join(L, R);
1900 }
1901
1902 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
1903 switch (UO->getOpcode()) {
1904 // Boolean-valued operations are white-listed.
1905 case UnaryOperator::LNot:
1906 return IntRange::forBoolType();
1907
1908 // Operations with opaque sources are black-listed.
1909 case UnaryOperator::Deref:
1910 case UnaryOperator::AddrOf: // should be impossible
1911 case UnaryOperator::OffsetOf:
1912 return IntRange::forType(C, E->getType());
1913
1914 default:
1915 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
1916 }
1917 }
1918
1919 FieldDecl *BitField = E->getBitField();
1920 if (BitField) {
1921 llvm::APSInt BitWidthAP = BitField->getBitWidth()->EvaluateAsInt(C);
1922 unsigned BitWidth = BitWidthAP.getZExtValue();
1923
1924 return IntRange(BitWidth, BitField->getType()->isUnsignedIntegerType());
1925 }
1926
1927 return IntRange::forType(C, E->getType());
1928}
John McCall51313c32010-01-04 23:31:57 +00001929
1930/// Checks whether the given value, which currently has the given
1931/// source semantics, has the same value when coerced through the
1932/// target semantics.
John McCallf2370c92010-01-06 05:24:50 +00001933bool IsSameFloatAfterCast(const llvm::APFloat &value,
1934 const llvm::fltSemantics &Src,
1935 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00001936 llvm::APFloat truncated = value;
1937
1938 bool ignored;
1939 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
1940 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
1941
1942 return truncated.bitwiseIsEqual(value);
1943}
1944
1945/// Checks whether the given value, which currently has the given
1946/// source semantics, has the same value when coerced through the
1947/// target semantics.
1948///
1949/// The value might be a vector of floats (or a complex number).
John McCallf2370c92010-01-06 05:24:50 +00001950bool IsSameFloatAfterCast(const APValue &value,
1951 const llvm::fltSemantics &Src,
1952 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00001953 if (value.isFloat())
1954 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
1955
1956 if (value.isVector()) {
1957 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
1958 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
1959 return false;
1960 return true;
1961 }
1962
1963 assert(value.isComplexFloat());
1964 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
1965 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
1966}
1967
John McCallf2370c92010-01-06 05:24:50 +00001968} // end anonymous namespace
John McCall51313c32010-01-04 23:31:57 +00001969
John McCallba26e582010-01-04 23:21:16 +00001970/// \brief Implements -Wsign-compare.
1971///
1972/// \param lex the left-hand expression
1973/// \param rex the right-hand expression
1974/// \param OpLoc the location of the joining operator
1975/// \param Equality whether this is an "equality-like" join, which
1976/// suppresses the warning in some cases
1977void Sema::CheckSignCompare(Expr *lex, Expr *rex, SourceLocation OpLoc,
1978 const PartialDiagnostic &PD, bool Equality) {
1979 // Don't warn if we're in an unevaluated context.
1980 if (ExprEvalContexts.back().Context == Unevaluated)
1981 return;
1982
John McCallf2370c92010-01-06 05:24:50 +00001983 // If either expression is value-dependent, don't warn. We'll get another
1984 // chance at instantiation time.
1985 if (lex->isValueDependent() || rex->isValueDependent())
1986 return;
1987
John McCallba26e582010-01-04 23:21:16 +00001988 QualType lt = lex->getType(), rt = rex->getType();
1989
1990 // Only warn if both operands are integral.
1991 if (!lt->isIntegerType() || !rt->isIntegerType())
1992 return;
1993
John McCallf2370c92010-01-06 05:24:50 +00001994 // In C, the width of a bitfield determines its type, and the
1995 // declared type only contributes the signedness. This duplicates
1996 // the work that will later be done by UsualUnaryConversions.
1997 // Eventually, this check will be reorganized in a way that avoids
1998 // this duplication.
1999 if (!getLangOptions().CPlusPlus) {
2000 QualType tmp;
2001 tmp = Context.isPromotableBitField(lex);
2002 if (!tmp.isNull()) lt = tmp;
2003 tmp = Context.isPromotableBitField(rex);
2004 if (!tmp.isNull()) rt = tmp;
2005 }
John McCallba26e582010-01-04 23:21:16 +00002006
2007 // The rule is that the signed operand becomes unsigned, so isolate the
2008 // signed operand.
John McCallf2370c92010-01-06 05:24:50 +00002009 Expr *signedOperand = lex, *unsignedOperand = rex;
2010 QualType signedType = lt, unsignedType = rt;
John McCallba26e582010-01-04 23:21:16 +00002011 if (lt->isSignedIntegerType()) {
2012 if (rt->isSignedIntegerType()) return;
John McCallba26e582010-01-04 23:21:16 +00002013 } else {
2014 if (!rt->isSignedIntegerType()) return;
John McCallf2370c92010-01-06 05:24:50 +00002015 std::swap(signedOperand, unsignedOperand);
2016 std::swap(signedType, unsignedType);
John McCallba26e582010-01-04 23:21:16 +00002017 }
2018
John McCallf2370c92010-01-06 05:24:50 +00002019 unsigned unsignedWidth = Context.getIntWidth(unsignedType);
2020 unsigned signedWidth = Context.getIntWidth(signedType);
2021
John McCallba26e582010-01-04 23:21:16 +00002022 // If the unsigned type is strictly smaller than the signed type,
2023 // then (1) the result type will be signed and (2) the unsigned
2024 // value will fit fully within the signed type, and thus the result
2025 // of the comparison will be exact.
John McCallf2370c92010-01-06 05:24:50 +00002026 if (signedWidth > unsignedWidth)
John McCallba26e582010-01-04 23:21:16 +00002027 return;
2028
John McCallf2370c92010-01-06 05:24:50 +00002029 // Otherwise, calculate the effective ranges.
2030 IntRange signedRange = GetExprRange(Context, signedOperand, signedWidth);
2031 IntRange unsignedRange = GetExprRange(Context, unsignedOperand, unsignedWidth);
2032
2033 // We should never be unable to prove that the unsigned operand is
2034 // non-negative.
2035 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
2036
2037 // If the signed operand is non-negative, then the signed->unsigned
2038 // conversion won't change it.
2039 if (signedRange.NonNegative)
John McCallba26e582010-01-04 23:21:16 +00002040 return;
2041
2042 // For (in)equality comparisons, if the unsigned operand is a
2043 // constant which cannot collide with a overflowed signed operand,
2044 // then reinterpreting the signed operand as unsigned will not
2045 // change the result of the comparison.
John McCallf2370c92010-01-06 05:24:50 +00002046 if (Equality && unsignedRange.Width < unsignedWidth)
John McCallba26e582010-01-04 23:21:16 +00002047 return;
2048
2049 Diag(OpLoc, PD)
John McCallf2370c92010-01-06 05:24:50 +00002050 << lt << rt << lex->getSourceRange() << rex->getSourceRange();
John McCallba26e582010-01-04 23:21:16 +00002051}
2052
John McCall51313c32010-01-04 23:31:57 +00002053/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
2054static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, unsigned diag) {
2055 S.Diag(E->getExprLoc(), diag) << E->getType() << T << E->getSourceRange();
2056}
2057
2058/// Implements -Wconversion.
2059void Sema::CheckImplicitConversion(Expr *E, QualType T) {
2060 // Don't diagnose in unevaluated contexts.
2061 if (ExprEvalContexts.back().Context == Sema::Unevaluated)
2062 return;
2063
2064 // Don't diagnose for value-dependent expressions.
2065 if (E->isValueDependent())
2066 return;
2067
2068 const Type *Source = Context.getCanonicalType(E->getType()).getTypePtr();
2069 const Type *Target = Context.getCanonicalType(T).getTypePtr();
2070
2071 // Never diagnose implicit casts to bool.
2072 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
2073 return;
2074
2075 // Strip vector types.
2076 if (isa<VectorType>(Source)) {
2077 if (!isa<VectorType>(Target))
2078 return DiagnoseImpCast(*this, E, T, diag::warn_impcast_vector_scalar);
2079
2080 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
2081 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
2082 }
2083
2084 // Strip complex types.
2085 if (isa<ComplexType>(Source)) {
2086 if (!isa<ComplexType>(Target))
2087 return DiagnoseImpCast(*this, E, T, diag::warn_impcast_complex_scalar);
2088
2089 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
2090 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
2091 }
2092
2093 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
2094 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
2095
2096 // If the source is floating point...
2097 if (SourceBT && SourceBT->isFloatingPoint()) {
2098 // ...and the target is floating point...
2099 if (TargetBT && TargetBT->isFloatingPoint()) {
2100 // ...then warn if we're dropping FP rank.
2101
2102 // Builtin FP kinds are ordered by increasing FP rank.
2103 if (SourceBT->getKind() > TargetBT->getKind()) {
2104 // Don't warn about float constants that are precisely
2105 // representable in the target type.
2106 Expr::EvalResult result;
2107 if (E->Evaluate(result, Context)) {
2108 // Value might be a float, a float vector, or a float complex.
2109 if (IsSameFloatAfterCast(result.Val,
2110 Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
2111 Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
2112 return;
2113 }
2114
2115 DiagnoseImpCast(*this, E, T, diag::warn_impcast_float_precision);
2116 }
2117 return;
2118 }
2119
2120 // If the target is integral, always warn.
2121 if ((TargetBT && TargetBT->isInteger()))
2122 // TODO: don't warn for integer values?
2123 return DiagnoseImpCast(*this, E, T, diag::warn_impcast_float_integer);
2124
2125 return;
2126 }
2127
John McCallf2370c92010-01-06 05:24:50 +00002128 if (!Source->isIntegerType() || !Target->isIntegerType())
John McCall51313c32010-01-04 23:31:57 +00002129 return;
2130
John McCallf2370c92010-01-06 05:24:50 +00002131 IntRange SourceRange = GetExprRange(Context, E, Context.getIntWidth(E->getType()));
2132 IntRange TargetRange = IntRange::forCanonicalType(Context, Target);
John McCall51313c32010-01-04 23:31:57 +00002133
John McCallf2370c92010-01-06 05:24:50 +00002134 // FIXME: also signed<->unsigned?
2135
2136 if (SourceRange.Width > TargetRange.Width) {
John McCall51313c32010-01-04 23:31:57 +00002137 // People want to build with -Wshorten-64-to-32 and not -Wconversion
2138 // and by god we'll let them.
John McCallf2370c92010-01-06 05:24:50 +00002139 if (SourceRange.Width == 64 && TargetRange.Width == 32)
John McCall51313c32010-01-04 23:31:57 +00002140 return DiagnoseImpCast(*this, E, T, diag::warn_impcast_integer_64_32);
2141 return DiagnoseImpCast(*this, E, T, diag::warn_impcast_integer_precision);
2142 }
2143
2144 return;
2145}
2146
Mike Stumpe5fba702010-01-21 19:44:04 +00002147
Mike Stumpf8c49212010-01-21 03:59:47 +00002148
Mike Stump4a415672010-01-21 23:49:01 +00002149namespace {
Ted Kremenek72919a32010-02-23 05:59:20 +00002150class UnreachableCodeHandler : public reachable_code::Callback {
2151 Sema &S;
2152public:
2153 UnreachableCodeHandler(Sema *s) : S(*s) {}
2154
2155 void HandleUnreachable(SourceLocation L, SourceRange R1, SourceRange R2) {
2156 S.Diag(L, diag::warn_unreachable) << R1 << R2;
2157 }
2158};
Mike Stump4a415672010-01-21 23:49:01 +00002159}
2160
Mike Stumpf8c49212010-01-21 03:59:47 +00002161/// CheckUnreachable - Check for unreachable code.
2162void Sema::CheckUnreachable(AnalysisContext &AC) {
Mike Stumpf8c49212010-01-21 03:59:47 +00002163 // We avoid checking when there are errors, as the CFG won't faithfully match
2164 // the user's code.
Ted Kremenekf067d8e2010-02-23 01:39:04 +00002165 if (getDiagnostics().hasErrorOccurred() ||
2166 Diags.getDiagnosticLevel(diag::warn_unreachable) == Diagnostic::Ignored)
Mike Stumpf8c49212010-01-21 03:59:47 +00002167 return;
2168
Ted Kremenek72919a32010-02-23 05:59:20 +00002169 UnreachableCodeHandler UC(this);
2170 reachable_code::FindUnreachableCode(AC, UC);
Mike Stumpf8c49212010-01-21 03:59:47 +00002171}
2172
2173/// CheckFallThrough - Check that we don't fall off the end of a
2174/// Statement that should return a value.
2175///
2176/// \returns AlwaysFallThrough iff we always fall off the end of the statement,
2177/// MaybeFallThrough iff we might or might not fall off the end,
2178/// NeverFallThroughOrReturn iff we never fall off the end of the statement or
2179/// return. We assume NeverFallThrough iff we never fall off the end of the
2180/// statement but we may return. We assume that functions not marked noreturn
2181/// will return.
2182Sema::ControlFlowKind Sema::CheckFallThrough(AnalysisContext &AC) {
2183 CFG *cfg = AC.getCFG();
2184 if (cfg == 0)
2185 // FIXME: This should be NeverFallThrough
2186 return NeverFallThroughOrReturn;
2187
Mike Stump4c45aa12010-01-21 15:20:48 +00002188 // The CFG leaves in dead things, and we don't want the dead code paths to
Mike Stumpf8c49212010-01-21 03:59:47 +00002189 // confuse us, so we mark all live things first.
2190 std::queue<CFGBlock*> workq;
2191 llvm::BitVector live(cfg->getNumBlockIDs());
Ted Kremenek72919a32010-02-23 05:59:20 +00002192 unsigned count = reachable_code::ScanReachableFromBlock(cfg->getEntry(),
2193 live);
Mike Stump4c45aa12010-01-21 15:20:48 +00002194
2195 bool AddEHEdges = AC.getAddEHEdges();
2196 if (!AddEHEdges && count != cfg->getNumBlockIDs())
2197 // When there are things remaining dead, and we didn't add EH edges
2198 // from CallExprs to the catch clauses, we have to go back and
2199 // mark them as live.
2200 for (CFG::iterator I = cfg->begin(), E = cfg->end(); I != E; ++I) {
2201 CFGBlock &b = **I;
2202 if (!live[b.getBlockID()]) {
2203 if (b.pred_begin() == b.pred_end()) {
2204 if (b.getTerminator() && isa<CXXTryStmt>(b.getTerminator()))
2205 // When not adding EH edges from calls, catch clauses
2206 // can otherwise seem dead. Avoid noting them as dead.
Ted Kremenek72919a32010-02-23 05:59:20 +00002207 count += reachable_code::ScanReachableFromBlock(b, live);
Mike Stump4c45aa12010-01-21 15:20:48 +00002208 continue;
2209 }
2210 }
2211 }
Mike Stumpf8c49212010-01-21 03:59:47 +00002212
2213 // Now we know what is live, we check the live precessors of the exit block
2214 // and look for fall through paths, being careful to ignore normal returns,
2215 // and exceptional paths.
2216 bool HasLiveReturn = false;
2217 bool HasFakeEdge = false;
2218 bool HasPlainEdge = false;
2219 bool HasAbnormalEdge = false;
2220 for (CFGBlock::pred_iterator I=cfg->getExit().pred_begin(),
2221 E = cfg->getExit().pred_end();
2222 I != E;
2223 ++I) {
2224 CFGBlock& B = **I;
2225 if (!live[B.getBlockID()])
2226 continue;
2227 if (B.size() == 0) {
Mike Stump4c45aa12010-01-21 15:20:48 +00002228 if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
2229 HasAbnormalEdge = true;
2230 continue;
2231 }
2232
Mike Stumpf8c49212010-01-21 03:59:47 +00002233 // A labeled empty statement, or the entry block...
2234 HasPlainEdge = true;
2235 continue;
2236 }
2237 Stmt *S = B[B.size()-1];
2238 if (isa<ReturnStmt>(S)) {
2239 HasLiveReturn = true;
2240 continue;
2241 }
2242 if (isa<ObjCAtThrowStmt>(S)) {
2243 HasFakeEdge = true;
2244 continue;
2245 }
2246 if (isa<CXXThrowExpr>(S)) {
2247 HasFakeEdge = true;
2248 continue;
2249 }
2250 if (const AsmStmt *AS = dyn_cast<AsmStmt>(S)) {
2251 if (AS->isMSAsm()) {
2252 HasFakeEdge = true;
2253 HasLiveReturn = true;
2254 continue;
2255 }
2256 }
2257 if (isa<CXXTryStmt>(S)) {
2258 HasAbnormalEdge = true;
2259 continue;
2260 }
2261
2262 bool NoReturnEdge = false;
2263 if (CallExpr *C = dyn_cast<CallExpr>(S)) {
2264 if (B.succ_begin()[0] != &cfg->getExit()) {
2265 HasAbnormalEdge = true;
2266 continue;
2267 }
2268 Expr *CEE = C->getCallee()->IgnoreParenCasts();
2269 if (CEE->getType().getNoReturnAttr()) {
2270 NoReturnEdge = true;
2271 HasFakeEdge = true;
2272 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE)) {
2273 ValueDecl *VD = DRE->getDecl();
2274 if (VD->hasAttr<NoReturnAttr>()) {
2275 NoReturnEdge = true;
2276 HasFakeEdge = true;
2277 }
2278 }
2279 }
2280 // FIXME: Add noreturn message sends.
2281 if (NoReturnEdge == false)
2282 HasPlainEdge = true;
2283 }
2284 if (!HasPlainEdge) {
2285 if (HasLiveReturn)
2286 return NeverFallThrough;
2287 return NeverFallThroughOrReturn;
2288 }
2289 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
2290 return MaybeFallThrough;
2291 // This says AlwaysFallThrough for calls to functions that are not marked
2292 // noreturn, that don't return. If people would like this warning to be more
2293 // accurate, such functions should be marked as noreturn.
2294 return AlwaysFallThrough;
2295}
2296
2297/// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
2298/// function that should return a value. Check that we don't fall off the end
2299/// of a noreturn function. We assume that functions and blocks not marked
2300/// noreturn will return.
2301void Sema::CheckFallThroughForFunctionDef(Decl *D, Stmt *Body,
2302 AnalysisContext &AC) {
2303 // FIXME: Would be nice if we had a better way to control cascading errors,
2304 // but for now, avoid them. The problem is that when Parse sees:
2305 // int foo() { return a; }
2306 // The return is eaten and the Sema code sees just:
2307 // int foo() { }
2308 // which this code would then warn about.
2309 if (getDiagnostics().hasErrorOccurred())
2310 return;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002311
Mike Stumpf8c49212010-01-21 03:59:47 +00002312 bool ReturnsVoid = false;
2313 bool HasNoReturn = false;
Ted Kremenek1e025f22010-02-23 01:19:11 +00002314
Mike Stumpf8c49212010-01-21 03:59:47 +00002315 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Anders Carlsson4855a522010-02-06 05:31:15 +00002316 // For function templates, class templates and member function templates
2317 // we'll do the analysis at instantiation time.
2318 if (FD->isDependentContext())
Mike Stumpf8c49212010-01-21 03:59:47 +00002319 return;
Anders Carlsson4855a522010-02-06 05:31:15 +00002320
Ted Kremenek1e025f22010-02-23 01:19:11 +00002321 ReturnsVoid = FD->getResultType()->isVoidType();
2322 HasNoReturn = FD->hasAttr<NoReturnAttr>() ||
2323 FD->getType()->getAs<FunctionType>()->getNoReturnAttr();
2324
Mike Stumpf8c49212010-01-21 03:59:47 +00002325 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Ted Kremenek1e025f22010-02-23 01:19:11 +00002326 ReturnsVoid = MD->getResultType()->isVoidType();
2327 HasNoReturn = MD->hasAttr<NoReturnAttr>();
Mike Stumpf8c49212010-01-21 03:59:47 +00002328 }
2329
2330 // Short circuit for compilation speed.
2331 if ((Diags.getDiagnosticLevel(diag::warn_maybe_falloff_nonvoid_function)
2332 == Diagnostic::Ignored || ReturnsVoid)
2333 && (Diags.getDiagnosticLevel(diag::warn_noreturn_function_has_return_expr)
2334 == Diagnostic::Ignored || !HasNoReturn)
2335 && (Diags.getDiagnosticLevel(diag::warn_suggest_noreturn_block)
2336 == Diagnostic::Ignored || !ReturnsVoid))
2337 return;
2338 // FIXME: Function try block
2339 if (CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) {
2340 switch (CheckFallThrough(AC)) {
2341 case MaybeFallThrough:
2342 if (HasNoReturn)
2343 Diag(Compound->getRBracLoc(), diag::warn_falloff_noreturn_function);
2344 else if (!ReturnsVoid)
2345 Diag(Compound->getRBracLoc(),diag::warn_maybe_falloff_nonvoid_function);
2346 break;
2347 case AlwaysFallThrough:
2348 if (HasNoReturn)
2349 Diag(Compound->getRBracLoc(), diag::warn_falloff_noreturn_function);
2350 else if (!ReturnsVoid)
2351 Diag(Compound->getRBracLoc(), diag::warn_falloff_nonvoid_function);
2352 break;
2353 case NeverFallThroughOrReturn:
2354 if (ReturnsVoid && !HasNoReturn)
2355 Diag(Compound->getLBracLoc(), diag::warn_suggest_noreturn_function);
2356 break;
2357 case NeverFallThrough:
2358 break;
2359 }
2360 }
2361}
2362
2363/// CheckFallThroughForBlock - Check that we don't fall off the end of a block
2364/// that should return a value. Check that we don't fall off the end of a
2365/// noreturn block. We assume that functions and blocks not marked noreturn
2366/// will return.
2367void Sema::CheckFallThroughForBlock(QualType BlockTy, Stmt *Body,
2368 AnalysisContext &AC) {
2369 // FIXME: Would be nice if we had a better way to control cascading errors,
2370 // but for now, avoid them. The problem is that when Parse sees:
2371 // int foo() { return a; }
2372 // The return is eaten and the Sema code sees just:
2373 // int foo() { }
2374 // which this code would then warn about.
2375 if (getDiagnostics().hasErrorOccurred())
2376 return;
2377 bool ReturnsVoid = false;
2378 bool HasNoReturn = false;
2379 if (const FunctionType *FT =BlockTy->getPointeeType()->getAs<FunctionType>()){
2380 if (FT->getResultType()->isVoidType())
2381 ReturnsVoid = true;
2382 if (FT->getNoReturnAttr())
2383 HasNoReturn = true;
2384 }
2385
2386 // Short circuit for compilation speed.
2387 if (ReturnsVoid
2388 && !HasNoReturn
2389 && (Diags.getDiagnosticLevel(diag::warn_suggest_noreturn_block)
2390 == Diagnostic::Ignored || !ReturnsVoid))
2391 return;
2392 // FIXME: Funtion try block
2393 if (CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) {
2394 switch (CheckFallThrough(AC)) {
2395 case MaybeFallThrough:
2396 if (HasNoReturn)
2397 Diag(Compound->getRBracLoc(), diag::err_noreturn_block_has_return_expr);
2398 else if (!ReturnsVoid)
2399 Diag(Compound->getRBracLoc(), diag::err_maybe_falloff_nonvoid_block);
2400 break;
2401 case AlwaysFallThrough:
2402 if (HasNoReturn)
2403 Diag(Compound->getRBracLoc(), diag::err_noreturn_block_has_return_expr);
2404 else if (!ReturnsVoid)
2405 Diag(Compound->getRBracLoc(), diag::err_falloff_nonvoid_block);
2406 break;
2407 case NeverFallThroughOrReturn:
2408 if (ReturnsVoid)
2409 Diag(Compound->getLBracLoc(), diag::warn_suggest_noreturn_block);
2410 break;
2411 case NeverFallThrough:
2412 break;
2413 }
2414 }
2415}
2416
2417/// CheckParmsForFunctionDef - Check that the parameters of the given
2418/// function are appropriate for the definition of a function. This
2419/// takes care of any checks that cannot be performed on the
2420/// declaration itself, e.g., that the types of each of the function
2421/// parameters are complete.
2422bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
2423 bool HasInvalidParm = false;
2424 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2425 ParmVarDecl *Param = FD->getParamDecl(p);
2426
2427 // C99 6.7.5.3p4: the parameters in a parameter type list in a
2428 // function declarator that is part of a function definition of
2429 // that function shall not have incomplete type.
2430 //
2431 // This is also C++ [dcl.fct]p6.
2432 if (!Param->isInvalidDecl() &&
2433 RequireCompleteType(Param->getLocation(), Param->getType(),
2434 diag::err_typecheck_decl_incomplete_type)) {
2435 Param->setInvalidDecl();
2436 HasInvalidParm = true;
2437 }
2438
2439 // C99 6.9.1p5: If the declarator includes a parameter type list, the
2440 // declaration of each parameter shall include an identifier.
2441 if (Param->getIdentifier() == 0 &&
2442 !Param->isImplicit() &&
2443 !getLangOptions().CPlusPlus)
2444 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00002445
2446 // C99 6.7.5.3p12:
2447 // If the function declarator is not part of a definition of that
2448 // function, parameters may have incomplete type and may use the [*]
2449 // notation in their sequences of declarator specifiers to specify
2450 // variable length array types.
2451 QualType PType = Param->getOriginalType();
2452 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
2453 if (AT->getSizeModifier() == ArrayType::Star) {
2454 // FIXME: This diagnosic should point the the '[*]' if source-location
2455 // information is added for it.
2456 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
2457 }
2458 }
John McCall4f9506a2010-02-02 08:45:54 +00002459
John McCall68c6c9a2010-02-02 09:10:11 +00002460 if (getLangOptions().CPlusPlus)
2461 if (const RecordType *RT = Param->getType()->getAs<RecordType>())
2462 FinalizeVarWithDestructor(Param, RT);
Mike Stumpf8c49212010-01-21 03:59:47 +00002463 }
2464
2465 return HasInvalidParm;
2466}