blob: 3a77552f48289682acc4df9b54c1d275b24868e4 [file] [log] [blame]
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-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 Lattnerb87b1b32007-08-10 20:18:51 +00007//
8//===----------------------------------------------------------------------===//
9//
Mike Stump11289f42009-09-09 15:08:12 +000010// This file implements extra semantic analysis beyond what is enforced
Chris Lattnerb87b1b32007-08-10 20:18:51 +000011// by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
15#include "Sema.h"
Mike Stump0c2ec772010-01-21 03:59:47 +000016#include "clang/Analysis/CFG.h"
Ted Kremenekd6b87082010-01-25 04:41:41 +000017#include "clang/Analysis/AnalysisContext.h"
Ted Kremenekab278de2010-01-28 23:39:18 +000018#include "clang/Analysis/Analyses/PrintfFormatString.h"
Chris Lattnerb87b1b32007-08-10 20:18:51 +000019#include "clang/AST/ASTContext.h"
Ken Dyck40775002010-01-11 17:06:35 +000020#include "clang/AST/CharUnits.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000021#include "clang/AST/DeclObjC.h"
Ted Kremenekc81614d2007-08-20 16:18:38 +000022#include "clang/AST/ExprCXX.h"
Ted Kremenek34f664d2008-06-16 18:00:42 +000023#include "clang/AST/ExprObjC.h"
Mike Stump0c2ec772010-01-21 03:59:47 +000024#include "clang/AST/DeclObjC.h"
25#include "clang/AST/StmtCXX.h"
26#include "clang/AST/StmtObjC.h"
Chris Lattnerddb71912009-02-18 19:21:10 +000027#include "clang/Lex/LiteralSupport.h"
Chris Lattnerb87b1b32007-08-10 20:18:51 +000028#include "clang/Lex/Preprocessor.h"
Mike Stump0c2ec772010-01-21 03:59:47 +000029#include "llvm/ADT/BitVector.h"
30#include "llvm/ADT/STLExtras.h"
Zhongxing Xu050379b2009-05-20 01:55:10 +000031#include <limits>
Mike Stump0c2ec772010-01-21 03:59:47 +000032#include <queue>
Chris Lattnerb87b1b32007-08-10 20:18:51 +000033using namespace clang;
34
Chris Lattnera26fb342009-02-18 17:49:48 +000035/// getLocationOfStringLiteralByte - Return a source location that points to the
36/// specified byte of the specified string literal.
37///
38/// Strings are amazingly complex. They can be formed from multiple tokens and
39/// can have escape sequences in them in addition to the usual trigraph and
40/// escaped newline business. This routine handles this complexity.
41///
42SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
43 unsigned ByteNo) const {
44 assert(!SL->isWide() && "This doesn't work for wide strings yet");
Mike Stump11289f42009-09-09 15:08:12 +000045
Chris Lattnera26fb342009-02-18 17:49:48 +000046 // Loop over all of the tokens in this string until we find the one that
47 // contains the byte we're looking for.
48 unsigned TokNo = 0;
49 while (1) {
50 assert(TokNo < SL->getNumConcatenated() && "Invalid byte number!");
51 SourceLocation StrTokLoc = SL->getStrTokenLoc(TokNo);
Mike Stump11289f42009-09-09 15:08:12 +000052
Chris Lattnera26fb342009-02-18 17:49:48 +000053 // Get the spelling of the string so that we can get the data that makes up
54 // the string literal, not the identifier for the macro it is potentially
55 // expanded through.
56 SourceLocation StrTokSpellingLoc = SourceMgr.getSpellingLoc(StrTokLoc);
57
58 // Re-lex the token to get its length and original spelling.
59 std::pair<FileID, unsigned> LocInfo =
60 SourceMgr.getDecomposedLoc(StrTokSpellingLoc);
61 std::pair<const char *,const char *> Buffer =
62 SourceMgr.getBufferData(LocInfo.first);
63 const char *StrData = Buffer.first+LocInfo.second;
Mike Stump11289f42009-09-09 15:08:12 +000064
Chris Lattnera26fb342009-02-18 17:49:48 +000065 // Create a langops struct and enable trigraphs. This is sufficient for
66 // relexing tokens.
67 LangOptions LangOpts;
68 LangOpts.Trigraphs = true;
Mike Stump11289f42009-09-09 15:08:12 +000069
Chris Lattnera26fb342009-02-18 17:49:48 +000070 // Create a lexer starting at the beginning of this token.
71 Lexer TheLexer(StrTokSpellingLoc, LangOpts, Buffer.first, StrData,
72 Buffer.second);
73 Token TheTok;
74 TheLexer.LexFromRawLexer(TheTok);
Mike Stump11289f42009-09-09 15:08:12 +000075
Chris Lattner3dd56f92009-02-18 19:26:42 +000076 // Use the StringLiteralParser to compute the length of the string in bytes.
77 StringLiteralParser SLP(&TheTok, 1, PP);
78 unsigned TokNumBytes = SLP.GetStringLength();
Mike Stump11289f42009-09-09 15:08:12 +000079
Chris Lattnerec396b52009-02-18 18:52:52 +000080 // If the byte is in this token, return the location of the byte.
Chris Lattnera26fb342009-02-18 17:49:48 +000081 if (ByteNo < TokNumBytes ||
82 (ByteNo == TokNumBytes && TokNo == SL->getNumConcatenated())) {
Mike Stump11289f42009-09-09 15:08:12 +000083 unsigned Offset =
Chris Lattnerddb71912009-02-18 19:21:10 +000084 StringLiteralParser::getOffsetOfStringByte(TheTok, ByteNo, PP);
Mike Stump11289f42009-09-09 15:08:12 +000085
Chris Lattnerddb71912009-02-18 19:21:10 +000086 // Now that we know the offset of the token in the spelling, use the
87 // preprocessor to get the offset in the original source.
88 return PP.AdvanceToTokenCharacter(StrTokLoc, Offset);
Chris Lattnera26fb342009-02-18 17:49:48 +000089 }
Mike Stump11289f42009-09-09 15:08:12 +000090
Chris Lattnera26fb342009-02-18 17:49:48 +000091 // Move to the next string token.
92 ++TokNo;
93 ByteNo -= TokNumBytes;
94 }
95}
96
Ryan Flynnaa5e5fd2009-08-06 03:00:50 +000097/// CheckablePrintfAttr - does a function call have a "printf" attribute
98/// and arguments that merit checking?
99bool Sema::CheckablePrintfAttr(const FormatAttr *Format, CallExpr *TheCall) {
100 if (Format->getType() == "printf") return true;
101 if (Format->getType() == "printf0") {
102 // printf0 allows null "format" string; if so don't check format/args
103 unsigned format_idx = Format->getFormatIdx() - 1;
Sebastian Redl6eedcc12009-11-17 18:02:24 +0000104 // Does the index refer to the implicit object argument?
105 if (isa<CXXMemberCallExpr>(TheCall)) {
106 if (format_idx == 0)
107 return false;
108 --format_idx;
109 }
Ryan Flynnaa5e5fd2009-08-06 03:00:50 +0000110 if (format_idx < TheCall->getNumArgs()) {
111 Expr *Format = TheCall->getArg(format_idx)->IgnoreParenCasts();
Douglas Gregor56751b52009-09-25 04:25:58 +0000112 if (!Format->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
Ryan Flynnaa5e5fd2009-08-06 03:00:50 +0000113 return true;
114 }
115 }
116 return false;
117}
Chris Lattnera26fb342009-02-18 17:49:48 +0000118
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000119Action::OwningExprResult
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000120Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000121 OwningExprResult TheCallResult(Owned(TheCall));
Douglas Gregorae2fbad2008-11-17 20:34:05 +0000122
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000123 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000124 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000125 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000126 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000127 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000128 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000129 break;
Ted Kremeneka174c522008-07-09 17:58:53 +0000130 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000131 case Builtin::BI__builtin_va_start:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000132 if (SemaBuiltinVAStart(TheCall))
133 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000134 break;
Chris Lattner2da14fb2007-12-20 00:26:33 +0000135 case Builtin::BI__builtin_isgreater:
136 case Builtin::BI__builtin_isgreaterequal:
137 case Builtin::BI__builtin_isless:
138 case Builtin::BI__builtin_islessequal:
139 case Builtin::BI__builtin_islessgreater:
140 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000141 if (SemaBuiltinUnorderedCompare(TheCall))
142 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000143 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000144 case Builtin::BI__builtin_isfinite:
145 case Builtin::BI__builtin_isinf:
146 case Builtin::BI__builtin_isinf_sign:
147 case Builtin::BI__builtin_isnan:
148 case Builtin::BI__builtin_isnormal:
149 if (SemaBuiltinUnaryFP(TheCall))
150 return ExprError();
151 break;
Eli Friedmanf8353032008-05-20 08:23:37 +0000152 case Builtin::BI__builtin_return_address:
153 case Builtin::BI__builtin_frame_address:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000154 if (SemaBuiltinStackAddress(TheCall))
155 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000156 break;
Chris Lattnerd545ad12009-09-23 06:06:36 +0000157 case Builtin::BI__builtin_eh_return_data_regno:
158 if (SemaBuiltinEHReturnDataRegNo(TheCall))
159 return ExprError();
160 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000161 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000162 return SemaBuiltinShuffleVector(TheCall);
163 // TheCall will be freed by the smart pointer here, but that's fine, since
164 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000165 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000166 if (SemaBuiltinPrefetch(TheCall))
167 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000168 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000169 case Builtin::BI__builtin_object_size:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000170 if (SemaBuiltinObjectSize(TheCall))
171 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000172 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000173 case Builtin::BI__builtin_longjmp:
174 if (SemaBuiltinLongjmp(TheCall))
175 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000176 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000177 case Builtin::BI__sync_fetch_and_add:
178 case Builtin::BI__sync_fetch_and_sub:
179 case Builtin::BI__sync_fetch_and_or:
180 case Builtin::BI__sync_fetch_and_and:
181 case Builtin::BI__sync_fetch_and_xor:
Chris Lattner94578cb2009-05-13 04:37:52 +0000182 case Builtin::BI__sync_fetch_and_nand:
Chris Lattnerdc046542009-05-08 06:58:22 +0000183 case Builtin::BI__sync_add_and_fetch:
184 case Builtin::BI__sync_sub_and_fetch:
185 case Builtin::BI__sync_and_and_fetch:
186 case Builtin::BI__sync_or_and_fetch:
187 case Builtin::BI__sync_xor_and_fetch:
Chris Lattner94578cb2009-05-13 04:37:52 +0000188 case Builtin::BI__sync_nand_and_fetch:
Chris Lattnerdc046542009-05-08 06:58:22 +0000189 case Builtin::BI__sync_val_compare_and_swap:
190 case Builtin::BI__sync_bool_compare_and_swap:
191 case Builtin::BI__sync_lock_test_and_set:
192 case Builtin::BI__sync_lock_release:
193 if (SemaBuiltinAtomicOverloaded(TheCall))
194 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000195 break;
Anders Carlsson98f07902007-08-17 05:31:46 +0000196 }
Mike Stump11289f42009-09-09 15:08:12 +0000197
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000198 return move(TheCallResult);
199}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000200
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000201/// CheckFunctionCall - Check a direct function call for various correctness
202/// and safety properties not strictly enforced by the C type system.
203bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
204 // Get the IdentifierInfo* for the called function.
205 IdentifierInfo *FnInfo = FDecl->getIdentifier();
206
207 // None of the checks below are needed for functions that don't have
208 // simple names (e.g., C++ conversion functions).
209 if (!FnInfo)
210 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000211
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000212 // FIXME: This mechanism should be abstracted to be less fragile and
213 // more efficient. For example, just map function ids to custom
214 // handlers.
215
Chris Lattnerb87b1b32007-08-10 20:18:51 +0000216 // Printf checking.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000217 if (const FormatAttr *Format = FDecl->getAttr<FormatAttr>()) {
Ryan Flynnaa5e5fd2009-08-06 03:00:50 +0000218 if (CheckablePrintfAttr(Format, TheCall)) {
Ted Kremenek9723bcf2009-02-27 17:58:43 +0000219 bool HasVAListArg = Format->getFirstArg() == 0;
220 if (!HasVAListArg) {
Mike Stump11289f42009-09-09 15:08:12 +0000221 if (const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +0000222 = FDecl->getType()->getAs<FunctionProtoType>())
Sebastian Redl6eedcc12009-11-17 18:02:24 +0000223 HasVAListArg = !Proto->isVariadic();
Ted Kremenek9723bcf2009-02-27 17:58:43 +0000224 }
Douglas Gregore711f702009-02-14 18:57:46 +0000225 CheckPrintfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
Ted Kremenek9723bcf2009-02-27 17:58:43 +0000226 HasVAListArg ? 0 : Format->getFirstArg() - 1);
Douglas Gregore711f702009-02-14 18:57:46 +0000227 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +0000228 }
Mike Stump11289f42009-09-09 15:08:12 +0000229
230 for (const NonNullAttr *NonNull = FDecl->getAttr<NonNullAttr>(); NonNull;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000231 NonNull = NonNull->getNext<NonNullAttr>())
232 CheckNonNullArguments(NonNull, TheCall);
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000233
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000234 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +0000235}
236
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000237bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000238 // Printf checking.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000239 const FormatAttr *Format = NDecl->getAttr<FormatAttr>();
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000240 if (!Format)
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000241 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000242
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000243 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
244 if (!V)
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000245 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000246
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000247 QualType Ty = V->getType();
248 if (!Ty->isBlockPointerType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000249 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000250
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000251 if (!CheckablePrintfAttr(Format, TheCall))
252 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000253
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000254 bool HasVAListArg = Format->getFirstArg() == 0;
255 if (!HasVAListArg) {
Mike Stump11289f42009-09-09 15:08:12 +0000256 const FunctionType *FT =
John McCall9dd450b2009-09-21 23:43:11 +0000257 Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000258 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT))
259 HasVAListArg = !Proto->isVariadic();
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000260 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000261 CheckPrintfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
262 HasVAListArg ? 0 : Format->getFirstArg() - 1);
263
264 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000265}
266
Chris Lattnerdc046542009-05-08 06:58:22 +0000267/// SemaBuiltinAtomicOverloaded - We have a call to a function like
268/// __sync_fetch_and_add, which is an overloaded function based on the pointer
269/// type of its first argument. The main ActOnCallExpr routines have already
270/// promoted the types of arguments because all of these calls are prototyped as
271/// void(...).
272///
273/// This function goes through and does final semantic checking for these
274/// builtins,
275bool Sema::SemaBuiltinAtomicOverloaded(CallExpr *TheCall) {
276 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
277 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
278
279 // Ensure that we have at least one argument to do type inference from.
280 if (TheCall->getNumArgs() < 1)
281 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
282 << 0 << TheCall->getCallee()->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +0000283
Chris Lattnerdc046542009-05-08 06:58:22 +0000284 // Inspect the first argument of the atomic builtin. This should always be
285 // a pointer type, whose element is an integral scalar or pointer type.
286 // Because it is a pointer type, we don't have to worry about any implicit
287 // casts here.
288 Expr *FirstArg = TheCall->getArg(0);
289 if (!FirstArg->getType()->isPointerType())
290 return Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
291 << FirstArg->getType() << FirstArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +0000292
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000293 QualType ValType = FirstArg->getType()->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +0000294 if (!ValType->isIntegerType() && !ValType->isPointerType() &&
Chris Lattnerdc046542009-05-08 06:58:22 +0000295 !ValType->isBlockPointerType())
296 return Diag(DRE->getLocStart(),
297 diag::err_atomic_builtin_must_be_pointer_intptr)
298 << FirstArg->getType() << FirstArg->getSourceRange();
299
300 // We need to figure out which concrete builtin this maps onto. For example,
301 // __sync_fetch_and_add with a 2 byte object turns into
302 // __sync_fetch_and_add_2.
303#define BUILTIN_ROW(x) \
304 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
305 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +0000306
Chris Lattnerdc046542009-05-08 06:58:22 +0000307 static const unsigned BuiltinIndices[][5] = {
308 BUILTIN_ROW(__sync_fetch_and_add),
309 BUILTIN_ROW(__sync_fetch_and_sub),
310 BUILTIN_ROW(__sync_fetch_and_or),
311 BUILTIN_ROW(__sync_fetch_and_and),
312 BUILTIN_ROW(__sync_fetch_and_xor),
Chris Lattner94578cb2009-05-13 04:37:52 +0000313 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +0000314
Chris Lattnerdc046542009-05-08 06:58:22 +0000315 BUILTIN_ROW(__sync_add_and_fetch),
316 BUILTIN_ROW(__sync_sub_and_fetch),
317 BUILTIN_ROW(__sync_and_and_fetch),
318 BUILTIN_ROW(__sync_or_and_fetch),
319 BUILTIN_ROW(__sync_xor_and_fetch),
Chris Lattner94578cb2009-05-13 04:37:52 +0000320 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +0000321
Chris Lattnerdc046542009-05-08 06:58:22 +0000322 BUILTIN_ROW(__sync_val_compare_and_swap),
323 BUILTIN_ROW(__sync_bool_compare_and_swap),
324 BUILTIN_ROW(__sync_lock_test_and_set),
325 BUILTIN_ROW(__sync_lock_release)
326 };
Mike Stump11289f42009-09-09 15:08:12 +0000327#undef BUILTIN_ROW
328
Chris Lattnerdc046542009-05-08 06:58:22 +0000329 // Determine the index of the size.
330 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +0000331 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +0000332 case 1: SizeIndex = 0; break;
333 case 2: SizeIndex = 1; break;
334 case 4: SizeIndex = 2; break;
335 case 8: SizeIndex = 3; break;
336 case 16: SizeIndex = 4; break;
337 default:
338 return Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
339 << FirstArg->getType() << FirstArg->getSourceRange();
340 }
Mike Stump11289f42009-09-09 15:08:12 +0000341
Chris Lattnerdc046542009-05-08 06:58:22 +0000342 // Each of these builtins has one pointer argument, followed by some number of
343 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
344 // that we ignore. Find out which row of BuiltinIndices to read from as well
345 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +0000346 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +0000347 unsigned BuiltinIndex, NumFixed = 1;
348 switch (BuiltinID) {
349 default: assert(0 && "Unknown overloaded atomic builtin!");
350 case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break;
351 case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break;
352 case Builtin::BI__sync_fetch_and_or: BuiltinIndex = 2; break;
353 case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break;
354 case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break;
Chris Lattner94578cb2009-05-13 04:37:52 +0000355 case Builtin::BI__sync_fetch_and_nand:BuiltinIndex = 5; break;
Mike Stump11289f42009-09-09 15:08:12 +0000356
Chris Lattner94578cb2009-05-13 04:37:52 +0000357 case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 6; break;
358 case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 7; break;
359 case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 8; break;
360 case Builtin::BI__sync_or_and_fetch: BuiltinIndex = 9; break;
361 case Builtin::BI__sync_xor_and_fetch: BuiltinIndex =10; break;
362 case Builtin::BI__sync_nand_and_fetch:BuiltinIndex =11; break;
Mike Stump11289f42009-09-09 15:08:12 +0000363
Chris Lattnerdc046542009-05-08 06:58:22 +0000364 case Builtin::BI__sync_val_compare_and_swap:
Chris Lattner94578cb2009-05-13 04:37:52 +0000365 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +0000366 NumFixed = 2;
367 break;
368 case Builtin::BI__sync_bool_compare_and_swap:
Chris Lattner94578cb2009-05-13 04:37:52 +0000369 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +0000370 NumFixed = 2;
371 break;
Chris Lattner94578cb2009-05-13 04:37:52 +0000372 case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 14; break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000373 case Builtin::BI__sync_lock_release:
Chris Lattner94578cb2009-05-13 04:37:52 +0000374 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +0000375 NumFixed = 0;
376 break;
377 }
Mike Stump11289f42009-09-09 15:08:12 +0000378
Chris Lattnerdc046542009-05-08 06:58:22 +0000379 // Now that we know how many fixed arguments we expect, first check that we
380 // have at least that many.
381 if (TheCall->getNumArgs() < 1+NumFixed)
382 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
383 << 0 << TheCall->getCallee()->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +0000384
385
Chris Lattner5b9241b2009-05-08 15:36:58 +0000386 // Get the decl for the concrete builtin from this, we can tell what the
387 // concrete integer type we should convert to is.
388 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
389 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
390 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
Mike Stump11289f42009-09-09 15:08:12 +0000391 FunctionDecl *NewBuiltinDecl =
Chris Lattner5b9241b2009-05-08 15:36:58 +0000392 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
393 TUScope, false, DRE->getLocStart()));
394 const FunctionProtoType *BuiltinFT =
John McCall9dd450b2009-09-21 23:43:11 +0000395 NewBuiltinDecl->getType()->getAs<FunctionProtoType>();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000396 ValType = BuiltinFT->getArgType(0)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +0000397
Chris Lattner5b9241b2009-05-08 15:36:58 +0000398 // If the first type needs to be converted (e.g. void** -> int*), do it now.
399 if (BuiltinFT->getArgType(0) != FirstArg->getType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +0000400 ImpCastExprToType(FirstArg, BuiltinFT->getArgType(0), CastExpr::CK_BitCast);
Chris Lattner5b9241b2009-05-08 15:36:58 +0000401 TheCall->setArg(0, FirstArg);
402 }
Mike Stump11289f42009-09-09 15:08:12 +0000403
Chris Lattnerdc046542009-05-08 06:58:22 +0000404 // Next, walk the valid ones promoting to the right type.
405 for (unsigned i = 0; i != NumFixed; ++i) {
406 Expr *Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +0000407
Chris Lattnerdc046542009-05-08 06:58:22 +0000408 // If the argument is an implicit cast, then there was a promotion due to
409 // "...", just remove it now.
410 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
411 Arg = ICE->getSubExpr();
412 ICE->setSubExpr(0);
413 ICE->Destroy(Context);
414 TheCall->setArg(i+1, Arg);
415 }
Mike Stump11289f42009-09-09 15:08:12 +0000416
Chris Lattnerdc046542009-05-08 06:58:22 +0000417 // GCC does an implicit conversion to the pointer or integer ValType. This
418 // can fail in some cases (1i -> int**), check for this error case now.
Anders Carlssonf10e4142009-08-07 22:21:05 +0000419 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +0000420 CXXMethodDecl *ConversionDecl = 0;
421 if (CheckCastTypes(Arg->getSourceRange(), ValType, Arg, Kind,
422 ConversionDecl))
Chris Lattnerdc046542009-05-08 06:58:22 +0000423 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000424
Chris Lattnerdc046542009-05-08 06:58:22 +0000425 // Okay, we have something that *can* be converted to the right type. Check
426 // to see if there is a potentially weird extension going on here. This can
427 // happen when you do an atomic operation on something like an char* and
428 // pass in 42. The 42 gets converted to char. This is even more strange
429 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +0000430 // FIXME: Do this check.
Anders Carlssonf10e4142009-08-07 22:21:05 +0000431 ImpCastExprToType(Arg, ValType, Kind, /*isLvalue=*/false);
Chris Lattnerdc046542009-05-08 06:58:22 +0000432 TheCall->setArg(i+1, Arg);
433 }
Mike Stump11289f42009-09-09 15:08:12 +0000434
Chris Lattnerdc046542009-05-08 06:58:22 +0000435 // Switch the DeclRefExpr to refer to the new decl.
436 DRE->setDecl(NewBuiltinDecl);
437 DRE->setType(NewBuiltinDecl->getType());
Mike Stump11289f42009-09-09 15:08:12 +0000438
Chris Lattnerdc046542009-05-08 06:58:22 +0000439 // Set the callee in the CallExpr.
440 // FIXME: This leaks the original parens and implicit casts.
441 Expr *PromotedCall = DRE;
442 UsualUnaryConversions(PromotedCall);
443 TheCall->setCallee(PromotedCall);
Mike Stump11289f42009-09-09 15:08:12 +0000444
Chris Lattnerdc046542009-05-08 06:58:22 +0000445
446 // Change the result type of the call to match the result type of the decl.
447 TheCall->setType(NewBuiltinDecl->getResultType());
448 return false;
449}
450
451
Chris Lattner6436fb62009-02-18 06:01:06 +0000452/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +0000453/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +0000454/// FIXME: GCC currently emits the following warning:
Mike Stump11289f42009-09-09 15:08:12 +0000455/// "warning: input conversion stopped due to an input byte that does not
Steve Narofffb46e862009-04-13 20:26:29 +0000456/// belong to the input codeset UTF-8"
457/// Note: It might also make sense to do the UTF-16 conversion here (would
458/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +0000459bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +0000460 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +0000461 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
462
463 if (!Literal || Literal->isWide()) {
Chris Lattner3b054132008-11-19 05:08:23 +0000464 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
465 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +0000466 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +0000467 }
Mike Stump11289f42009-09-09 15:08:12 +0000468
Daniel Dunbarb879c3c2009-09-22 10:03:52 +0000469 const char *Data = Literal->getStrData();
470 unsigned Length = Literal->getByteLength();
Mike Stump11289f42009-09-09 15:08:12 +0000471
Daniel Dunbarb879c3c2009-09-22 10:03:52 +0000472 for (unsigned i = 0; i < Length; ++i) {
473 if (!Data[i]) {
474 Diag(getLocationOfStringLiteralByte(Literal, i),
475 diag::warn_cfstring_literal_contains_nul_character)
476 << Arg->getSourceRange();
477 break;
478 }
479 }
Mike Stump11289f42009-09-09 15:08:12 +0000480
Anders Carlssona3a9c432007-08-17 15:44:17 +0000481 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +0000482}
483
Chris Lattnere202e6a2007-12-20 00:05:45 +0000484/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
485/// Emit an error and return true on failure, return false on success.
Chris Lattner08464942007-12-28 05:29:59 +0000486bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
487 Expr *Fn = TheCall->getCallee();
488 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +0000489 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000490 diag::err_typecheck_call_too_many_args)
Chris Lattnercedef8d2008-11-21 18:44:24 +0000491 << 0 /*function call*/ << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +0000492 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000493 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +0000494 return true;
495 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +0000496
497 if (TheCall->getNumArgs() < 2) {
498 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
499 << 0 /*function call*/;
500 }
501
Chris Lattnere202e6a2007-12-20 00:05:45 +0000502 // Determine whether the current function is variadic or not.
503 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +0000504 if (CurBlock)
505 isVariadic = CurBlock->isVariadic;
506 else if (getCurFunctionDecl()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000507 if (FunctionProtoType* FTP =
508 dyn_cast<FunctionProtoType>(getCurFunctionDecl()->getType()))
Eli Friedmanbb2b3be2008-12-15 22:05:35 +0000509 isVariadic = FTP->isVariadic();
510 else
511 isVariadic = false;
512 } else {
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +0000513 isVariadic = getCurMethodDecl()->isVariadic();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +0000514 }
Mike Stump11289f42009-09-09 15:08:12 +0000515
Chris Lattnere202e6a2007-12-20 00:05:45 +0000516 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000517 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
518 return true;
519 }
Mike Stump11289f42009-09-09 15:08:12 +0000520
Chris Lattner43be2e62007-12-19 23:59:04 +0000521 // Verify that the second argument to the builtin is the last argument of the
522 // current function or method.
523 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +0000524 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +0000525
Anders Carlsson6a8350b2008-02-11 04:20:54 +0000526 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
527 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000528 // FIXME: This isn't correct for methods (results in bogus warning).
529 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +0000530 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +0000531 if (CurBlock)
532 LastArg = *(CurBlock->TheDecl->param_end()-1);
533 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +0000534 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +0000535 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +0000536 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +0000537 SecondArgIsLastNamedArgument = PV == LastArg;
538 }
539 }
Mike Stump11289f42009-09-09 15:08:12 +0000540
Chris Lattner43be2e62007-12-19 23:59:04 +0000541 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +0000542 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +0000543 diag::warn_second_parameter_of_va_start_not_last_named_argument);
544 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +0000545}
Chris Lattner43be2e62007-12-19 23:59:04 +0000546
Chris Lattner2da14fb2007-12-20 00:26:33 +0000547/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
548/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +0000549bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
550 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +0000551 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
552 << 0 /*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +0000553 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +0000554 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000555 diag::err_typecheck_call_too_many_args)
Chris Lattnercedef8d2008-11-21 18:44:24 +0000556 << 0 /*function call*/
Chris Lattner3b054132008-11-19 05:08:23 +0000557 << SourceRange(TheCall->getArg(2)->getLocStart(),
558 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +0000559
Chris Lattner08464942007-12-28 05:29:59 +0000560 Expr *OrigArg0 = TheCall->getArg(0);
561 Expr *OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +0000562
Chris Lattner2da14fb2007-12-20 00:26:33 +0000563 // Do standard promotions between the two arguments, returning their common
564 // type.
Chris Lattner08464942007-12-28 05:29:59 +0000565 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
Daniel Dunbar96f86772009-02-19 19:28:43 +0000566
567 // Make sure any conversions are pushed back into the call; this is
568 // type safe since unordered compare builtins are declared as "_Bool
569 // foo(...)".
570 TheCall->setArg(0, OrigArg0);
571 TheCall->setArg(1, OrigArg1);
Mike Stump11289f42009-09-09 15:08:12 +0000572
Douglas Gregorc25f7662009-05-19 22:10:17 +0000573 if (OrigArg0->isTypeDependent() || OrigArg1->isTypeDependent())
574 return false;
575
Chris Lattner2da14fb2007-12-20 00:26:33 +0000576 // If the common type isn't a real floating type, then the arguments were
577 // invalid for this operation.
578 if (!Res->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +0000579 return Diag(OrigArg0->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000580 diag::err_typecheck_call_invalid_ordered_compare)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000581 << OrigArg0->getType() << OrigArg1->getType()
Chris Lattner3b054132008-11-19 05:08:23 +0000582 << SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +0000583
Chris Lattner2da14fb2007-12-20 00:26:33 +0000584 return false;
585}
586
Eli Friedman7e4faac2009-08-31 20:06:00 +0000587/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isnan and
588/// friends. This is declared to take (...), so we have to check everything.
589bool Sema::SemaBuiltinUnaryFP(CallExpr *TheCall) {
590 if (TheCall->getNumArgs() < 1)
591 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
592 << 0 /*function call*/;
593 if (TheCall->getNumArgs() > 1)
Mike Stump11289f42009-09-09 15:08:12 +0000594 return Diag(TheCall->getArg(1)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +0000595 diag::err_typecheck_call_too_many_args)
596 << 0 /*function call*/
597 << SourceRange(TheCall->getArg(1)->getLocStart(),
598 (*(TheCall->arg_end()-1))->getLocEnd());
599
600 Expr *OrigArg = TheCall->getArg(0);
Mike Stump11289f42009-09-09 15:08:12 +0000601
Eli Friedman7e4faac2009-08-31 20:06:00 +0000602 if (OrigArg->isTypeDependent())
603 return false;
604
605 // This operation requires a floating-point number
606 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +0000607 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +0000608 diag::err_typecheck_call_invalid_unary_fp)
609 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +0000610
Eli Friedman7e4faac2009-08-31 20:06:00 +0000611 return false;
612}
613
Eli Friedmanf8353032008-05-20 08:23:37 +0000614bool Sema::SemaBuiltinStackAddress(CallExpr *TheCall) {
615 // The signature for these builtins is exact; the only thing we need
616 // to check is that the argument is a constant.
617 SourceLocation Loc;
Douglas Gregorc25f7662009-05-19 22:10:17 +0000618 if (!TheCall->getArg(0)->isTypeDependent() &&
619 !TheCall->getArg(0)->isValueDependent() &&
620 !TheCall->getArg(0)->isIntegerConstantExpr(Context, &Loc))
Chris Lattner3b054132008-11-19 05:08:23 +0000621 return Diag(Loc, diag::err_stack_const_level) << TheCall->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +0000622
Eli Friedmanf8353032008-05-20 08:23:37 +0000623 return false;
624}
625
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000626/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
627// This is declared to take (...), so we have to check everything.
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000628Action::OwningExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000629 if (TheCall->getNumArgs() < 3)
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000630 return ExprError(Diag(TheCall->getLocEnd(),
631 diag::err_typecheck_call_too_few_args)
632 << 0 /*function call*/ << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000633
Douglas Gregorc25f7662009-05-19 22:10:17 +0000634 unsigned numElements = std::numeric_limits<unsigned>::max();
635 if (!TheCall->getArg(0)->isTypeDependent() &&
636 !TheCall->getArg(1)->isTypeDependent()) {
637 QualType FAType = TheCall->getArg(0)->getType();
638 QualType SAType = TheCall->getArg(1)->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000639
Douglas Gregorc25f7662009-05-19 22:10:17 +0000640 if (!FAType->isVectorType() || !SAType->isVectorType()) {
641 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump11289f42009-09-09 15:08:12 +0000642 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorc25f7662009-05-19 22:10:17 +0000643 TheCall->getArg(1)->getLocEnd());
644 return ExprError();
645 }
Mike Stump11289f42009-09-09 15:08:12 +0000646
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000647 if (!Context.hasSameUnqualifiedType(FAType, SAType)) {
Douglas Gregorc25f7662009-05-19 22:10:17 +0000648 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump11289f42009-09-09 15:08:12 +0000649 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorc25f7662009-05-19 22:10:17 +0000650 TheCall->getArg(1)->getLocEnd());
651 return ExprError();
652 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000653
John McCall9dd450b2009-09-21 23:43:11 +0000654 numElements = FAType->getAs<VectorType>()->getNumElements();
Douglas Gregorc25f7662009-05-19 22:10:17 +0000655 if (TheCall->getNumArgs() != numElements+2) {
656 if (TheCall->getNumArgs() < numElements+2)
657 return ExprError(Diag(TheCall->getLocEnd(),
658 diag::err_typecheck_call_too_few_args)
659 << 0 /*function call*/ << TheCall->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000660 return ExprError(Diag(TheCall->getLocEnd(),
Douglas Gregorc25f7662009-05-19 22:10:17 +0000661 diag::err_typecheck_call_too_many_args)
662 << 0 /*function call*/ << TheCall->getSourceRange());
663 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000664 }
665
666 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +0000667 if (TheCall->getArg(i)->isTypeDependent() ||
668 TheCall->getArg(i)->isValueDependent())
669 continue;
670
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000671 llvm::APSInt Result(32);
Chris Lattner7ab824e2008-08-10 02:05:13 +0000672 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000673 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000674 diag::err_shufflevector_nonconstant_argument)
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000675 << TheCall->getArg(i)->getSourceRange());
676
Chris Lattner7ab824e2008-08-10 02:05:13 +0000677 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000678 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000679 diag::err_shufflevector_argument_too_large)
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000680 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000681 }
682
683 llvm::SmallVector<Expr*, 32> exprs;
684
Chris Lattner7ab824e2008-08-10 02:05:13 +0000685 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000686 exprs.push_back(TheCall->getArg(i));
687 TheCall->setArg(i, 0);
688 }
689
Nate Begemanf485fb52009-08-12 02:10:25 +0000690 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
691 exprs.size(), exprs[0]->getType(),
Ted Kremenek5a201952009-02-07 01:47:29 +0000692 TheCall->getCallee()->getLocStart(),
693 TheCall->getRParenLoc()));
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000694}
Chris Lattner43be2e62007-12-19 23:59:04 +0000695
Daniel Dunbarb7257262008-07-21 22:59:13 +0000696/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
697// This is declared to take (const void*, ...) and can take two
698// optional constant int args.
699bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +0000700 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +0000701
Chris Lattner3b054132008-11-19 05:08:23 +0000702 if (NumArgs > 3)
703 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_many_args)
Chris Lattnercedef8d2008-11-21 18:44:24 +0000704 << 0 /*function call*/ << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +0000705
706 // Argument 0 is checked for us and the remaining arguments must be
707 // constant integers.
Chris Lattner3b054132008-11-19 05:08:23 +0000708 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbarb7257262008-07-21 22:59:13 +0000709 Expr *Arg = TheCall->getArg(i);
Douglas Gregorc25f7662009-05-19 22:10:17 +0000710 if (Arg->isTypeDependent())
711 continue;
712
Eli Friedman5efba262009-12-04 00:30:06 +0000713 if (!Arg->getType()->isIntegralType())
714 return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_arg_type)
Chris Lattnerd545ad12009-09-23 06:06:36 +0000715 << Arg->getSourceRange();
Douglas Gregorc25f7662009-05-19 22:10:17 +0000716
Eli Friedman5efba262009-12-04 00:30:06 +0000717 ImpCastExprToType(Arg, Context.IntTy, CastExpr::CK_IntegralCast);
718 TheCall->setArg(i, Arg);
719
Douglas Gregorc25f7662009-05-19 22:10:17 +0000720 if (Arg->isValueDependent())
721 continue;
722
Eli Friedman5efba262009-12-04 00:30:06 +0000723 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +0000724 if (!Arg->isIntegerConstantExpr(Result, Context))
Eli Friedman5efba262009-12-04 00:30:06 +0000725 return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_arg_ice)
Douglas Gregorc25f7662009-05-19 22:10:17 +0000726 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +0000727
Daniel Dunbarb7257262008-07-21 22:59:13 +0000728 // FIXME: gcc issues a warning and rewrites these to 0. These
729 // seems especially odd for the third argument since the default
730 // is 3.
Chris Lattner3b054132008-11-19 05:08:23 +0000731 if (i == 1) {
Eli Friedman5efba262009-12-04 00:30:06 +0000732 if (Result.getLimitedValue() > 1)
Chris Lattner3b054132008-11-19 05:08:23 +0000733 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattnerd545ad12009-09-23 06:06:36 +0000734 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +0000735 } else {
Eli Friedman5efba262009-12-04 00:30:06 +0000736 if (Result.getLimitedValue() > 3)
Chris Lattner3b054132008-11-19 05:08:23 +0000737 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattnerd545ad12009-09-23 06:06:36 +0000738 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +0000739 }
740 }
741
Chris Lattner3b054132008-11-19 05:08:23 +0000742 return false;
Daniel Dunbarb7257262008-07-21 22:59:13 +0000743}
744
Chris Lattnerd545ad12009-09-23 06:06:36 +0000745/// SemaBuiltinEHReturnDataRegNo - Handle __builtin_eh_return_data_regno, the
746/// operand must be an integer constant.
747bool Sema::SemaBuiltinEHReturnDataRegNo(CallExpr *TheCall) {
748 llvm::APSInt Result;
749 if (!TheCall->getArg(0)->isIntegerConstantExpr(Result, Context))
750 return Diag(TheCall->getLocStart(), diag::err_expr_not_ice)
751 << TheCall->getArg(0)->getSourceRange();
752
753 return false;
754}
755
756
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000757/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
758/// int type). This simply type checks that type is one of the defined
759/// constants (0-3).
Eric Christopherc8791562009-12-23 03:49:37 +0000760// For compatability check 0-3, llvm only handles 0 and 2.
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000761bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
762 Expr *Arg = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +0000763 if (Arg->isTypeDependent())
764 return false;
765
Mike Stump11289f42009-09-09 15:08:12 +0000766 QualType ArgType = Arg->getType();
John McCall9dd450b2009-09-21 23:43:11 +0000767 const BuiltinType *BT = ArgType->getAs<BuiltinType>();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000768 llvm::APSInt Result(32);
Douglas Gregorc25f7662009-05-19 22:10:17 +0000769 if (!BT || BT->getKind() != BuiltinType::Int)
770 return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument)
771 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
772
773 if (Arg->isValueDependent())
774 return false;
775
776 if (!Arg->isIntegerConstantExpr(Result, Context)) {
Chris Lattner3b054132008-11-19 05:08:23 +0000777 return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument)
778 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000779 }
780
781 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattner3b054132008-11-19 05:08:23 +0000782 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
783 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000784 }
785
786 return false;
787}
788
Eli Friedmanc97d0142009-05-03 06:04:26 +0000789/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000790/// This checks that val is a constant 1.
791bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
792 Expr *Arg = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +0000793 if (Arg->isTypeDependent() || Arg->isValueDependent())
794 return false;
795
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000796 llvm::APSInt Result(32);
797 if (!Arg->isIntegerConstantExpr(Result, Context) || Result != 1)
798 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
799 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
800
801 return false;
802}
803
Ted Kremenek6dfeb552009-01-12 23:09:09 +0000804// Handle i > 1 ? "x" : "y", recursivelly
Ted Kremenekdfd72c22009-03-20 21:35:28 +0000805bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
806 bool HasVAListArg,
Douglas Gregore711f702009-02-14 18:57:46 +0000807 unsigned format_idx, unsigned firstDataArg) {
Douglas Gregorc25f7662009-05-19 22:10:17 +0000808 if (E->isTypeDependent() || E->isValueDependent())
809 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +0000810
811 switch (E->getStmtClass()) {
812 case Stmt::ConditionalOperatorClass: {
Ted Kremenekdfd72c22009-03-20 21:35:28 +0000813 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Chris Lattnerd806cbc2009-12-22 06:00:13 +0000814 return SemaCheckStringLiteral(C->getTrueExpr(), TheCall,
Douglas Gregore711f702009-02-14 18:57:46 +0000815 HasVAListArg, format_idx, firstDataArg)
Ted Kremenek6dfeb552009-01-12 23:09:09 +0000816 && SemaCheckStringLiteral(C->getRHS(), TheCall,
Douglas Gregore711f702009-02-14 18:57:46 +0000817 HasVAListArg, format_idx, firstDataArg);
Ted Kremenek6dfeb552009-01-12 23:09:09 +0000818 }
819
820 case Stmt::ImplicitCastExprClass: {
Ted Kremenekdfd72c22009-03-20 21:35:28 +0000821 const ImplicitCastExpr *Expr = cast<ImplicitCastExpr>(E);
Ted Kremenek6dfeb552009-01-12 23:09:09 +0000822 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
Douglas Gregore711f702009-02-14 18:57:46 +0000823 format_idx, firstDataArg);
Ted Kremenek6dfeb552009-01-12 23:09:09 +0000824 }
825
826 case Stmt::ParenExprClass: {
Ted Kremenekdfd72c22009-03-20 21:35:28 +0000827 const ParenExpr *Expr = cast<ParenExpr>(E);
Ted Kremenek6dfeb552009-01-12 23:09:09 +0000828 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
Douglas Gregore711f702009-02-14 18:57:46 +0000829 format_idx, firstDataArg);
Ted Kremenek6dfeb552009-01-12 23:09:09 +0000830 }
Mike Stump11289f42009-09-09 15:08:12 +0000831
Ted Kremenekdfd72c22009-03-20 21:35:28 +0000832 case Stmt::DeclRefExprClass: {
833 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +0000834
Ted Kremenekdfd72c22009-03-20 21:35:28 +0000835 // As an exception, do not flag errors for variables binding to
836 // const string literals.
837 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
838 bool isConstant = false;
839 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +0000840
Ted Kremenekdfd72c22009-03-20 21:35:28 +0000841 if (const ArrayType *AT = Context.getAsArrayType(T)) {
842 isConstant = AT->getElementType().isConstant(Context);
Mike Stump12b8ce12009-08-04 21:02:39 +0000843 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump11289f42009-09-09 15:08:12 +0000844 isConstant = T.isConstant(Context) &&
Ted Kremenekdfd72c22009-03-20 21:35:28 +0000845 PT->getPointeeType().isConstant(Context);
846 }
Mike Stump11289f42009-09-09 15:08:12 +0000847
Ted Kremenekdfd72c22009-03-20 21:35:28 +0000848 if (isConstant) {
Sebastian Redl5ca79842010-02-01 20:16:42 +0000849 if (const Expr *Init = VD->getAnyInitializer())
Ted Kremenekdfd72c22009-03-20 21:35:28 +0000850 return SemaCheckStringLiteral(Init, TheCall,
851 HasVAListArg, format_idx, firstDataArg);
852 }
Mike Stump11289f42009-09-09 15:08:12 +0000853
Anders Carlssonb012ca92009-06-28 19:55:58 +0000854 // For vprintf* functions (i.e., HasVAListArg==true), we add a
855 // special check to see if the format string is a function parameter
856 // of the function calling the printf function. If the function
857 // has an attribute indicating it is a printf-like function, then we
858 // should suppress warnings concerning non-literals being used in a call
859 // to a vprintf function. For example:
860 //
861 // void
862 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
863 // va_list ap;
864 // va_start(ap, fmt);
865 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
866 // ...
867 //
868 //
869 // FIXME: We don't have full attribute support yet, so just check to see
870 // if the argument is a DeclRefExpr that references a parameter. We'll
871 // add proper support for checking the attribute later.
872 if (HasVAListArg)
873 if (isa<ParmVarDecl>(VD))
874 return true;
Ted Kremenekdfd72c22009-03-20 21:35:28 +0000875 }
Mike Stump11289f42009-09-09 15:08:12 +0000876
Ted Kremenekdfd72c22009-03-20 21:35:28 +0000877 return false;
878 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +0000879
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +0000880 case Stmt::CallExprClass: {
881 const CallExpr *CE = cast<CallExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +0000882 if (const ImplicitCastExpr *ICE
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +0000883 = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
884 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
885 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000886 if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +0000887 unsigned ArgIndex = FA->getFormatIdx();
888 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +0000889
890 return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg,
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +0000891 format_idx, firstDataArg);
892 }
893 }
894 }
895 }
Mike Stump11289f42009-09-09 15:08:12 +0000896
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +0000897 return false;
898 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +0000899 case Stmt::ObjCStringLiteralClass:
900 case Stmt::StringLiteralClass: {
901 const StringLiteral *StrE = NULL;
Mike Stump11289f42009-09-09 15:08:12 +0000902
Ted Kremenekdfd72c22009-03-20 21:35:28 +0000903 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +0000904 StrE = ObjCFExpr->getString();
905 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +0000906 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +0000907
Ted Kremenek6dfeb552009-01-12 23:09:09 +0000908 if (StrE) {
Mike Stump11289f42009-09-09 15:08:12 +0000909 CheckPrintfString(StrE, E, TheCall, HasVAListArg, format_idx,
Douglas Gregore711f702009-02-14 18:57:46 +0000910 firstDataArg);
Ted Kremenek6dfeb552009-01-12 23:09:09 +0000911 return true;
912 }
Mike Stump11289f42009-09-09 15:08:12 +0000913
Ted Kremenek6dfeb552009-01-12 23:09:09 +0000914 return false;
915 }
Mike Stump11289f42009-09-09 15:08:12 +0000916
Ted Kremenekdfd72c22009-03-20 21:35:28 +0000917 default:
918 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +0000919 }
920}
921
Fariborz Jahaniancd1a88d2009-05-21 18:48:51 +0000922void
Mike Stump11289f42009-09-09 15:08:12 +0000923Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
924 const CallExpr *TheCall) {
Fariborz Jahaniancd1a88d2009-05-21 18:48:51 +0000925 for (NonNullAttr::iterator i = NonNull->begin(), e = NonNull->end();
926 i != e; ++i) {
Chris Lattner23464b82009-05-25 18:23:36 +0000927 const Expr *ArgExpr = TheCall->getArg(*i);
Douglas Gregor56751b52009-09-25 04:25:58 +0000928 if (ArgExpr->isNullPointerConstant(Context,
929 Expr::NPC_ValueDependentIsNotNull))
Chris Lattner23464b82009-05-25 18:23:36 +0000930 Diag(TheCall->getCallee()->getLocStart(), diag::warn_null_arg)
931 << ArgExpr->getSourceRange();
Fariborz Jahaniancd1a88d2009-05-21 18:48:51 +0000932 }
933}
Ted Kremenek6dfeb552009-01-12 23:09:09 +0000934
Chris Lattnerb87b1b32007-08-10 20:18:51 +0000935/// CheckPrintfArguments - Check calls to printf (and similar functions) for
Mike Stump11289f42009-09-09 15:08:12 +0000936/// correct use of format strings.
Ted Kremeneke68f1aa2007-08-14 17:39:48 +0000937///
938/// HasVAListArg - A predicate indicating whether the printf-like
939/// function is passed an explicit va_arg argument (e.g., vprintf)
940///
941/// format_idx - The index into Args for the format string.
942///
943/// Improper format strings to functions in the printf family can be
944/// the source of bizarre bugs and very serious security holes. A
945/// good source of information is available in the following paper
946/// (which includes additional references):
Chris Lattnerb87b1b32007-08-10 20:18:51 +0000947///
948/// FormatGuard: Automatic Protection From printf Format String
949/// Vulnerabilities, Proceedings of the 10th USENIX Security Symposium, 2001.
Ted Kremeneke68f1aa2007-08-14 17:39:48 +0000950///
951/// Functionality implemented:
952///
953/// We can statically check the following properties for string
954/// literal format strings for non v.*printf functions (where the
955/// arguments are passed directly):
956//
957/// (1) Are the number of format conversions equal to the number of
958/// data arguments?
959///
960/// (2) Does each format conversion correctly match the type of the
961/// corresponding data argument? (TODO)
962///
963/// Moreover, for all printf functions we can:
964///
965/// (3) Check for a missing format string (when not caught by type checking).
966///
967/// (4) Check for no-operation flags; e.g. using "#" with format
968/// conversion 'c' (TODO)
969///
970/// (5) Check the use of '%n', a major source of security holes.
971///
972/// (6) Check for malformed format conversions that don't specify anything.
973///
974/// (7) Check for empty format strings. e.g: printf("");
975///
976/// (8) Check that the format string is a wide literal.
977///
978/// All of these checks can be done by parsing the format string.
979///
980/// For now, we ONLY do (1), (3), (5), (6), (7), and (8).
Chris Lattnerb87b1b32007-08-10 20:18:51 +0000981void
Mike Stump11289f42009-09-09 15:08:12 +0000982Sema::CheckPrintfArguments(const CallExpr *TheCall, bool HasVAListArg,
Douglas Gregore711f702009-02-14 18:57:46 +0000983 unsigned format_idx, unsigned firstDataArg) {
Ted Kremenekdfd72c22009-03-20 21:35:28 +0000984 const Expr *Fn = TheCall->getCallee();
Chris Lattner08464942007-12-28 05:29:59 +0000985
Sebastian Redl6eedcc12009-11-17 18:02:24 +0000986 // The way the format attribute works in GCC, the implicit this argument
987 // of member functions is counted. However, it doesn't appear in our own
988 // lists, so decrement format_idx in that case.
989 if (isa<CXXMemberCallExpr>(TheCall)) {
990 // Catch a format attribute mistakenly referring to the object argument.
991 if (format_idx == 0)
992 return;
993 --format_idx;
994 if(firstDataArg != 0)
995 --firstDataArg;
996 }
997
Mike Stump11289f42009-09-09 15:08:12 +0000998 // CHECK: printf-like function is called with no format string.
Chris Lattner08464942007-12-28 05:29:59 +0000999 if (format_idx >= TheCall->getNumArgs()) {
Chris Lattnerf490e152008-11-19 05:27:50 +00001000 Diag(TheCall->getRParenLoc(), diag::warn_printf_missing_format_string)
1001 << Fn->getSourceRange();
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00001002 return;
1003 }
Mike Stump11289f42009-09-09 15:08:12 +00001004
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001005 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00001006
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001007 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00001008 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00001009 // Dynamically generated format strings are difficult to
1010 // automatically vet at compile time. Requiring that format strings
1011 // are string literals: (1) permits the checking of format strings by
1012 // the compiler and thereby (2) can practically remove the source of
1013 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00001014
Mike Stump11289f42009-09-09 15:08:12 +00001015 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00001016 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00001017 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00001018 // the same format string checking logic for both ObjC and C strings.
Chris Lattnere009a882009-04-29 04:49:34 +00001019 if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
1020 firstDataArg))
1021 return; // Literal format string found, check done!
Ted Kremenek34f664d2008-06-16 18:00:42 +00001022
Chris Lattnercc5d1c22009-04-29 04:59:47 +00001023 // If there are no arguments specified, warn with -Wformat-security, otherwise
1024 // warn only with -Wformat-nonliteral.
1025 if (TheCall->getNumArgs() == format_idx+1)
Mike Stump11289f42009-09-09 15:08:12 +00001026 Diag(TheCall->getArg(format_idx)->getLocStart(),
Chris Lattnercc5d1c22009-04-29 04:59:47 +00001027 diag::warn_printf_nonliteral_noargs)
1028 << OrigFormatExpr->getSourceRange();
1029 else
Mike Stump11289f42009-09-09 15:08:12 +00001030 Diag(TheCall->getArg(format_idx)->getLocStart(),
Chris Lattnercc5d1c22009-04-29 04:59:47 +00001031 diag::warn_printf_nonliteral)
1032 << OrigFormatExpr->getSourceRange();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001033}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00001034
Ted Kremenekab278de2010-01-28 23:39:18 +00001035namespace {
Ted Kremenek1de17072010-02-04 20:46:58 +00001036class CheckPrintfHandler : public analyze_printf::FormatStringHandler {
Ted Kremenekab278de2010-01-28 23:39:18 +00001037 Sema &S;
1038 const StringLiteral *FExpr;
1039 const Expr *OrigFormatExpr;
1040 unsigned NumConversions;
1041 const unsigned NumDataArgs;
1042 const bool IsObjCLiteral;
1043 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00001044 const bool HasVAListArg;
1045 const CallExpr *TheCall;
1046 unsigned FormatIdx;
Ted Kremenekab278de2010-01-28 23:39:18 +00001047public:
1048 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
1049 const Expr *origFormatExpr,
1050 unsigned numDataArgs, bool isObjCLiteral,
Ted Kremenek5739de72010-01-29 01:06:55 +00001051 const char *beg, bool hasVAListArg,
1052 const CallExpr *theCall, unsigned formatIdx)
Ted Kremenekab278de2010-01-28 23:39:18 +00001053 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
1054 NumConversions(0), NumDataArgs(numDataArgs),
Ted Kremenek5739de72010-01-29 01:06:55 +00001055 IsObjCLiteral(isObjCLiteral), Beg(beg),
1056 HasVAListArg(hasVAListArg),
1057 TheCall(theCall), FormatIdx(formatIdx) {}
Ted Kremenek019d2242010-01-29 01:50:07 +00001058
1059 void DoneProcessing();
Ted Kremenekc22f78d2010-01-29 03:16:21 +00001060
1061 void HandleIncompleteFormatSpecifier(const char *startSpecifier,
1062 unsigned specifierLen);
Ted Kremenek94af5752010-01-29 02:40:24 +00001063
Ted Kremenek1de17072010-02-04 20:46:58 +00001064 void
1065 HandleInvalidConversionSpecifier(const analyze_printf::FormatSpecifier &FS,
1066 const char *startSpecifier,
1067 unsigned specifierLen);
Ted Kremenek94af5752010-01-29 02:40:24 +00001068
Ted Kremenekab278de2010-01-28 23:39:18 +00001069 void HandleNullChar(const char *nullCharacter);
1070
1071 bool HandleFormatSpecifier(const analyze_printf::FormatSpecifier &FS,
1072 const char *startSpecifier,
1073 unsigned specifierLen);
1074private:
Ted Kremenek8d9842d2010-01-29 20:55:36 +00001075 SourceRange getFormatStringRange();
1076 SourceRange getFormatSpecifierRange(const char *startSpecifier,
Ted Kremenekfb45d352010-02-10 02:16:30 +00001077 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00001078 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek5739de72010-01-29 01:06:55 +00001079
1080 bool HandleAmount(const analyze_printf::OptionalAmount &Amt,
Ted Kremenek8d9842d2010-01-29 20:55:36 +00001081 unsigned MissingArgDiag, unsigned BadTypeDiag,
Ted Kremenekfb45d352010-02-10 02:16:30 +00001082 const char *startSpecifier, unsigned specifierLen);
Ted Kremenekd31b2632010-02-11 09:27:41 +00001083 void HandleFlags(const analyze_printf::FormatSpecifier &FS,
1084 llvm::StringRef flag, llvm::StringRef cspec,
1085 const char *startSpecifier, unsigned specifierLen);
Ted Kremenek5739de72010-01-29 01:06:55 +00001086
Ted Kremenekc3bdff72010-01-30 00:49:51 +00001087 bool MatchType(QualType A, QualType B, bool ignoreSign);
1088
Ted Kremenek5739de72010-01-29 01:06:55 +00001089 const Expr *getDataArg(unsigned i) const;
Ted Kremenekab278de2010-01-28 23:39:18 +00001090};
1091}
1092
Ted Kremenek8d9842d2010-01-29 20:55:36 +00001093SourceRange CheckPrintfHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00001094 return OrigFormatExpr->getSourceRange();
1095}
1096
Ted Kremenek8d9842d2010-01-29 20:55:36 +00001097SourceRange CheckPrintfHandler::
1098getFormatSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
1099 return SourceRange(getLocationOfByte(startSpecifier),
Ted Kremenekfb45d352010-02-10 02:16:30 +00001100 getLocationOfByte(startSpecifier+specifierLen-1));
Ted Kremenek8d9842d2010-01-29 20:55:36 +00001101}
1102
Ted Kremenekab278de2010-01-28 23:39:18 +00001103SourceLocation CheckPrintfHandler::getLocationOfByte(const char *x) {
1104 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
1105}
1106
Ted Kremenek94af5752010-01-29 02:40:24 +00001107void CheckPrintfHandler::
Ted Kremenekc22f78d2010-01-29 03:16:21 +00001108HandleIncompleteFormatSpecifier(const char *startSpecifier,
1109 unsigned specifierLen) {
1110 SourceLocation Loc = getLocationOfByte(startSpecifier);
1111 S.Diag(Loc, diag::warn_printf_incomplete_specifier)
Ted Kremenek8d9842d2010-01-29 20:55:36 +00001112 << getFormatSpecifierRange(startSpecifier, specifierLen);
Ted Kremenekc22f78d2010-01-29 03:16:21 +00001113}
1114
1115void CheckPrintfHandler::
Ted Kremenek94af5752010-01-29 02:40:24 +00001116HandleInvalidConversionSpecifier(const analyze_printf::FormatSpecifier &FS,
1117 const char *startSpecifier,
1118 unsigned specifierLen) {
1119
1120 ++NumConversions;
Ted Kremenekc22f78d2010-01-29 03:16:21 +00001121 const analyze_printf::ConversionSpecifier &CS =
1122 FS.getConversionSpecifier();
1123 SourceLocation Loc = getLocationOfByte(CS.getStart());
Ted Kremenek94af5752010-01-29 02:40:24 +00001124 S.Diag(Loc, diag::warn_printf_invalid_conversion)
Ted Kremenekc22f78d2010-01-29 03:16:21 +00001125 << llvm::StringRef(CS.getStart(), CS.getLength())
Ted Kremenek8d9842d2010-01-29 20:55:36 +00001126 << getFormatSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek94af5752010-01-29 02:40:24 +00001127}
1128
Ted Kremenekab278de2010-01-28 23:39:18 +00001129void CheckPrintfHandler::HandleNullChar(const char *nullCharacter) {
1130 // The presence of a null character is likely an error.
1131 S.Diag(getLocationOfByte(nullCharacter),
1132 diag::warn_printf_format_string_contains_null_char)
Ted Kremenek8d9842d2010-01-29 20:55:36 +00001133 << getFormatStringRange();
Ted Kremenekab278de2010-01-28 23:39:18 +00001134}
1135
Ted Kremenek5739de72010-01-29 01:06:55 +00001136const Expr *CheckPrintfHandler::getDataArg(unsigned i) const {
1137 return TheCall->getArg(FormatIdx + i);
1138}
1139
Ted Kremenekc3bdff72010-01-30 00:49:51 +00001140bool CheckPrintfHandler::MatchType(QualType A, QualType B, bool ignoreSign) {
1141 A = S.Context.getCanonicalType(A).getUnqualifiedType();
1142 B = S.Context.getCanonicalType(B).getUnqualifiedType();
1143
1144 if (A == B)
1145 return true;
1146
1147 if (ignoreSign) {
1148 if (const BuiltinType *BT = B->getAs<BuiltinType>()) {
1149 switch (BT->getKind()) {
1150 default:
1151 return false;
1152 case BuiltinType::Char_S:
1153 case BuiltinType::SChar:
1154 return A == S.Context.UnsignedCharTy;
1155 case BuiltinType::Char_U:
1156 case BuiltinType::UChar:
1157 return A == S.Context.SignedCharTy;
1158 case BuiltinType::Short:
1159 return A == S.Context.UnsignedShortTy;
1160 case BuiltinType::UShort:
1161 return A == S.Context.ShortTy;
1162 case BuiltinType::Int:
1163 return A == S.Context.UnsignedIntTy;
1164 case BuiltinType::UInt:
1165 return A == S.Context.IntTy;
1166 case BuiltinType::Long:
1167 return A == S.Context.UnsignedLongTy;
1168 case BuiltinType::ULong:
1169 return A == S.Context.LongTy;
1170 case BuiltinType::LongLong:
1171 return A == S.Context.UnsignedLongLongTy;
1172 case BuiltinType::ULongLong:
1173 return A == S.Context.LongLongTy;
1174 }
1175 return A == B;
1176 }
1177 }
1178 return false;
1179}
1180
Ted Kremenekd31b2632010-02-11 09:27:41 +00001181void CheckPrintfHandler::HandleFlags(const analyze_printf::FormatSpecifier &FS,
1182 llvm::StringRef flag,
1183 llvm::StringRef cspec,
1184 const char *startSpecifier,
1185 unsigned specifierLen) {
1186 const analyze_printf::ConversionSpecifier &CS = FS.getConversionSpecifier();
1187 S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_nonsensical_flag)
1188 << flag << cspec << getFormatSpecifierRange(startSpecifier, specifierLen);
1189}
1190
Ted Kremenek5739de72010-01-29 01:06:55 +00001191bool
1192CheckPrintfHandler::HandleAmount(const analyze_printf::OptionalAmount &Amt,
1193 unsigned MissingArgDiag,
Ted Kremenek8d9842d2010-01-29 20:55:36 +00001194 unsigned BadTypeDiag,
Ted Kremenekfb45d352010-02-10 02:16:30 +00001195 const char *startSpecifier,
1196 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00001197
1198 if (Amt.hasDataArgument()) {
1199 ++NumConversions;
1200 if (!HasVAListArg) {
1201 if (NumConversions > NumDataArgs) {
1202 S.Diag(getLocationOfByte(Amt.getStart()), MissingArgDiag)
Ted Kremenek8d9842d2010-01-29 20:55:36 +00001203 << getFormatSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek5739de72010-01-29 01:06:55 +00001204 // Don't do any more checking. We will just emit
1205 // spurious errors.
1206 return false;
1207 }
1208
1209 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00001210 // Although not in conformance with C99, we also allow the argument to be
1211 // an 'unsigned int' as that is a reasonably safe case. GCC also
1212 // doesn't emit a warning for that case.
Ted Kremenek5739de72010-01-29 01:06:55 +00001213 const Expr *Arg = getDataArg(NumConversions);
1214 QualType T = Arg->getType();
Ted Kremenekc3bdff72010-01-30 00:49:51 +00001215 if (!MatchType(T, S.Context.IntTy, true)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00001216 S.Diag(getLocationOfByte(Amt.getStart()), BadTypeDiag)
Ted Kremenekc3bdff72010-01-30 00:49:51 +00001217 << S.Context.IntTy << T
1218 << getFormatSpecifierRange(startSpecifier, specifierLen)
1219 << Arg->getSourceRange();
Ted Kremenek5739de72010-01-29 01:06:55 +00001220 // Don't do any more checking. We will just emit
1221 // spurious errors.
1222 return false;
1223 }
1224 }
1225 }
1226 return true;
1227}
Ted Kremenek5739de72010-01-29 01:06:55 +00001228
Ted Kremenekab278de2010-01-28 23:39:18 +00001229bool
Ted Kremenekd31b2632010-02-11 09:27:41 +00001230CheckPrintfHandler::HandleFormatSpecifier(const analyze_printf::FormatSpecifier
1231 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00001232 const char *startSpecifier,
1233 unsigned specifierLen) {
1234
1235 using namespace analyze_printf;
1236 const ConversionSpecifier &CS = FS.getConversionSpecifier();
1237
Ted Kremenek5739de72010-01-29 01:06:55 +00001238 // First check if the field width, precision, and conversion specifier
1239 // have matching data arguments.
1240 if (!HandleAmount(FS.getFieldWidth(),
1241 diag::warn_printf_asterisk_width_missing_arg,
Ted Kremenek8d9842d2010-01-29 20:55:36 +00001242 diag::warn_printf_asterisk_width_wrong_type,
Ted Kremenekfb45d352010-02-10 02:16:30 +00001243 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00001244 return false;
1245 }
1246
1247 if (!HandleAmount(FS.getPrecision(),
1248 diag::warn_printf_asterisk_precision_missing_arg,
Ted Kremenek8d9842d2010-01-29 20:55:36 +00001249 diag::warn_printf_asterisk_precision_wrong_type,
Ted Kremenekfb45d352010-02-10 02:16:30 +00001250 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00001251 return false;
1252 }
1253
Ted Kremenekab278de2010-01-28 23:39:18 +00001254 // Check for using an Objective-C specific conversion specifier
1255 // in a non-ObjC literal.
1256 if (!IsObjCLiteral && CS.isObjCArg()) {
Ted Kremenek94af5752010-01-29 02:40:24 +00001257 HandleInvalidConversionSpecifier(FS, startSpecifier, specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00001258
1259 // Continue checking the other format specifiers.
1260 return true;
1261 }
Ted Kremenek8d9842d2010-01-29 20:55:36 +00001262
1263 if (!CS.consumesDataArgument()) {
1264 // FIXME: Technically specifying a precision or field width here
1265 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00001266 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00001267 }
Ted Kremenekd5fd0fa2010-01-29 01:35:25 +00001268
Ted Kremenek94af5752010-01-29 02:40:24 +00001269 ++NumConversions;
1270
Ted Kremenekd5fd0fa2010-01-29 01:35:25 +00001271 // Are we using '%n'? Issue a warning about this being
1272 // a possible security issue.
1273 if (CS.getKind() == ConversionSpecifier::OutIntPtrArg) {
1274 S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_write_back)
Ted Kremenek8d9842d2010-01-29 20:55:36 +00001275 << getFormatSpecifierRange(startSpecifier, specifierLen);
Ted Kremenekd5fd0fa2010-01-29 01:35:25 +00001276 // Continue checking the other format specifiers.
1277 return true;
1278 }
Ted Kremenekd31b2632010-02-11 09:27:41 +00001279
1280 if (CS.getKind() == ConversionSpecifier::VoidPtrArg) {
1281 if (FS.getPrecision().getHowSpecified() != OptionalAmount::NotSpecified)
1282 S.Diag(getLocationOfByte(CS.getStart()),
1283 diag::warn_printf_nonsensical_precision)
1284 << CS.getCharacters()
1285 << getFormatSpecifierRange(startSpecifier, specifierLen);
1286 }
1287 if (CS.getKind() == ConversionSpecifier::VoidPtrArg ||
1288 CS.getKind() == ConversionSpecifier::CStrArg) {
1289 // FIXME: Instead of using "0", "+", etc., eventually get them from
1290 // the FormatSpecifier.
1291 if (FS.hasLeadingZeros())
1292 HandleFlags(FS, "0", CS.getCharacters(), startSpecifier, specifierLen);
1293 if (FS.hasPlusPrefix())
1294 HandleFlags(FS, "+", CS.getCharacters(), startSpecifier, specifierLen);
1295 if (FS.hasSpacePrefix())
1296 HandleFlags(FS, " ", CS.getCharacters(), startSpecifier, specifierLen);
1297 }
Ted Kremenek9fcd8302010-01-29 01:43:31 +00001298
1299 // The remaining checks depend on the data arguments.
1300 if (HasVAListArg)
1301 return true;
1302
1303 if (NumConversions > NumDataArgs) {
1304 S.Diag(getLocationOfByte(CS.getStart()),
1305 diag::warn_printf_insufficient_data_args)
Ted Kremenek8d9842d2010-01-29 20:55:36 +00001306 << getFormatSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek9fcd8302010-01-29 01:43:31 +00001307 // Don't do any more checking.
1308 return false;
1309 }
Ted Kremenekc3bdff72010-01-30 00:49:51 +00001310
1311 // Now type check the data expression that matches the
1312 // format specifier.
1313 const Expr *Ex = getDataArg(NumConversions);
1314 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context);
Ted Kremenekcd831062010-02-01 19:28:15 +00001315
Ted Kremenekc3bdff72010-01-30 00:49:51 +00001316 if (const QualType *T = ATR.getSpecificType()) {
1317 if (!MatchType(*T, Ex->getType(), true)) {
Ted Kremenekcd831062010-02-01 19:28:15 +00001318 // Check if we didn't match because of an implicit cast from a 'char'
1319 // or 'short' to an 'int'. This is done because printf is a varargs
1320 // function.
Ted Kremenekcd831062010-02-01 19:28:15 +00001321 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
Ted Kremenekfb20c412010-02-01 19:38:10 +00001322 if (ICE->getType() == S.Context.IntTy)
1323 if (MatchType(*T, ICE->getSubExpr()->getType(), true))
1324 return true;
1325
1326 S.Diag(getLocationOfByte(CS.getStart()),
1327 diag::warn_printf_conversion_argument_type_mismatch)
Ted Kremenek1de17072010-02-04 20:46:58 +00001328 << *T << Ex->getType();
1329// << getFormatSpecifierRange(startSpecifier, specifierLen)
1330// << Ex->getSourceRange();
Ted Kremenekc3bdff72010-01-30 00:49:51 +00001331 }
1332 return true;
1333 }
Ted Kremenekab278de2010-01-28 23:39:18 +00001334
1335 return true;
1336}
1337
Ted Kremenek019d2242010-01-29 01:50:07 +00001338void CheckPrintfHandler::DoneProcessing() {
1339 // Does the number of data arguments exceed the number of
1340 // format conversions in the format string?
1341 if (!HasVAListArg && NumConversions < NumDataArgs)
1342 S.Diag(getDataArg(NumConversions+1)->getLocStart(),
1343 diag::warn_printf_too_many_data_args)
Ted Kremenek8d9842d2010-01-29 20:55:36 +00001344 << getFormatStringRange();
Ted Kremenek019d2242010-01-29 01:50:07 +00001345}
Ted Kremenekab278de2010-01-28 23:39:18 +00001346
Ted Kremenek8d9842d2010-01-29 20:55:36 +00001347void Sema::CheckPrintfString(const StringLiteral *FExpr,
Ted Kremenekfb45d352010-02-10 02:16:30 +00001348 const Expr *OrigFormatExpr,
1349 const CallExpr *TheCall, bool HasVAListArg,
1350 unsigned format_idx, unsigned firstDataArg) {
1351
Ted Kremenekab278de2010-01-28 23:39:18 +00001352 // CHECK: is the format string a wide literal?
1353 if (FExpr->isWide()) {
1354 Diag(FExpr->getLocStart(),
1355 diag::warn_printf_format_string_is_wide_literal)
1356 << OrigFormatExpr->getSourceRange();
1357 return;
1358 }
Ted Kremenekc70ee862010-01-28 01:18:22 +00001359
Ted Kremenekab278de2010-01-28 23:39:18 +00001360 // Str - The format string. NOTE: this is NOT null-terminated!
1361 const char *Str = FExpr->getStrData();
1362
1363 // CHECK: empty format string?
1364 unsigned StrLen = FExpr->getByteLength();
1365
1366 if (StrLen == 0) {
1367 Diag(FExpr->getLocStart(), diag::warn_printf_empty_format_string)
1368 << OrigFormatExpr->getSourceRange();
1369 return;
1370 }
1371
1372 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr,
1373 TheCall->getNumArgs() - firstDataArg,
Ted Kremenek5739de72010-01-29 01:06:55 +00001374 isa<ObjCStringLiteral>(OrigFormatExpr), Str,
1375 HasVAListArg, TheCall, format_idx);
Ted Kremenekab278de2010-01-28 23:39:18 +00001376
Ted Kremenek1de17072010-02-04 20:46:58 +00001377 if (!analyze_printf::ParseFormatString(H, Str, Str + StrLen))
Ted Kremenekc22f78d2010-01-29 03:16:21 +00001378 H.DoneProcessing();
Ted Kremenekc70ee862010-01-28 01:18:22 +00001379}
1380
Ted Kremenekcff94fa2007-08-17 16:46:58 +00001381//===--- CHECK: Return Address of Stack Variable --------------------------===//
1382
1383static DeclRefExpr* EvalVal(Expr *E);
1384static DeclRefExpr* EvalAddr(Expr* E);
1385
1386/// CheckReturnStackAddr - Check if a return statement returns the address
1387/// of a stack variable.
1388void
1389Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
1390 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00001391
Ted Kremenekcff94fa2007-08-17 16:46:58 +00001392 // Perform checking for returned stack addresses.
Steve Naroff8de9c3a2008-09-05 22:11:13 +00001393 if (lhsType->isPointerType() || lhsType->isBlockPointerType()) {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00001394 if (DeclRefExpr *DR = EvalAddr(RetValExp))
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001395 Diag(DR->getLocStart(), diag::warn_ret_stack_addr)
Chris Lattnere3d20d92008-11-23 21:45:46 +00001396 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001397
Steve Naroff3b1e1722008-09-16 22:25:10 +00001398 // Skip over implicit cast expressions when checking for block expressions.
Chris Lattner870158e2009-09-08 00:36:37 +00001399 RetValExp = RetValExp->IgnoreParenCasts();
Steve Naroff3b1e1722008-09-16 22:25:10 +00001400
Chris Lattner252d36e2009-10-30 04:01:58 +00001401 if (BlockExpr *C = dyn_cast<BlockExpr>(RetValExp))
Mike Stump5c3285b2009-04-17 00:09:41 +00001402 if (C->hasBlockDeclRefExprs())
1403 Diag(C->getLocStart(), diag::err_ret_local_block)
1404 << C->getSourceRange();
Chris Lattner252d36e2009-10-30 04:01:58 +00001405
1406 if (AddrLabelExpr *ALE = dyn_cast<AddrLabelExpr>(RetValExp))
1407 Diag(ALE->getLocStart(), diag::warn_ret_addr_label)
1408 << ALE->getSourceRange();
1409
Mike Stump12b8ce12009-08-04 21:02:39 +00001410 } else if (lhsType->isReferenceType()) {
1411 // Perform checking for stack values returned by reference.
Douglas Gregore200adc2008-10-27 19:41:14 +00001412 // Check for a reference to the stack
1413 if (DeclRefExpr *DR = EvalVal(RetValExp))
Chris Lattnerf490e152008-11-19 05:27:50 +00001414 Diag(DR->getLocStart(), diag::warn_ret_stack_ref)
Chris Lattnere3d20d92008-11-23 21:45:46 +00001415 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Ted Kremenekcff94fa2007-08-17 16:46:58 +00001416 }
1417}
1418
1419/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
1420/// check if the expression in a return statement evaluates to an address
1421/// to a location on the stack. The recursion is used to traverse the
1422/// AST of the return expression, with recursion backtracking when we
1423/// encounter a subexpression that (1) clearly does not lead to the address
1424/// of a stack variable or (2) is something we cannot determine leads to
1425/// the address of a stack variable based on such local checking.
1426///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00001427/// EvalAddr processes expressions that are pointers that are used as
1428/// references (and not L-values). EvalVal handles all other values.
Mike Stump11289f42009-09-09 15:08:12 +00001429/// At the base case of the recursion is a check for a DeclRefExpr* in
Ted Kremenekcff94fa2007-08-17 16:46:58 +00001430/// the refers to a stack variable.
1431///
1432/// This implementation handles:
1433///
1434/// * pointer-to-pointer casts
1435/// * implicit conversions from array references to pointers
1436/// * taking the address of fields
1437/// * arbitrary interplay between "&" and "*" operators
1438/// * pointer arithmetic from an address of a stack variable
1439/// * taking the address of an array element where the array is on the stack
1440static DeclRefExpr* EvalAddr(Expr *E) {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00001441 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00001442 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00001443 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001444 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00001445 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00001446
Ted Kremenekcff94fa2007-08-17 16:46:58 +00001447 // Our "symbolic interpreter" is just a dispatch off the currently
1448 // viewed AST node. We then recursively traverse the AST by calling
1449 // EvalAddr and EvalVal appropriately.
1450 switch (E->getStmtClass()) {
Chris Lattner934edb22007-12-28 05:31:15 +00001451 case Stmt::ParenExprClass:
1452 // Ignore parentheses.
1453 return EvalAddr(cast<ParenExpr>(E)->getSubExpr());
Ted Kremenekcff94fa2007-08-17 16:46:58 +00001454
Chris Lattner934edb22007-12-28 05:31:15 +00001455 case Stmt::UnaryOperatorClass: {
1456 // The only unary operator that make sense to handle here
1457 // is AddrOf. All others don't make sense as pointers.
1458 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00001459
Chris Lattner934edb22007-12-28 05:31:15 +00001460 if (U->getOpcode() == UnaryOperator::AddrOf)
1461 return EvalVal(U->getSubExpr());
1462 else
Ted Kremenekcff94fa2007-08-17 16:46:58 +00001463 return NULL;
1464 }
Mike Stump11289f42009-09-09 15:08:12 +00001465
Chris Lattner934edb22007-12-28 05:31:15 +00001466 case Stmt::BinaryOperatorClass: {
1467 // Handle pointer arithmetic. All other binary operators are not valid
1468 // in this context.
1469 BinaryOperator *B = cast<BinaryOperator>(E);
1470 BinaryOperator::Opcode op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00001471
Chris Lattner934edb22007-12-28 05:31:15 +00001472 if (op != BinaryOperator::Add && op != BinaryOperator::Sub)
1473 return NULL;
Mike Stump11289f42009-09-09 15:08:12 +00001474
Chris Lattner934edb22007-12-28 05:31:15 +00001475 Expr *Base = B->getLHS();
1476
1477 // Determine which argument is the real pointer base. It could be
1478 // the RHS argument instead of the LHS.
1479 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00001480
Chris Lattner934edb22007-12-28 05:31:15 +00001481 assert (Base->getType()->isPointerType());
1482 return EvalAddr(Base);
1483 }
Steve Naroff2752a172008-09-10 19:17:48 +00001484
Chris Lattner934edb22007-12-28 05:31:15 +00001485 // For conditional operators we need to see if either the LHS or RHS are
1486 // valid DeclRefExpr*s. If one of them is valid, we return it.
1487 case Stmt::ConditionalOperatorClass: {
1488 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00001489
Chris Lattner934edb22007-12-28 05:31:15 +00001490 // Handle the GNU extension for missing LHS.
1491 if (Expr *lhsExpr = C->getLHS())
1492 if (DeclRefExpr* LHS = EvalAddr(lhsExpr))
1493 return LHS;
1494
1495 return EvalAddr(C->getRHS());
1496 }
Mike Stump11289f42009-09-09 15:08:12 +00001497
Ted Kremenekc3b4c522008-08-07 00:49:01 +00001498 // For casts, we need to handle conversions from arrays to
1499 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00001500 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00001501 case Stmt::CStyleCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00001502 case Stmt::CXXFunctionalCastExprClass: {
Argyrios Kyrtzidis3bab3d22008-08-18 23:01:59 +00001503 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenekc3b4c522008-08-07 00:49:01 +00001504 QualType T = SubExpr->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001505
Steve Naroff8de9c3a2008-09-05 22:11:13 +00001506 if (SubExpr->getType()->isPointerType() ||
1507 SubExpr->getType()->isBlockPointerType() ||
1508 SubExpr->getType()->isObjCQualifiedIdType())
Ted Kremenekc3b4c522008-08-07 00:49:01 +00001509 return EvalAddr(SubExpr);
1510 else if (T->isArrayType())
Chris Lattner934edb22007-12-28 05:31:15 +00001511 return EvalVal(SubExpr);
Chris Lattner934edb22007-12-28 05:31:15 +00001512 else
Ted Kremenekc3b4c522008-08-07 00:49:01 +00001513 return 0;
Chris Lattner934edb22007-12-28 05:31:15 +00001514 }
Mike Stump11289f42009-09-09 15:08:12 +00001515
Chris Lattner934edb22007-12-28 05:31:15 +00001516 // C++ casts. For dynamic casts, static casts, and const casts, we
1517 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregore200adc2008-10-27 19:41:14 +00001518 // through the cast. In the case the dynamic cast doesn't fail (and
1519 // return NULL), we take the conservative route and report cases
Chris Lattner934edb22007-12-28 05:31:15 +00001520 // where we return the address of a stack variable. For Reinterpre
Douglas Gregore200adc2008-10-27 19:41:14 +00001521 // FIXME: The comment about is wrong; we're not always converting
1522 // from pointer to pointer. I'm guessing that this code should also
Mike Stump11289f42009-09-09 15:08:12 +00001523 // handle references to objects.
1524 case Stmt::CXXStaticCastExprClass:
1525 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00001526 case Stmt::CXXConstCastExprClass:
1527 case Stmt::CXXReinterpretCastExprClass: {
1528 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00001529 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Chris Lattner934edb22007-12-28 05:31:15 +00001530 return EvalAddr(S);
1531 else
1532 return NULL;
Chris Lattner934edb22007-12-28 05:31:15 +00001533 }
Mike Stump11289f42009-09-09 15:08:12 +00001534
Chris Lattner934edb22007-12-28 05:31:15 +00001535 // Everything else: we simply don't reason about them.
1536 default:
1537 return NULL;
1538 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00001539}
Mike Stump11289f42009-09-09 15:08:12 +00001540
Ted Kremenekcff94fa2007-08-17 16:46:58 +00001541
1542/// EvalVal - This function is complements EvalAddr in the mutual recursion.
1543/// See the comments for EvalAddr for more details.
1544static DeclRefExpr* EvalVal(Expr *E) {
Mike Stump11289f42009-09-09 15:08:12 +00001545
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00001546 // We should only be called for evaluating non-pointer expressions, or
1547 // expressions with a pointer type that are not used as references but instead
1548 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00001549
Ted Kremenekcff94fa2007-08-17 16:46:58 +00001550 // Our "symbolic interpreter" is just a dispatch off the currently
1551 // viewed AST node. We then recursively traverse the AST by calling
1552 // EvalAddr and EvalVal appropriately.
1553 switch (E->getStmtClass()) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00001554 case Stmt::DeclRefExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00001555 // DeclRefExpr: the base case. When we hit a DeclRefExpr we are looking
1556 // at code that refers to a variable's name. We check if it has local
1557 // storage within the function, and if so, return the expression.
1558 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00001559
Ted Kremenekcff94fa2007-08-17 16:46:58 +00001560 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Mike Stump11289f42009-09-09 15:08:12 +00001561 if (V->hasLocalStorage() && !V->getType()->isReferenceType()) return DR;
1562
Ted Kremenekcff94fa2007-08-17 16:46:58 +00001563 return NULL;
1564 }
Mike Stump11289f42009-09-09 15:08:12 +00001565
Ted Kremenekcff94fa2007-08-17 16:46:58 +00001566 case Stmt::ParenExprClass:
1567 // Ignore parentheses.
1568 return EvalVal(cast<ParenExpr>(E)->getSubExpr());
Mike Stump11289f42009-09-09 15:08:12 +00001569
Ted Kremenekcff94fa2007-08-17 16:46:58 +00001570 case Stmt::UnaryOperatorClass: {
1571 // The only unary operator that make sense to handle here
1572 // is Deref. All others don't resolve to a "name." This includes
1573 // handling all sorts of rvalues passed to a unary operator.
1574 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00001575
Ted Kremenekcff94fa2007-08-17 16:46:58 +00001576 if (U->getOpcode() == UnaryOperator::Deref)
1577 return EvalAddr(U->getSubExpr());
1578
1579 return NULL;
1580 }
Mike Stump11289f42009-09-09 15:08:12 +00001581
Ted Kremenekcff94fa2007-08-17 16:46:58 +00001582 case Stmt::ArraySubscriptExprClass: {
1583 // Array subscripts are potential references to data on the stack. We
1584 // retrieve the DeclRefExpr* for the array variable if it indeed
1585 // has local storage.
Ted Kremenekc81614d2007-08-20 16:18:38 +00001586 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase());
Ted Kremenekcff94fa2007-08-17 16:46:58 +00001587 }
Mike Stump11289f42009-09-09 15:08:12 +00001588
Ted Kremenekcff94fa2007-08-17 16:46:58 +00001589 case Stmt::ConditionalOperatorClass: {
1590 // For conditional operators we need to see if either the LHS or RHS are
1591 // non-NULL DeclRefExpr's. If one is non-NULL, we return it.
1592 ConditionalOperator *C = cast<ConditionalOperator>(E);
1593
Anders Carlsson801c5c72007-11-30 19:04:31 +00001594 // Handle the GNU extension for missing LHS.
1595 if (Expr *lhsExpr = C->getLHS())
1596 if (DeclRefExpr *LHS = EvalVal(lhsExpr))
1597 return LHS;
1598
1599 return EvalVal(C->getRHS());
Ted Kremenekcff94fa2007-08-17 16:46:58 +00001600 }
Mike Stump11289f42009-09-09 15:08:12 +00001601
Ted Kremenekcff94fa2007-08-17 16:46:58 +00001602 // Accesses to members are potential references to data on the stack.
Douglas Gregorf405d7e2009-08-31 23:41:50 +00001603 case Stmt::MemberExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00001604 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00001605
Ted Kremenekcff94fa2007-08-17 16:46:58 +00001606 // Check for indirect access. We only want direct field accesses.
1607 if (!M->isArrow())
1608 return EvalVal(M->getBase());
1609 else
1610 return NULL;
1611 }
Mike Stump11289f42009-09-09 15:08:12 +00001612
Ted Kremenekcff94fa2007-08-17 16:46:58 +00001613 // Everything else: we simply don't reason about them.
1614 default:
1615 return NULL;
1616 }
1617}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00001618
1619//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
1620
1621/// Check for comparisons of floating point operands using != and ==.
1622/// Issue a warning if these are no self-comparisons, as they are not likely
1623/// to do what the programmer intended.
1624void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
1625 bool EmitWarning = true;
Mike Stump11289f42009-09-09 15:08:12 +00001626
Ted Kremenekfff70962008-01-17 16:57:34 +00001627 Expr* LeftExprSansParen = lex->IgnoreParens();
Ted Kremenek32a33582008-01-17 17:55:13 +00001628 Expr* RightExprSansParen = rex->IgnoreParens();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00001629
1630 // Special case: check for x == x (which is OK).
1631 // Do not emit warnings for such cases.
1632 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
1633 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
1634 if (DRL->getDecl() == DRR->getDecl())
1635 EmitWarning = false;
Mike Stump11289f42009-09-09 15:08:12 +00001636
1637
Ted Kremenekeda40e22007-11-29 00:59:04 +00001638 // Special case: check for comparisons against literals that can be exactly
1639 // represented by APFloat. In such cases, do not emit a warning. This
1640 // is a heuristic: often comparison against such literals are used to
1641 // detect if a value in a variable has not changed. This clearly can
1642 // lead to false negatives.
1643 if (EmitWarning) {
1644 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
1645 if (FLL->isExact())
1646 EmitWarning = false;
Mike Stump12b8ce12009-08-04 21:02:39 +00001647 } else
Ted Kremenekeda40e22007-11-29 00:59:04 +00001648 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
1649 if (FLR->isExact())
1650 EmitWarning = false;
1651 }
1652 }
Mike Stump11289f42009-09-09 15:08:12 +00001653
Ted Kremenek43fb8b02007-11-25 00:58:00 +00001654 // Check for comparisons with builtin types.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001655 if (EmitWarning)
Ted Kremenek43fb8b02007-11-25 00:58:00 +00001656 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Douglas Gregore711f702009-02-14 18:57:46 +00001657 if (CL->isBuiltinCall(Context))
Ted Kremenek43fb8b02007-11-25 00:58:00 +00001658 EmitWarning = false;
Mike Stump11289f42009-09-09 15:08:12 +00001659
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001660 if (EmitWarning)
Ted Kremenek43fb8b02007-11-25 00:58:00 +00001661 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Douglas Gregore711f702009-02-14 18:57:46 +00001662 if (CR->isBuiltinCall(Context))
Ted Kremenek43fb8b02007-11-25 00:58:00 +00001663 EmitWarning = false;
Mike Stump11289f42009-09-09 15:08:12 +00001664
Ted Kremenek43fb8b02007-11-25 00:58:00 +00001665 // Emit the diagnostic.
1666 if (EmitWarning)
Chris Lattner3b054132008-11-19 05:08:23 +00001667 Diag(loc, diag::warn_floatingpoint_eq)
1668 << lex->getSourceRange() << rex->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00001669}
John McCallca01b222010-01-04 23:21:16 +00001670
John McCall70aa5392010-01-06 05:24:50 +00001671//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
1672//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00001673
John McCall70aa5392010-01-06 05:24:50 +00001674namespace {
John McCallca01b222010-01-04 23:21:16 +00001675
John McCall70aa5392010-01-06 05:24:50 +00001676/// Structure recording the 'active' range of an integer-valued
1677/// expression.
1678struct IntRange {
1679 /// The number of bits active in the int.
1680 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00001681
John McCall70aa5392010-01-06 05:24:50 +00001682 /// True if the int is known not to have negative values.
1683 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00001684
John McCall70aa5392010-01-06 05:24:50 +00001685 IntRange() {}
1686 IntRange(unsigned Width, bool NonNegative)
1687 : Width(Width), NonNegative(NonNegative)
1688 {}
John McCallca01b222010-01-04 23:21:16 +00001689
John McCall70aa5392010-01-06 05:24:50 +00001690 // Returns the range of the bool type.
1691 static IntRange forBoolType() {
1692 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00001693 }
1694
John McCall70aa5392010-01-06 05:24:50 +00001695 // Returns the range of an integral type.
1696 static IntRange forType(ASTContext &C, QualType T) {
1697 return forCanonicalType(C, T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00001698 }
1699
John McCall70aa5392010-01-06 05:24:50 +00001700 // Returns the range of an integeral type based on its canonical
1701 // representation.
1702 static IntRange forCanonicalType(ASTContext &C, const Type *T) {
1703 assert(T->isCanonicalUnqualified());
1704
1705 if (const VectorType *VT = dyn_cast<VectorType>(T))
1706 T = VT->getElementType().getTypePtr();
1707 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
1708 T = CT->getElementType().getTypePtr();
1709 if (const EnumType *ET = dyn_cast<EnumType>(T))
1710 T = ET->getDecl()->getIntegerType().getTypePtr();
1711
1712 const BuiltinType *BT = cast<BuiltinType>(T);
1713 assert(BT->isInteger());
1714
1715 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
1716 }
1717
1718 // Returns the supremum of two ranges: i.e. their conservative merge.
1719 static IntRange join(const IntRange &L, const IntRange &R) {
1720 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00001721 L.NonNegative && R.NonNegative);
1722 }
1723
1724 // Returns the infinum of two ranges: i.e. their aggressive merge.
1725 static IntRange meet(const IntRange &L, const IntRange &R) {
1726 return IntRange(std::min(L.Width, R.Width),
1727 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00001728 }
1729};
1730
1731IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
1732 if (value.isSigned() && value.isNegative())
1733 return IntRange(value.getMinSignedBits(), false);
1734
1735 if (value.getBitWidth() > MaxWidth)
1736 value.trunc(MaxWidth);
1737
1738 // isNonNegative() just checks the sign bit without considering
1739 // signedness.
1740 return IntRange(value.getActiveBits(), true);
1741}
1742
John McCall74430522010-01-06 22:57:21 +00001743IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
John McCall70aa5392010-01-06 05:24:50 +00001744 unsigned MaxWidth) {
1745 if (result.isInt())
1746 return GetValueRange(C, result.getInt(), MaxWidth);
1747
1748 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00001749 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
1750 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
1751 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
1752 R = IntRange::join(R, El);
1753 }
John McCall70aa5392010-01-06 05:24:50 +00001754 return R;
1755 }
1756
1757 if (result.isComplexInt()) {
1758 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
1759 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
1760 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00001761 }
1762
1763 // This can happen with lossless casts to intptr_t of "based" lvalues.
1764 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00001765 // FIXME: The only reason we need to pass the type in here is to get
1766 // the sign right on this one case. It would be nice if APValue
1767 // preserved this.
John McCall70aa5392010-01-06 05:24:50 +00001768 assert(result.isLValue());
John McCall74430522010-01-06 22:57:21 +00001769 return IntRange(MaxWidth, Ty->isUnsignedIntegerType());
John McCall263a48b2010-01-04 23:31:57 +00001770}
John McCall70aa5392010-01-06 05:24:50 +00001771
1772/// Pseudo-evaluate the given integer expression, estimating the
1773/// range of values it might take.
1774///
1775/// \param MaxWidth - the width to which the value will be truncated
1776IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
1777 E = E->IgnoreParens();
1778
1779 // Try a full evaluation first.
1780 Expr::EvalResult result;
1781 if (E->Evaluate(result, C))
John McCall74430522010-01-06 22:57:21 +00001782 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00001783
1784 // I think we only want to look through implicit casts here; if the
1785 // user has an explicit widening cast, we should treat the value as
1786 // being of the new, wider type.
1787 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
1788 if (CE->getCastKind() == CastExpr::CK_NoOp)
1789 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
1790
1791 IntRange OutputTypeRange = IntRange::forType(C, CE->getType());
1792
John McCall2ce81ad2010-01-06 22:07:33 +00001793 bool isIntegerCast = (CE->getCastKind() == CastExpr::CK_IntegralCast);
1794 if (!isIntegerCast && CE->getCastKind() == CastExpr::CK_Unknown)
1795 isIntegerCast = CE->getSubExpr()->getType()->isIntegerType();
1796
John McCall70aa5392010-01-06 05:24:50 +00001797 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00001798 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00001799 return OutputTypeRange;
1800
1801 IntRange SubRange
1802 = GetExprRange(C, CE->getSubExpr(),
1803 std::min(MaxWidth, OutputTypeRange.Width));
1804
1805 // Bail out if the subexpr's range is as wide as the cast type.
1806 if (SubRange.Width >= OutputTypeRange.Width)
1807 return OutputTypeRange;
1808
1809 // Otherwise, we take the smaller width, and we're non-negative if
1810 // either the output type or the subexpr is.
1811 return IntRange(SubRange.Width,
1812 SubRange.NonNegative || OutputTypeRange.NonNegative);
1813 }
1814
1815 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1816 // If we can fold the condition, just take that operand.
1817 bool CondResult;
1818 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
1819 return GetExprRange(C, CondResult ? CO->getTrueExpr()
1820 : CO->getFalseExpr(),
1821 MaxWidth);
1822
1823 // Otherwise, conservatively merge.
1824 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
1825 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
1826 return IntRange::join(L, R);
1827 }
1828
1829 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
1830 switch (BO->getOpcode()) {
1831
1832 // Boolean-valued operations are single-bit and positive.
1833 case BinaryOperator::LAnd:
1834 case BinaryOperator::LOr:
1835 case BinaryOperator::LT:
1836 case BinaryOperator::GT:
1837 case BinaryOperator::LE:
1838 case BinaryOperator::GE:
1839 case BinaryOperator::EQ:
1840 case BinaryOperator::NE:
1841 return IntRange::forBoolType();
1842
1843 // Operations with opaque sources are black-listed.
1844 case BinaryOperator::PtrMemD:
1845 case BinaryOperator::PtrMemI:
1846 return IntRange::forType(C, E->getType());
1847
John McCall2ce81ad2010-01-06 22:07:33 +00001848 // Bitwise-and uses the *infinum* of the two source ranges.
1849 case BinaryOperator::And:
1850 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
1851 GetExprRange(C, BO->getRHS(), MaxWidth));
1852
John McCall70aa5392010-01-06 05:24:50 +00001853 // Left shift gets black-listed based on a judgement call.
1854 case BinaryOperator::Shl:
1855 return IntRange::forType(C, E->getType());
1856
John McCall2ce81ad2010-01-06 22:07:33 +00001857 // Right shift by a constant can narrow its left argument.
1858 case BinaryOperator::Shr: {
1859 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
1860
1861 // If the shift amount is a positive constant, drop the width by
1862 // that much.
1863 llvm::APSInt shift;
1864 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
1865 shift.isNonNegative()) {
1866 unsigned zext = shift.getZExtValue();
1867 if (zext >= L.Width)
1868 L.Width = (L.NonNegative ? 0 : 1);
1869 else
1870 L.Width -= zext;
1871 }
1872
1873 return L;
1874 }
1875
1876 // Comma acts as its right operand.
John McCall70aa5392010-01-06 05:24:50 +00001877 case BinaryOperator::Comma:
1878 return GetExprRange(C, BO->getRHS(), MaxWidth);
1879
John McCall2ce81ad2010-01-06 22:07:33 +00001880 // Black-list pointer subtractions.
John McCall70aa5392010-01-06 05:24:50 +00001881 case BinaryOperator::Sub:
1882 if (BO->getLHS()->getType()->isPointerType())
1883 return IntRange::forType(C, E->getType());
1884 // fallthrough
1885
1886 default:
1887 break;
1888 }
1889
1890 // Treat every other operator as if it were closed on the
1891 // narrowest type that encompasses both operands.
1892 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
1893 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
1894 return IntRange::join(L, R);
1895 }
1896
1897 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
1898 switch (UO->getOpcode()) {
1899 // Boolean-valued operations are white-listed.
1900 case UnaryOperator::LNot:
1901 return IntRange::forBoolType();
1902
1903 // Operations with opaque sources are black-listed.
1904 case UnaryOperator::Deref:
1905 case UnaryOperator::AddrOf: // should be impossible
1906 case UnaryOperator::OffsetOf:
1907 return IntRange::forType(C, E->getType());
1908
1909 default:
1910 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
1911 }
1912 }
1913
1914 FieldDecl *BitField = E->getBitField();
1915 if (BitField) {
1916 llvm::APSInt BitWidthAP = BitField->getBitWidth()->EvaluateAsInt(C);
1917 unsigned BitWidth = BitWidthAP.getZExtValue();
1918
1919 return IntRange(BitWidth, BitField->getType()->isUnsignedIntegerType());
1920 }
1921
1922 return IntRange::forType(C, E->getType());
1923}
John McCall263a48b2010-01-04 23:31:57 +00001924
1925/// Checks whether the given value, which currently has the given
1926/// source semantics, has the same value when coerced through the
1927/// target semantics.
John McCall70aa5392010-01-06 05:24:50 +00001928bool IsSameFloatAfterCast(const llvm::APFloat &value,
1929 const llvm::fltSemantics &Src,
1930 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00001931 llvm::APFloat truncated = value;
1932
1933 bool ignored;
1934 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
1935 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
1936
1937 return truncated.bitwiseIsEqual(value);
1938}
1939
1940/// Checks whether the given value, which currently has the given
1941/// source semantics, has the same value when coerced through the
1942/// target semantics.
1943///
1944/// The value might be a vector of floats (or a complex number).
John McCall70aa5392010-01-06 05:24:50 +00001945bool IsSameFloatAfterCast(const APValue &value,
1946 const llvm::fltSemantics &Src,
1947 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00001948 if (value.isFloat())
1949 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
1950
1951 if (value.isVector()) {
1952 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
1953 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
1954 return false;
1955 return true;
1956 }
1957
1958 assert(value.isComplexFloat());
1959 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
1960 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
1961}
1962
John McCall70aa5392010-01-06 05:24:50 +00001963} // end anonymous namespace
John McCall263a48b2010-01-04 23:31:57 +00001964
John McCallca01b222010-01-04 23:21:16 +00001965/// \brief Implements -Wsign-compare.
1966///
1967/// \param lex the left-hand expression
1968/// \param rex the right-hand expression
1969/// \param OpLoc the location of the joining operator
1970/// \param Equality whether this is an "equality-like" join, which
1971/// suppresses the warning in some cases
1972void Sema::CheckSignCompare(Expr *lex, Expr *rex, SourceLocation OpLoc,
1973 const PartialDiagnostic &PD, bool Equality) {
1974 // Don't warn if we're in an unevaluated context.
1975 if (ExprEvalContexts.back().Context == Unevaluated)
1976 return;
1977
John McCall70aa5392010-01-06 05:24:50 +00001978 // If either expression is value-dependent, don't warn. We'll get another
1979 // chance at instantiation time.
1980 if (lex->isValueDependent() || rex->isValueDependent())
1981 return;
1982
John McCallca01b222010-01-04 23:21:16 +00001983 QualType lt = lex->getType(), rt = rex->getType();
1984
1985 // Only warn if both operands are integral.
1986 if (!lt->isIntegerType() || !rt->isIntegerType())
1987 return;
1988
John McCall70aa5392010-01-06 05:24:50 +00001989 // In C, the width of a bitfield determines its type, and the
1990 // declared type only contributes the signedness. This duplicates
1991 // the work that will later be done by UsualUnaryConversions.
1992 // Eventually, this check will be reorganized in a way that avoids
1993 // this duplication.
1994 if (!getLangOptions().CPlusPlus) {
1995 QualType tmp;
1996 tmp = Context.isPromotableBitField(lex);
1997 if (!tmp.isNull()) lt = tmp;
1998 tmp = Context.isPromotableBitField(rex);
1999 if (!tmp.isNull()) rt = tmp;
2000 }
John McCallca01b222010-01-04 23:21:16 +00002001
2002 // The rule is that the signed operand becomes unsigned, so isolate the
2003 // signed operand.
John McCall70aa5392010-01-06 05:24:50 +00002004 Expr *signedOperand = lex, *unsignedOperand = rex;
2005 QualType signedType = lt, unsignedType = rt;
John McCallca01b222010-01-04 23:21:16 +00002006 if (lt->isSignedIntegerType()) {
2007 if (rt->isSignedIntegerType()) return;
John McCallca01b222010-01-04 23:21:16 +00002008 } else {
2009 if (!rt->isSignedIntegerType()) return;
John McCall70aa5392010-01-06 05:24:50 +00002010 std::swap(signedOperand, unsignedOperand);
2011 std::swap(signedType, unsignedType);
John McCallca01b222010-01-04 23:21:16 +00002012 }
2013
John McCall70aa5392010-01-06 05:24:50 +00002014 unsigned unsignedWidth = Context.getIntWidth(unsignedType);
2015 unsigned signedWidth = Context.getIntWidth(signedType);
2016
John McCallca01b222010-01-04 23:21:16 +00002017 // If the unsigned type is strictly smaller than the signed type,
2018 // then (1) the result type will be signed and (2) the unsigned
2019 // value will fit fully within the signed type, and thus the result
2020 // of the comparison will be exact.
John McCall70aa5392010-01-06 05:24:50 +00002021 if (signedWidth > unsignedWidth)
John McCallca01b222010-01-04 23:21:16 +00002022 return;
2023
John McCall70aa5392010-01-06 05:24:50 +00002024 // Otherwise, calculate the effective ranges.
2025 IntRange signedRange = GetExprRange(Context, signedOperand, signedWidth);
2026 IntRange unsignedRange = GetExprRange(Context, unsignedOperand, unsignedWidth);
2027
2028 // We should never be unable to prove that the unsigned operand is
2029 // non-negative.
2030 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
2031
2032 // If the signed operand is non-negative, then the signed->unsigned
2033 // conversion won't change it.
2034 if (signedRange.NonNegative)
John McCallca01b222010-01-04 23:21:16 +00002035 return;
2036
2037 // For (in)equality comparisons, if the unsigned operand is a
2038 // constant which cannot collide with a overflowed signed operand,
2039 // then reinterpreting the signed operand as unsigned will not
2040 // change the result of the comparison.
John McCall70aa5392010-01-06 05:24:50 +00002041 if (Equality && unsignedRange.Width < unsignedWidth)
John McCallca01b222010-01-04 23:21:16 +00002042 return;
2043
2044 Diag(OpLoc, PD)
John McCall70aa5392010-01-06 05:24:50 +00002045 << lt << rt << lex->getSourceRange() << rex->getSourceRange();
John McCallca01b222010-01-04 23:21:16 +00002046}
2047
John McCall263a48b2010-01-04 23:31:57 +00002048/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
2049static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, unsigned diag) {
2050 S.Diag(E->getExprLoc(), diag) << E->getType() << T << E->getSourceRange();
2051}
2052
2053/// Implements -Wconversion.
2054void Sema::CheckImplicitConversion(Expr *E, QualType T) {
2055 // Don't diagnose in unevaluated contexts.
2056 if (ExprEvalContexts.back().Context == Sema::Unevaluated)
2057 return;
2058
2059 // Don't diagnose for value-dependent expressions.
2060 if (E->isValueDependent())
2061 return;
2062
2063 const Type *Source = Context.getCanonicalType(E->getType()).getTypePtr();
2064 const Type *Target = Context.getCanonicalType(T).getTypePtr();
2065
2066 // Never diagnose implicit casts to bool.
2067 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
2068 return;
2069
2070 // Strip vector types.
2071 if (isa<VectorType>(Source)) {
2072 if (!isa<VectorType>(Target))
2073 return DiagnoseImpCast(*this, E, T, diag::warn_impcast_vector_scalar);
2074
2075 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
2076 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
2077 }
2078
2079 // Strip complex types.
2080 if (isa<ComplexType>(Source)) {
2081 if (!isa<ComplexType>(Target))
2082 return DiagnoseImpCast(*this, E, T, diag::warn_impcast_complex_scalar);
2083
2084 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
2085 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
2086 }
2087
2088 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
2089 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
2090
2091 // If the source is floating point...
2092 if (SourceBT && SourceBT->isFloatingPoint()) {
2093 // ...and the target is floating point...
2094 if (TargetBT && TargetBT->isFloatingPoint()) {
2095 // ...then warn if we're dropping FP rank.
2096
2097 // Builtin FP kinds are ordered by increasing FP rank.
2098 if (SourceBT->getKind() > TargetBT->getKind()) {
2099 // Don't warn about float constants that are precisely
2100 // representable in the target type.
2101 Expr::EvalResult result;
2102 if (E->Evaluate(result, Context)) {
2103 // Value might be a float, a float vector, or a float complex.
2104 if (IsSameFloatAfterCast(result.Val,
2105 Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
2106 Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
2107 return;
2108 }
2109
2110 DiagnoseImpCast(*this, E, T, diag::warn_impcast_float_precision);
2111 }
2112 return;
2113 }
2114
2115 // If the target is integral, always warn.
2116 if ((TargetBT && TargetBT->isInteger()))
2117 // TODO: don't warn for integer values?
2118 return DiagnoseImpCast(*this, E, T, diag::warn_impcast_float_integer);
2119
2120 return;
2121 }
2122
John McCall70aa5392010-01-06 05:24:50 +00002123 if (!Source->isIntegerType() || !Target->isIntegerType())
John McCall263a48b2010-01-04 23:31:57 +00002124 return;
2125
John McCall70aa5392010-01-06 05:24:50 +00002126 IntRange SourceRange = GetExprRange(Context, E, Context.getIntWidth(E->getType()));
2127 IntRange TargetRange = IntRange::forCanonicalType(Context, Target);
John McCall263a48b2010-01-04 23:31:57 +00002128
John McCall70aa5392010-01-06 05:24:50 +00002129 // FIXME: also signed<->unsigned?
2130
2131 if (SourceRange.Width > TargetRange.Width) {
John McCall263a48b2010-01-04 23:31:57 +00002132 // People want to build with -Wshorten-64-to-32 and not -Wconversion
2133 // and by god we'll let them.
John McCall70aa5392010-01-06 05:24:50 +00002134 if (SourceRange.Width == 64 && TargetRange.Width == 32)
John McCall263a48b2010-01-04 23:31:57 +00002135 return DiagnoseImpCast(*this, E, T, diag::warn_impcast_integer_64_32);
2136 return DiagnoseImpCast(*this, E, T, diag::warn_impcast_integer_precision);
2137 }
2138
2139 return;
2140}
2141
Mike Stump0c2ec772010-01-21 03:59:47 +00002142// MarkLive - Mark all the blocks reachable from e as live. Returns the total
2143// number of blocks just marked live.
2144static unsigned MarkLive(CFGBlock *e, llvm::BitVector &live) {
2145 unsigned count = 0;
2146 std::queue<CFGBlock*> workq;
2147 // Prep work queue
2148 live.set(e->getBlockID());
2149 ++count;
2150 workq.push(e);
2151 // Solve
2152 while (!workq.empty()) {
2153 CFGBlock *item = workq.front();
2154 workq.pop();
2155 for (CFGBlock::succ_iterator I=item->succ_begin(),
2156 E=item->succ_end();
2157 I != E;
2158 ++I) {
2159 if ((*I) && !live[(*I)->getBlockID()]) {
2160 live.set((*I)->getBlockID());
2161 ++count;
2162 workq.push(*I);
2163 }
2164 }
2165 }
2166 return count;
2167}
2168
Mike Stumpcc3a8532010-01-21 17:21:23 +00002169static SourceLocation GetUnreachableLoc(CFGBlock &b, SourceRange &R1,
2170 SourceRange &R2) {
Mike Stump0c2ec772010-01-21 03:59:47 +00002171 Stmt *S;
Mike Stumpc18c4032010-01-21 19:44:04 +00002172 unsigned sn = 0;
2173 R1 = R2 = SourceRange();
2174
2175 top:
2176 if (sn < b.size())
2177 S = b[sn].getStmt();
Mike Stump0c2ec772010-01-21 03:59:47 +00002178 else if (b.getTerminator())
2179 S = b.getTerminator();
2180 else
2181 return SourceLocation();
2182
2183 switch (S->getStmtClass()) {
2184 case Expr::BinaryOperatorClass: {
Mike Stumpcc3a8532010-01-21 17:21:23 +00002185 BinaryOperator *BO = cast<BinaryOperator>(S);
2186 if (BO->getOpcode() == BinaryOperator::Comma) {
Mike Stumpc18c4032010-01-21 19:44:04 +00002187 if (sn+1 < b.size())
2188 return b[sn+1].getStmt()->getLocStart();
Mike Stump0c2ec772010-01-21 03:59:47 +00002189 CFGBlock *n = &b;
2190 while (1) {
2191 if (n->getTerminator())
2192 return n->getTerminator()->getLocStart();
2193 if (n->succ_size() != 1)
2194 return SourceLocation();
2195 n = n[0].succ_begin()[0];
2196 if (n->pred_size() != 1)
2197 return SourceLocation();
2198 if (!n->empty())
2199 return n[0][0].getStmt()->getLocStart();
2200 }
2201 }
Mike Stumpcc3a8532010-01-21 17:21:23 +00002202 R1 = BO->getLHS()->getSourceRange();
2203 R2 = BO->getRHS()->getSourceRange();
2204 return BO->getOperatorLoc();
2205 }
2206 case Expr::UnaryOperatorClass: {
2207 const UnaryOperator *UO = cast<UnaryOperator>(S);
2208 R1 = UO->getSubExpr()->getSourceRange();
2209 return UO->getOperatorLoc();
Mike Stump0c2ec772010-01-21 03:59:47 +00002210 }
Mike Stump14781502010-01-21 17:31:41 +00002211 case Expr::CompoundAssignOperatorClass: {
2212 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(S);
2213 R1 = CAO->getLHS()->getSourceRange();
2214 R2 = CAO->getRHS()->getSourceRange();
2215 return CAO->getOperatorLoc();
2216 }
Mike Stumpc18c4032010-01-21 19:44:04 +00002217 case Expr::ConditionalOperatorClass: {
2218 const ConditionalOperator *CO = cast<ConditionalOperator>(S);
2219 return CO->getQuestionLoc();
2220 }
Mike Stump60dbeeb2010-01-21 23:15:53 +00002221 case Expr::MemberExprClass: {
2222 const MemberExpr *ME = cast<MemberExpr>(S);
2223 R1 = ME->getSourceRange();
2224 return ME->getMemberLoc();
2225 }
2226 case Expr::ArraySubscriptExprClass: {
2227 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(S);
2228 R1 = ASE->getLHS()->getSourceRange();
2229 R2 = ASE->getRHS()->getSourceRange();
2230 return ASE->getRBracketLoc();
2231 }
Mike Stumpd12e4952010-01-21 19:51:34 +00002232 case Expr::CStyleCastExprClass: {
2233 const CStyleCastExpr *CSC = cast<CStyleCastExpr>(S);
2234 R1 = CSC->getSubExpr()->getSourceRange();
2235 return CSC->getLParenLoc();
2236 }
Mike Stumpfcd6f942010-01-21 22:12:18 +00002237 case Expr::CXXFunctionalCastExprClass: {
2238 const CXXFunctionalCastExpr *CE = cast <CXXFunctionalCastExpr>(S);
2239 R1 = CE->getSubExpr()->getSourceRange();
2240 return CE->getTypeBeginLoc();
2241 }
Mike Stumpc18c4032010-01-21 19:44:04 +00002242 case Expr::ImplicitCastExprClass:
2243 ++sn;
2244 goto top;
Mike Stump04c68512010-01-21 15:20:48 +00002245 case Stmt::CXXTryStmtClass: {
2246 return cast<CXXTryStmt>(S)->getHandler(0)->getCatchLoc();
2247 }
Mike Stump0c2ec772010-01-21 03:59:47 +00002248 default: ;
2249 }
Mike Stump60dbeeb2010-01-21 23:15:53 +00002250 R1 = S->getSourceRange();
Mike Stump0c2ec772010-01-21 03:59:47 +00002251 return S->getLocStart();
2252}
2253
2254static SourceLocation MarkLiveTop(CFGBlock *e, llvm::BitVector &live,
2255 SourceManager &SM) {
2256 std::queue<CFGBlock*> workq;
2257 // Prep work queue
2258 workq.push(e);
Mike Stumpcc3a8532010-01-21 17:21:23 +00002259 SourceRange R1, R2;
2260 SourceLocation top = GetUnreachableLoc(*e, R1, R2);
Mike Stump0c2ec772010-01-21 03:59:47 +00002261 bool FromMainFile = false;
2262 bool FromSystemHeader = false;
2263 bool TopValid = false;
2264 if (top.isValid()) {
2265 FromMainFile = SM.isFromMainFile(top);
2266 FromSystemHeader = SM.isInSystemHeader(top);
2267 TopValid = true;
2268 }
2269 // Solve
2270 while (!workq.empty()) {
2271 CFGBlock *item = workq.front();
2272 workq.pop();
Mike Stumpcc3a8532010-01-21 17:21:23 +00002273 SourceLocation c = GetUnreachableLoc(*item, R1, R2);
Mike Stump0c2ec772010-01-21 03:59:47 +00002274 if (c.isValid()
2275 && (!TopValid
2276 || (SM.isFromMainFile(c) && !FromMainFile)
2277 || (FromSystemHeader && !SM.isInSystemHeader(c))
2278 || SM.isBeforeInTranslationUnit(c, top))) {
2279 top = c;
2280 FromMainFile = SM.isFromMainFile(top);
2281 FromSystemHeader = SM.isInSystemHeader(top);
2282 }
2283 live.set(item->getBlockID());
2284 for (CFGBlock::succ_iterator I=item->succ_begin(),
2285 E=item->succ_end();
2286 I != E;
2287 ++I) {
2288 if ((*I) && !live[(*I)->getBlockID()]) {
2289 live.set((*I)->getBlockID());
2290 workq.push(*I);
2291 }
2292 }
2293 }
2294 return top;
2295}
2296
2297static int LineCmp(const void *p1, const void *p2) {
2298 SourceLocation *Line1 = (SourceLocation *)p1;
2299 SourceLocation *Line2 = (SourceLocation *)p2;
2300 return !(*Line1 < *Line2);
2301}
2302
Mike Stump6cbe36f2010-01-21 23:49:01 +00002303namespace {
2304 struct ErrLoc {
2305 SourceLocation Loc;
2306 SourceRange R1;
2307 SourceRange R2;
2308 ErrLoc(SourceLocation l, SourceRange r1, SourceRange r2)
2309 : Loc(l), R1(r1), R2(r2) { }
2310 };
2311}
2312
Mike Stump0c2ec772010-01-21 03:59:47 +00002313/// CheckUnreachable - Check for unreachable code.
2314void Sema::CheckUnreachable(AnalysisContext &AC) {
2315 unsigned count;
2316 // We avoid checking when there are errors, as the CFG won't faithfully match
2317 // the user's code.
2318 if (getDiagnostics().hasErrorOccurred())
2319 return;
2320 if (Diags.getDiagnosticLevel(diag::warn_unreachable) == Diagnostic::Ignored)
2321 return;
2322
2323 CFG *cfg = AC.getCFG();
2324 if (cfg == 0)
2325 return;
2326
2327 llvm::BitVector live(cfg->getNumBlockIDs());
2328 // Mark all live things first.
2329 count = MarkLive(&cfg->getEntry(), live);
2330
2331 if (count == cfg->getNumBlockIDs())
2332 // If there are no dead blocks, we're done.
2333 return;
2334
Mike Stumpcc3a8532010-01-21 17:21:23 +00002335 SourceRange R1, R2;
2336
Mike Stump6cbe36f2010-01-21 23:49:01 +00002337 llvm::SmallVector<ErrLoc, 24> lines;
Mike Stump04c68512010-01-21 15:20:48 +00002338 bool AddEHEdges = AC.getAddEHEdges();
Mike Stump0c2ec772010-01-21 03:59:47 +00002339 // First, give warnings for blocks with no predecessors, as they
2340 // can't be part of a loop.
2341 for (CFG::iterator I = cfg->begin(), E = cfg->end(); I != E; ++I) {
2342 CFGBlock &b = **I;
2343 if (!live[b.getBlockID()]) {
2344 if (b.pred_begin() == b.pred_end()) {
Mike Stump04c68512010-01-21 15:20:48 +00002345 if (!AddEHEdges && b.getTerminator()
2346 && isa<CXXTryStmt>(b.getTerminator())) {
2347 // When not adding EH edges from calls, catch clauses
2348 // can otherwise seem dead. Avoid noting them as dead.
2349 count += MarkLive(&b, live);
2350 continue;
2351 }
Mike Stumpcc3a8532010-01-21 17:21:23 +00002352 SourceLocation c = GetUnreachableLoc(b, R1, R2);
Mike Stump0c2ec772010-01-21 03:59:47 +00002353 if (!c.isValid()) {
2354 // Blocks without a location can't produce a warning, so don't mark
2355 // reachable blocks from here as live.
2356 live.set(b.getBlockID());
2357 ++count;
2358 continue;
2359 }
Mike Stump6cbe36f2010-01-21 23:49:01 +00002360 lines.push_back(ErrLoc(c, R1, R2));
Mike Stump0c2ec772010-01-21 03:59:47 +00002361 // Avoid excessive errors by marking everything reachable from here
2362 count += MarkLive(&b, live);
2363 }
2364 }
2365 }
2366
2367 if (count < cfg->getNumBlockIDs()) {
2368 // And then give warnings for the tops of loops.
2369 for (CFG::iterator I = cfg->begin(), E = cfg->end(); I != E; ++I) {
2370 CFGBlock &b = **I;
2371 if (!live[b.getBlockID()])
2372 // Avoid excessive errors by marking everything reachable from here
Ted Kremeneke4fd3302010-01-28 01:04:48 +00002373 lines.push_back(ErrLoc(MarkLiveTop(&b, live,
2374 Context.getSourceManager()),
2375 SourceRange(), SourceRange()));
Mike Stump0c2ec772010-01-21 03:59:47 +00002376 }
2377 }
2378
2379 llvm::array_pod_sort(lines.begin(), lines.end(), LineCmp);
Mike Stump6cbe36f2010-01-21 23:49:01 +00002380 for (llvm::SmallVector<ErrLoc, 24>::iterator I = lines.begin(),
Mike Stump0c2ec772010-01-21 03:59:47 +00002381 E = lines.end();
2382 I != E;
2383 ++I)
Mike Stump6cbe36f2010-01-21 23:49:01 +00002384 if (I->Loc.isValid())
2385 Diag(I->Loc, diag::warn_unreachable) << I->R1 << I->R2;
Mike Stump0c2ec772010-01-21 03:59:47 +00002386}
2387
2388/// CheckFallThrough - Check that we don't fall off the end of a
2389/// Statement that should return a value.
2390///
2391/// \returns AlwaysFallThrough iff we always fall off the end of the statement,
2392/// MaybeFallThrough iff we might or might not fall off the end,
2393/// NeverFallThroughOrReturn iff we never fall off the end of the statement or
2394/// return. We assume NeverFallThrough iff we never fall off the end of the
2395/// statement but we may return. We assume that functions not marked noreturn
2396/// will return.
2397Sema::ControlFlowKind Sema::CheckFallThrough(AnalysisContext &AC) {
2398 CFG *cfg = AC.getCFG();
2399 if (cfg == 0)
2400 // FIXME: This should be NeverFallThrough
2401 return NeverFallThroughOrReturn;
2402
Mike Stump04c68512010-01-21 15:20:48 +00002403 // The CFG leaves in dead things, and we don't want the dead code paths to
Mike Stump0c2ec772010-01-21 03:59:47 +00002404 // confuse us, so we mark all live things first.
2405 std::queue<CFGBlock*> workq;
2406 llvm::BitVector live(cfg->getNumBlockIDs());
Mike Stump04c68512010-01-21 15:20:48 +00002407 unsigned count = MarkLive(&cfg->getEntry(), live);
2408
2409 bool AddEHEdges = AC.getAddEHEdges();
2410 if (!AddEHEdges && count != cfg->getNumBlockIDs())
2411 // When there are things remaining dead, and we didn't add EH edges
2412 // from CallExprs to the catch clauses, we have to go back and
2413 // mark them as live.
2414 for (CFG::iterator I = cfg->begin(), E = cfg->end(); I != E; ++I) {
2415 CFGBlock &b = **I;
2416 if (!live[b.getBlockID()]) {
2417 if (b.pred_begin() == b.pred_end()) {
2418 if (b.getTerminator() && isa<CXXTryStmt>(b.getTerminator()))
2419 // When not adding EH edges from calls, catch clauses
2420 // can otherwise seem dead. Avoid noting them as dead.
2421 count += MarkLive(&b, live);
2422 continue;
2423 }
2424 }
2425 }
Mike Stump0c2ec772010-01-21 03:59:47 +00002426
2427 // Now we know what is live, we check the live precessors of the exit block
2428 // and look for fall through paths, being careful to ignore normal returns,
2429 // and exceptional paths.
2430 bool HasLiveReturn = false;
2431 bool HasFakeEdge = false;
2432 bool HasPlainEdge = false;
2433 bool HasAbnormalEdge = false;
2434 for (CFGBlock::pred_iterator I=cfg->getExit().pred_begin(),
2435 E = cfg->getExit().pred_end();
2436 I != E;
2437 ++I) {
2438 CFGBlock& B = **I;
2439 if (!live[B.getBlockID()])
2440 continue;
2441 if (B.size() == 0) {
Mike Stump04c68512010-01-21 15:20:48 +00002442 if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
2443 HasAbnormalEdge = true;
2444 continue;
2445 }
2446
Mike Stump0c2ec772010-01-21 03:59:47 +00002447 // A labeled empty statement, or the entry block...
2448 HasPlainEdge = true;
2449 continue;
2450 }
2451 Stmt *S = B[B.size()-1];
2452 if (isa<ReturnStmt>(S)) {
2453 HasLiveReturn = true;
2454 continue;
2455 }
2456 if (isa<ObjCAtThrowStmt>(S)) {
2457 HasFakeEdge = true;
2458 continue;
2459 }
2460 if (isa<CXXThrowExpr>(S)) {
2461 HasFakeEdge = true;
2462 continue;
2463 }
2464 if (const AsmStmt *AS = dyn_cast<AsmStmt>(S)) {
2465 if (AS->isMSAsm()) {
2466 HasFakeEdge = true;
2467 HasLiveReturn = true;
2468 continue;
2469 }
2470 }
2471 if (isa<CXXTryStmt>(S)) {
2472 HasAbnormalEdge = true;
2473 continue;
2474 }
2475
2476 bool NoReturnEdge = false;
2477 if (CallExpr *C = dyn_cast<CallExpr>(S)) {
2478 if (B.succ_begin()[0] != &cfg->getExit()) {
2479 HasAbnormalEdge = true;
2480 continue;
2481 }
2482 Expr *CEE = C->getCallee()->IgnoreParenCasts();
2483 if (CEE->getType().getNoReturnAttr()) {
2484 NoReturnEdge = true;
2485 HasFakeEdge = true;
2486 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE)) {
2487 ValueDecl *VD = DRE->getDecl();
2488 if (VD->hasAttr<NoReturnAttr>()) {
2489 NoReturnEdge = true;
2490 HasFakeEdge = true;
2491 }
2492 }
2493 }
2494 // FIXME: Add noreturn message sends.
2495 if (NoReturnEdge == false)
2496 HasPlainEdge = true;
2497 }
2498 if (!HasPlainEdge) {
2499 if (HasLiveReturn)
2500 return NeverFallThrough;
2501 return NeverFallThroughOrReturn;
2502 }
2503 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
2504 return MaybeFallThrough;
2505 // This says AlwaysFallThrough for calls to functions that are not marked
2506 // noreturn, that don't return. If people would like this warning to be more
2507 // accurate, such functions should be marked as noreturn.
2508 return AlwaysFallThrough;
2509}
2510
2511/// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
2512/// function that should return a value. Check that we don't fall off the end
2513/// of a noreturn function. We assume that functions and blocks not marked
2514/// noreturn will return.
2515void Sema::CheckFallThroughForFunctionDef(Decl *D, Stmt *Body,
2516 AnalysisContext &AC) {
2517 // FIXME: Would be nice if we had a better way to control cascading errors,
2518 // but for now, avoid them. The problem is that when Parse sees:
2519 // int foo() { return a; }
2520 // The return is eaten and the Sema code sees just:
2521 // int foo() { }
2522 // which this code would then warn about.
2523 if (getDiagnostics().hasErrorOccurred())
2524 return;
2525
2526 bool ReturnsVoid = false;
2527 bool HasNoReturn = false;
2528 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Anders Carlsson96c15b12010-02-06 05:31:15 +00002529 // For function templates, class templates and member function templates
2530 // we'll do the analysis at instantiation time.
2531 if (FD->isDependentContext())
Mike Stump0c2ec772010-01-21 03:59:47 +00002532 return;
Anders Carlsson96c15b12010-02-06 05:31:15 +00002533
Mike Stump0c2ec772010-01-21 03:59:47 +00002534 if (FD->getResultType()->isVoidType())
2535 ReturnsVoid = true;
John McCallab26cfa2010-02-05 21:31:56 +00002536 if (FD->hasAttr<NoReturnAttr>() ||
2537 FD->getType()->getAs<FunctionType>()->getNoReturnAttr())
Mike Stump0c2ec772010-01-21 03:59:47 +00002538 HasNoReturn = true;
2539 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2540 if (MD->getResultType()->isVoidType())
2541 ReturnsVoid = true;
2542 if (MD->hasAttr<NoReturnAttr>())
2543 HasNoReturn = true;
2544 }
2545
2546 // Short circuit for compilation speed.
2547 if ((Diags.getDiagnosticLevel(diag::warn_maybe_falloff_nonvoid_function)
2548 == Diagnostic::Ignored || ReturnsVoid)
2549 && (Diags.getDiagnosticLevel(diag::warn_noreturn_function_has_return_expr)
2550 == Diagnostic::Ignored || !HasNoReturn)
2551 && (Diags.getDiagnosticLevel(diag::warn_suggest_noreturn_block)
2552 == Diagnostic::Ignored || !ReturnsVoid))
2553 return;
2554 // FIXME: Function try block
2555 if (CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) {
2556 switch (CheckFallThrough(AC)) {
2557 case MaybeFallThrough:
2558 if (HasNoReturn)
2559 Diag(Compound->getRBracLoc(), diag::warn_falloff_noreturn_function);
2560 else if (!ReturnsVoid)
2561 Diag(Compound->getRBracLoc(),diag::warn_maybe_falloff_nonvoid_function);
2562 break;
2563 case AlwaysFallThrough:
2564 if (HasNoReturn)
2565 Diag(Compound->getRBracLoc(), diag::warn_falloff_noreturn_function);
2566 else if (!ReturnsVoid)
2567 Diag(Compound->getRBracLoc(), diag::warn_falloff_nonvoid_function);
2568 break;
2569 case NeverFallThroughOrReturn:
2570 if (ReturnsVoid && !HasNoReturn)
2571 Diag(Compound->getLBracLoc(), diag::warn_suggest_noreturn_function);
2572 break;
2573 case NeverFallThrough:
2574 break;
2575 }
2576 }
2577}
2578
2579/// CheckFallThroughForBlock - Check that we don't fall off the end of a block
2580/// that should return a value. Check that we don't fall off the end of a
2581/// noreturn block. We assume that functions and blocks not marked noreturn
2582/// will return.
2583void Sema::CheckFallThroughForBlock(QualType BlockTy, Stmt *Body,
2584 AnalysisContext &AC) {
2585 // FIXME: Would be nice if we had a better way to control cascading errors,
2586 // but for now, avoid them. The problem is that when Parse sees:
2587 // int foo() { return a; }
2588 // The return is eaten and the Sema code sees just:
2589 // int foo() { }
2590 // which this code would then warn about.
2591 if (getDiagnostics().hasErrorOccurred())
2592 return;
2593 bool ReturnsVoid = false;
2594 bool HasNoReturn = false;
2595 if (const FunctionType *FT =BlockTy->getPointeeType()->getAs<FunctionType>()){
2596 if (FT->getResultType()->isVoidType())
2597 ReturnsVoid = true;
2598 if (FT->getNoReturnAttr())
2599 HasNoReturn = true;
2600 }
2601
2602 // Short circuit for compilation speed.
2603 if (ReturnsVoid
2604 && !HasNoReturn
2605 && (Diags.getDiagnosticLevel(diag::warn_suggest_noreturn_block)
2606 == Diagnostic::Ignored || !ReturnsVoid))
2607 return;
2608 // FIXME: Funtion try block
2609 if (CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) {
2610 switch (CheckFallThrough(AC)) {
2611 case MaybeFallThrough:
2612 if (HasNoReturn)
2613 Diag(Compound->getRBracLoc(), diag::err_noreturn_block_has_return_expr);
2614 else if (!ReturnsVoid)
2615 Diag(Compound->getRBracLoc(), diag::err_maybe_falloff_nonvoid_block);
2616 break;
2617 case AlwaysFallThrough:
2618 if (HasNoReturn)
2619 Diag(Compound->getRBracLoc(), diag::err_noreturn_block_has_return_expr);
2620 else if (!ReturnsVoid)
2621 Diag(Compound->getRBracLoc(), diag::err_falloff_nonvoid_block);
2622 break;
2623 case NeverFallThroughOrReturn:
2624 if (ReturnsVoid)
2625 Diag(Compound->getLBracLoc(), diag::warn_suggest_noreturn_block);
2626 break;
2627 case NeverFallThrough:
2628 break;
2629 }
2630 }
2631}
2632
2633/// CheckParmsForFunctionDef - Check that the parameters of the given
2634/// function are appropriate for the definition of a function. This
2635/// takes care of any checks that cannot be performed on the
2636/// declaration itself, e.g., that the types of each of the function
2637/// parameters are complete.
2638bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
2639 bool HasInvalidParm = false;
2640 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2641 ParmVarDecl *Param = FD->getParamDecl(p);
2642
2643 // C99 6.7.5.3p4: the parameters in a parameter type list in a
2644 // function declarator that is part of a function definition of
2645 // that function shall not have incomplete type.
2646 //
2647 // This is also C++ [dcl.fct]p6.
2648 if (!Param->isInvalidDecl() &&
2649 RequireCompleteType(Param->getLocation(), Param->getType(),
2650 diag::err_typecheck_decl_incomplete_type)) {
2651 Param->setInvalidDecl();
2652 HasInvalidParm = true;
2653 }
2654
2655 // C99 6.9.1p5: If the declarator includes a parameter type list, the
2656 // declaration of each parameter shall include an identifier.
2657 if (Param->getIdentifier() == 0 &&
2658 !Param->isImplicit() &&
2659 !getLangOptions().CPlusPlus)
2660 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00002661
2662 // C99 6.7.5.3p12:
2663 // If the function declarator is not part of a definition of that
2664 // function, parameters may have incomplete type and may use the [*]
2665 // notation in their sequences of declarator specifiers to specify
2666 // variable length array types.
2667 QualType PType = Param->getOriginalType();
2668 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
2669 if (AT->getSizeModifier() == ArrayType::Star) {
2670 // FIXME: This diagnosic should point the the '[*]' if source-location
2671 // information is added for it.
2672 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
2673 }
2674 }
John McCall6781b052010-02-02 08:45:54 +00002675
John McCall03c48482010-02-02 09:10:11 +00002676 if (getLangOptions().CPlusPlus)
2677 if (const RecordType *RT = Param->getType()->getAs<RecordType>())
2678 FinalizeVarWithDestructor(Param, RT);
Mike Stump0c2ec772010-01-21 03:59:47 +00002679 }
2680
2681 return HasInvalidParm;
2682}