blob: aec90bd9ceedbbd18f8a4675e1b0edb7092c2c83 [file] [log] [blame]
Chris Lattner59907c42007-08-10 20:18:51 +00001//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner59907c42007-08-10 20:18:51 +00007//
8//===----------------------------------------------------------------------===//
9//
Mike Stump1eb44332009-09-09 15:08:12 +000010// This file implements extra semantic analysis beyond what is enforced
Chris Lattner59907c42007-08-10 20:18:51 +000011// by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
John McCall5f8d6042011-08-27 01:09:30 +000015#include "clang/Sema/Initialization.h"
Douglas Gregore737f502010-08-12 20:07:10 +000016#include "clang/Sema/Sema.h"
John McCall2d887082010-08-25 22:03:47 +000017#include "clang/Sema/SemaInternal.h"
John McCall781472f2010-08-25 08:40:02 +000018#include "clang/Sema/ScopeInfo.h"
Ted Kremenek826a3452010-07-16 02:11:22 +000019#include "clang/Analysis/Analyses/FormatString.h"
Chris Lattner59907c42007-08-10 20:18:51 +000020#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000021#include "clang/AST/CharUnits.h"
John McCall384aff82010-08-25 07:42:41 +000022#include "clang/AST/DeclCXX.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000023#include "clang/AST/DeclObjC.h"
Ted Kremenek23245122007-08-20 16:18:38 +000024#include "clang/AST/ExprCXX.h"
Ted Kremenek7ff22b22008-06-16 18:00:42 +000025#include "clang/AST/ExprObjC.h"
John McCallf85e1932011-06-15 23:02:42 +000026#include "clang/AST/EvaluatedExprVisitor.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000027#include "clang/AST/DeclObjC.h"
28#include "clang/AST/StmtCXX.h"
29#include "clang/AST/StmtObjC.h"
Chris Lattner59907c42007-08-10 20:18:51 +000030#include "clang/Lex/Preprocessor.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000031#include "llvm/ADT/BitVector.h"
32#include "llvm/ADT/STLExtras.h"
Tom Care3bfc5f42010-06-09 04:11:11 +000033#include "llvm/Support/raw_ostream.h"
Eric Christopher691ebc32010-04-17 02:26:23 +000034#include "clang/Basic/TargetBuiltins.h"
Nate Begeman26a31422010-06-08 02:47:44 +000035#include "clang/Basic/TargetInfo.h"
Fariborz Jahanian7da71022010-09-07 19:38:13 +000036#include "clang/Basic/ConvertUTF.h"
Zhongxing Xua1f3dba2009-05-20 01:55:10 +000037#include <limits>
Chris Lattner59907c42007-08-10 20:18:51 +000038using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000039using namespace sema;
Chris Lattner59907c42007-08-10 20:18:51 +000040
Chris Lattner60800082009-02-18 17:49:48 +000041SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
42 unsigned ByteNo) const {
Chris Lattner08f92e32010-11-17 07:37:15 +000043 return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
44 PP.getLangOptions(), PP.getTargetInfo());
Chris Lattner60800082009-02-18 17:49:48 +000045}
Chris Lattner08f92e32010-11-17 07:37:15 +000046
Chris Lattner60800082009-02-18 17:49:48 +000047
Ryan Flynn4403a5e2009-08-06 03:00:50 +000048/// CheckablePrintfAttr - does a function call have a "printf" attribute
49/// and arguments that merit checking?
50bool Sema::CheckablePrintfAttr(const FormatAttr *Format, CallExpr *TheCall) {
51 if (Format->getType() == "printf") return true;
52 if (Format->getType() == "printf0") {
53 // printf0 allows null "format" string; if so don't check format/args
54 unsigned format_idx = Format->getFormatIdx() - 1;
Sebastian Redl4a2614e2009-11-17 18:02:24 +000055 // Does the index refer to the implicit object argument?
56 if (isa<CXXMemberCallExpr>(TheCall)) {
57 if (format_idx == 0)
58 return false;
59 --format_idx;
60 }
Ryan Flynn4403a5e2009-08-06 03:00:50 +000061 if (format_idx < TheCall->getNumArgs()) {
62 Expr *Format = TheCall->getArg(format_idx)->IgnoreParenCasts();
Ted Kremenekefaff192010-02-27 01:41:03 +000063 if (!Format->isNullPointerConstant(Context,
64 Expr::NPC_ValueDependentIsNull))
Ryan Flynn4403a5e2009-08-06 03:00:50 +000065 return true;
66 }
67 }
68 return false;
69}
Chris Lattner60800082009-02-18 17:49:48 +000070
John McCall8e10f3b2011-02-26 05:39:39 +000071/// Checks that a call expression's argument count is the desired number.
72/// This is useful when doing custom type-checking. Returns true on error.
73static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
74 unsigned argCount = call->getNumArgs();
75 if (argCount == desiredArgCount) return false;
76
77 if (argCount < desiredArgCount)
78 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
79 << 0 /*function call*/ << desiredArgCount << argCount
80 << call->getSourceRange();
81
82 // Highlight all the excess arguments.
83 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
84 call->getArg(argCount - 1)->getLocEnd());
85
86 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
87 << 0 /*function call*/ << desiredArgCount << argCount
88 << call->getArg(1)->getSourceRange();
89}
90
John McCall60d7b3a2010-08-24 06:29:42 +000091ExprResult
Anders Carlssond406bf02009-08-16 01:56:34 +000092Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
John McCall60d7b3a2010-08-24 06:29:42 +000093 ExprResult TheCallResult(Owned(TheCall));
Douglas Gregor2def4832008-11-17 20:34:05 +000094
Chris Lattner946928f2010-10-01 23:23:24 +000095 // Find out if any arguments are required to be integer constant expressions.
96 unsigned ICEArguments = 0;
97 ASTContext::GetBuiltinTypeError Error;
98 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
99 if (Error != ASTContext::GE_None)
100 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
101
102 // If any arguments are required to be ICE's, check and diagnose.
103 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
104 // Skip arguments not required to be ICE's.
105 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
106
107 llvm::APSInt Result;
108 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
109 return true;
110 ICEArguments &= ~(1 << ArgNo);
111 }
112
Anders Carlssond406bf02009-08-16 01:56:34 +0000113 switch (BuiltinID) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000114 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +0000115 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +0000116 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner69039812009-02-18 06:01:06 +0000117 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000118 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000119 break;
Ted Kremenek49ff7a12008-07-09 17:58:53 +0000120 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +0000121 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000122 if (SemaBuiltinVAStart(TheCall))
123 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000124 break;
Chris Lattner1b9a0792007-12-20 00:26:33 +0000125 case Builtin::BI__builtin_isgreater:
126 case Builtin::BI__builtin_isgreaterequal:
127 case Builtin::BI__builtin_isless:
128 case Builtin::BI__builtin_islessequal:
129 case Builtin::BI__builtin_islessgreater:
130 case Builtin::BI__builtin_isunordered:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000131 if (SemaBuiltinUnorderedCompare(TheCall))
132 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000133 break;
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000134 case Builtin::BI__builtin_fpclassify:
135 if (SemaBuiltinFPClassification(TheCall, 6))
136 return ExprError();
137 break;
Eli Friedman9ac6f622009-08-31 20:06:00 +0000138 case Builtin::BI__builtin_isfinite:
139 case Builtin::BI__builtin_isinf:
140 case Builtin::BI__builtin_isinf_sign:
141 case Builtin::BI__builtin_isnan:
142 case Builtin::BI__builtin_isnormal:
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000143 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman9ac6f622009-08-31 20:06:00 +0000144 return ExprError();
145 break;
Eli Friedmand38617c2008-05-14 19:38:39 +0000146 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000147 return SemaBuiltinShuffleVector(TheCall);
148 // TheCall will be freed by the smart pointer here, but that's fine, since
149 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000150 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000151 if (SemaBuiltinPrefetch(TheCall))
152 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000153 break;
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000154 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000155 if (SemaBuiltinObjectSize(TheCall))
156 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000157 break;
Eli Friedmand875fed2009-05-03 04:46:36 +0000158 case Builtin::BI__builtin_longjmp:
159 if (SemaBuiltinLongjmp(TheCall))
160 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000161 break;
John McCall8e10f3b2011-02-26 05:39:39 +0000162
163 case Builtin::BI__builtin_classify_type:
164 if (checkArgCount(*this, TheCall, 1)) return true;
165 TheCall->setType(Context.IntTy);
166 break;
Chris Lattner75c29a02010-10-12 17:47:42 +0000167 case Builtin::BI__builtin_constant_p:
John McCall8e10f3b2011-02-26 05:39:39 +0000168 if (checkArgCount(*this, TheCall, 1)) return true;
169 TheCall->setType(Context.IntTy);
Chris Lattner75c29a02010-10-12 17:47:42 +0000170 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000171 case Builtin::BI__sync_fetch_and_add:
172 case Builtin::BI__sync_fetch_and_sub:
173 case Builtin::BI__sync_fetch_and_or:
174 case Builtin::BI__sync_fetch_and_and:
175 case Builtin::BI__sync_fetch_and_xor:
176 case Builtin::BI__sync_add_and_fetch:
177 case Builtin::BI__sync_sub_and_fetch:
178 case Builtin::BI__sync_and_and_fetch:
179 case Builtin::BI__sync_or_and_fetch:
180 case Builtin::BI__sync_xor_and_fetch:
181 case Builtin::BI__sync_val_compare_and_swap:
182 case Builtin::BI__sync_bool_compare_and_swap:
183 case Builtin::BI__sync_lock_test_and_set:
184 case Builtin::BI__sync_lock_release:
Chris Lattner23aa9c82011-04-09 03:57:26 +0000185 case Builtin::BI__sync_swap:
Chandler Carruthd2014572010-07-09 18:59:35 +0000186 return SemaBuiltinAtomicOverloaded(move(TheCallResult));
Nate Begeman26a31422010-06-08 02:47:44 +0000187 }
188
189 // Since the target specific builtins for each arch overlap, only check those
190 // of the arch we are compiling for.
191 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000192 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman26a31422010-06-08 02:47:44 +0000193 case llvm::Triple::arm:
194 case llvm::Triple::thumb:
195 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
196 return ExprError();
197 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000198 default:
199 break;
200 }
201 }
202
203 return move(TheCallResult);
204}
205
Nate Begeman61eecf52010-06-14 05:21:25 +0000206// Get the valid immediate range for the specified NEON type code.
207static unsigned RFT(unsigned t, bool shift = false) {
208 bool quad = t & 0x10;
209
210 switch (t & 0x7) {
211 case 0: // i8
Nate Begemand69ec162010-06-17 02:26:59 +0000212 return shift ? 7 : (8 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000213 case 1: // i16
Nate Begemand69ec162010-06-17 02:26:59 +0000214 return shift ? 15 : (4 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000215 case 2: // i32
Nate Begemand69ec162010-06-17 02:26:59 +0000216 return shift ? 31 : (2 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000217 case 3: // i64
Nate Begemand69ec162010-06-17 02:26:59 +0000218 return shift ? 63 : (1 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000219 case 4: // f32
220 assert(!shift && "cannot shift float types!");
Nate Begemand69ec162010-06-17 02:26:59 +0000221 return (2 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000222 case 5: // poly8
Bob Wilson42499f92010-12-10 19:45:06 +0000223 return shift ? 7 : (8 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000224 case 6: // poly16
Bob Wilson42499f92010-12-10 19:45:06 +0000225 return shift ? 15 : (4 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000226 case 7: // float16
227 assert(!shift && "cannot shift float types!");
Nate Begemand69ec162010-06-17 02:26:59 +0000228 return (4 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000229 }
230 return 0;
231}
232
Nate Begeman26a31422010-06-08 02:47:44 +0000233bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000234 llvm::APSInt Result;
235
Nate Begeman0d15c532010-06-13 04:47:52 +0000236 unsigned mask = 0;
Nate Begeman61eecf52010-06-14 05:21:25 +0000237 unsigned TV = 0;
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000238 switch (BuiltinID) {
Nate Begemana23326b2010-06-17 04:17:01 +0000239#define GET_NEON_OVERLOAD_CHECK
240#include "clang/Basic/arm_neon.inc"
241#undef GET_NEON_OVERLOAD_CHECK
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000242 }
243
Nate Begeman0d15c532010-06-13 04:47:52 +0000244 // For NEON intrinsics which are overloaded on vector element type, validate
245 // the immediate which specifies which variant to emit.
246 if (mask) {
247 unsigned ArgNo = TheCall->getNumArgs()-1;
248 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
249 return true;
250
Nate Begeman61eecf52010-06-14 05:21:25 +0000251 TV = Result.getLimitedValue(32);
252 if ((TV > 31) || (mask & (1 << TV)) == 0)
Nate Begeman0d15c532010-06-13 04:47:52 +0000253 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
254 << TheCall->getArg(ArgNo)->getSourceRange();
255 }
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000256
Nate Begeman0d15c532010-06-13 04:47:52 +0000257 // For NEON intrinsics which take an immediate value as part of the
258 // instruction, range check them here.
Nate Begeman61eecf52010-06-14 05:21:25 +0000259 unsigned i = 0, l = 0, u = 0;
Nate Begeman0d15c532010-06-13 04:47:52 +0000260 switch (BuiltinID) {
261 default: return false;
Nate Begemanbb37f502010-07-29 22:48:34 +0000262 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
263 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begeman99c40bb2010-08-03 21:32:34 +0000264 case ARM::BI__builtin_arm_vcvtr_f:
265 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Nate Begemana23326b2010-06-17 04:17:01 +0000266#define GET_NEON_IMMEDIATE_CHECK
267#include "clang/Basic/arm_neon.inc"
268#undef GET_NEON_IMMEDIATE_CHECK
Nate Begeman0d15c532010-06-13 04:47:52 +0000269 };
270
Nate Begeman61eecf52010-06-14 05:21:25 +0000271 // Check that the immediate argument is actually a constant.
Nate Begeman0d15c532010-06-13 04:47:52 +0000272 if (SemaBuiltinConstantArg(TheCall, i, Result))
273 return true;
274
Nate Begeman61eecf52010-06-14 05:21:25 +0000275 // Range check against the upper/lower values for this isntruction.
Nate Begeman0d15c532010-06-13 04:47:52 +0000276 unsigned Val = Result.getZExtValue();
Nate Begeman61eecf52010-06-14 05:21:25 +0000277 if (Val < l || Val > (u + l))
Nate Begeman0d15c532010-06-13 04:47:52 +0000278 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramer476d8b82010-08-11 14:47:12 +0000279 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begeman0d15c532010-06-13 04:47:52 +0000280
Nate Begeman99c40bb2010-08-03 21:32:34 +0000281 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman26a31422010-06-08 02:47:44 +0000282 return false;
Anders Carlssond406bf02009-08-16 01:56:34 +0000283}
Daniel Dunbarde454282008-10-02 18:44:07 +0000284
Anders Carlssond406bf02009-08-16 01:56:34 +0000285/// CheckFunctionCall - Check a direct function call for various correctness
286/// and safety properties not strictly enforced by the C type system.
287bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
288 // Get the IdentifierInfo* for the called function.
289 IdentifierInfo *FnInfo = FDecl->getIdentifier();
290
291 // None of the checks below are needed for functions that don't have
292 // simple names (e.g., C++ conversion functions).
293 if (!FnInfo)
294 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000295
Daniel Dunbarde454282008-10-02 18:44:07 +0000296 // FIXME: This mechanism should be abstracted to be less fragile and
297 // more efficient. For example, just map function ids to custom
298 // handlers.
299
Ted Kremenekc82faca2010-09-09 04:33:05 +0000300 // Printf and scanf checking.
301 for (specific_attr_iterator<FormatAttr>
302 i = FDecl->specific_attr_begin<FormatAttr>(),
303 e = FDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) {
304
305 const FormatAttr *Format = *i;
Ted Kremenek826a3452010-07-16 02:11:22 +0000306 const bool b = Format->getType() == "scanf";
307 if (b || CheckablePrintfAttr(Format, TheCall)) {
Ted Kremenek3d692df2009-02-27 17:58:43 +0000308 bool HasVAListArg = Format->getFirstArg() == 0;
Ted Kremenek826a3452010-07-16 02:11:22 +0000309 CheckPrintfScanfArguments(TheCall, HasVAListArg,
310 Format->getFormatIdx() - 1,
311 HasVAListArg ? 0 : Format->getFirstArg() - 1,
312 !b);
Douglas Gregor3c385e52009-02-14 18:57:46 +0000313 }
Chris Lattner59907c42007-08-10 20:18:51 +0000314 }
Mike Stump1eb44332009-09-09 15:08:12 +0000315
Ted Kremenekc82faca2010-09-09 04:33:05 +0000316 for (specific_attr_iterator<NonNullAttr>
317 i = FDecl->specific_attr_begin<NonNullAttr>(),
318 e = FDecl->specific_attr_end<NonNullAttr>(); i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +0000319 CheckNonNullArguments(*i, TheCall->getArgs(),
320 TheCall->getCallee()->getLocStart());
Ted Kremenekc82faca2010-09-09 04:33:05 +0000321 }
Sebastian Redl0eb23302009-01-19 00:08:26 +0000322
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000323 // Builtin handling
Douglas Gregor707a23e2011-06-16 17:56:04 +0000324 int CMF = -1;
325 switch (FDecl->getBuiltinID()) {
326 case Builtin::BI__builtin_memset:
327 case Builtin::BI__builtin___memset_chk:
328 case Builtin::BImemset:
329 CMF = CMF_Memset;
330 break;
331
332 case Builtin::BI__builtin_memcpy:
333 case Builtin::BI__builtin___memcpy_chk:
334 case Builtin::BImemcpy:
335 CMF = CMF_Memcpy;
336 break;
337
338 case Builtin::BI__builtin_memmove:
339 case Builtin::BI__builtin___memmove_chk:
340 case Builtin::BImemmove:
341 CMF = CMF_Memmove;
342 break;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000343
344 case Builtin::BIstrlcpy:
345 case Builtin::BIstrlcat:
346 CheckStrlcpycatArguments(TheCall, FnInfo);
347 break;
Douglas Gregor707a23e2011-06-16 17:56:04 +0000348
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +0000349 case Builtin::BI__builtin_memcmp:
350 CMF = CMF_Memcmp;
351 break;
352
Douglas Gregor707a23e2011-06-16 17:56:04 +0000353 default:
354 if (FDecl->getLinkage() == ExternalLinkage &&
355 (!getLangOptions().CPlusPlus || FDecl->isExternC())) {
356 if (FnInfo->isStr("memset"))
357 CMF = CMF_Memset;
358 else if (FnInfo->isStr("memcpy"))
359 CMF = CMF_Memcpy;
360 else if (FnInfo->isStr("memmove"))
361 CMF = CMF_Memmove;
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +0000362 else if (FnInfo->isStr("memcmp"))
363 CMF = CMF_Memcmp;
Douglas Gregor707a23e2011-06-16 17:56:04 +0000364 }
365 break;
Douglas Gregor06bc9eb2011-05-03 20:37:33 +0000366 }
Douglas Gregor707a23e2011-06-16 17:56:04 +0000367
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000368 // Memset/memcpy/memmove handling
Douglas Gregor707a23e2011-06-16 17:56:04 +0000369 if (CMF != -1)
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +0000370 CheckMemaccessArguments(TheCall, CheckedMemoryFunction(CMF), FnInfo);
Chandler Carruth7ccc95b2011-04-27 07:05:31 +0000371
Anders Carlssond406bf02009-08-16 01:56:34 +0000372 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000373}
374
Anders Carlssond406bf02009-08-16 01:56:34 +0000375bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000376 // Printf checking.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000377 const FormatAttr *Format = NDecl->getAttr<FormatAttr>();
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000378 if (!Format)
Anders Carlssond406bf02009-08-16 01:56:34 +0000379 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000380
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000381 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
382 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000383 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000384
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000385 QualType Ty = V->getType();
386 if (!Ty->isBlockPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000387 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000388
Ted Kremenek826a3452010-07-16 02:11:22 +0000389 const bool b = Format->getType() == "scanf";
390 if (!b && !CheckablePrintfAttr(Format, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +0000391 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000392
Anders Carlssond406bf02009-08-16 01:56:34 +0000393 bool HasVAListArg = Format->getFirstArg() == 0;
Ted Kremenek826a3452010-07-16 02:11:22 +0000394 CheckPrintfScanfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
395 HasVAListArg ? 0 : Format->getFirstArg() - 1, !b);
Anders Carlssond406bf02009-08-16 01:56:34 +0000396
397 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000398}
399
John McCall5f8d6042011-08-27 01:09:30 +0000400/// checkBuiltinArgument - Given a call to a builtin function, perform
401/// normal type-checking on the given argument, updating the call in
402/// place. This is useful when a builtin function requires custom
403/// type-checking for some of its arguments but not necessarily all of
404/// them.
405///
406/// Returns true on error.
407static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
408 FunctionDecl *Fn = E->getDirectCallee();
409 assert(Fn && "builtin call without direct callee!");
410
411 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
412 InitializedEntity Entity =
413 InitializedEntity::InitializeParameter(S.Context, Param);
414
415 ExprResult Arg = E->getArg(0);
416 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
417 if (Arg.isInvalid())
418 return true;
419
420 E->setArg(ArgIndex, Arg.take());
421 return false;
422}
423
Chris Lattner5caa3702009-05-08 06:58:22 +0000424/// SemaBuiltinAtomicOverloaded - We have a call to a function like
425/// __sync_fetch_and_add, which is an overloaded function based on the pointer
426/// type of its first argument. The main ActOnCallExpr routines have already
427/// promoted the types of arguments because all of these calls are prototyped as
428/// void(...).
429///
430/// This function goes through and does final semantic checking for these
431/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +0000432ExprResult
433Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000434 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +0000435 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
436 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
437
438 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +0000439 if (TheCall->getNumArgs() < 1) {
440 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
441 << 0 << 1 << TheCall->getNumArgs()
442 << TheCall->getCallee()->getSourceRange();
443 return ExprError();
444 }
Mike Stump1eb44332009-09-09 15:08:12 +0000445
Chris Lattner5caa3702009-05-08 06:58:22 +0000446 // Inspect the first argument of the atomic builtin. This should always be
447 // a pointer type, whose element is an integral scalar or pointer type.
448 // Because it is a pointer type, we don't have to worry about any implicit
449 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +0000450 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +0000451 Expr *FirstArg = TheCall->getArg(0);
John McCallf85e1932011-06-15 23:02:42 +0000452 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
453 if (!pointerType) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000454 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
455 << FirstArg->getType() << FirstArg->getSourceRange();
456 return ExprError();
457 }
Mike Stump1eb44332009-09-09 15:08:12 +0000458
John McCallf85e1932011-06-15 23:02:42 +0000459 QualType ValType = pointerType->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +0000460 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +0000461 !ValType->isBlockPointerType()) {
462 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
463 << FirstArg->getType() << FirstArg->getSourceRange();
464 return ExprError();
465 }
Chris Lattner5caa3702009-05-08 06:58:22 +0000466
John McCallf85e1932011-06-15 23:02:42 +0000467 switch (ValType.getObjCLifetime()) {
468 case Qualifiers::OCL_None:
469 case Qualifiers::OCL_ExplicitNone:
470 // okay
471 break;
472
473 case Qualifiers::OCL_Weak:
474 case Qualifiers::OCL_Strong:
475 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +0000476 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCallf85e1932011-06-15 23:02:42 +0000477 << ValType << FirstArg->getSourceRange();
478 return ExprError();
479 }
480
Chandler Carruth8d13d222010-07-18 20:54:12 +0000481 // The majority of builtins return a value, but a few have special return
482 // types, so allow them to override appropriately below.
483 QualType ResultType = ValType;
484
Chris Lattner5caa3702009-05-08 06:58:22 +0000485 // We need to figure out which concrete builtin this maps onto. For example,
486 // __sync_fetch_and_add with a 2 byte object turns into
487 // __sync_fetch_and_add_2.
488#define BUILTIN_ROW(x) \
489 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
490 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +0000491
Chris Lattner5caa3702009-05-08 06:58:22 +0000492 static const unsigned BuiltinIndices[][5] = {
493 BUILTIN_ROW(__sync_fetch_and_add),
494 BUILTIN_ROW(__sync_fetch_and_sub),
495 BUILTIN_ROW(__sync_fetch_and_or),
496 BUILTIN_ROW(__sync_fetch_and_and),
497 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +0000498
Chris Lattner5caa3702009-05-08 06:58:22 +0000499 BUILTIN_ROW(__sync_add_and_fetch),
500 BUILTIN_ROW(__sync_sub_and_fetch),
501 BUILTIN_ROW(__sync_and_and_fetch),
502 BUILTIN_ROW(__sync_or_and_fetch),
503 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +0000504
Chris Lattner5caa3702009-05-08 06:58:22 +0000505 BUILTIN_ROW(__sync_val_compare_and_swap),
506 BUILTIN_ROW(__sync_bool_compare_and_swap),
507 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner23aa9c82011-04-09 03:57:26 +0000508 BUILTIN_ROW(__sync_lock_release),
509 BUILTIN_ROW(__sync_swap)
Chris Lattner5caa3702009-05-08 06:58:22 +0000510 };
Mike Stump1eb44332009-09-09 15:08:12 +0000511#undef BUILTIN_ROW
512
Chris Lattner5caa3702009-05-08 06:58:22 +0000513 // Determine the index of the size.
514 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +0000515 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +0000516 case 1: SizeIndex = 0; break;
517 case 2: SizeIndex = 1; break;
518 case 4: SizeIndex = 2; break;
519 case 8: SizeIndex = 3; break;
520 case 16: SizeIndex = 4; break;
521 default:
Chandler Carruthd2014572010-07-09 18:59:35 +0000522 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
523 << FirstArg->getType() << FirstArg->getSourceRange();
524 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +0000525 }
Mike Stump1eb44332009-09-09 15:08:12 +0000526
Chris Lattner5caa3702009-05-08 06:58:22 +0000527 // Each of these builtins has one pointer argument, followed by some number of
528 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
529 // that we ignore. Find out which row of BuiltinIndices to read from as well
530 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +0000531 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +0000532 unsigned BuiltinIndex, NumFixed = 1;
533 switch (BuiltinID) {
534 default: assert(0 && "Unknown overloaded atomic builtin!");
535 case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break;
536 case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break;
537 case Builtin::BI__sync_fetch_and_or: BuiltinIndex = 2; break;
538 case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break;
539 case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000540
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000541 case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 5; break;
542 case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 6; break;
543 case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 7; break;
544 case Builtin::BI__sync_or_and_fetch: BuiltinIndex = 8; break;
545 case Builtin::BI__sync_xor_and_fetch: BuiltinIndex = 9; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000546
Chris Lattner5caa3702009-05-08 06:58:22 +0000547 case Builtin::BI__sync_val_compare_and_swap:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000548 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +0000549 NumFixed = 2;
550 break;
551 case Builtin::BI__sync_bool_compare_and_swap:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000552 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +0000553 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +0000554 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +0000555 break;
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000556 case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 12; break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000557 case Builtin::BI__sync_lock_release:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000558 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +0000559 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +0000560 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +0000561 break;
Chris Lattner23aa9c82011-04-09 03:57:26 +0000562 case Builtin::BI__sync_swap: BuiltinIndex = 14; break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000563 }
Mike Stump1eb44332009-09-09 15:08:12 +0000564
Chris Lattner5caa3702009-05-08 06:58:22 +0000565 // Now that we know how many fixed arguments we expect, first check that we
566 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +0000567 if (TheCall->getNumArgs() < 1+NumFixed) {
568 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
569 << 0 << 1+NumFixed << TheCall->getNumArgs()
570 << TheCall->getCallee()->getSourceRange();
571 return ExprError();
572 }
Mike Stump1eb44332009-09-09 15:08:12 +0000573
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000574 // Get the decl for the concrete builtin from this, we can tell what the
575 // concrete integer type we should convert to is.
576 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
577 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
578 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
Mike Stump1eb44332009-09-09 15:08:12 +0000579 FunctionDecl *NewBuiltinDecl =
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000580 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
581 TUScope, false, DRE->getLocStart()));
Chandler Carruthd2014572010-07-09 18:59:35 +0000582
John McCallf871d0c2010-08-07 06:22:56 +0000583 // The first argument --- the pointer --- has a fixed type; we
584 // deduce the types of the rest of the arguments accordingly. Walk
585 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +0000586 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley429bb272011-04-08 18:41:53 +0000587 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +0000588
Chris Lattner5caa3702009-05-08 06:58:22 +0000589 // If the argument is an implicit cast, then there was a promotion due to
590 // "...", just remove it now.
John Wiegley429bb272011-04-08 18:41:53 +0000591 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg.get())) {
Chris Lattner5caa3702009-05-08 06:58:22 +0000592 Arg = ICE->getSubExpr();
593 ICE->setSubExpr(0);
John Wiegley429bb272011-04-08 18:41:53 +0000594 TheCall->setArg(i+1, Arg.get());
Chris Lattner5caa3702009-05-08 06:58:22 +0000595 }
Mike Stump1eb44332009-09-09 15:08:12 +0000596
Chris Lattner5caa3702009-05-08 06:58:22 +0000597 // GCC does an implicit conversion to the pointer or integer ValType. This
598 // can fail in some cases (1i -> int**), check for this error case now.
John McCalldaa8e4e2010-11-15 09:13:47 +0000599 CastKind Kind = CK_Invalid;
John McCallf89e55a2010-11-18 06:31:45 +0000600 ExprValueKind VK = VK_RValue;
John McCallf871d0c2010-08-07 06:22:56 +0000601 CXXCastPath BasePath;
John McCallf85e1932011-06-15 23:02:42 +0000602 Arg = CheckCastTypes(Arg.get()->getLocStart(), Arg.get()->getSourceRange(),
603 ValType, Arg.take(), Kind, VK, BasePath);
John Wiegley429bb272011-04-08 18:41:53 +0000604 if (Arg.isInvalid())
Chandler Carruthd2014572010-07-09 18:59:35 +0000605 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000606
Chris Lattner5caa3702009-05-08 06:58:22 +0000607 // Okay, we have something that *can* be converted to the right type. Check
608 // to see if there is a potentially weird extension going on here. This can
609 // happen when you do an atomic operation on something like an char* and
610 // pass in 42. The 42 gets converted to char. This is even more strange
611 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +0000612 // FIXME: Do this check.
John Wiegley429bb272011-04-08 18:41:53 +0000613 Arg = ImpCastExprToType(Arg.take(), ValType, Kind, VK, &BasePath);
614 TheCall->setArg(i+1, Arg.get());
Chris Lattner5caa3702009-05-08 06:58:22 +0000615 }
Mike Stump1eb44332009-09-09 15:08:12 +0000616
Chris Lattner5caa3702009-05-08 06:58:22 +0000617 // Switch the DeclRefExpr to refer to the new decl.
618 DRE->setDecl(NewBuiltinDecl);
619 DRE->setType(NewBuiltinDecl->getType());
Mike Stump1eb44332009-09-09 15:08:12 +0000620
Chris Lattner5caa3702009-05-08 06:58:22 +0000621 // Set the callee in the CallExpr.
622 // FIXME: This leaks the original parens and implicit casts.
John Wiegley429bb272011-04-08 18:41:53 +0000623 ExprResult PromotedCall = UsualUnaryConversions(DRE);
624 if (PromotedCall.isInvalid())
625 return ExprError();
626 TheCall->setCallee(PromotedCall.take());
Mike Stump1eb44332009-09-09 15:08:12 +0000627
Chandler Carruthdb4325b2010-07-18 07:23:17 +0000628 // Change the result type of the call to match the original value type. This
629 // is arbitrary, but the codegen for these builtins ins design to handle it
630 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +0000631 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +0000632
633 return move(TheCallResult);
Chris Lattner5caa3702009-05-08 06:58:22 +0000634}
635
636
Chris Lattner69039812009-02-18 06:01:06 +0000637/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +0000638/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +0000639/// Note: It might also make sense to do the UTF-16 conversion here (would
640/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +0000641bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +0000642 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000643 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
644
Douglas Gregor5cee1192011-07-27 05:40:30 +0000645 if (!Literal || !Literal->isAscii()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000646 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
647 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000648 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000649 }
Mike Stump1eb44332009-09-09 15:08:12 +0000650
Fariborz Jahanian7da71022010-09-07 19:38:13 +0000651 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000652 StringRef String = Literal->getString();
Fariborz Jahanian7da71022010-09-07 19:38:13 +0000653 unsigned NumBytes = String.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000654 SmallVector<UTF16, 128> ToBuf(NumBytes);
Fariborz Jahanian7da71022010-09-07 19:38:13 +0000655 const UTF8 *FromPtr = (UTF8 *)String.data();
656 UTF16 *ToPtr = &ToBuf[0];
657
658 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
659 &ToPtr, ToPtr + NumBytes,
660 strictConversion);
661 // Check for conversion failure.
662 if (Result != conversionOK)
663 Diag(Arg->getLocStart(),
664 diag::warn_cfstring_truncated) << Arg->getSourceRange();
665 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000666 return false;
Chris Lattner59907c42007-08-10 20:18:51 +0000667}
668
Chris Lattnerc27c6652007-12-20 00:05:45 +0000669/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
670/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +0000671bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
672 Expr *Fn = TheCall->getCallee();
673 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +0000674 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000675 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000676 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
677 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +0000678 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000679 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +0000680 return true;
681 }
Eli Friedman56f20ae2008-12-15 22:05:35 +0000682
683 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +0000684 return Diag(TheCall->getLocEnd(),
685 diag::err_typecheck_call_too_few_args_at_least)
686 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +0000687 }
688
John McCall5f8d6042011-08-27 01:09:30 +0000689 // Type-check the first argument normally.
690 if (checkBuiltinArgument(*this, TheCall, 0))
691 return true;
692
Chris Lattnerc27c6652007-12-20 00:05:45 +0000693 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000694 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +0000695 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000696 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +0000697 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +0000698 else if (FunctionDecl *FD = getCurFunctionDecl())
699 isVariadic = FD->isVariadic();
700 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000701 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +0000702
Chris Lattnerc27c6652007-12-20 00:05:45 +0000703 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000704 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
705 return true;
706 }
Mike Stump1eb44332009-09-09 15:08:12 +0000707
Chris Lattner30ce3442007-12-19 23:59:04 +0000708 // Verify that the second argument to the builtin is the last argument of the
709 // current function or method.
710 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +0000711 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +0000712
Anders Carlsson88cf2262008-02-11 04:20:54 +0000713 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
714 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000715 // FIXME: This isn't correct for methods (results in bogus warning).
716 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +0000717 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000718 if (CurBlock)
719 LastArg = *(CurBlock->TheDecl->param_end()-1);
720 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +0000721 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000722 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000723 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000724 SecondArgIsLastNamedArgument = PV == LastArg;
725 }
726 }
Mike Stump1eb44332009-09-09 15:08:12 +0000727
Chris Lattner30ce3442007-12-19 23:59:04 +0000728 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +0000729 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +0000730 diag::warn_second_parameter_of_va_start_not_last_named_argument);
731 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +0000732}
Chris Lattner30ce3442007-12-19 23:59:04 +0000733
Chris Lattner1b9a0792007-12-20 00:26:33 +0000734/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
735/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +0000736bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
737 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +0000738 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +0000739 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +0000740 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +0000741 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000742 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000743 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000744 << SourceRange(TheCall->getArg(2)->getLocStart(),
745 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000746
John Wiegley429bb272011-04-08 18:41:53 +0000747 ExprResult OrigArg0 = TheCall->getArg(0);
748 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +0000749
Chris Lattner1b9a0792007-12-20 00:26:33 +0000750 // Do standard promotions between the two arguments, returning their common
751 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +0000752 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley429bb272011-04-08 18:41:53 +0000753 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
754 return true;
Daniel Dunbar403bc2b2009-02-19 19:28:43 +0000755
756 // Make sure any conversions are pushed back into the call; this is
757 // type safe since unordered compare builtins are declared as "_Bool
758 // foo(...)".
John Wiegley429bb272011-04-08 18:41:53 +0000759 TheCall->setArg(0, OrigArg0.get());
760 TheCall->setArg(1, OrigArg1.get());
Mike Stump1eb44332009-09-09 15:08:12 +0000761
John Wiegley429bb272011-04-08 18:41:53 +0000762 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorcde01732009-05-19 22:10:17 +0000763 return false;
764
Chris Lattner1b9a0792007-12-20 00:26:33 +0000765 // If the common type isn't a real floating type, then the arguments were
766 // invalid for this operation.
767 if (!Res->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +0000768 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000769 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley429bb272011-04-08 18:41:53 +0000770 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
771 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000772
Chris Lattner1b9a0792007-12-20 00:26:33 +0000773 return false;
774}
775
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000776/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
777/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000778/// to check everything. We expect the last argument to be a floating point
779/// value.
780bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
781 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +0000782 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +0000783 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000784 if (TheCall->getNumArgs() > NumArgs)
785 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000786 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000787 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000788 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000789 (*(TheCall->arg_end()-1))->getLocEnd());
790
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000791 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +0000792
Eli Friedman9ac6f622009-08-31 20:06:00 +0000793 if (OrigArg->isTypeDependent())
794 return false;
795
Chris Lattner81368fb2010-05-06 05:50:07 +0000796 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +0000797 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +0000798 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000799 diag::err_typecheck_call_invalid_unary_fp)
800 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000801
Chris Lattner81368fb2010-05-06 05:50:07 +0000802 // If this is an implicit conversion from float -> double, remove it.
803 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
804 Expr *CastArg = Cast->getSubExpr();
805 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
806 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
807 "promotion from float to double is the only expected cast here");
808 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +0000809 TheCall->setArg(NumArgs-1, CastArg);
810 OrigArg = CastArg;
811 }
812 }
813
Eli Friedman9ac6f622009-08-31 20:06:00 +0000814 return false;
815}
816
Eli Friedmand38617c2008-05-14 19:38:39 +0000817/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
818// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +0000819ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +0000820 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000821 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +0000822 diag::err_typecheck_call_too_few_args_at_least)
Nate Begeman37b6a572010-06-08 00:16:34 +0000823 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherd77b9a22010-04-16 04:48:22 +0000824 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000825
Nate Begeman37b6a572010-06-08 00:16:34 +0000826 // Determine which of the following types of shufflevector we're checking:
827 // 1) unary, vector mask: (lhs, mask)
828 // 2) binary, vector mask: (lhs, rhs, mask)
829 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
830 QualType resType = TheCall->getArg(0)->getType();
831 unsigned numElements = 0;
832
Douglas Gregorcde01732009-05-19 22:10:17 +0000833 if (!TheCall->getArg(0)->isTypeDependent() &&
834 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +0000835 QualType LHSType = TheCall->getArg(0)->getType();
836 QualType RHSType = TheCall->getArg(1)->getType();
837
838 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000839 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +0000840 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000841 TheCall->getArg(1)->getLocEnd());
842 return ExprError();
843 }
Nate Begeman37b6a572010-06-08 00:16:34 +0000844
845 numElements = LHSType->getAs<VectorType>()->getNumElements();
846 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +0000847
Nate Begeman37b6a572010-06-08 00:16:34 +0000848 // Check to see if we have a call with 2 vector arguments, the unary shuffle
849 // with mask. If so, verify that RHS is an integer vector type with the
850 // same number of elts as lhs.
851 if (TheCall->getNumArgs() == 2) {
Douglas Gregorf6094622010-07-23 15:58:24 +0000852 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +0000853 RHSType->getAs<VectorType>()->getNumElements() != numElements)
854 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
855 << SourceRange(TheCall->getArg(1)->getLocStart(),
856 TheCall->getArg(1)->getLocEnd());
857 numResElements = numElements;
858 }
859 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000860 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +0000861 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000862 TheCall->getArg(1)->getLocEnd());
863 return ExprError();
Nate Begeman37b6a572010-06-08 00:16:34 +0000864 } else if (numElements != numResElements) {
865 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +0000866 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +0000867 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +0000868 }
Eli Friedmand38617c2008-05-14 19:38:39 +0000869 }
870
871 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000872 if (TheCall->getArg(i)->isTypeDependent() ||
873 TheCall->getArg(i)->isValueDependent())
874 continue;
875
Nate Begeman37b6a572010-06-08 00:16:34 +0000876 llvm::APSInt Result(32);
877 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
878 return ExprError(Diag(TheCall->getLocStart(),
879 diag::err_shufflevector_nonconstant_argument)
880 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +0000881
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000882 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000883 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000884 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000885 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000886 }
887
Chris Lattner5f9e2722011-07-23 10:55:15 +0000888 SmallVector<Expr*, 32> exprs;
Eli Friedmand38617c2008-05-14 19:38:39 +0000889
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000890 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000891 exprs.push_back(TheCall->getArg(i));
892 TheCall->setArg(i, 0);
893 }
894
Nate Begemana88dc302009-08-12 02:10:25 +0000895 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
Nate Begeman37b6a572010-06-08 00:16:34 +0000896 exprs.size(), resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000897 TheCall->getCallee()->getLocStart(),
898 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +0000899}
Chris Lattner30ce3442007-12-19 23:59:04 +0000900
Daniel Dunbar4493f792008-07-21 22:59:13 +0000901/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
902// This is declared to take (const void*, ...) and can take two
903// optional constant int args.
904bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000905 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000906
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000907 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +0000908 return Diag(TheCall->getLocEnd(),
909 diag::err_typecheck_call_too_many_args_at_most)
910 << 0 /*function call*/ << 3 << NumArgs
911 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000912
913 // Argument 0 is checked for us and the remaining arguments must be
914 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000915 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +0000916 Expr *Arg = TheCall->getArg(i);
Eric Christopher691ebc32010-04-17 02:26:23 +0000917
Eli Friedman9aef7262009-12-04 00:30:06 +0000918 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +0000919 if (SemaBuiltinConstantArg(TheCall, i, Result))
920 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000921
Daniel Dunbar4493f792008-07-21 22:59:13 +0000922 // FIXME: gcc issues a warning and rewrites these to 0. These
923 // seems especially odd for the third argument since the default
924 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000925 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +0000926 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000927 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000928 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000929 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +0000930 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000931 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000932 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000933 }
934 }
935
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000936 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +0000937}
938
Eric Christopher691ebc32010-04-17 02:26:23 +0000939/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
940/// TheCall is a constant expression.
941bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
942 llvm::APSInt &Result) {
943 Expr *Arg = TheCall->getArg(ArgNum);
944 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
945 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
946
947 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
948
949 if (!Arg->isIntegerConstantExpr(Result, Context))
950 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +0000951 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +0000952
Chris Lattner21fb98e2009-09-23 06:06:36 +0000953 return false;
954}
955
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000956/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
957/// int type). This simply type checks that type is one of the defined
958/// constants (0-3).
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000959// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000960bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +0000961 llvm::APSInt Result;
962
963 // Check constant-ness first.
964 if (SemaBuiltinConstantArg(TheCall, 1, Result))
965 return true;
966
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000967 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000968 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000969 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
970 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000971 }
972
973 return false;
974}
975
Eli Friedman586d6a82009-05-03 06:04:26 +0000976/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +0000977/// This checks that val is a constant 1.
978bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
979 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +0000980 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +0000981
Eric Christopher691ebc32010-04-17 02:26:23 +0000982 // TODO: This is less than ideal. Overload this to take a value.
983 if (SemaBuiltinConstantArg(TheCall, 1, Result))
984 return true;
985
986 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +0000987 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
988 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
989
990 return false;
991}
992
Ted Kremenekb43e8ad2011-02-24 23:03:04 +0000993// Handle i > 1 ? "x" : "y", recursively.
Ted Kremenek082d9362009-03-20 21:35:28 +0000994bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
995 bool HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +0000996 unsigned format_idx, unsigned firstDataArg,
997 bool isPrintf) {
Ted Kremenek4fe64412010-09-09 03:51:39 +0000998 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +0000999 if (E->isTypeDependent() || E->isValueDependent())
1000 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001001
Peter Collingbournef111d932011-04-15 00:35:48 +00001002 E = E->IgnoreParens();
1003
Ted Kremenekd30ef872009-01-12 23:09:09 +00001004 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +00001005 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +00001006 case Stmt::ConditionalOperatorClass: {
John McCall56ca35d2011-02-17 10:25:35 +00001007 const AbstractConditionalOperator *C = cast<AbstractConditionalOperator>(E);
Ted Kremenek826a3452010-07-16 02:11:22 +00001008 return SemaCheckStringLiteral(C->getTrueExpr(), TheCall, HasVAListArg,
1009 format_idx, firstDataArg, isPrintf)
John McCall56ca35d2011-02-17 10:25:35 +00001010 && SemaCheckStringLiteral(C->getFalseExpr(), TheCall, HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00001011 format_idx, firstDataArg, isPrintf);
Ted Kremenekd30ef872009-01-12 23:09:09 +00001012 }
1013
Ted Kremenek95355bb2010-09-09 03:51:42 +00001014 case Stmt::IntegerLiteralClass:
1015 // Technically -Wformat-nonliteral does not warn about this case.
1016 // The behavior of printf and friends in this case is implementation
1017 // dependent. Ideally if the format string cannot be null then
1018 // it should have a 'nonnull' attribute in the function prototype.
1019 return true;
1020
Ted Kremenekd30ef872009-01-12 23:09:09 +00001021 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001022 E = cast<ImplicitCastExpr>(E)->getSubExpr();
1023 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001024 }
1025
John McCall56ca35d2011-02-17 10:25:35 +00001026 case Stmt::OpaqueValueExprClass:
1027 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
1028 E = src;
1029 goto tryAgain;
1030 }
1031 return false;
1032
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001033 case Stmt::PredefinedExprClass:
1034 // While __func__, etc., are technically not string literals, they
1035 // cannot contain format specifiers and thus are not a security
1036 // liability.
1037 return true;
1038
Ted Kremenek082d9362009-03-20 21:35:28 +00001039 case Stmt::DeclRefExprClass: {
1040 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001041
Ted Kremenek082d9362009-03-20 21:35:28 +00001042 // As an exception, do not flag errors for variables binding to
1043 // const string literals.
1044 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1045 bool isConstant = false;
1046 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001047
Ted Kremenek082d9362009-03-20 21:35:28 +00001048 if (const ArrayType *AT = Context.getAsArrayType(T)) {
1049 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001050 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001051 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +00001052 PT->getPointeeType().isConstant(Context);
1053 }
Mike Stump1eb44332009-09-09 15:08:12 +00001054
Ted Kremenek082d9362009-03-20 21:35:28 +00001055 if (isConstant) {
Sebastian Redl31310a22010-02-01 20:16:42 +00001056 if (const Expr *Init = VD->getAnyInitializer())
Ted Kremenek082d9362009-03-20 21:35:28 +00001057 return SemaCheckStringLiteral(Init, TheCall,
Ted Kremenek826a3452010-07-16 02:11:22 +00001058 HasVAListArg, format_idx, firstDataArg,
1059 isPrintf);
Ted Kremenek082d9362009-03-20 21:35:28 +00001060 }
Mike Stump1eb44332009-09-09 15:08:12 +00001061
Anders Carlssond966a552009-06-28 19:55:58 +00001062 // For vprintf* functions (i.e., HasVAListArg==true), we add a
1063 // special check to see if the format string is a function parameter
1064 // of the function calling the printf function. If the function
1065 // has an attribute indicating it is a printf-like function, then we
1066 // should suppress warnings concerning non-literals being used in a call
1067 // to a vprintf function. For example:
1068 //
1069 // void
1070 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
1071 // va_list ap;
1072 // va_start(ap, fmt);
1073 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
1074 // ...
1075 //
1076 //
1077 // FIXME: We don't have full attribute support yet, so just check to see
1078 // if the argument is a DeclRefExpr that references a parameter. We'll
1079 // add proper support for checking the attribute later.
1080 if (HasVAListArg)
1081 if (isa<ParmVarDecl>(VD))
1082 return true;
Ted Kremenek082d9362009-03-20 21:35:28 +00001083 }
Mike Stump1eb44332009-09-09 15:08:12 +00001084
Ted Kremenek082d9362009-03-20 21:35:28 +00001085 return false;
1086 }
Ted Kremenekd30ef872009-01-12 23:09:09 +00001087
Anders Carlsson8f031b32009-06-27 04:05:33 +00001088 case Stmt::CallExprClass: {
1089 const CallExpr *CE = cast<CallExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001090 if (const ImplicitCastExpr *ICE
Anders Carlsson8f031b32009-06-27 04:05:33 +00001091 = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
1092 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
1093 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001094 if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
Anders Carlsson8f031b32009-06-27 04:05:33 +00001095 unsigned ArgIndex = FA->getFormatIdx();
1096 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001097
1098 return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00001099 format_idx, firstDataArg, isPrintf);
Anders Carlsson8f031b32009-06-27 04:05:33 +00001100 }
1101 }
1102 }
1103 }
Mike Stump1eb44332009-09-09 15:08:12 +00001104
Anders Carlsson8f031b32009-06-27 04:05:33 +00001105 return false;
1106 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001107 case Stmt::ObjCStringLiteralClass:
1108 case Stmt::StringLiteralClass: {
1109 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001110
Ted Kremenek082d9362009-03-20 21:35:28 +00001111 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00001112 StrE = ObjCFExpr->getString();
1113 else
Ted Kremenek082d9362009-03-20 21:35:28 +00001114 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001115
Ted Kremenekd30ef872009-01-12 23:09:09 +00001116 if (StrE) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001117 CheckFormatString(StrE, E, TheCall, HasVAListArg, format_idx,
1118 firstDataArg, isPrintf);
Ted Kremenekd30ef872009-01-12 23:09:09 +00001119 return true;
1120 }
Mike Stump1eb44332009-09-09 15:08:12 +00001121
Ted Kremenekd30ef872009-01-12 23:09:09 +00001122 return false;
1123 }
Mike Stump1eb44332009-09-09 15:08:12 +00001124
Ted Kremenek082d9362009-03-20 21:35:28 +00001125 default:
1126 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001127 }
1128}
1129
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001130void
Mike Stump1eb44332009-09-09 15:08:12 +00001131Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewycky909a70d2011-03-25 01:44:32 +00001132 const Expr * const *ExprArgs,
1133 SourceLocation CallSiteLoc) {
Sean Huntcf807c42010-08-18 23:23:40 +00001134 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1135 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001136 i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +00001137 const Expr *ArgExpr = ExprArgs[*i];
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001138 if (ArgExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00001139 Expr::NPC_ValueDependentIsNotNull))
Nick Lewycky909a70d2011-03-25 01:44:32 +00001140 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001141 }
1142}
Ted Kremenekd30ef872009-01-12 23:09:09 +00001143
Ted Kremenek826a3452010-07-16 02:11:22 +00001144/// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar
1145/// functions) for correct use of format strings.
Chris Lattner59907c42007-08-10 20:18:51 +00001146void
Ted Kremenek826a3452010-07-16 02:11:22 +00001147Sema::CheckPrintfScanfArguments(const CallExpr *TheCall, bool HasVAListArg,
1148 unsigned format_idx, unsigned firstDataArg,
1149 bool isPrintf) {
1150
Ted Kremenek082d9362009-03-20 21:35:28 +00001151 const Expr *Fn = TheCall->getCallee();
Chris Lattner925e60d2007-12-28 05:29:59 +00001152
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001153 // The way the format attribute works in GCC, the implicit this argument
1154 // of member functions is counted. However, it doesn't appear in our own
1155 // lists, so decrement format_idx in that case.
1156 if (isa<CXXMemberCallExpr>(TheCall)) {
Chandler Carruth9263a302010-11-16 08:49:43 +00001157 const CXXMethodDecl *method_decl =
1158 dyn_cast<CXXMethodDecl>(TheCall->getCalleeDecl());
1159 if (method_decl && method_decl->isInstance()) {
1160 // Catch a format attribute mistakenly referring to the object argument.
1161 if (format_idx == 0)
1162 return;
1163 --format_idx;
1164 if(firstDataArg != 0)
1165 --firstDataArg;
1166 }
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001167 }
1168
Ted Kremenek826a3452010-07-16 02:11:22 +00001169 // CHECK: printf/scanf-like function is called with no format string.
Chris Lattner925e60d2007-12-28 05:29:59 +00001170 if (format_idx >= TheCall->getNumArgs()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001171 Diag(TheCall->getRParenLoc(), diag::warn_missing_format_string)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001172 << Fn->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001173 return;
1174 }
Mike Stump1eb44332009-09-09 15:08:12 +00001175
Ted Kremenek082d9362009-03-20 21:35:28 +00001176 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001177
Chris Lattner59907c42007-08-10 20:18:51 +00001178 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001179 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001180 // Dynamically generated format strings are difficult to
1181 // automatically vet at compile time. Requiring that format strings
1182 // are string literals: (1) permits the checking of format strings by
1183 // the compiler and thereby (2) can practically remove the source of
1184 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001185
Mike Stump1eb44332009-09-09 15:08:12 +00001186 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001187 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001188 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001189 // the same format string checking logic for both ObjC and C strings.
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001190 if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
Ted Kremenek826a3452010-07-16 02:11:22 +00001191 firstDataArg, isPrintf))
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001192 return; // Literal format string found, check done!
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001193
Chris Lattner655f1412009-04-29 04:59:47 +00001194 // If there are no arguments specified, warn with -Wformat-security, otherwise
1195 // warn only with -Wformat-nonliteral.
1196 if (TheCall->getNumArgs() == format_idx+1)
Mike Stump1eb44332009-09-09 15:08:12 +00001197 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001198 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00001199 << OrigFormatExpr->getSourceRange();
1200 else
Mike Stump1eb44332009-09-09 15:08:12 +00001201 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001202 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00001203 << OrigFormatExpr->getSourceRange();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001204}
Ted Kremenek71895b92007-08-14 17:39:48 +00001205
Ted Kremeneke0e53132010-01-28 23:39:18 +00001206namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00001207class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1208protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00001209 Sema &S;
1210 const StringLiteral *FExpr;
1211 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00001212 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001213 const unsigned NumDataArgs;
1214 const bool IsObjCLiteral;
1215 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00001216 const bool HasVAListArg;
1217 const CallExpr *TheCall;
1218 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001219 llvm::BitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00001220 bool usesPositionalArgs;
1221 bool atFirstArg;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001222public:
Ted Kremenek826a3452010-07-16 02:11:22 +00001223 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00001224 const Expr *origFormatExpr, unsigned firstDataArg,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001225 unsigned numDataArgs, bool isObjCLiteral,
Ted Kremenek0d277352010-01-29 01:06:55 +00001226 const char *beg, bool hasVAListArg,
1227 const CallExpr *theCall, unsigned formatIdx)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001228 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Ted Kremenek6ee76532010-03-25 03:59:12 +00001229 FirstDataArg(firstDataArg),
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001230 NumDataArgs(numDataArgs),
Ted Kremenek0d277352010-01-29 01:06:55 +00001231 IsObjCLiteral(isObjCLiteral), Beg(beg),
1232 HasVAListArg(hasVAListArg),
Ted Kremenekefaff192010-02-27 01:41:03 +00001233 TheCall(theCall), FormatIdx(formatIdx),
1234 usesPositionalArgs(false), atFirstArg(true) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001235 CoveredArgs.resize(numDataArgs);
1236 CoveredArgs.reset();
1237 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001238
Ted Kremenek07d161f2010-01-29 01:50:07 +00001239 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001240
Ted Kremenek826a3452010-07-16 02:11:22 +00001241 void HandleIncompleteSpecifier(const char *startSpecifier,
1242 unsigned specifierLen);
1243
Ted Kremenekefaff192010-02-27 01:41:03 +00001244 virtual void HandleInvalidPosition(const char *startSpecifier,
1245 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00001246 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00001247
1248 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1249
Ted Kremeneke0e53132010-01-28 23:39:18 +00001250 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001251
Ted Kremenek826a3452010-07-16 02:11:22 +00001252protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001253 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
1254 const char *startSpec,
1255 unsigned specifierLen,
1256 const char *csStart, unsigned csLen);
1257
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001258 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00001259 CharSourceRange getSpecifierRange(const char *startSpecifier,
1260 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001261 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001262
Ted Kremenek0d277352010-01-29 01:06:55 +00001263 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00001264
1265 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
1266 const analyze_format_string::ConversionSpecifier &CS,
1267 const char *startSpecifier, unsigned specifierLen,
1268 unsigned argIndex);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001269};
1270}
1271
Ted Kremenek826a3452010-07-16 02:11:22 +00001272SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00001273 return OrigFormatExpr->getSourceRange();
1274}
1275
Ted Kremenek826a3452010-07-16 02:11:22 +00001276CharSourceRange CheckFormatHandler::
1277getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00001278 SourceLocation Start = getLocationOfByte(startSpecifier);
1279 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
1280
1281 // Advance the end SourceLocation by one due to half-open ranges.
1282 End = End.getFileLocWithOffset(1);
1283
1284 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001285}
1286
Ted Kremenek826a3452010-07-16 02:11:22 +00001287SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001288 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001289}
1290
Ted Kremenek826a3452010-07-16 02:11:22 +00001291void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
1292 unsigned specifierLen){
Ted Kremenek808015a2010-01-29 03:16:21 +00001293 SourceLocation Loc = getLocationOfByte(startSpecifier);
1294 S.Diag(Loc, diag::warn_printf_incomplete_specifier)
Ted Kremenek826a3452010-07-16 02:11:22 +00001295 << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek808015a2010-01-29 03:16:21 +00001296}
1297
Ted Kremenekefaff192010-02-27 01:41:03 +00001298void
Ted Kremenek826a3452010-07-16 02:11:22 +00001299CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
1300 analyze_format_string::PositionContext p) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001301 SourceLocation Loc = getLocationOfByte(startPos);
Ted Kremenek826a3452010-07-16 02:11:22 +00001302 S.Diag(Loc, diag::warn_format_invalid_positional_specifier)
1303 << (unsigned) p << getSpecifierRange(startPos, posLen);
Ted Kremenekefaff192010-02-27 01:41:03 +00001304}
1305
Ted Kremenek826a3452010-07-16 02:11:22 +00001306void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00001307 unsigned posLen) {
1308 SourceLocation Loc = getLocationOfByte(startPos);
Ted Kremenek826a3452010-07-16 02:11:22 +00001309 S.Diag(Loc, diag::warn_format_zero_positional_specifier)
1310 << getSpecifierRange(startPos, posLen);
Ted Kremenekefaff192010-02-27 01:41:03 +00001311}
1312
Ted Kremenek826a3452010-07-16 02:11:22 +00001313void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Ted Kremenek0c069442011-03-15 21:18:48 +00001314 if (!IsObjCLiteral) {
1315 // The presence of a null character is likely an error.
1316 S.Diag(getLocationOfByte(nullCharacter),
1317 diag::warn_printf_format_string_contains_null_char)
1318 << getFormatStringRange();
1319 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001320}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001321
Ted Kremenek826a3452010-07-16 02:11:22 +00001322const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
1323 return TheCall->getArg(FirstDataArg + i);
1324}
1325
1326void CheckFormatHandler::DoneProcessing() {
1327 // Does the number of data arguments exceed the number of
1328 // format conversions in the format string?
1329 if (!HasVAListArg) {
1330 // Find any arguments that weren't covered.
1331 CoveredArgs.flip();
1332 signed notCoveredArg = CoveredArgs.find_first();
1333 if (notCoveredArg >= 0) {
1334 assert((unsigned)notCoveredArg < NumDataArgs);
1335 S.Diag(getDataArg((unsigned) notCoveredArg)->getLocStart(),
1336 diag::warn_printf_data_arg_not_used)
1337 << getFormatStringRange();
1338 }
1339 }
1340}
1341
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001342bool
1343CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
1344 SourceLocation Loc,
1345 const char *startSpec,
1346 unsigned specifierLen,
1347 const char *csStart,
1348 unsigned csLen) {
1349
1350 bool keepGoing = true;
1351 if (argIndex < NumDataArgs) {
1352 // Consider the argument coverered, even though the specifier doesn't
1353 // make sense.
1354 CoveredArgs.set(argIndex);
1355 }
1356 else {
1357 // If argIndex exceeds the number of data arguments we
1358 // don't issue a warning because that is just a cascade of warnings (and
1359 // they may have intended '%%' anyway). We don't want to continue processing
1360 // the format string after this point, however, as we will like just get
1361 // gibberish when trying to match arguments.
1362 keepGoing = false;
1363 }
1364
1365 S.Diag(Loc, diag::warn_format_invalid_conversion)
Chris Lattner5f9e2722011-07-23 10:55:15 +00001366 << StringRef(csStart, csLen)
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001367 << getSpecifierRange(startSpec, specifierLen);
1368
1369 return keepGoing;
1370}
1371
Ted Kremenek666a1972010-07-26 19:45:42 +00001372bool
1373CheckFormatHandler::CheckNumArgs(
1374 const analyze_format_string::FormatSpecifier &FS,
1375 const analyze_format_string::ConversionSpecifier &CS,
1376 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
1377
1378 if (argIndex >= NumDataArgs) {
1379 if (FS.usesPositionalArg()) {
1380 S.Diag(getLocationOfByte(CS.getStart()),
1381 diag::warn_printf_positional_arg_exceeds_data_args)
1382 << (argIndex+1) << NumDataArgs
1383 << getSpecifierRange(startSpecifier, specifierLen);
1384 }
1385 else {
1386 S.Diag(getLocationOfByte(CS.getStart()),
1387 diag::warn_printf_insufficient_data_args)
1388 << getSpecifierRange(startSpecifier, specifierLen);
1389 }
1390
1391 return false;
1392 }
1393 return true;
1394}
1395
Ted Kremenek826a3452010-07-16 02:11:22 +00001396//===--- CHECK: Printf format string checking ------------------------------===//
1397
1398namespace {
1399class CheckPrintfHandler : public CheckFormatHandler {
1400public:
1401 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
1402 const Expr *origFormatExpr, unsigned firstDataArg,
1403 unsigned numDataArgs, bool isObjCLiteral,
1404 const char *beg, bool hasVAListArg,
1405 const CallExpr *theCall, unsigned formatIdx)
1406 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1407 numDataArgs, isObjCLiteral, beg, hasVAListArg,
1408 theCall, formatIdx) {}
1409
1410
1411 bool HandleInvalidPrintfConversionSpecifier(
1412 const analyze_printf::PrintfSpecifier &FS,
1413 const char *startSpecifier,
1414 unsigned specifierLen);
1415
1416 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
1417 const char *startSpecifier,
1418 unsigned specifierLen);
1419
1420 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
1421 const char *startSpecifier, unsigned specifierLen);
1422 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
1423 const analyze_printf::OptionalAmount &Amt,
1424 unsigned type,
1425 const char *startSpecifier, unsigned specifierLen);
1426 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
1427 const analyze_printf::OptionalFlag &flag,
1428 const char *startSpecifier, unsigned specifierLen);
1429 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
1430 const analyze_printf::OptionalFlag &ignoredFlag,
1431 const analyze_printf::OptionalFlag &flag,
1432 const char *startSpecifier, unsigned specifierLen);
1433};
1434}
1435
1436bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
1437 const analyze_printf::PrintfSpecifier &FS,
1438 const char *startSpecifier,
1439 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001440 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001441 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00001442
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001443 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1444 getLocationOfByte(CS.getStart()),
1445 startSpecifier, specifierLen,
1446 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001447}
1448
Ted Kremenek826a3452010-07-16 02:11:22 +00001449bool CheckPrintfHandler::HandleAmount(
1450 const analyze_format_string::OptionalAmount &Amt,
1451 unsigned k, const char *startSpecifier,
1452 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001453
1454 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001455 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001456 unsigned argIndex = Amt.getArgIndex();
1457 if (argIndex >= NumDataArgs) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001458 S.Diag(getLocationOfByte(Amt.getStart()),
1459 diag::warn_printf_asterisk_missing_arg)
Ted Kremenek826a3452010-07-16 02:11:22 +00001460 << k << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek0d277352010-01-29 01:06:55 +00001461 // Don't do any more checking. We will just emit
1462 // spurious errors.
1463 return false;
1464 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001465
Ted Kremenek0d277352010-01-29 01:06:55 +00001466 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00001467 // Although not in conformance with C99, we also allow the argument to be
1468 // an 'unsigned int' as that is a reasonably safe case. GCC also
1469 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001470 CoveredArgs.set(argIndex);
1471 const Expr *Arg = getDataArg(argIndex);
Ted Kremenek0d277352010-01-29 01:06:55 +00001472 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001473
1474 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
1475 assert(ATR.isValid());
1476
1477 if (!ATR.matchesType(S.Context, T)) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001478 S.Diag(getLocationOfByte(Amt.getStart()),
1479 diag::warn_printf_asterisk_wrong_type)
1480 << k
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001481 << ATR.getRepresentativeType(S.Context) << T
Ted Kremenek826a3452010-07-16 02:11:22 +00001482 << getSpecifierRange(startSpecifier, specifierLen)
Ted Kremenekd635c5f2010-01-30 00:49:51 +00001483 << Arg->getSourceRange();
Ted Kremenek0d277352010-01-29 01:06:55 +00001484 // Don't do any more checking. We will just emit
1485 // spurious errors.
1486 return false;
1487 }
1488 }
1489 }
1490 return true;
1491}
Ted Kremenek0d277352010-01-29 01:06:55 +00001492
Tom Caree4ee9662010-06-17 19:00:27 +00001493void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00001494 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001495 const analyze_printf::OptionalAmount &Amt,
1496 unsigned type,
1497 const char *startSpecifier,
1498 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001499 const analyze_printf::PrintfConversionSpecifier &CS =
1500 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00001501 switch (Amt.getHowSpecified()) {
1502 case analyze_printf::OptionalAmount::Constant:
1503 S.Diag(getLocationOfByte(Amt.getStart()),
1504 diag::warn_printf_nonsensical_optional_amount)
1505 << type
1506 << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001507 << getSpecifierRange(startSpecifier, specifierLen)
1508 << FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
Tom Caree4ee9662010-06-17 19:00:27 +00001509 Amt.getConstantLength()));
1510 break;
1511
1512 default:
1513 S.Diag(getLocationOfByte(Amt.getStart()),
1514 diag::warn_printf_nonsensical_optional_amount)
1515 << type
1516 << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001517 << getSpecifierRange(startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001518 break;
1519 }
1520}
1521
Ted Kremenek826a3452010-07-16 02:11:22 +00001522void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001523 const analyze_printf::OptionalFlag &flag,
1524 const char *startSpecifier,
1525 unsigned specifierLen) {
1526 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001527 const analyze_printf::PrintfConversionSpecifier &CS =
1528 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00001529 S.Diag(getLocationOfByte(flag.getPosition()),
1530 diag::warn_printf_nonsensical_flag)
1531 << flag.toString() << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001532 << getSpecifierRange(startSpecifier, specifierLen)
1533 << FixItHint::CreateRemoval(getSpecifierRange(flag.getPosition(), 1));
Tom Caree4ee9662010-06-17 19:00:27 +00001534}
1535
1536void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00001537 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001538 const analyze_printf::OptionalFlag &ignoredFlag,
1539 const analyze_printf::OptionalFlag &flag,
1540 const char *startSpecifier,
1541 unsigned specifierLen) {
1542 // Warn about ignored flag with a fixit removal.
1543 S.Diag(getLocationOfByte(ignoredFlag.getPosition()),
1544 diag::warn_printf_ignored_flag)
1545 << ignoredFlag.toString() << flag.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001546 << getSpecifierRange(startSpecifier, specifierLen)
1547 << FixItHint::CreateRemoval(getSpecifierRange(
Tom Caree4ee9662010-06-17 19:00:27 +00001548 ignoredFlag.getPosition(), 1));
1549}
1550
Ted Kremeneke0e53132010-01-28 23:39:18 +00001551bool
Ted Kremenek826a3452010-07-16 02:11:22 +00001552CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001553 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001554 const char *startSpecifier,
1555 unsigned specifierLen) {
1556
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001557 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00001558 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001559 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00001560
Ted Kremenekbaa40062010-07-19 22:01:06 +00001561 if (FS.consumesDataArgument()) {
1562 if (atFirstArg) {
1563 atFirstArg = false;
1564 usesPositionalArgs = FS.usesPositionalArg();
1565 }
1566 else if (usesPositionalArgs != FS.usesPositionalArg()) {
1567 // Cannot mix-and-match positional and non-positional arguments.
1568 S.Diag(getLocationOfByte(CS.getStart()),
1569 diag::warn_format_mix_positional_nonpositional_args)
1570 << getSpecifierRange(startSpecifier, specifierLen);
1571 return false;
1572 }
Ted Kremenek0d277352010-01-29 01:06:55 +00001573 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001574
Ted Kremenekefaff192010-02-27 01:41:03 +00001575 // First check if the field width, precision, and conversion specifier
1576 // have matching data arguments.
1577 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
1578 startSpecifier, specifierLen)) {
1579 return false;
1580 }
1581
1582 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
1583 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001584 return false;
1585 }
1586
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001587 if (!CS.consumesDataArgument()) {
1588 // FIXME: Technically specifying a precision or field width here
1589 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001590 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001591 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001592
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001593 // Consume the argument.
1594 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00001595 if (argIndex < NumDataArgs) {
1596 // The check to see if the argIndex is valid will come later.
1597 // We set the bit here because we may exit early from this
1598 // function if we encounter some other error.
1599 CoveredArgs.set(argIndex);
1600 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001601
1602 // Check for using an Objective-C specific conversion specifier
1603 // in a non-ObjC literal.
1604 if (!IsObjCLiteral && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001605 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
1606 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001607 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001608
Tom Caree4ee9662010-06-17 19:00:27 +00001609 // Check for invalid use of field width
1610 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00001611 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00001612 startSpecifier, specifierLen);
1613 }
1614
1615 // Check for invalid use of precision
1616 if (!FS.hasValidPrecision()) {
1617 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
1618 startSpecifier, specifierLen);
1619 }
1620
1621 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00001622 if (!FS.hasValidThousandsGroupingPrefix())
1623 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001624 if (!FS.hasValidLeadingZeros())
1625 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
1626 if (!FS.hasValidPlusPrefix())
1627 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00001628 if (!FS.hasValidSpacePrefix())
1629 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001630 if (!FS.hasValidAlternativeForm())
1631 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
1632 if (!FS.hasValidLeftJustified())
1633 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
1634
1635 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00001636 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
1637 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
1638 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001639 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
1640 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
1641 startSpecifier, specifierLen);
1642
1643 // Check the length modifier is valid with the given conversion specifier.
1644 const LengthModifier &LM = FS.getLengthModifier();
1645 if (!FS.hasValidLengthModifier())
1646 S.Diag(getLocationOfByte(LM.getStart()),
Ted Kremenek649aecf2010-07-20 20:03:43 +00001647 diag::warn_format_nonsensical_length)
Tom Caree4ee9662010-06-17 19:00:27 +00001648 << LM.toString() << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001649 << getSpecifierRange(startSpecifier, specifierLen)
1650 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
Tom Caree4ee9662010-06-17 19:00:27 +00001651 LM.getLength()));
1652
1653 // Are we using '%n'?
Ted Kremenek35d353b2010-07-20 20:04:10 +00001654 if (CS.getKind() == ConversionSpecifier::nArg) {
Tom Caree4ee9662010-06-17 19:00:27 +00001655 // Issue a warning about this being a possible security issue.
Ted Kremeneke82d8042010-01-29 01:35:25 +00001656 S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_write_back)
Ted Kremenek826a3452010-07-16 02:11:22 +00001657 << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremeneke82d8042010-01-29 01:35:25 +00001658 // Continue checking the other format specifiers.
1659 return true;
1660 }
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001661
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001662 // The remaining checks depend on the data arguments.
1663 if (HasVAListArg)
1664 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001665
Ted Kremenek666a1972010-07-26 19:45:42 +00001666 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001667 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001668
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001669 // Now type check the data expression that matches the
1670 // format specifier.
1671 const Expr *Ex = getDataArg(argIndex);
1672 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context);
1673 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
1674 // Check if we didn't match because of an implicit cast from a 'char'
1675 // or 'short' to an 'int'. This is done because printf is a varargs
1676 // function.
1677 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00001678 if (ICE->getType() == S.Context.IntTy) {
1679 // All further checking is done on the subexpression.
1680 Ex = ICE->getSubExpr();
1681 if (ATR.matchesType(S.Context, Ex->getType()))
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001682 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00001683 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001684
1685 // We may be able to offer a FixItHint if it is a supported type.
1686 PrintfSpecifier fixedFS = FS;
1687 bool success = fixedFS.fixType(Ex->getType());
1688
1689 if (success) {
1690 // Get the fix string from the fixed format specifier
1691 llvm::SmallString<128> buf;
1692 llvm::raw_svector_ostream os(buf);
1693 fixedFS.toString(os);
1694
Ted Kremenek9325eaf2010-08-24 22:24:51 +00001695 // FIXME: getRepresentativeType() perhaps should return a string
1696 // instead of a QualType to better handle when the representative
1697 // type is 'wint_t' (which is defined in the system headers).
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001698 S.Diag(getLocationOfByte(CS.getStart()),
1699 diag::warn_printf_conversion_argument_type_mismatch)
1700 << ATR.getRepresentativeType(S.Context) << Ex->getType()
1701 << getSpecifierRange(startSpecifier, specifierLen)
1702 << Ex->getSourceRange()
1703 << FixItHint::CreateReplacement(
1704 getSpecifierRange(startSpecifier, specifierLen),
1705 os.str());
1706 }
1707 else {
1708 S.Diag(getLocationOfByte(CS.getStart()),
1709 diag::warn_printf_conversion_argument_type_mismatch)
1710 << ATR.getRepresentativeType(S.Context) << Ex->getType()
1711 << getSpecifierRange(startSpecifier, specifierLen)
1712 << Ex->getSourceRange();
1713 }
1714 }
1715
Ted Kremeneke0e53132010-01-28 23:39:18 +00001716 return true;
1717}
1718
Ted Kremenek826a3452010-07-16 02:11:22 +00001719//===--- CHECK: Scanf format string checking ------------------------------===//
1720
1721namespace {
1722class CheckScanfHandler : public CheckFormatHandler {
1723public:
1724 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
1725 const Expr *origFormatExpr, unsigned firstDataArg,
1726 unsigned numDataArgs, bool isObjCLiteral,
1727 const char *beg, bool hasVAListArg,
1728 const CallExpr *theCall, unsigned formatIdx)
1729 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1730 numDataArgs, isObjCLiteral, beg, hasVAListArg,
1731 theCall, formatIdx) {}
1732
1733 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
1734 const char *startSpecifier,
1735 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001736
1737 bool HandleInvalidScanfConversionSpecifier(
1738 const analyze_scanf::ScanfSpecifier &FS,
1739 const char *startSpecifier,
1740 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00001741
1742 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00001743};
Ted Kremenek07d161f2010-01-29 01:50:07 +00001744}
Ted Kremeneke0e53132010-01-28 23:39:18 +00001745
Ted Kremenekb7c21012010-07-16 18:28:03 +00001746void CheckScanfHandler::HandleIncompleteScanList(const char *start,
1747 const char *end) {
1748 S.Diag(getLocationOfByte(end), diag::warn_scanf_scanlist_incomplete)
1749 << getSpecifierRange(start, end - start);
1750}
1751
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001752bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
1753 const analyze_scanf::ScanfSpecifier &FS,
1754 const char *startSpecifier,
1755 unsigned specifierLen) {
1756
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001757 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001758 FS.getConversionSpecifier();
1759
1760 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1761 getLocationOfByte(CS.getStart()),
1762 startSpecifier, specifierLen,
1763 CS.getStart(), CS.getLength());
1764}
1765
Ted Kremenek826a3452010-07-16 02:11:22 +00001766bool CheckScanfHandler::HandleScanfSpecifier(
1767 const analyze_scanf::ScanfSpecifier &FS,
1768 const char *startSpecifier,
1769 unsigned specifierLen) {
1770
1771 using namespace analyze_scanf;
1772 using namespace analyze_format_string;
1773
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001774 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00001775
Ted Kremenekbaa40062010-07-19 22:01:06 +00001776 // Handle case where '%' and '*' don't consume an argument. These shouldn't
1777 // be used to decide if we are using positional arguments consistently.
1778 if (FS.consumesDataArgument()) {
1779 if (atFirstArg) {
1780 atFirstArg = false;
1781 usesPositionalArgs = FS.usesPositionalArg();
1782 }
1783 else if (usesPositionalArgs != FS.usesPositionalArg()) {
1784 // Cannot mix-and-match positional and non-positional arguments.
1785 S.Diag(getLocationOfByte(CS.getStart()),
1786 diag::warn_format_mix_positional_nonpositional_args)
1787 << getSpecifierRange(startSpecifier, specifierLen);
1788 return false;
1789 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001790 }
1791
1792 // Check if the field with is non-zero.
1793 const OptionalAmount &Amt = FS.getFieldWidth();
1794 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
1795 if (Amt.getConstantAmount() == 0) {
1796 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
1797 Amt.getConstantLength());
1798 S.Diag(getLocationOfByte(Amt.getStart()),
1799 diag::warn_scanf_nonzero_width)
1800 << R << FixItHint::CreateRemoval(R);
1801 }
1802 }
1803
1804 if (!FS.consumesDataArgument()) {
1805 // FIXME: Technically specifying a precision or field width here
1806 // makes no sense. Worth issuing a warning at some point.
1807 return true;
1808 }
1809
1810 // Consume the argument.
1811 unsigned argIndex = FS.getArgIndex();
1812 if (argIndex < NumDataArgs) {
1813 // The check to see if the argIndex is valid will come later.
1814 // We set the bit here because we may exit early from this
1815 // function if we encounter some other error.
1816 CoveredArgs.set(argIndex);
1817 }
1818
Ted Kremenek1e51c202010-07-20 20:04:47 +00001819 // Check the length modifier is valid with the given conversion specifier.
1820 const LengthModifier &LM = FS.getLengthModifier();
1821 if (!FS.hasValidLengthModifier()) {
1822 S.Diag(getLocationOfByte(LM.getStart()),
1823 diag::warn_format_nonsensical_length)
1824 << LM.toString() << CS.toString()
1825 << getSpecifierRange(startSpecifier, specifierLen)
1826 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
1827 LM.getLength()));
1828 }
1829
Ted Kremenek826a3452010-07-16 02:11:22 +00001830 // The remaining checks depend on the data arguments.
1831 if (HasVAListArg)
1832 return true;
1833
Ted Kremenek666a1972010-07-26 19:45:42 +00001834 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00001835 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00001836
1837 // FIXME: Check that the argument type matches the format specifier.
1838
1839 return true;
1840}
1841
1842void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001843 const Expr *OrigFormatExpr,
1844 const CallExpr *TheCall, bool HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00001845 unsigned format_idx, unsigned firstDataArg,
1846 bool isPrintf) {
1847
Ted Kremeneke0e53132010-01-28 23:39:18 +00001848 // CHECK: is the format string a wide literal?
Douglas Gregor5cee1192011-07-27 05:40:30 +00001849 if (!FExpr->isAscii()) {
Ted Kremeneke0e53132010-01-28 23:39:18 +00001850 Diag(FExpr->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001851 diag::warn_format_string_is_wide_literal)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001852 << OrigFormatExpr->getSourceRange();
1853 return;
1854 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001855
Ted Kremeneke0e53132010-01-28 23:39:18 +00001856 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner5f9e2722011-07-23 10:55:15 +00001857 StringRef StrRef = FExpr->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00001858 const char *Str = StrRef.data();
1859 unsigned StrLen = StrRef.size();
Ted Kremenek826a3452010-07-16 02:11:22 +00001860
Ted Kremeneke0e53132010-01-28 23:39:18 +00001861 // CHECK: empty format string?
Ted Kremeneke0e53132010-01-28 23:39:18 +00001862 if (StrLen == 0) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001863 Diag(FExpr->getLocStart(), diag::warn_empty_format_string)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001864 << OrigFormatExpr->getSourceRange();
1865 return;
1866 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001867
1868 if (isPrintf) {
1869 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
1870 TheCall->getNumArgs() - firstDataArg,
1871 isa<ObjCStringLiteral>(OrigFormatExpr), Str,
1872 HasVAListArg, TheCall, format_idx);
1873
1874 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen))
1875 H.DoneProcessing();
1876 }
1877 else {
1878 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
1879 TheCall->getNumArgs() - firstDataArg,
1880 isa<ObjCStringLiteral>(OrigFormatExpr), Str,
1881 HasVAListArg, TheCall, format_idx);
1882
1883 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen))
1884 H.DoneProcessing();
1885 }
Ted Kremenekce7024e2010-01-28 01:18:22 +00001886}
1887
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00001888//===--- CHECK: Standard memory functions ---------------------------------===//
1889
Douglas Gregor2a053a32011-05-03 20:05:22 +00001890/// \brief Determine whether the given type is a dynamic class type (e.g.,
1891/// whether it has a vtable).
1892static bool isDynamicClassType(QualType T) {
1893 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
1894 if (CXXRecordDecl *Definition = Record->getDefinition())
1895 if (Definition->isDynamicClass())
1896 return true;
1897
1898 return false;
1899}
1900
Chandler Carrutha72a12f2011-06-21 23:04:20 +00001901/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth000d4282011-06-16 09:09:40 +00001902/// otherwise returns NULL.
1903static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Webere4a1c642011-06-14 16:14:58 +00001904 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth000d4282011-06-16 09:09:40 +00001905 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
1906 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
1907 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00001908
Chandler Carruth000d4282011-06-16 09:09:40 +00001909 return 0;
1910}
1911
Chandler Carrutha72a12f2011-06-21 23:04:20 +00001912/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth000d4282011-06-16 09:09:40 +00001913static QualType getSizeOfArgType(const Expr* E) {
1914 if (const UnaryExprOrTypeTraitExpr *SizeOf =
1915 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
1916 if (SizeOf->getKind() == clang::UETT_SizeOf)
1917 return SizeOf->getTypeOfArgument();
1918
1919 return QualType();
Nico Webere4a1c642011-06-14 16:14:58 +00001920}
1921
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00001922/// \brief Check for dangerous or invalid arguments to memset().
1923///
Chandler Carruth929f0132011-06-03 06:23:57 +00001924/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00001925/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
1926/// function calls.
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00001927///
1928/// \param Call The call expression to diagnose.
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00001929void Sema::CheckMemaccessArguments(const CallExpr *Call,
1930 CheckedMemoryFunction CMF,
1931 IdentifierInfo *FnName) {
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00001932 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor707a23e2011-06-16 17:56:04 +00001933 // we have enough arguments, and if not, abort further checking.
1934 if (Call->getNumArgs() < 3)
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00001935 return;
1936
Douglas Gregor707a23e2011-06-16 17:56:04 +00001937 unsigned LastArg = (CMF == CMF_Memset? 1 : 2);
Nico Webere4a1c642011-06-14 16:14:58 +00001938 const Expr *LenExpr = Call->getArg(2)->IgnoreParenImpCasts();
Chandler Carruth000d4282011-06-16 09:09:40 +00001939
1940 // We have special checking when the length is a sizeof expression.
1941 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
1942 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
1943 llvm::FoldingSetNodeID SizeOfArgID;
1944
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00001945 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
1946 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00001947 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00001948
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00001949 QualType DestTy = Dest->getType();
1950 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
1951 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00001952
Chandler Carruth000d4282011-06-16 09:09:40 +00001953 // Never warn about void type pointers. This can be used to suppress
1954 // false positives.
1955 if (PointeeTy->isVoidType())
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00001956 continue;
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00001957
Chandler Carruth000d4282011-06-16 09:09:40 +00001958 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
1959 // actually comparing the expressions for equality. Because computing the
1960 // expression IDs can be expensive, we only do this if the diagnostic is
1961 // enabled.
1962 if (SizeOfArg &&
1963 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
1964 SizeOfArg->getExprLoc())) {
1965 // We only compute IDs for expressions if the warning is enabled, and
1966 // cache the sizeof arg's ID.
1967 if (SizeOfArgID == llvm::FoldingSetNodeID())
1968 SizeOfArg->Profile(SizeOfArgID, Context, true);
1969 llvm::FoldingSetNodeID DestID;
1970 Dest->Profile(DestID, Context, true);
1971 if (DestID == SizeOfArgID) {
1972 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
1973 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
1974 if (UnaryOp->getOpcode() == UO_AddrOf)
1975 ActionIdx = 1; // If its an address-of operator, just remove it.
1976 if (Context.getTypeSize(PointeeTy) == Context.getCharWidth())
1977 ActionIdx = 2; // If the pointee's size is sizeof(char),
1978 // suggest an explicit length.
1979 DiagRuntimeBehavior(SizeOfArg->getExprLoc(), Dest,
1980 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
1981 << FnName << ArgIdx << ActionIdx
1982 << Dest->getSourceRange()
1983 << SizeOfArg->getSourceRange());
1984 break;
1985 }
1986 }
1987
1988 // Also check for cases where the sizeof argument is the exact same
1989 // type as the memory argument, and where it points to a user-defined
1990 // record type.
1991 if (SizeOfArgTy != QualType()) {
1992 if (PointeeTy->isRecordType() &&
1993 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
1994 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
1995 PDiag(diag::warn_sizeof_pointer_type_memaccess)
1996 << FnName << SizeOfArgTy << ArgIdx
1997 << PointeeTy << Dest->getSourceRange()
1998 << LenExpr->getSourceRange());
1999 break;
2000 }
Nico Webere4a1c642011-06-14 16:14:58 +00002001 }
2002
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002003 // Always complain about dynamic classes.
John McCallf85e1932011-06-15 23:02:42 +00002004 if (isDynamicClassType(PointeeTy))
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00002005 DiagRuntimeBehavior(
2006 Dest->getExprLoc(), Dest,
2007 PDiag(diag::warn_dyn_class_memaccess)
2008 << (CMF == CMF_Memcmp ? ArgIdx + 2 : ArgIdx) << FnName << PointeeTy
2009 // "overwritten" if we're warning about the destination for any call
2010 // but memcmp; otherwise a verb appropriate to the call.
2011 << (ArgIdx == 0 && CMF != CMF_Memcmp ? 0 : (unsigned)CMF)
2012 << Call->getCallee()->getSourceRange());
Douglas Gregor707a23e2011-06-16 17:56:04 +00002013 else if (PointeeTy.hasNonTrivialObjCLifetime() && CMF != CMF_Memset)
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00002014 DiagRuntimeBehavior(
2015 Dest->getExprLoc(), Dest,
2016 PDiag(diag::warn_arc_object_memaccess)
2017 << ArgIdx << FnName << PointeeTy
2018 << Call->getCallee()->getSourceRange());
John McCallf85e1932011-06-15 23:02:42 +00002019 else
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002020 continue;
John McCallf85e1932011-06-15 23:02:42 +00002021
2022 DiagRuntimeBehavior(
2023 Dest->getExprLoc(), Dest,
Chandler Carruth929f0132011-06-03 06:23:57 +00002024 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002025 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
2026 break;
2027 }
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002028 }
2029}
2030
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002031// A little helper routine: ignore addition and subtraction of integer literals.
2032// This intentionally does not ignore all integer constant expressions because
2033// we don't want to remove sizeof().
2034static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
2035 Ex = Ex->IgnoreParenCasts();
2036
2037 for (;;) {
2038 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
2039 if (!BO || !BO->isAdditiveOp())
2040 break;
2041
2042 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
2043 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
2044
2045 if (isa<IntegerLiteral>(RHS))
2046 Ex = LHS;
2047 else if (isa<IntegerLiteral>(LHS))
2048 Ex = RHS;
2049 else
2050 break;
2051 }
2052
2053 return Ex;
2054}
2055
2056// Warn if the user has made the 'size' argument to strlcpy or strlcat
2057// be the size of the source, instead of the destination.
2058void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
2059 IdentifierInfo *FnName) {
2060
2061 // Don't crash if the user has the wrong number of arguments
2062 if (Call->getNumArgs() != 3)
2063 return;
2064
2065 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
2066 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
2067 const Expr *CompareWithSrc = NULL;
2068
2069 // Look for 'strlcpy(dst, x, sizeof(x))'
2070 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
2071 CompareWithSrc = Ex;
2072 else {
2073 // Look for 'strlcpy(dst, x, strlen(x))'
2074 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
2075 if (SizeCall->isBuiltinCall(Context) == Builtin::BIstrlen
2076 && SizeCall->getNumArgs() == 1)
2077 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
2078 }
2079 }
2080
2081 if (!CompareWithSrc)
2082 return;
2083
2084 // Determine if the argument to sizeof/strlen is equal to the source
2085 // argument. In principle there's all kinds of things you could do
2086 // here, for instance creating an == expression and evaluating it with
2087 // EvaluateAsBooleanCondition, but this uses a more direct technique:
2088 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
2089 if (!SrcArgDRE)
2090 return;
2091
2092 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
2093 if (!CompareWithSrcDRE ||
2094 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
2095 return;
2096
2097 const Expr *OriginalSizeArg = Call->getArg(2);
2098 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
2099 << OriginalSizeArg->getSourceRange() << FnName;
2100
2101 // Output a FIXIT hint if the destination is an array (rather than a
2102 // pointer to an array). This could be enhanced to handle some
2103 // pointers if we know the actual size, like if DstArg is 'array+2'
2104 // we could say 'sizeof(array)-2'.
2105 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Ted Kremenek8f746222011-08-18 22:48:41 +00002106 QualType DstArgTy = DstArg->getType();
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002107
Ted Kremenek8f746222011-08-18 22:48:41 +00002108 // Only handle constant-sized or VLAs, but not flexible members.
2109 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(DstArgTy)) {
2110 // Only issue the FIXIT for arrays of size > 1.
2111 if (CAT->getSize().getSExtValue() <= 1)
2112 return;
2113 } else if (!DstArgTy->isVariableArrayType()) {
2114 return;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002115 }
Ted Kremenek8f746222011-08-18 22:48:41 +00002116
2117 llvm::SmallString<128> sizeString;
2118 llvm::raw_svector_ostream OS(sizeString);
2119 OS << "sizeof(";
2120 DstArg->printPretty(OS, Context, 0, Context.PrintingPolicy);
2121 OS << ")";
2122
2123 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
2124 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
2125 OS.str());
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002126}
2127
Ted Kremenek06de2762007-08-17 16:46:58 +00002128//===--- CHECK: Return Address of Stack Variable --------------------------===//
2129
Chris Lattner5f9e2722011-07-23 10:55:15 +00002130static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars);
2131static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002132
2133/// CheckReturnStackAddr - Check if a return statement returns the address
2134/// of a stack variable.
2135void
2136Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
2137 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00002138
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002139 Expr *stackE = 0;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002140 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002141
2142 // Perform checking for returned stack addresses, local blocks,
2143 // label addresses or references to temporaries.
John McCallf85e1932011-06-15 23:02:42 +00002144 if (lhsType->isPointerType() ||
2145 (!getLangOptions().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002146 stackE = EvalAddr(RetValExp, refVars);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002147 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002148 stackE = EvalVal(RetValExp, refVars);
2149 }
2150
2151 if (stackE == 0)
2152 return; // Nothing suspicious was found.
2153
2154 SourceLocation diagLoc;
2155 SourceRange diagRange;
2156 if (refVars.empty()) {
2157 diagLoc = stackE->getLocStart();
2158 diagRange = stackE->getSourceRange();
2159 } else {
2160 // We followed through a reference variable. 'stackE' contains the
2161 // problematic expression but we will warn at the return statement pointing
2162 // at the reference variable. We will later display the "trail" of
2163 // reference variables using notes.
2164 diagLoc = refVars[0]->getLocStart();
2165 diagRange = refVars[0]->getSourceRange();
2166 }
2167
2168 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
2169 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
2170 : diag::warn_ret_stack_addr)
2171 << DR->getDecl()->getDeclName() << diagRange;
2172 } else if (isa<BlockExpr>(stackE)) { // local block.
2173 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
2174 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
2175 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
2176 } else { // local temporary.
2177 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
2178 : diag::warn_ret_local_temp_addr)
2179 << diagRange;
2180 }
2181
2182 // Display the "trail" of reference variables that we followed until we
2183 // found the problematic expression using notes.
2184 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
2185 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
2186 // If this var binds to another reference var, show the range of the next
2187 // var, otherwise the var binds to the problematic expression, in which case
2188 // show the range of the expression.
2189 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
2190 : stackE->getSourceRange();
2191 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
2192 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00002193 }
2194}
2195
2196/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
2197/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002198/// to a location on the stack, a local block, an address of a label, or a
2199/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00002200/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002201/// encounter a subexpression that (1) clearly does not lead to one of the
2202/// above problematic expressions (2) is something we cannot determine leads to
2203/// a problematic expression based on such local checking.
2204///
2205/// Both EvalAddr and EvalVal follow through reference variables to evaluate
2206/// the expression that they point to. Such variables are added to the
2207/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00002208///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00002209/// EvalAddr processes expressions that are pointers that are used as
2210/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002211/// At the base case of the recursion is a check for the above problematic
2212/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00002213///
2214/// This implementation handles:
2215///
2216/// * pointer-to-pointer casts
2217/// * implicit conversions from array references to pointers
2218/// * taking the address of fields
2219/// * arbitrary interplay between "&" and "*" operators
2220/// * pointer arithmetic from an address of a stack variable
2221/// * taking the address of an array element where the array is on the stack
Chris Lattner5f9e2722011-07-23 10:55:15 +00002222static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002223 if (E->isTypeDependent())
2224 return NULL;
2225
Ted Kremenek06de2762007-08-17 16:46:58 +00002226 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00002227 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00002228 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002229 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002230 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00002231
Peter Collingbournef111d932011-04-15 00:35:48 +00002232 E = E->IgnoreParens();
2233
Ted Kremenek06de2762007-08-17 16:46:58 +00002234 // Our "symbolic interpreter" is just a dispatch off the currently
2235 // viewed AST node. We then recursively traverse the AST by calling
2236 // EvalAddr and EvalVal appropriately.
2237 switch (E->getStmtClass()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002238 case Stmt::DeclRefExprClass: {
2239 DeclRefExpr *DR = cast<DeclRefExpr>(E);
2240
2241 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
2242 // If this is a reference variable, follow through to the expression that
2243 // it points to.
2244 if (V->hasLocalStorage() &&
2245 V->getType()->isReferenceType() && V->hasInit()) {
2246 // Add the reference variable to the "trail".
2247 refVars.push_back(DR);
2248 return EvalAddr(V->getInit(), refVars);
2249 }
2250
2251 return NULL;
2252 }
Ted Kremenek06de2762007-08-17 16:46:58 +00002253
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002254 case Stmt::UnaryOperatorClass: {
2255 // The only unary operator that make sense to handle here
2256 // is AddrOf. All others don't make sense as pointers.
2257 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002258
John McCall2de56d12010-08-25 11:45:40 +00002259 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002260 return EvalVal(U->getSubExpr(), refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002261 else
Ted Kremenek06de2762007-08-17 16:46:58 +00002262 return NULL;
2263 }
Mike Stump1eb44332009-09-09 15:08:12 +00002264
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002265 case Stmt::BinaryOperatorClass: {
2266 // Handle pointer arithmetic. All other binary operators are not valid
2267 // in this context.
2268 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00002269 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00002270
John McCall2de56d12010-08-25 11:45:40 +00002271 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002272 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00002273
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002274 Expr *Base = B->getLHS();
2275
2276 // Determine which argument is the real pointer base. It could be
2277 // the RHS argument instead of the LHS.
2278 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00002279
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002280 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002281 return EvalAddr(Base, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002282 }
Steve Naroff61f40a22008-09-10 19:17:48 +00002283
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002284 // For conditional operators we need to see if either the LHS or RHS are
2285 // valid DeclRefExpr*s. If one of them is valid, we return it.
2286 case Stmt::ConditionalOperatorClass: {
2287 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002288
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002289 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00002290 if (Expr *lhsExpr = C->getLHS()) {
2291 // In C++, we can have a throw-expression, which has 'void' type.
2292 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002293 if (Expr* LHS = EvalAddr(lhsExpr, refVars))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00002294 return LHS;
2295 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002296
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00002297 // In C++, we can have a throw-expression, which has 'void' type.
2298 if (C->getRHS()->getType()->isVoidType())
2299 return NULL;
2300
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002301 return EvalAddr(C->getRHS(), refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002302 }
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002303
2304 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00002305 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002306 return E; // local block.
2307 return NULL;
2308
2309 case Stmt::AddrLabelExprClass:
2310 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00002311
Ted Kremenek54b52742008-08-07 00:49:01 +00002312 // For casts, we need to handle conversions from arrays to
2313 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00002314 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002315 case Stmt::CStyleCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00002316 case Stmt::CXXFunctionalCastExprClass:
2317 case Stmt::ObjCBridgedCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002318 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenek54b52742008-08-07 00:49:01 +00002319 QualType T = SubExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002320
Steve Naroffdd972f22008-09-05 22:11:13 +00002321 if (SubExpr->getType()->isPointerType() ||
2322 SubExpr->getType()->isBlockPointerType() ||
2323 SubExpr->getType()->isObjCQualifiedIdType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002324 return EvalAddr(SubExpr, refVars);
Ted Kremenek54b52742008-08-07 00:49:01 +00002325 else if (T->isArrayType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002326 return EvalVal(SubExpr, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002327 else
Ted Kremenek54b52742008-08-07 00:49:01 +00002328 return 0;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002329 }
Mike Stump1eb44332009-09-09 15:08:12 +00002330
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002331 // C++ casts. For dynamic casts, static casts, and const casts, we
2332 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor49badde2008-10-27 19:41:14 +00002333 // through the cast. In the case the dynamic cast doesn't fail (and
2334 // return NULL), we take the conservative route and report cases
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002335 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor49badde2008-10-27 19:41:14 +00002336 // FIXME: The comment about is wrong; we're not always converting
2337 // from pointer to pointer. I'm guessing that this code should also
Mike Stump1eb44332009-09-09 15:08:12 +00002338 // handle references to objects.
2339 case Stmt::CXXStaticCastExprClass:
2340 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00002341 case Stmt::CXXConstCastExprClass:
2342 case Stmt::CXXReinterpretCastExprClass: {
2343 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffdd972f22008-09-05 22:11:13 +00002344 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002345 return EvalAddr(S, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002346 else
2347 return NULL;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002348 }
Mike Stump1eb44332009-09-09 15:08:12 +00002349
Douglas Gregor03e80032011-06-21 17:03:29 +00002350 case Stmt::MaterializeTemporaryExprClass:
2351 if (Expr *Result = EvalAddr(
2352 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
2353 refVars))
2354 return Result;
2355
2356 return E;
2357
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002358 // Everything else: we simply don't reason about them.
2359 default:
2360 return NULL;
2361 }
Ted Kremenek06de2762007-08-17 16:46:58 +00002362}
Mike Stump1eb44332009-09-09 15:08:12 +00002363
Ted Kremenek06de2762007-08-17 16:46:58 +00002364
2365/// EvalVal - This function is complements EvalAddr in the mutual recursion.
2366/// See the comments for EvalAddr for more details.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002367static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002368do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00002369 // We should only be called for evaluating non-pointer expressions, or
2370 // expressions with a pointer type that are not used as references but instead
2371 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00002372
Ted Kremenek06de2762007-08-17 16:46:58 +00002373 // Our "symbolic interpreter" is just a dispatch off the currently
2374 // viewed AST node. We then recursively traverse the AST by calling
2375 // EvalAddr and EvalVal appropriately.
Peter Collingbournef111d932011-04-15 00:35:48 +00002376
2377 E = E->IgnoreParens();
Ted Kremenek06de2762007-08-17 16:46:58 +00002378 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002379 case Stmt::ImplicitCastExprClass: {
2380 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00002381 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002382 E = IE->getSubExpr();
2383 continue;
2384 }
2385 return NULL;
2386 }
2387
Douglas Gregora2813ce2009-10-23 18:54:35 +00002388 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002389 // When we hit a DeclRefExpr we are looking at code that refers to a
2390 // variable's name. If it's not a reference variable we check if it has
2391 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00002392 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002393
Ted Kremenek06de2762007-08-17 16:46:58 +00002394 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002395 if (V->hasLocalStorage()) {
2396 if (!V->getType()->isReferenceType())
2397 return DR;
2398
2399 // Reference variable, follow through to the expression that
2400 // it points to.
2401 if (V->hasInit()) {
2402 // Add the reference variable to the "trail".
2403 refVars.push_back(DR);
2404 return EvalVal(V->getInit(), refVars);
2405 }
2406 }
Mike Stump1eb44332009-09-09 15:08:12 +00002407
Ted Kremenek06de2762007-08-17 16:46:58 +00002408 return NULL;
2409 }
Mike Stump1eb44332009-09-09 15:08:12 +00002410
Ted Kremenek06de2762007-08-17 16:46:58 +00002411 case Stmt::UnaryOperatorClass: {
2412 // The only unary operator that make sense to handle here
2413 // is Deref. All others don't resolve to a "name." This includes
2414 // handling all sorts of rvalues passed to a unary operator.
2415 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002416
John McCall2de56d12010-08-25 11:45:40 +00002417 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002418 return EvalAddr(U->getSubExpr(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002419
2420 return NULL;
2421 }
Mike Stump1eb44332009-09-09 15:08:12 +00002422
Ted Kremenek06de2762007-08-17 16:46:58 +00002423 case Stmt::ArraySubscriptExprClass: {
2424 // Array subscripts are potential references to data on the stack. We
2425 // retrieve the DeclRefExpr* for the array variable if it indeed
2426 // has local storage.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002427 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002428 }
Mike Stump1eb44332009-09-09 15:08:12 +00002429
Ted Kremenek06de2762007-08-17 16:46:58 +00002430 case Stmt::ConditionalOperatorClass: {
2431 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002432 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00002433 ConditionalOperator *C = cast<ConditionalOperator>(E);
2434
Anders Carlsson39073232007-11-30 19:04:31 +00002435 // Handle the GNU extension for missing LHS.
2436 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002437 if (Expr *LHS = EvalVal(lhsExpr, refVars))
Anders Carlsson39073232007-11-30 19:04:31 +00002438 return LHS;
2439
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002440 return EvalVal(C->getRHS(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002441 }
Mike Stump1eb44332009-09-09 15:08:12 +00002442
Ted Kremenek06de2762007-08-17 16:46:58 +00002443 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00002444 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00002445 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002446
Ted Kremenek06de2762007-08-17 16:46:58 +00002447 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00002448 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00002449 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00002450
2451 // Check whether the member type is itself a reference, in which case
2452 // we're not going to refer to the member, but to what the member refers to.
2453 if (M->getMemberDecl()->getType()->isReferenceType())
2454 return NULL;
2455
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002456 return EvalVal(M->getBase(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002457 }
Mike Stump1eb44332009-09-09 15:08:12 +00002458
Douglas Gregor03e80032011-06-21 17:03:29 +00002459 case Stmt::MaterializeTemporaryExprClass:
2460 if (Expr *Result = EvalVal(
2461 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
2462 refVars))
2463 return Result;
2464
2465 return E;
2466
Ted Kremenek06de2762007-08-17 16:46:58 +00002467 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002468 // Check that we don't return or take the address of a reference to a
2469 // temporary. This is only useful in C++.
2470 if (!E->isTypeDependent() && E->isRValue())
2471 return E;
2472
2473 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00002474 return NULL;
2475 }
Ted Kremenek68957a92010-08-04 20:01:07 +00002476} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00002477}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002478
2479//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
2480
2481/// Check for comparisons of floating point operands using != and ==.
2482/// Issue a warning if these are no self-comparisons, as they are not likely
2483/// to do what the programmer intended.
2484void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
2485 bool EmitWarning = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002486
John McCallf6a16482010-12-04 03:47:34 +00002487 Expr* LeftExprSansParen = lex->IgnoreParenImpCasts();
2488 Expr* RightExprSansParen = rex->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002489
2490 // Special case: check for x == x (which is OK).
2491 // Do not emit warnings for such cases.
2492 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
2493 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
2494 if (DRL->getDecl() == DRR->getDecl())
2495 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002496
2497
Ted Kremenek1b500bb2007-11-29 00:59:04 +00002498 // Special case: check for comparisons against literals that can be exactly
2499 // represented by APFloat. In such cases, do not emit a warning. This
2500 // is a heuristic: often comparison against such literals are used to
2501 // detect if a value in a variable has not changed. This clearly can
2502 // lead to false negatives.
2503 if (EmitWarning) {
2504 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
2505 if (FLL->isExact())
2506 EmitWarning = false;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002507 } else
Ted Kremenek1b500bb2007-11-29 00:59:04 +00002508 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
2509 if (FLR->isExact())
2510 EmitWarning = false;
2511 }
2512 }
Mike Stump1eb44332009-09-09 15:08:12 +00002513
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002514 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002515 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002516 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00002517 if (CL->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002518 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002519
Sebastian Redl0eb23302009-01-19 00:08:26 +00002520 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002521 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00002522 if (CR->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002523 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002524
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002525 // Emit the diagnostic.
2526 if (EmitWarning)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002527 Diag(loc, diag::warn_floatingpoint_eq)
2528 << lex->getSourceRange() << rex->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002529}
John McCallba26e582010-01-04 23:21:16 +00002530
John McCallf2370c92010-01-06 05:24:50 +00002531//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
2532//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00002533
John McCallf2370c92010-01-06 05:24:50 +00002534namespace {
John McCallba26e582010-01-04 23:21:16 +00002535
John McCallf2370c92010-01-06 05:24:50 +00002536/// Structure recording the 'active' range of an integer-valued
2537/// expression.
2538struct IntRange {
2539 /// The number of bits active in the int.
2540 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00002541
John McCallf2370c92010-01-06 05:24:50 +00002542 /// True if the int is known not to have negative values.
2543 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00002544
John McCallf2370c92010-01-06 05:24:50 +00002545 IntRange(unsigned Width, bool NonNegative)
2546 : Width(Width), NonNegative(NonNegative)
2547 {}
John McCallba26e582010-01-04 23:21:16 +00002548
John McCall1844a6e2010-11-10 23:38:19 +00002549 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00002550 static IntRange forBoolType() {
2551 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00002552 }
2553
John McCall1844a6e2010-11-10 23:38:19 +00002554 /// Returns the range of an opaque value of the given integral type.
2555 static IntRange forValueOfType(ASTContext &C, QualType T) {
2556 return forValueOfCanonicalType(C,
2557 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00002558 }
2559
John McCall1844a6e2010-11-10 23:38:19 +00002560 /// Returns the range of an opaque value of a canonical integral type.
2561 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00002562 assert(T->isCanonicalUnqualified());
2563
2564 if (const VectorType *VT = dyn_cast<VectorType>(T))
2565 T = VT->getElementType().getTypePtr();
2566 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2567 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00002568
John McCall091f23f2010-11-09 22:22:12 +00002569 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00002570 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
2571 EnumDecl *Enum = ET->getDecl();
John McCall091f23f2010-11-09 22:22:12 +00002572 if (!Enum->isDefinition())
2573 return IntRange(C.getIntWidth(QualType(T, 0)), false);
2574
John McCall323ed742010-05-06 08:58:33 +00002575 unsigned NumPositive = Enum->getNumPositiveBits();
2576 unsigned NumNegative = Enum->getNumNegativeBits();
2577
2578 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
2579 }
John McCallf2370c92010-01-06 05:24:50 +00002580
2581 const BuiltinType *BT = cast<BuiltinType>(T);
2582 assert(BT->isInteger());
2583
2584 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2585 }
2586
John McCall1844a6e2010-11-10 23:38:19 +00002587 /// Returns the "target" range of a canonical integral type, i.e.
2588 /// the range of values expressible in the type.
2589 ///
2590 /// This matches forValueOfCanonicalType except that enums have the
2591 /// full range of their type, not the range of their enumerators.
2592 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
2593 assert(T->isCanonicalUnqualified());
2594
2595 if (const VectorType *VT = dyn_cast<VectorType>(T))
2596 T = VT->getElementType().getTypePtr();
2597 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2598 T = CT->getElementType().getTypePtr();
2599 if (const EnumType *ET = dyn_cast<EnumType>(T))
2600 T = ET->getDecl()->getIntegerType().getTypePtr();
2601
2602 const BuiltinType *BT = cast<BuiltinType>(T);
2603 assert(BT->isInteger());
2604
2605 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2606 }
2607
2608 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00002609 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00002610 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00002611 L.NonNegative && R.NonNegative);
2612 }
2613
John McCall1844a6e2010-11-10 23:38:19 +00002614 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00002615 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00002616 return IntRange(std::min(L.Width, R.Width),
2617 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00002618 }
2619};
2620
2621IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
2622 if (value.isSigned() && value.isNegative())
2623 return IntRange(value.getMinSignedBits(), false);
2624
2625 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00002626 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00002627
2628 // isNonNegative() just checks the sign bit without considering
2629 // signedness.
2630 return IntRange(value.getActiveBits(), true);
2631}
2632
John McCall0acc3112010-01-06 22:57:21 +00002633IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
John McCallf2370c92010-01-06 05:24:50 +00002634 unsigned MaxWidth) {
2635 if (result.isInt())
2636 return GetValueRange(C, result.getInt(), MaxWidth);
2637
2638 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00002639 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
2640 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
2641 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
2642 R = IntRange::join(R, El);
2643 }
John McCallf2370c92010-01-06 05:24:50 +00002644 return R;
2645 }
2646
2647 if (result.isComplexInt()) {
2648 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
2649 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
2650 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00002651 }
2652
2653 // This can happen with lossless casts to intptr_t of "based" lvalues.
2654 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00002655 // FIXME: The only reason we need to pass the type in here is to get
2656 // the sign right on this one case. It would be nice if APValue
2657 // preserved this.
John McCallf2370c92010-01-06 05:24:50 +00002658 assert(result.isLValue());
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00002659 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall51313c32010-01-04 23:31:57 +00002660}
John McCallf2370c92010-01-06 05:24:50 +00002661
2662/// Pseudo-evaluate the given integer expression, estimating the
2663/// range of values it might take.
2664///
2665/// \param MaxWidth - the width to which the value will be truncated
2666IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
2667 E = E->IgnoreParens();
2668
2669 // Try a full evaluation first.
2670 Expr::EvalResult result;
2671 if (E->Evaluate(result, C))
John McCall0acc3112010-01-06 22:57:21 +00002672 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00002673
2674 // I think we only want to look through implicit casts here; if the
2675 // user has an explicit widening cast, we should treat the value as
2676 // being of the new, wider type.
2677 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall2de56d12010-08-25 11:45:40 +00002678 if (CE->getCastKind() == CK_NoOp)
John McCallf2370c92010-01-06 05:24:50 +00002679 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
2680
John McCall1844a6e2010-11-10 23:38:19 +00002681 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
John McCallf2370c92010-01-06 05:24:50 +00002682
John McCall2de56d12010-08-25 11:45:40 +00002683 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00002684
John McCallf2370c92010-01-06 05:24:50 +00002685 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00002686 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00002687 return OutputTypeRange;
2688
2689 IntRange SubRange
2690 = GetExprRange(C, CE->getSubExpr(),
2691 std::min(MaxWidth, OutputTypeRange.Width));
2692
2693 // Bail out if the subexpr's range is as wide as the cast type.
2694 if (SubRange.Width >= OutputTypeRange.Width)
2695 return OutputTypeRange;
2696
2697 // Otherwise, we take the smaller width, and we're non-negative if
2698 // either the output type or the subexpr is.
2699 return IntRange(SubRange.Width,
2700 SubRange.NonNegative || OutputTypeRange.NonNegative);
2701 }
2702
2703 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2704 // If we can fold the condition, just take that operand.
2705 bool CondResult;
2706 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
2707 return GetExprRange(C, CondResult ? CO->getTrueExpr()
2708 : CO->getFalseExpr(),
2709 MaxWidth);
2710
2711 // Otherwise, conservatively merge.
2712 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
2713 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
2714 return IntRange::join(L, R);
2715 }
2716
2717 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2718 switch (BO->getOpcode()) {
2719
2720 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00002721 case BO_LAnd:
2722 case BO_LOr:
2723 case BO_LT:
2724 case BO_GT:
2725 case BO_LE:
2726 case BO_GE:
2727 case BO_EQ:
2728 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00002729 return IntRange::forBoolType();
2730
John McCall862ff872011-07-13 06:35:24 +00002731 // The type of the assignments is the type of the LHS, so the RHS
2732 // is not necessarily the same type.
John McCall2de56d12010-08-25 11:45:40 +00002733 case BO_MulAssign:
2734 case BO_DivAssign:
2735 case BO_RemAssign:
2736 case BO_AddAssign:
2737 case BO_SubAssign:
John McCall862ff872011-07-13 06:35:24 +00002738 case BO_XorAssign:
2739 case BO_OrAssign:
2740 // TODO: bitfields?
John McCall1844a6e2010-11-10 23:38:19 +00002741 return IntRange::forValueOfType(C, E->getType());
John McCallc0cd21d2010-02-23 19:22:29 +00002742
John McCall862ff872011-07-13 06:35:24 +00002743 // Simple assignments just pass through the RHS, which will have
2744 // been coerced to the LHS type.
2745 case BO_Assign:
2746 // TODO: bitfields?
2747 return GetExprRange(C, BO->getRHS(), MaxWidth);
2748
John McCallf2370c92010-01-06 05:24:50 +00002749 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00002750 case BO_PtrMemD:
2751 case BO_PtrMemI:
John McCall1844a6e2010-11-10 23:38:19 +00002752 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002753
John McCall60fad452010-01-06 22:07:33 +00002754 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00002755 case BO_And:
2756 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00002757 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
2758 GetExprRange(C, BO->getRHS(), MaxWidth));
2759
John McCallf2370c92010-01-06 05:24:50 +00002760 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00002761 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00002762 // ...except that we want to treat '1 << (blah)' as logically
2763 // positive. It's an important idiom.
2764 if (IntegerLiteral *I
2765 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
2766 if (I->getValue() == 1) {
John McCall1844a6e2010-11-10 23:38:19 +00002767 IntRange R = IntRange::forValueOfType(C, E->getType());
John McCall3aae6092010-04-07 01:14:35 +00002768 return IntRange(R.Width, /*NonNegative*/ true);
2769 }
2770 }
2771 // fallthrough
2772
John McCall2de56d12010-08-25 11:45:40 +00002773 case BO_ShlAssign:
John McCall1844a6e2010-11-10 23:38:19 +00002774 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002775
John McCall60fad452010-01-06 22:07:33 +00002776 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00002777 case BO_Shr:
2778 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00002779 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
2780
2781 // If the shift amount is a positive constant, drop the width by
2782 // that much.
2783 llvm::APSInt shift;
2784 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
2785 shift.isNonNegative()) {
2786 unsigned zext = shift.getZExtValue();
2787 if (zext >= L.Width)
2788 L.Width = (L.NonNegative ? 0 : 1);
2789 else
2790 L.Width -= zext;
2791 }
2792
2793 return L;
2794 }
2795
2796 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00002797 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00002798 return GetExprRange(C, BO->getRHS(), MaxWidth);
2799
John McCall60fad452010-01-06 22:07:33 +00002800 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00002801 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00002802 if (BO->getLHS()->getType()->isPointerType())
John McCall1844a6e2010-11-10 23:38:19 +00002803 return IntRange::forValueOfType(C, E->getType());
John McCall00fe7612011-07-14 22:39:48 +00002804 break;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002805
John McCall00fe7612011-07-14 22:39:48 +00002806 // The width of a division result is mostly determined by the size
2807 // of the LHS.
2808 case BO_Div: {
2809 // Don't 'pre-truncate' the operands.
2810 unsigned opWidth = C.getIntWidth(E->getType());
2811 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
2812
2813 // If the divisor is constant, use that.
2814 llvm::APSInt divisor;
2815 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
2816 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
2817 if (log2 >= L.Width)
2818 L.Width = (L.NonNegative ? 0 : 1);
2819 else
2820 L.Width = std::min(L.Width - log2, MaxWidth);
2821 return L;
2822 }
2823
2824 // Otherwise, just use the LHS's width.
2825 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
2826 return IntRange(L.Width, L.NonNegative && R.NonNegative);
2827 }
2828
2829 // The result of a remainder can't be larger than the result of
2830 // either side.
2831 case BO_Rem: {
2832 // Don't 'pre-truncate' the operands.
2833 unsigned opWidth = C.getIntWidth(E->getType());
2834 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
2835 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
2836
2837 IntRange meet = IntRange::meet(L, R);
2838 meet.Width = std::min(meet.Width, MaxWidth);
2839 return meet;
2840 }
2841
2842 // The default behavior is okay for these.
2843 case BO_Mul:
2844 case BO_Add:
2845 case BO_Xor:
2846 case BO_Or:
John McCallf2370c92010-01-06 05:24:50 +00002847 break;
2848 }
2849
John McCall00fe7612011-07-14 22:39:48 +00002850 // The default case is to treat the operation as if it were closed
2851 // on the narrowest type that encompasses both operands.
John McCallf2370c92010-01-06 05:24:50 +00002852 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
2853 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
2854 return IntRange::join(L, R);
2855 }
2856
2857 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
2858 switch (UO->getOpcode()) {
2859 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00002860 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00002861 return IntRange::forBoolType();
2862
2863 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00002864 case UO_Deref:
2865 case UO_AddrOf: // should be impossible
John McCall1844a6e2010-11-10 23:38:19 +00002866 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002867
2868 default:
2869 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
2870 }
2871 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00002872
2873 if (dyn_cast<OffsetOfExpr>(E)) {
John McCall1844a6e2010-11-10 23:38:19 +00002874 IntRange::forValueOfType(C, E->getType());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00002875 }
John McCallf2370c92010-01-06 05:24:50 +00002876
2877 FieldDecl *BitField = E->getBitField();
2878 if (BitField) {
2879 llvm::APSInt BitWidthAP = BitField->getBitWidth()->EvaluateAsInt(C);
2880 unsigned BitWidth = BitWidthAP.getZExtValue();
2881
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00002882 return IntRange(BitWidth,
2883 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCallf2370c92010-01-06 05:24:50 +00002884 }
2885
John McCall1844a6e2010-11-10 23:38:19 +00002886 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002887}
John McCall51313c32010-01-04 23:31:57 +00002888
John McCall323ed742010-05-06 08:58:33 +00002889IntRange GetExprRange(ASTContext &C, Expr *E) {
2890 return GetExprRange(C, E, C.getIntWidth(E->getType()));
2891}
2892
John McCall51313c32010-01-04 23:31:57 +00002893/// Checks whether the given value, which currently has the given
2894/// source semantics, has the same value when coerced through the
2895/// target semantics.
John McCallf2370c92010-01-06 05:24:50 +00002896bool IsSameFloatAfterCast(const llvm::APFloat &value,
2897 const llvm::fltSemantics &Src,
2898 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00002899 llvm::APFloat truncated = value;
2900
2901 bool ignored;
2902 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
2903 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
2904
2905 return truncated.bitwiseIsEqual(value);
2906}
2907
2908/// Checks whether the given value, which currently has the given
2909/// source semantics, has the same value when coerced through the
2910/// target semantics.
2911///
2912/// The value might be a vector of floats (or a complex number).
John McCallf2370c92010-01-06 05:24:50 +00002913bool IsSameFloatAfterCast(const APValue &value,
2914 const llvm::fltSemantics &Src,
2915 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00002916 if (value.isFloat())
2917 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
2918
2919 if (value.isVector()) {
2920 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
2921 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
2922 return false;
2923 return true;
2924 }
2925
2926 assert(value.isComplexFloat());
2927 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
2928 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
2929}
2930
John McCallb4eb64d2010-10-08 02:01:28 +00002931void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00002932
Ted Kremeneke3b159c2010-09-23 21:43:44 +00002933static bool IsZero(Sema &S, Expr *E) {
2934 // Suppress cases where we are comparing against an enum constant.
2935 if (const DeclRefExpr *DR =
2936 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
2937 if (isa<EnumConstantDecl>(DR->getDecl()))
2938 return false;
2939
2940 // Suppress cases where the '0' value is expanded from a macro.
2941 if (E->getLocStart().isMacroID())
2942 return false;
2943
John McCall323ed742010-05-06 08:58:33 +00002944 llvm::APSInt Value;
2945 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
2946}
2947
John McCall372e1032010-10-06 00:25:24 +00002948static bool HasEnumType(Expr *E) {
2949 // Strip off implicit integral promotions.
2950 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00002951 if (ICE->getCastKind() != CK_IntegralCast &&
2952 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00002953 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00002954 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00002955 }
2956
2957 return E->getType()->isEnumeralType();
2958}
2959
John McCall323ed742010-05-06 08:58:33 +00002960void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002961 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00002962 if (E->isValueDependent())
2963 return;
2964
John McCall2de56d12010-08-25 11:45:40 +00002965 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00002966 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002967 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00002968 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00002969 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00002970 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002971 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00002972 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00002973 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00002974 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002975 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00002976 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00002977 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00002978 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002979 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00002980 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
2981 }
2982}
2983
2984/// Analyze the operands of the given comparison. Implements the
2985/// fallback case from AnalyzeComparison.
2986void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00002987 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
2988 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00002989}
John McCall51313c32010-01-04 23:31:57 +00002990
John McCallba26e582010-01-04 23:21:16 +00002991/// \brief Implements -Wsign-compare.
2992///
2993/// \param lex the left-hand expression
2994/// \param rex the right-hand expression
2995/// \param OpLoc the location of the joining operator
John McCalld1b47bf2010-03-11 19:43:18 +00002996/// \param BinOpc binary opcode or 0
John McCall323ed742010-05-06 08:58:33 +00002997void AnalyzeComparison(Sema &S, BinaryOperator *E) {
2998 // The type the comparison is being performed in.
2999 QualType T = E->getLHS()->getType();
3000 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
3001 && "comparison with mismatched types");
John McCallba26e582010-01-04 23:21:16 +00003002
John McCall323ed742010-05-06 08:58:33 +00003003 // We don't do anything special if this isn't an unsigned integral
3004 // comparison: we're only interested in integral comparisons, and
3005 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00003006 //
3007 // We also don't care about value-dependent expressions or expressions
3008 // whose result is a constant.
3009 if (!T->hasUnsignedIntegerRepresentation()
3010 || E->isValueDependent() || E->isIntegerConstantExpr(S.Context))
John McCall323ed742010-05-06 08:58:33 +00003011 return AnalyzeImpConvsInComparison(S, E);
John McCallf2370c92010-01-06 05:24:50 +00003012
John McCall323ed742010-05-06 08:58:33 +00003013 Expr *lex = E->getLHS()->IgnoreParenImpCasts();
3014 Expr *rex = E->getRHS()->IgnoreParenImpCasts();
John McCallba26e582010-01-04 23:21:16 +00003015
John McCall323ed742010-05-06 08:58:33 +00003016 // Check to see if one of the (unmodified) operands is of different
3017 // signedness.
3018 Expr *signedOperand, *unsignedOperand;
Douglas Gregorf6094622010-07-23 15:58:24 +00003019 if (lex->getType()->hasSignedIntegerRepresentation()) {
3020 assert(!rex->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00003021 "unsigned comparison between two signed integer expressions?");
3022 signedOperand = lex;
3023 unsignedOperand = rex;
Douglas Gregorf6094622010-07-23 15:58:24 +00003024 } else if (rex->getType()->hasSignedIntegerRepresentation()) {
John McCall323ed742010-05-06 08:58:33 +00003025 signedOperand = rex;
3026 unsignedOperand = lex;
John McCallba26e582010-01-04 23:21:16 +00003027 } else {
John McCall323ed742010-05-06 08:58:33 +00003028 CheckTrivialUnsignedComparison(S, E);
3029 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00003030 }
3031
John McCall323ed742010-05-06 08:58:33 +00003032 // Otherwise, calculate the effective range of the signed operand.
3033 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00003034
John McCall323ed742010-05-06 08:58:33 +00003035 // Go ahead and analyze implicit conversions in the operands. Note
3036 // that we skip the implicit conversions on both sides.
John McCallb4eb64d2010-10-08 02:01:28 +00003037 AnalyzeImplicitConversions(S, lex, E->getOperatorLoc());
3038 AnalyzeImplicitConversions(S, rex, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00003039
John McCall323ed742010-05-06 08:58:33 +00003040 // If the signed range is non-negative, -Wsign-compare won't fire,
3041 // but we should still check for comparisons which are always true
3042 // or false.
3043 if (signedRange.NonNegative)
3044 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00003045
3046 // For (in)equality comparisons, if the unsigned operand is a
3047 // constant which cannot collide with a overflowed signed operand,
3048 // then reinterpreting the signed operand as unsigned will not
3049 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00003050 if (E->isEqualityOp()) {
3051 unsigned comparisonWidth = S.Context.getIntWidth(T);
3052 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00003053
John McCall323ed742010-05-06 08:58:33 +00003054 // We should never be unable to prove that the unsigned operand is
3055 // non-negative.
3056 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
3057
3058 if (unsignedRange.Width < comparisonWidth)
3059 return;
3060 }
3061
3062 S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison)
3063 << lex->getType() << rex->getType()
3064 << lex->getSourceRange() << rex->getSourceRange();
John McCallba26e582010-01-04 23:21:16 +00003065}
3066
John McCall15d7d122010-11-11 03:21:53 +00003067/// Analyzes an attempt to assign the given value to a bitfield.
3068///
3069/// Returns true if there was something fishy about the attempt.
3070bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
3071 SourceLocation InitLoc) {
3072 assert(Bitfield->isBitField());
3073 if (Bitfield->isInvalidDecl())
3074 return false;
3075
John McCall91b60142010-11-11 05:33:51 +00003076 // White-list bool bitfields.
3077 if (Bitfield->getType()->isBooleanType())
3078 return false;
3079
Douglas Gregor46ff3032011-02-04 13:09:01 +00003080 // Ignore value- or type-dependent expressions.
3081 if (Bitfield->getBitWidth()->isValueDependent() ||
3082 Bitfield->getBitWidth()->isTypeDependent() ||
3083 Init->isValueDependent() ||
3084 Init->isTypeDependent())
3085 return false;
3086
John McCall15d7d122010-11-11 03:21:53 +00003087 Expr *OriginalInit = Init->IgnoreParenImpCasts();
3088
3089 llvm::APSInt Width(32);
3090 Expr::EvalResult InitValue;
3091 if (!Bitfield->getBitWidth()->isIntegerConstantExpr(Width, S.Context) ||
John McCall91b60142010-11-11 05:33:51 +00003092 !OriginalInit->Evaluate(InitValue, S.Context) ||
John McCall15d7d122010-11-11 03:21:53 +00003093 !InitValue.Val.isInt())
3094 return false;
3095
3096 const llvm::APSInt &Value = InitValue.Val.getInt();
3097 unsigned OriginalWidth = Value.getBitWidth();
3098 unsigned FieldWidth = Width.getZExtValue();
3099
3100 if (OriginalWidth <= FieldWidth)
3101 return false;
3102
Jay Foad9f71a8f2010-12-07 08:25:34 +00003103 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
John McCall15d7d122010-11-11 03:21:53 +00003104
3105 // It's fairly common to write values into signed bitfields
3106 // that, if sign-extended, would end up becoming a different
3107 // value. We don't want to warn about that.
3108 if (Value.isSigned() && Value.isNegative())
Jay Foad9f71a8f2010-12-07 08:25:34 +00003109 TruncatedValue = TruncatedValue.sext(OriginalWidth);
John McCall15d7d122010-11-11 03:21:53 +00003110 else
Jay Foad9f71a8f2010-12-07 08:25:34 +00003111 TruncatedValue = TruncatedValue.zext(OriginalWidth);
John McCall15d7d122010-11-11 03:21:53 +00003112
3113 if (Value == TruncatedValue)
3114 return false;
3115
3116 std::string PrettyValue = Value.toString(10);
3117 std::string PrettyTrunc = TruncatedValue.toString(10);
3118
3119 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
3120 << PrettyValue << PrettyTrunc << OriginalInit->getType()
3121 << Init->getSourceRange();
3122
3123 return true;
3124}
3125
John McCallbeb22aa2010-11-09 23:24:47 +00003126/// Analyze the given simple or compound assignment for warning-worthy
3127/// operations.
3128void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
3129 // Just recurse on the LHS.
3130 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
3131
3132 // We want to recurse on the RHS as normal unless we're assigning to
3133 // a bitfield.
3134 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
John McCall15d7d122010-11-11 03:21:53 +00003135 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
3136 E->getOperatorLoc())) {
3137 // Recurse, ignoring any implicit conversions on the RHS.
3138 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
3139 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00003140 }
3141 }
3142
3143 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
3144}
3145
John McCall51313c32010-01-04 23:31:57 +00003146/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00003147void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
3148 SourceLocation CContext, unsigned diag) {
3149 S.Diag(E->getExprLoc(), diag)
3150 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
3151}
3152
Chandler Carruthe1b02e02011-04-05 06:47:57 +00003153/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
3154void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
3155 unsigned diag) {
3156 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag);
3157}
3158
Chandler Carruthf65076e2011-04-10 08:36:24 +00003159/// Diagnose an implicit cast from a literal expression. Also attemps to supply
3160/// fixit hints when the cast wouldn't lose information to simply write the
3161/// expression with the expected type.
3162void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
3163 SourceLocation CContext) {
3164 // Emit the primary warning first, then try to emit a fixit hint note if
3165 // reasonable.
3166 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
3167 << FL->getType() << T << FL->getSourceRange() << SourceRange(CContext);
3168
3169 const llvm::APFloat &Value = FL->getValue();
3170
3171 // Don't attempt to fix PPC double double literals.
3172 if (&Value.getSemantics() == &llvm::APFloat::PPCDoubleDouble)
3173 return;
3174
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00003175 // Try to convert this exactly to an integer.
Chandler Carruthf65076e2011-04-10 08:36:24 +00003176 bool isExact = false;
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00003177 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
3178 T->hasUnsignedIntegerRepresentation());
3179 if (Value.convertToInteger(IntegerValue,
Chandler Carruthf65076e2011-04-10 08:36:24 +00003180 llvm::APFloat::rmTowardZero, &isExact)
3181 != llvm::APFloat::opOK || !isExact)
3182 return;
3183
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00003184 std::string LiteralValue = IntegerValue.toString(10);
Chandler Carruthf65076e2011-04-10 08:36:24 +00003185 S.Diag(FL->getExprLoc(), diag::note_fix_integral_float_as_integer)
3186 << FixItHint::CreateReplacement(FL->getSourceRange(), LiteralValue);
3187}
3188
John McCall091f23f2010-11-09 22:22:12 +00003189std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
3190 if (!Range.Width) return "0";
3191
3192 llvm::APSInt ValueInRange = Value;
3193 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00003194 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00003195 return ValueInRange.toString(10);
3196}
3197
Ted Kremenekef9ff882011-03-10 20:03:42 +00003198static bool isFromSystemMacro(Sema &S, SourceLocation loc) {
3199 SourceManager &smgr = S.Context.getSourceManager();
3200 return loc.isMacroID() && smgr.isInSystemHeader(smgr.getSpellingLoc(loc));
3201}
Chandler Carruthf65076e2011-04-10 08:36:24 +00003202
John McCall323ed742010-05-06 08:58:33 +00003203void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00003204 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00003205 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00003206
John McCall323ed742010-05-06 08:58:33 +00003207 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
3208 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
3209 if (Source == Target) return;
3210 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00003211
Chandler Carruth108f7562011-07-26 05:40:03 +00003212 // If the conversion context location is invalid don't complain. We also
3213 // don't want to emit a warning if the issue occurs from the expansion of
3214 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
3215 // delay this check as long as possible. Once we detect we are in that
3216 // scenario, we just return.
Ted Kremenekef9ff882011-03-10 20:03:42 +00003217 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00003218 return;
3219
John McCall51313c32010-01-04 23:31:57 +00003220 // Never diagnose implicit casts to bool.
3221 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
3222 return;
3223
3224 // Strip vector types.
3225 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003226 if (!isa<VectorType>(Target)) {
3227 if (isFromSystemMacro(S, CC))
3228 return;
John McCallb4eb64d2010-10-08 02:01:28 +00003229 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00003230 }
Chris Lattnerb792b302011-06-14 04:51:15 +00003231
3232 // If the vector cast is cast between two vectors of the same size, it is
3233 // a bitcast, not a conversion.
3234 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
3235 return;
John McCall51313c32010-01-04 23:31:57 +00003236
3237 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
3238 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
3239 }
3240
3241 // Strip complex types.
3242 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003243 if (!isa<ComplexType>(Target)) {
3244 if (isFromSystemMacro(S, CC))
3245 return;
3246
John McCallb4eb64d2010-10-08 02:01:28 +00003247 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00003248 }
John McCall51313c32010-01-04 23:31:57 +00003249
3250 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
3251 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
3252 }
3253
3254 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
3255 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
3256
3257 // If the source is floating point...
3258 if (SourceBT && SourceBT->isFloatingPoint()) {
3259 // ...and the target is floating point...
3260 if (TargetBT && TargetBT->isFloatingPoint()) {
3261 // ...then warn if we're dropping FP rank.
3262
3263 // Builtin FP kinds are ordered by increasing FP rank.
3264 if (SourceBT->getKind() > TargetBT->getKind()) {
3265 // Don't warn about float constants that are precisely
3266 // representable in the target type.
3267 Expr::EvalResult result;
John McCall323ed742010-05-06 08:58:33 +00003268 if (E->Evaluate(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00003269 // Value might be a float, a float vector, or a float complex.
3270 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00003271 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
3272 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00003273 return;
3274 }
3275
Ted Kremenekef9ff882011-03-10 20:03:42 +00003276 if (isFromSystemMacro(S, CC))
3277 return;
3278
John McCallb4eb64d2010-10-08 02:01:28 +00003279 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00003280 }
3281 return;
3282 }
3283
Ted Kremenekef9ff882011-03-10 20:03:42 +00003284 // If the target is integral, always warn.
Chandler Carrutha5b93322011-02-17 11:05:49 +00003285 if ((TargetBT && TargetBT->isInteger())) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003286 if (isFromSystemMacro(S, CC))
3287 return;
3288
Chandler Carrutha5b93322011-02-17 11:05:49 +00003289 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay634c8af2011-09-08 22:30:47 +00003290 // We also want to warn on, e.g., "int i = -1.234"
3291 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
3292 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
3293 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
3294
Chandler Carruthf65076e2011-04-10 08:36:24 +00003295 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
3296 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00003297 } else {
3298 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
3299 }
3300 }
John McCall51313c32010-01-04 23:31:57 +00003301
3302 return;
3303 }
3304
John McCallf2370c92010-01-06 05:24:50 +00003305 if (!Source->isIntegerType() || !Target->isIntegerType())
John McCall51313c32010-01-04 23:31:57 +00003306 return;
3307
Richard Trieu1838ca52011-05-29 19:59:02 +00003308 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
3309 == Expr::NPCK_GNUNull) && Target->isIntegerType()) {
3310 S.Diag(E->getExprLoc(), diag::warn_impcast_null_pointer_to_integer)
3311 << E->getSourceRange() << clang::SourceRange(CC);
3312 return;
3313 }
3314
John McCall323ed742010-05-06 08:58:33 +00003315 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00003316 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00003317
3318 if (SourceRange.Width > TargetRange.Width) {
John McCall091f23f2010-11-09 22:22:12 +00003319 // If the source is a constant, use a default-on diagnostic.
3320 // TODO: this should happen for bitfield stores, too.
3321 llvm::APSInt Value(32);
3322 if (E->isIntegerConstantExpr(Value, S.Context)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003323 if (isFromSystemMacro(S, CC))
3324 return;
3325
John McCall091f23f2010-11-09 22:22:12 +00003326 std::string PrettySourceValue = Value.toString(10);
3327 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
3328
3329 S.Diag(E->getExprLoc(), diag::warn_impcast_integer_precision_constant)
3330 << PrettySourceValue << PrettyTargetValue
3331 << E->getType() << T << E->getSourceRange() << clang::SourceRange(CC);
3332 return;
3333 }
3334
Chris Lattnerb792b302011-06-14 04:51:15 +00003335 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
Ted Kremenekef9ff882011-03-10 20:03:42 +00003336 if (isFromSystemMacro(S, CC))
3337 return;
3338
John McCallf2370c92010-01-06 05:24:50 +00003339 if (SourceRange.Width == 64 && TargetRange.Width == 32)
John McCallb4eb64d2010-10-08 02:01:28 +00003340 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32);
3341 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00003342 }
3343
3344 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
3345 (!TargetRange.NonNegative && SourceRange.NonNegative &&
3346 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003347
3348 if (isFromSystemMacro(S, CC))
3349 return;
3350
John McCall323ed742010-05-06 08:58:33 +00003351 unsigned DiagID = diag::warn_impcast_integer_sign;
3352
3353 // Traditionally, gcc has warned about this under -Wsign-compare.
3354 // We also want to warn about it in -Wconversion.
3355 // So if -Wconversion is off, use a completely identical diagnostic
3356 // in the sign-compare group.
3357 // The conditional-checking code will
3358 if (ICContext) {
3359 DiagID = diag::warn_impcast_integer_sign_conditional;
3360 *ICContext = true;
3361 }
3362
John McCallb4eb64d2010-10-08 02:01:28 +00003363 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00003364 }
3365
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003366 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00003367 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
3368 // type, to give us better diagnostics.
3369 QualType SourceType = E->getType();
3370 if (!S.getLangOptions().CPlusPlus) {
3371 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3372 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3373 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
3374 SourceType = S.Context.getTypeDeclType(Enum);
3375 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
3376 }
3377 }
3378
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003379 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
3380 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
3381 if ((SourceEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00003382 SourceEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003383 (TargetEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00003384 TargetEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00003385 SourceEnum != TargetEnum) {
3386 if (isFromSystemMacro(S, CC))
3387 return;
3388
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00003389 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003390 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00003391 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003392
John McCall51313c32010-01-04 23:31:57 +00003393 return;
3394}
3395
John McCall323ed742010-05-06 08:58:33 +00003396void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T);
3397
3398void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00003399 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00003400 E = E->IgnoreParenImpCasts();
3401
3402 if (isa<ConditionalOperator>(E))
3403 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T);
3404
John McCallb4eb64d2010-10-08 02:01:28 +00003405 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00003406 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00003407 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00003408 return;
3409}
3410
3411void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00003412 SourceLocation CC = E->getQuestionLoc();
3413
3414 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00003415
3416 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00003417 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
3418 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00003419
3420 // If -Wconversion would have warned about either of the candidates
3421 // for a signedness conversion to the context type...
3422 if (!Suspicious) return;
3423
3424 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003425 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
3426 CC))
John McCall323ed742010-05-06 08:58:33 +00003427 return;
3428
John McCall323ed742010-05-06 08:58:33 +00003429 // ...then check whether it would have warned about either of the
3430 // candidates for a signedness conversion to the condition type.
Richard Trieu52541612011-07-21 02:46:28 +00003431 if (E->getType() == T) return;
3432
3433 Suspicious = false;
3434 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
3435 E->getType(), CC, &Suspicious);
3436 if (!Suspicious)
3437 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00003438 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00003439}
3440
3441/// AnalyzeImplicitConversions - Find and report any interesting
3442/// implicit conversions in the given expression. There are a couple
3443/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00003444void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00003445 QualType T = OrigE->getType();
3446 Expr *E = OrigE->IgnoreParenImpCasts();
3447
3448 // For conditional operators, we analyze the arguments as if they
3449 // were being fed directly into the output.
3450 if (isa<ConditionalOperator>(E)) {
3451 ConditionalOperator *CO = cast<ConditionalOperator>(E);
3452 CheckConditionalOperator(S, CO, T);
3453 return;
3454 }
3455
3456 // Go ahead and check any implicit conversions we might have skipped.
3457 // The non-canonical typecheck is just an optimization;
3458 // CheckImplicitConversion will filter out dead implicit conversions.
3459 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00003460 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00003461
3462 // Now continue drilling into this expression.
3463
3464 // Skip past explicit casts.
3465 if (isa<ExplicitCastExpr>(E)) {
3466 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00003467 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00003468 }
3469
John McCallbeb22aa2010-11-09 23:24:47 +00003470 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3471 // Do a somewhat different check with comparison operators.
3472 if (BO->isComparisonOp())
3473 return AnalyzeComparison(S, BO);
3474
3475 // And with assignments and compound assignments.
3476 if (BO->isAssignmentOp())
3477 return AnalyzeAssignment(S, BO);
3478 }
John McCall323ed742010-05-06 08:58:33 +00003479
3480 // These break the otherwise-useful invariant below. Fortunately,
3481 // we don't really need to recurse into them, because any internal
3482 // expressions should have been analyzed already when they were
3483 // built into statements.
3484 if (isa<StmtExpr>(E)) return;
3485
3486 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003487 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00003488
3489 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00003490 CC = E->getExprLoc();
John McCall7502c1d2011-02-13 04:07:26 +00003491 for (Stmt::child_range I = E->children(); I; ++I)
John McCallb4eb64d2010-10-08 02:01:28 +00003492 AnalyzeImplicitConversions(S, cast<Expr>(*I), CC);
John McCall323ed742010-05-06 08:58:33 +00003493}
3494
3495} // end anonymous namespace
3496
3497/// Diagnoses "dangerous" implicit conversions within the given
3498/// expression (which is a full expression). Implements -Wconversion
3499/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00003500///
3501/// \param CC the "context" location of the implicit conversion, i.e.
3502/// the most location of the syntactic entity requiring the implicit
3503/// conversion
3504void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00003505 // Don't diagnose in unevaluated contexts.
3506 if (ExprEvalContexts.back().Context == Sema::Unevaluated)
3507 return;
3508
3509 // Don't diagnose for value- or type-dependent expressions.
3510 if (E->isTypeDependent() || E->isValueDependent())
3511 return;
3512
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003513 // Check for array bounds violations in cases where the check isn't triggered
3514 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
3515 // ArraySubscriptExpr is on the RHS of a variable initialization.
3516 CheckArrayAccess(E);
3517
John McCallb4eb64d2010-10-08 02:01:28 +00003518 // This is not the right CC for (e.g.) a variable initialization.
3519 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00003520}
3521
John McCall15d7d122010-11-11 03:21:53 +00003522void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
3523 FieldDecl *BitField,
3524 Expr *Init) {
3525 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
3526}
3527
Mike Stumpf8c49212010-01-21 03:59:47 +00003528/// CheckParmsForFunctionDef - Check that the parameters of the given
3529/// function are appropriate for the definition of a function. This
3530/// takes care of any checks that cannot be performed on the
3531/// declaration itself, e.g., that the types of each of the function
3532/// parameters are complete.
Douglas Gregor82aa7132010-11-01 18:37:59 +00003533bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
3534 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00003535 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00003536 for (; P != PEnd; ++P) {
3537 ParmVarDecl *Param = *P;
3538
Mike Stumpf8c49212010-01-21 03:59:47 +00003539 // C99 6.7.5.3p4: the parameters in a parameter type list in a
3540 // function declarator that is part of a function definition of
3541 // that function shall not have incomplete type.
3542 //
3543 // This is also C++ [dcl.fct]p6.
3544 if (!Param->isInvalidDecl() &&
3545 RequireCompleteType(Param->getLocation(), Param->getType(),
3546 diag::err_typecheck_decl_incomplete_type)) {
3547 Param->setInvalidDecl();
3548 HasInvalidParm = true;
3549 }
3550
3551 // C99 6.9.1p5: If the declarator includes a parameter type list, the
3552 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00003553 if (CheckParameterNames &&
3554 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00003555 !Param->isImplicit() &&
3556 !getLangOptions().CPlusPlus)
3557 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00003558
3559 // C99 6.7.5.3p12:
3560 // If the function declarator is not part of a definition of that
3561 // function, parameters may have incomplete type and may use the [*]
3562 // notation in their sequences of declarator specifiers to specify
3563 // variable length array types.
3564 QualType PType = Param->getOriginalType();
3565 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
3566 if (AT->getSizeModifier() == ArrayType::Star) {
3567 // FIXME: This diagnosic should point the the '[*]' if source-location
3568 // information is added for it.
3569 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
3570 }
3571 }
Mike Stumpf8c49212010-01-21 03:59:47 +00003572 }
3573
3574 return HasInvalidParm;
3575}
John McCallb7f4ffe2010-08-12 21:44:57 +00003576
3577/// CheckCastAlign - Implements -Wcast-align, which warns when a
3578/// pointer cast increases the alignment requirements.
3579void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
3580 // This is actually a lot of work to potentially be doing on every
3581 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003582 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
3583 TRange.getBegin())
John McCallb7f4ffe2010-08-12 21:44:57 +00003584 == Diagnostic::Ignored)
3585 return;
3586
3587 // Ignore dependent types.
3588 if (T->isDependentType() || Op->getType()->isDependentType())
3589 return;
3590
3591 // Require that the destination be a pointer type.
3592 const PointerType *DestPtr = T->getAs<PointerType>();
3593 if (!DestPtr) return;
3594
3595 // If the destination has alignment 1, we're done.
3596 QualType DestPointee = DestPtr->getPointeeType();
3597 if (DestPointee->isIncompleteType()) return;
3598 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
3599 if (DestAlign.isOne()) return;
3600
3601 // Require that the source be a pointer type.
3602 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
3603 if (!SrcPtr) return;
3604 QualType SrcPointee = SrcPtr->getPointeeType();
3605
3606 // Whitelist casts from cv void*. We already implicitly
3607 // whitelisted casts to cv void*, since they have alignment 1.
3608 // Also whitelist casts involving incomplete types, which implicitly
3609 // includes 'void'.
3610 if (SrcPointee->isIncompleteType()) return;
3611
3612 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
3613 if (SrcAlign >= DestAlign) return;
3614
3615 Diag(TRange.getBegin(), diag::warn_cast_align)
3616 << Op->getType() << T
3617 << static_cast<unsigned>(SrcAlign.getQuantity())
3618 << static_cast<unsigned>(DestAlign.getQuantity())
3619 << TRange << Op->getSourceRange();
3620}
3621
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003622static const Type* getElementType(const Expr *BaseExpr) {
3623 const Type* EltType = BaseExpr->getType().getTypePtr();
3624 if (EltType->isAnyPointerType())
3625 return EltType->getPointeeType().getTypePtr();
3626 else if (EltType->isArrayType())
3627 return EltType->getBaseElementTypeUnsafe();
3628 return EltType;
3629}
3630
Chandler Carruthc2684342011-08-05 09:10:50 +00003631/// \brief Check whether this array fits the idiom of a size-one tail padded
3632/// array member of a struct.
3633///
3634/// We avoid emitting out-of-bounds access warnings for such arrays as they are
3635/// commonly used to emulate flexible arrays in C89 code.
3636static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
3637 const NamedDecl *ND) {
3638 if (Size != 1 || !ND) return false;
3639
3640 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
3641 if (!FD) return false;
3642
3643 // Don't consider sizes resulting from macro expansions or template argument
3644 // substitution to form C89 tail-padded arrays.
3645 ConstantArrayTypeLoc TL =
3646 cast<ConstantArrayTypeLoc>(FD->getTypeSourceInfo()->getTypeLoc());
3647 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(TL.getSizeExpr());
3648 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
3649 return false;
3650
3651 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
3652 if (!RD || !RD->isStruct())
3653 return false;
3654
Benjamin Kramer22d4fed2011-08-06 03:04:42 +00003655 // See if this is the last field decl in the record.
3656 const Decl *D = FD;
3657 while ((D = D->getNextDeclInContext()))
3658 if (isa<FieldDecl>(D))
3659 return false;
3660 return true;
Chandler Carruthc2684342011-08-05 09:10:50 +00003661}
3662
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003663void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
3664 bool isSubscript, bool AllowOnePastEnd) {
3665 const Type* EffectiveType = getElementType(BaseExpr);
3666 BaseExpr = BaseExpr->IgnoreParenCasts();
3667 IndexExpr = IndexExpr->IgnoreParenCasts();
3668
Chandler Carruth34064582011-02-17 20:55:08 +00003669 const ConstantArrayType *ArrayTy =
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003670 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00003671 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00003672 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00003673
Chandler Carruth34064582011-02-17 20:55:08 +00003674 if (IndexExpr->isValueDependent())
Ted Kremeneka0125d82011-02-16 01:57:07 +00003675 return;
Chandler Carruth34064582011-02-17 20:55:08 +00003676 llvm::APSInt index;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003677 if (!IndexExpr->isIntegerConstantExpr(index, Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00003678 return;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00003679
Chandler Carruthba447122011-08-05 08:07:29 +00003680 const NamedDecl *ND = NULL;
Chandler Carruthba447122011-08-05 08:07:29 +00003681 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
3682 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruthc2684342011-08-05 09:10:50 +00003683 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruthba447122011-08-05 08:07:29 +00003684 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruthba447122011-08-05 08:07:29 +00003685
Ted Kremenek9e060ca2011-02-23 23:06:04 +00003686 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00003687 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00003688 if (!size.isStrictlyPositive())
3689 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003690
3691 const Type* BaseType = getElementType(BaseExpr);
3692 if (!isSubscript && BaseType != EffectiveType) {
3693 // Make sure we're comparing apples to apples when comparing index to size
3694 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
3695 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhraind10f4bc2011-08-10 19:47:25 +00003696 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhrain18f16972011-08-10 18:49:28 +00003697 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003698 if (ptrarith_typesize != array_typesize) {
3699 // There's a cast to a different size type involved
3700 uint64_t ratio = array_typesize / ptrarith_typesize;
3701 // TODO: Be smarter about handling cases where array_typesize is not a
3702 // multiple of ptrarith_typesize
3703 if (ptrarith_typesize * ratio == array_typesize)
3704 size *= llvm::APInt(size.getBitWidth(), ratio);
3705 }
3706 }
3707
Chandler Carruth34064582011-02-17 20:55:08 +00003708 if (size.getBitWidth() > index.getBitWidth())
3709 index = index.sext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00003710 else if (size.getBitWidth() < index.getBitWidth())
3711 size = size.sext(index.getBitWidth());
3712
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003713 // For array subscripting the index must be less than size, but for pointer
3714 // arithmetic also allow the index (offset) to be equal to size since
3715 // computing the next address after the end of the array is legal and
3716 // commonly done e.g. in C++ iterators and range-based for loops.
3717 if (AllowOnePastEnd ? index.sle(size) : index.slt(size))
Chandler Carruthba447122011-08-05 08:07:29 +00003718 return;
3719
3720 // Also don't warn for arrays of size 1 which are members of some
3721 // structure. These are often used to approximate flexible arrays in C89
3722 // code.
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003723 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00003724 return;
Chandler Carruth34064582011-02-17 20:55:08 +00003725
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003726 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
3727 if (isSubscript)
3728 DiagID = diag::warn_array_index_exceeds_bounds;
3729
3730 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
3731 PDiag(DiagID) << index.toString(10, true)
3732 << size.toString(10, true)
3733 << (unsigned)size.getLimitedValue(~0U)
3734 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00003735 } else {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003736 unsigned DiagID = diag::warn_array_index_precedes_bounds;
3737 if (!isSubscript) {
3738 DiagID = diag::warn_ptr_arith_precedes_bounds;
3739 if (index.isNegative()) index = -index;
3740 }
3741
3742 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
3743 PDiag(DiagID) << index.toString(10, true)
3744 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00003745 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00003746
Chandler Carruth35001ca2011-02-17 21:10:52 +00003747 if (ND)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003748 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
3749 PDiag(diag::note_array_index_out_of_bounds)
3750 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00003751}
3752
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003753void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003754 int AllowOnePastEnd = 0;
3755 while (expr) {
3756 expr = expr->IgnoreParenImpCasts();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003757 switch (expr->getStmtClass()) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003758 case Stmt::ArraySubscriptExprClass: {
3759 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
3760 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), true,
3761 AllowOnePastEnd > 0);
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003762 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003763 }
3764 case Stmt::UnaryOperatorClass: {
3765 // Only unwrap the * and & unary operators
3766 const UnaryOperator *UO = cast<UnaryOperator>(expr);
3767 expr = UO->getSubExpr();
3768 switch (UO->getOpcode()) {
3769 case UO_AddrOf:
3770 AllowOnePastEnd++;
3771 break;
3772 case UO_Deref:
3773 AllowOnePastEnd--;
3774 break;
3775 default:
3776 return;
3777 }
3778 break;
3779 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003780 case Stmt::ConditionalOperatorClass: {
3781 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
3782 if (const Expr *lhs = cond->getLHS())
3783 CheckArrayAccess(lhs);
3784 if (const Expr *rhs = cond->getRHS())
3785 CheckArrayAccess(rhs);
3786 return;
3787 }
3788 default:
3789 return;
3790 }
Peter Collingbournef111d932011-04-15 00:35:48 +00003791 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003792}
John McCallf85e1932011-06-15 23:02:42 +00003793
3794//===--- CHECK: Objective-C retain cycles ----------------------------------//
3795
3796namespace {
3797 struct RetainCycleOwner {
3798 RetainCycleOwner() : Variable(0), Indirect(false) {}
3799 VarDecl *Variable;
3800 SourceRange Range;
3801 SourceLocation Loc;
3802 bool Indirect;
3803
3804 void setLocsFrom(Expr *e) {
3805 Loc = e->getExprLoc();
3806 Range = e->getSourceRange();
3807 }
3808 };
3809}
3810
3811/// Consider whether capturing the given variable can possibly lead to
3812/// a retain cycle.
3813static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
3814 // In ARC, it's captured strongly iff the variable has __strong
3815 // lifetime. In MRR, it's captured strongly if the variable is
3816 // __block and has an appropriate type.
3817 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
3818 return false;
3819
3820 owner.Variable = var;
3821 owner.setLocsFrom(ref);
3822 return true;
3823}
3824
3825static bool findRetainCycleOwner(Expr *e, RetainCycleOwner &owner) {
3826 while (true) {
3827 e = e->IgnoreParens();
3828 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
3829 switch (cast->getCastKind()) {
3830 case CK_BitCast:
3831 case CK_LValueBitCast:
3832 case CK_LValueToRValue:
John McCall7e5e5f42011-07-07 06:58:02 +00003833 case CK_ObjCReclaimReturnedObject:
John McCallf85e1932011-06-15 23:02:42 +00003834 e = cast->getSubExpr();
3835 continue;
3836
3837 case CK_GetObjCProperty: {
3838 // Bail out if this isn't a strong explicit property.
3839 const ObjCPropertyRefExpr *pre = cast->getSubExpr()->getObjCProperty();
3840 if (pre->isImplicitProperty()) return false;
3841 ObjCPropertyDecl *property = pre->getExplicitProperty();
3842 if (!(property->getPropertyAttributes() &
3843 (ObjCPropertyDecl::OBJC_PR_retain |
3844 ObjCPropertyDecl::OBJC_PR_copy |
3845 ObjCPropertyDecl::OBJC_PR_strong)) &&
3846 !(property->getPropertyIvarDecl() &&
3847 property->getPropertyIvarDecl()->getType()
3848 .getObjCLifetime() == Qualifiers::OCL_Strong))
3849 return false;
3850
3851 owner.Indirect = true;
3852 e = const_cast<Expr*>(pre->getBase());
3853 continue;
3854 }
3855
3856 default:
3857 return false;
3858 }
3859 }
3860
3861 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
3862 ObjCIvarDecl *ivar = ref->getDecl();
3863 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
3864 return false;
3865
3866 // Try to find a retain cycle in the base.
3867 if (!findRetainCycleOwner(ref->getBase(), owner))
3868 return false;
3869
3870 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
3871 owner.Indirect = true;
3872 return true;
3873 }
3874
3875 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
3876 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
3877 if (!var) return false;
3878 return considerVariable(var, ref, owner);
3879 }
3880
3881 if (BlockDeclRefExpr *ref = dyn_cast<BlockDeclRefExpr>(e)) {
3882 owner.Variable = ref->getDecl();
3883 owner.setLocsFrom(ref);
3884 return true;
3885 }
3886
3887 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
3888 if (member->isArrow()) return false;
3889
3890 // Don't count this as an indirect ownership.
3891 e = member->getBase();
3892 continue;
3893 }
3894
3895 // Array ivars?
3896
3897 return false;
3898 }
3899}
3900
3901namespace {
3902 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
3903 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
3904 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
3905 Variable(variable), Capturer(0) {}
3906
3907 VarDecl *Variable;
3908 Expr *Capturer;
3909
3910 void VisitDeclRefExpr(DeclRefExpr *ref) {
3911 if (ref->getDecl() == Variable && !Capturer)
3912 Capturer = ref;
3913 }
3914
3915 void VisitBlockDeclRefExpr(BlockDeclRefExpr *ref) {
3916 if (ref->getDecl() == Variable && !Capturer)
3917 Capturer = ref;
3918 }
3919
3920 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
3921 if (Capturer) return;
3922 Visit(ref->getBase());
3923 if (Capturer && ref->isFreeIvar())
3924 Capturer = ref;
3925 }
3926
3927 void VisitBlockExpr(BlockExpr *block) {
3928 // Look inside nested blocks
3929 if (block->getBlockDecl()->capturesVariable(Variable))
3930 Visit(block->getBlockDecl()->getBody());
3931 }
3932 };
3933}
3934
3935/// Check whether the given argument is a block which captures a
3936/// variable.
3937static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
3938 assert(owner.Variable && owner.Loc.isValid());
3939
3940 e = e->IgnoreParenCasts();
3941 BlockExpr *block = dyn_cast<BlockExpr>(e);
3942 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
3943 return 0;
3944
3945 FindCaptureVisitor visitor(S.Context, owner.Variable);
3946 visitor.Visit(block->getBlockDecl()->getBody());
3947 return visitor.Capturer;
3948}
3949
3950static void diagnoseRetainCycle(Sema &S, Expr *capturer,
3951 RetainCycleOwner &owner) {
3952 assert(capturer);
3953 assert(owner.Variable && owner.Loc.isValid());
3954
3955 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
3956 << owner.Variable << capturer->getSourceRange();
3957 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
3958 << owner.Indirect << owner.Range;
3959}
3960
3961/// Check for a keyword selector that starts with the word 'add' or
3962/// 'set'.
3963static bool isSetterLikeSelector(Selector sel) {
3964 if (sel.isUnarySelector()) return false;
3965
Chris Lattner5f9e2722011-07-23 10:55:15 +00003966 StringRef str = sel.getNameForSlot(0);
John McCallf85e1932011-06-15 23:02:42 +00003967 while (!str.empty() && str.front() == '_') str = str.substr(1);
3968 if (str.startswith("set") || str.startswith("add"))
3969 str = str.substr(3);
3970 else
3971 return false;
3972
3973 if (str.empty()) return true;
3974 return !islower(str.front());
3975}
3976
3977/// Check a message send to see if it's likely to cause a retain cycle.
3978void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
3979 // Only check instance methods whose selector looks like a setter.
3980 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
3981 return;
3982
3983 // Try to find a variable that the receiver is strongly owned by.
3984 RetainCycleOwner owner;
3985 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
3986 if (!findRetainCycleOwner(msg->getInstanceReceiver(), owner))
3987 return;
3988 } else {
3989 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
3990 owner.Variable = getCurMethodDecl()->getSelfDecl();
3991 owner.Loc = msg->getSuperLoc();
3992 owner.Range = msg->getSuperLoc();
3993 }
3994
3995 // Check whether the receiver is captured by any of the arguments.
3996 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
3997 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
3998 return diagnoseRetainCycle(*this, capturer, owner);
3999}
4000
4001/// Check a property assign to see if it's likely to cause a retain cycle.
4002void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
4003 RetainCycleOwner owner;
4004 if (!findRetainCycleOwner(receiver, owner))
4005 return;
4006
4007 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
4008 diagnoseRetainCycle(*this, capturer, owner);
4009}
4010
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004011bool Sema::checkUnsafeAssigns(SourceLocation Loc,
John McCallf85e1932011-06-15 23:02:42 +00004012 QualType LHS, Expr *RHS) {
4013 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
4014 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004015 return false;
4016 // strip off any implicit cast added to get to the one arc-specific
4017 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
4018 if (cast->getCastKind() == CK_ObjCConsumeObject) {
John McCallf85e1932011-06-15 23:02:42 +00004019 Diag(Loc, diag::warn_arc_retained_assign)
4020 << (LT == Qualifiers::OCL_ExplicitNone)
4021 << RHS->getSourceRange();
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004022 return true;
4023 }
4024 RHS = cast->getSubExpr();
4025 }
4026 return false;
John McCallf85e1932011-06-15 23:02:42 +00004027}
4028
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004029void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
4030 Expr *LHS, Expr *RHS) {
4031 QualType LHSType = LHS->getType();
4032 if (checkUnsafeAssigns(Loc, LHSType, RHS))
4033 return;
4034 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
4035 // FIXME. Check for other life times.
4036 if (LT != Qualifiers::OCL_None)
4037 return;
4038
4039 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(LHS)) {
4040 if (PRE->isImplicitProperty())
4041 return;
4042 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
4043 if (!PD)
4044 return;
4045
4046 unsigned Attributes = PD->getPropertyAttributes();
4047 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign)
4048 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
4049 if (cast->getCastKind() == CK_ObjCConsumeObject) {
4050 Diag(Loc, diag::warn_arc_retained_property_assign)
4051 << RHS->getSourceRange();
4052 return;
4053 }
4054 RHS = cast->getSubExpr();
4055 }
4056 }
4057}