blob: 90b9738039849bb556cb150947dd5f13e7c181f2 [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"
Eli Friedman276b0612011-10-11 02:20:01 +000018#include "clang/Sema/Initialization.h"
John McCall781472f2010-08-25 08:40:02 +000019#include "clang/Sema/ScopeInfo.h"
Ted Kremenek826a3452010-07-16 02:11:22 +000020#include "clang/Analysis/Analyses/FormatString.h"
Chris Lattner59907c42007-08-10 20:18:51 +000021#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000022#include "clang/AST/CharUnits.h"
John McCall384aff82010-08-25 07:42:41 +000023#include "clang/AST/DeclCXX.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000024#include "clang/AST/DeclObjC.h"
Ted Kremenek23245122007-08-20 16:18:38 +000025#include "clang/AST/ExprCXX.h"
Ted Kremenek7ff22b22008-06-16 18:00:42 +000026#include "clang/AST/ExprObjC.h"
John McCallf85e1932011-06-15 23:02:42 +000027#include "clang/AST/EvaluatedExprVisitor.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000028#include "clang/AST/DeclObjC.h"
29#include "clang/AST/StmtCXX.h"
30#include "clang/AST/StmtObjC.h"
Chris Lattner59907c42007-08-10 20:18:51 +000031#include "clang/Lex/Preprocessor.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000032#include "llvm/ADT/BitVector.h"
33#include "llvm/ADT/STLExtras.h"
Tom Care3bfc5f42010-06-09 04:11:11 +000034#include "llvm/Support/raw_ostream.h"
Eric Christopher691ebc32010-04-17 02:26:23 +000035#include "clang/Basic/TargetBuiltins.h"
Nate Begeman26a31422010-06-08 02:47:44 +000036#include "clang/Basic/TargetInfo.h"
Fariborz Jahanian7da71022010-09-07 19:38:13 +000037#include "clang/Basic/ConvertUTF.h"
Zhongxing Xua1f3dba2009-05-20 01:55:10 +000038#include <limits>
Chris Lattner59907c42007-08-10 20:18:51 +000039using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000040using namespace sema;
Chris Lattner59907c42007-08-10 20:18:51 +000041
Chris Lattner60800082009-02-18 17:49:48 +000042SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
43 unsigned ByteNo) const {
Chris Lattner08f92e32010-11-17 07:37:15 +000044 return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
45 PP.getLangOptions(), PP.getTargetInfo());
Chris Lattner60800082009-02-18 17:49:48 +000046}
Chris Lattner08f92e32010-11-17 07:37:15 +000047
Chris Lattner60800082009-02-18 17:49:48 +000048
Ryan Flynn4403a5e2009-08-06 03:00:50 +000049/// CheckablePrintfAttr - does a function call have a "printf" attribute
50/// and arguments that merit checking?
51bool Sema::CheckablePrintfAttr(const FormatAttr *Format, CallExpr *TheCall) {
52 if (Format->getType() == "printf") return true;
53 if (Format->getType() == "printf0") {
54 // printf0 allows null "format" string; if so don't check format/args
55 unsigned format_idx = Format->getFormatIdx() - 1;
Sebastian Redl4a2614e2009-11-17 18:02:24 +000056 // Does the index refer to the implicit object argument?
57 if (isa<CXXMemberCallExpr>(TheCall)) {
58 if (format_idx == 0)
59 return false;
60 --format_idx;
61 }
Ryan Flynn4403a5e2009-08-06 03:00:50 +000062 if (format_idx < TheCall->getNumArgs()) {
63 Expr *Format = TheCall->getArg(format_idx)->IgnoreParenCasts();
Ted Kremenekefaff192010-02-27 01:41:03 +000064 if (!Format->isNullPointerConstant(Context,
65 Expr::NPC_ValueDependentIsNull))
Ryan Flynn4403a5e2009-08-06 03:00:50 +000066 return true;
67 }
68 }
69 return false;
70}
Chris Lattner60800082009-02-18 17:49:48 +000071
John McCall8e10f3b2011-02-26 05:39:39 +000072/// Checks that a call expression's argument count is the desired number.
73/// This is useful when doing custom type-checking. Returns true on error.
74static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
75 unsigned argCount = call->getNumArgs();
76 if (argCount == desiredArgCount) return false;
77
78 if (argCount < desiredArgCount)
79 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
80 << 0 /*function call*/ << desiredArgCount << argCount
81 << call->getSourceRange();
82
83 // Highlight all the excess arguments.
84 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
85 call->getArg(argCount - 1)->getLocEnd());
86
87 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
88 << 0 /*function call*/ << desiredArgCount << argCount
89 << call->getArg(1)->getSourceRange();
90}
91
Julien Lerouge77f68bb2011-09-09 22:41:49 +000092/// CheckBuiltinAnnotationString - Checks that string argument to the builtin
93/// annotation is a non wide string literal.
94static bool CheckBuiltinAnnotationString(Sema &S, Expr *Arg) {
95 Arg = Arg->IgnoreParenCasts();
96 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
97 if (!Literal || !Literal->isAscii()) {
98 S.Diag(Arg->getLocStart(), diag::err_builtin_annotation_not_string_constant)
99 << Arg->getSourceRange();
100 return true;
101 }
102 return false;
103}
104
John McCall60d7b3a2010-08-24 06:29:42 +0000105ExprResult
Anders Carlssond406bf02009-08-16 01:56:34 +0000106Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
John McCall60d7b3a2010-08-24 06:29:42 +0000107 ExprResult TheCallResult(Owned(TheCall));
Douglas Gregor2def4832008-11-17 20:34:05 +0000108
Chris Lattner946928f2010-10-01 23:23:24 +0000109 // Find out if any arguments are required to be integer constant expressions.
110 unsigned ICEArguments = 0;
111 ASTContext::GetBuiltinTypeError Error;
112 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
113 if (Error != ASTContext::GE_None)
114 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
115
116 // If any arguments are required to be ICE's, check and diagnose.
117 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
118 // Skip arguments not required to be ICE's.
119 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
120
121 llvm::APSInt Result;
122 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
123 return true;
124 ICEArguments &= ~(1 << ArgNo);
125 }
126
Anders Carlssond406bf02009-08-16 01:56:34 +0000127 switch (BuiltinID) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000128 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +0000129 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +0000130 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner69039812009-02-18 06:01:06 +0000131 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000132 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000133 break;
Ted Kremenek49ff7a12008-07-09 17:58:53 +0000134 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +0000135 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000136 if (SemaBuiltinVAStart(TheCall))
137 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000138 break;
Chris Lattner1b9a0792007-12-20 00:26:33 +0000139 case Builtin::BI__builtin_isgreater:
140 case Builtin::BI__builtin_isgreaterequal:
141 case Builtin::BI__builtin_isless:
142 case Builtin::BI__builtin_islessequal:
143 case Builtin::BI__builtin_islessgreater:
144 case Builtin::BI__builtin_isunordered:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000145 if (SemaBuiltinUnorderedCompare(TheCall))
146 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000147 break;
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000148 case Builtin::BI__builtin_fpclassify:
149 if (SemaBuiltinFPClassification(TheCall, 6))
150 return ExprError();
151 break;
Eli Friedman9ac6f622009-08-31 20:06:00 +0000152 case Builtin::BI__builtin_isfinite:
153 case Builtin::BI__builtin_isinf:
154 case Builtin::BI__builtin_isinf_sign:
155 case Builtin::BI__builtin_isnan:
156 case Builtin::BI__builtin_isnormal:
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000157 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman9ac6f622009-08-31 20:06:00 +0000158 return ExprError();
159 break;
Eli Friedmand38617c2008-05-14 19:38:39 +0000160 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000161 return SemaBuiltinShuffleVector(TheCall);
162 // TheCall will be freed by the smart pointer here, but that's fine, since
163 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000164 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000165 if (SemaBuiltinPrefetch(TheCall))
166 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000167 break;
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000168 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000169 if (SemaBuiltinObjectSize(TheCall))
170 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000171 break;
Eli Friedmand875fed2009-05-03 04:46:36 +0000172 case Builtin::BI__builtin_longjmp:
173 if (SemaBuiltinLongjmp(TheCall))
174 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000175 break;
John McCall8e10f3b2011-02-26 05:39:39 +0000176
177 case Builtin::BI__builtin_classify_type:
178 if (checkArgCount(*this, TheCall, 1)) return true;
179 TheCall->setType(Context.IntTy);
180 break;
Chris Lattner75c29a02010-10-12 17:47:42 +0000181 case Builtin::BI__builtin_constant_p:
John McCall8e10f3b2011-02-26 05:39:39 +0000182 if (checkArgCount(*this, TheCall, 1)) return true;
183 TheCall->setType(Context.IntTy);
Chris Lattner75c29a02010-10-12 17:47:42 +0000184 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000185 case Builtin::BI__sync_fetch_and_add:
186 case Builtin::BI__sync_fetch_and_sub:
187 case Builtin::BI__sync_fetch_and_or:
188 case Builtin::BI__sync_fetch_and_and:
189 case Builtin::BI__sync_fetch_and_xor:
190 case Builtin::BI__sync_add_and_fetch:
191 case Builtin::BI__sync_sub_and_fetch:
192 case Builtin::BI__sync_and_and_fetch:
193 case Builtin::BI__sync_or_and_fetch:
194 case Builtin::BI__sync_xor_and_fetch:
195 case Builtin::BI__sync_val_compare_and_swap:
196 case Builtin::BI__sync_bool_compare_and_swap:
197 case Builtin::BI__sync_lock_test_and_set:
198 case Builtin::BI__sync_lock_release:
Chris Lattner23aa9c82011-04-09 03:57:26 +0000199 case Builtin::BI__sync_swap:
Chandler Carruthd2014572010-07-09 18:59:35 +0000200 return SemaBuiltinAtomicOverloaded(move(TheCallResult));
Eli Friedman276b0612011-10-11 02:20:01 +0000201 case Builtin::BI__atomic_load:
202 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Load);
203 case Builtin::BI__atomic_store:
204 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Store);
205 case Builtin::BI__atomic_exchange:
206 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Xchg);
207 case Builtin::BI__atomic_compare_exchange_strong:
208 return SemaAtomicOpsOverloaded(move(TheCallResult),
209 AtomicExpr::CmpXchgStrong);
210 case Builtin::BI__atomic_compare_exchange_weak:
211 return SemaAtomicOpsOverloaded(move(TheCallResult),
212 AtomicExpr::CmpXchgWeak);
213 case Builtin::BI__atomic_fetch_add:
214 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Add);
215 case Builtin::BI__atomic_fetch_sub:
216 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Sub);
217 case Builtin::BI__atomic_fetch_and:
218 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::And);
219 case Builtin::BI__atomic_fetch_or:
220 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Or);
221 case Builtin::BI__atomic_fetch_xor:
222 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Xor);
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000223 case Builtin::BI__builtin_annotation:
224 if (CheckBuiltinAnnotationString(*this, TheCall->getArg(1)))
225 return ExprError();
226 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000227 }
228
229 // Since the target specific builtins for each arch overlap, only check those
230 // of the arch we are compiling for.
231 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000232 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman26a31422010-06-08 02:47:44 +0000233 case llvm::Triple::arm:
234 case llvm::Triple::thumb:
235 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
236 return ExprError();
237 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000238 default:
239 break;
240 }
241 }
242
243 return move(TheCallResult);
244}
245
Nate Begeman61eecf52010-06-14 05:21:25 +0000246// Get the valid immediate range for the specified NEON type code.
247static unsigned RFT(unsigned t, bool shift = false) {
Bob Wilsonda95f732011-11-08 01:16:11 +0000248 NeonTypeFlags Type(t);
249 int IsQuad = Type.isQuad();
250 switch (Type.getEltType()) {
251 case NeonTypeFlags::Int8:
252 case NeonTypeFlags::Poly8:
253 return shift ? 7 : (8 << IsQuad) - 1;
254 case NeonTypeFlags::Int16:
255 case NeonTypeFlags::Poly16:
256 return shift ? 15 : (4 << IsQuad) - 1;
257 case NeonTypeFlags::Int32:
258 return shift ? 31 : (2 << IsQuad) - 1;
259 case NeonTypeFlags::Int64:
260 return shift ? 63 : (1 << IsQuad) - 1;
261 case NeonTypeFlags::Float16:
262 assert(!shift && "cannot shift float types!");
263 return (4 << IsQuad) - 1;
264 case NeonTypeFlags::Float32:
265 assert(!shift && "cannot shift float types!");
266 return (2 << IsQuad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000267 }
268 return 0;
269}
270
Nate Begeman26a31422010-06-08 02:47:44 +0000271bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000272 llvm::APSInt Result;
273
Nate Begeman0d15c532010-06-13 04:47:52 +0000274 unsigned mask = 0;
Nate Begeman61eecf52010-06-14 05:21:25 +0000275 unsigned TV = 0;
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000276 switch (BuiltinID) {
Nate Begemana23326b2010-06-17 04:17:01 +0000277#define GET_NEON_OVERLOAD_CHECK
278#include "clang/Basic/arm_neon.inc"
279#undef GET_NEON_OVERLOAD_CHECK
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000280 }
281
Nate Begeman0d15c532010-06-13 04:47:52 +0000282 // For NEON intrinsics which are overloaded on vector element type, validate
283 // the immediate which specifies which variant to emit.
284 if (mask) {
285 unsigned ArgNo = TheCall->getNumArgs()-1;
286 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
287 return true;
288
Bob Wilsonda95f732011-11-08 01:16:11 +0000289 TV = Result.getLimitedValue(64);
290 if ((TV > 63) || (mask & (1 << TV)) == 0)
Nate Begeman0d15c532010-06-13 04:47:52 +0000291 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
292 << TheCall->getArg(ArgNo)->getSourceRange();
293 }
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000294
Nate Begeman0d15c532010-06-13 04:47:52 +0000295 // For NEON intrinsics which take an immediate value as part of the
296 // instruction, range check them here.
Nate Begeman61eecf52010-06-14 05:21:25 +0000297 unsigned i = 0, l = 0, u = 0;
Nate Begeman0d15c532010-06-13 04:47:52 +0000298 switch (BuiltinID) {
299 default: return false;
Nate Begemanbb37f502010-07-29 22:48:34 +0000300 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
301 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begeman99c40bb2010-08-03 21:32:34 +0000302 case ARM::BI__builtin_arm_vcvtr_f:
303 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Nate Begemana23326b2010-06-17 04:17:01 +0000304#define GET_NEON_IMMEDIATE_CHECK
305#include "clang/Basic/arm_neon.inc"
306#undef GET_NEON_IMMEDIATE_CHECK
Nate Begeman0d15c532010-06-13 04:47:52 +0000307 };
308
Nate Begeman61eecf52010-06-14 05:21:25 +0000309 // Check that the immediate argument is actually a constant.
Nate Begeman0d15c532010-06-13 04:47:52 +0000310 if (SemaBuiltinConstantArg(TheCall, i, Result))
311 return true;
312
Nate Begeman61eecf52010-06-14 05:21:25 +0000313 // Range check against the upper/lower values for this isntruction.
Nate Begeman0d15c532010-06-13 04:47:52 +0000314 unsigned Val = Result.getZExtValue();
Nate Begeman61eecf52010-06-14 05:21:25 +0000315 if (Val < l || Val > (u + l))
Nate Begeman0d15c532010-06-13 04:47:52 +0000316 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramer476d8b82010-08-11 14:47:12 +0000317 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begeman0d15c532010-06-13 04:47:52 +0000318
Nate Begeman99c40bb2010-08-03 21:32:34 +0000319 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman26a31422010-06-08 02:47:44 +0000320 return false;
Anders Carlssond406bf02009-08-16 01:56:34 +0000321}
Daniel Dunbarde454282008-10-02 18:44:07 +0000322
Anders Carlssond406bf02009-08-16 01:56:34 +0000323/// CheckFunctionCall - Check a direct function call for various correctness
324/// and safety properties not strictly enforced by the C type system.
325bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
326 // Get the IdentifierInfo* for the called function.
327 IdentifierInfo *FnInfo = FDecl->getIdentifier();
328
329 // None of the checks below are needed for functions that don't have
330 // simple names (e.g., C++ conversion functions).
331 if (!FnInfo)
332 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000333
Daniel Dunbarde454282008-10-02 18:44:07 +0000334 // FIXME: This mechanism should be abstracted to be less fragile and
335 // more efficient. For example, just map function ids to custom
336 // handlers.
337
Ted Kremenekc82faca2010-09-09 04:33:05 +0000338 // Printf and scanf checking.
339 for (specific_attr_iterator<FormatAttr>
340 i = FDecl->specific_attr_begin<FormatAttr>(),
341 e = FDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) {
342
343 const FormatAttr *Format = *i;
Ted Kremenek826a3452010-07-16 02:11:22 +0000344 const bool b = Format->getType() == "scanf";
345 if (b || CheckablePrintfAttr(Format, TheCall)) {
Ted Kremenek3d692df2009-02-27 17:58:43 +0000346 bool HasVAListArg = Format->getFirstArg() == 0;
Ted Kremenek826a3452010-07-16 02:11:22 +0000347 CheckPrintfScanfArguments(TheCall, HasVAListArg,
348 Format->getFormatIdx() - 1,
349 HasVAListArg ? 0 : Format->getFirstArg() - 1,
350 !b);
Douglas Gregor3c385e52009-02-14 18:57:46 +0000351 }
Chris Lattner59907c42007-08-10 20:18:51 +0000352 }
Mike Stump1eb44332009-09-09 15:08:12 +0000353
Ted Kremenekc82faca2010-09-09 04:33:05 +0000354 for (specific_attr_iterator<NonNullAttr>
355 i = FDecl->specific_attr_begin<NonNullAttr>(),
356 e = FDecl->specific_attr_end<NonNullAttr>(); i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +0000357 CheckNonNullArguments(*i, TheCall->getArgs(),
358 TheCall->getCallee()->getLocStart());
Ted Kremenekc82faca2010-09-09 04:33:05 +0000359 }
Sebastian Redl0eb23302009-01-19 00:08:26 +0000360
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000361 // Builtin handling
Douglas Gregor707a23e2011-06-16 17:56:04 +0000362 int CMF = -1;
363 switch (FDecl->getBuiltinID()) {
364 case Builtin::BI__builtin_memset:
365 case Builtin::BI__builtin___memset_chk:
366 case Builtin::BImemset:
367 CMF = CMF_Memset;
368 break;
369
370 case Builtin::BI__builtin_memcpy:
371 case Builtin::BI__builtin___memcpy_chk:
372 case Builtin::BImemcpy:
373 CMF = CMF_Memcpy;
374 break;
375
376 case Builtin::BI__builtin_memmove:
377 case Builtin::BI__builtin___memmove_chk:
378 case Builtin::BImemmove:
379 CMF = CMF_Memmove;
380 break;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000381
382 case Builtin::BIstrlcpy:
383 case Builtin::BIstrlcat:
384 CheckStrlcpycatArguments(TheCall, FnInfo);
385 break;
Douglas Gregor707a23e2011-06-16 17:56:04 +0000386
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +0000387 case Builtin::BI__builtin_memcmp:
388 CMF = CMF_Memcmp;
389 break;
390
Nico Webercda57822011-10-13 22:30:23 +0000391 case Builtin::BI__builtin_strncpy:
392 case Builtin::BI__builtin___strncpy_chk:
393 case Builtin::BIstrncpy:
394 CMF = CMF_Strncpy;
395 break;
396
397 case Builtin::BI__builtin_strncmp:
398 CMF = CMF_Strncmp;
399 break;
400
401 case Builtin::BI__builtin_strncasecmp:
402 CMF = CMF_Strncasecmp;
403 break;
404
405 case Builtin::BI__builtin_strncat:
406 case Builtin::BIstrncat:
407 CMF = CMF_Strncat;
408 break;
409
410 case Builtin::BI__builtin_strndup:
411 case Builtin::BIstrndup:
412 CMF = CMF_Strndup;
413 break;
414
Douglas Gregor707a23e2011-06-16 17:56:04 +0000415 default:
416 if (FDecl->getLinkage() == ExternalLinkage &&
417 (!getLangOptions().CPlusPlus || FDecl->isExternC())) {
418 if (FnInfo->isStr("memset"))
419 CMF = CMF_Memset;
420 else if (FnInfo->isStr("memcpy"))
421 CMF = CMF_Memcpy;
422 else if (FnInfo->isStr("memmove"))
423 CMF = CMF_Memmove;
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +0000424 else if (FnInfo->isStr("memcmp"))
425 CMF = CMF_Memcmp;
Nico Webercda57822011-10-13 22:30:23 +0000426 else if (FnInfo->isStr("strncpy"))
427 CMF = CMF_Strncpy;
428 else if (FnInfo->isStr("strncmp"))
429 CMF = CMF_Strncmp;
430 else if (FnInfo->isStr("strncasecmp"))
431 CMF = CMF_Strncasecmp;
432 else if (FnInfo->isStr("strncat"))
433 CMF = CMF_Strncat;
434 else if (FnInfo->isStr("strndup"))
435 CMF = CMF_Strndup;
Douglas Gregor707a23e2011-06-16 17:56:04 +0000436 }
437 break;
Douglas Gregor06bc9eb2011-05-03 20:37:33 +0000438 }
Douglas Gregor707a23e2011-06-16 17:56:04 +0000439
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000440 // Memset/memcpy/memmove handling
Douglas Gregor707a23e2011-06-16 17:56:04 +0000441 if (CMF != -1)
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +0000442 CheckMemaccessArguments(TheCall, CheckedMemoryFunction(CMF), FnInfo);
Chandler Carruth7ccc95b2011-04-27 07:05:31 +0000443
Anders Carlssond406bf02009-08-16 01:56:34 +0000444 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000445}
446
Anders Carlssond406bf02009-08-16 01:56:34 +0000447bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000448 // Printf checking.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000449 const FormatAttr *Format = NDecl->getAttr<FormatAttr>();
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000450 if (!Format)
Anders Carlssond406bf02009-08-16 01:56:34 +0000451 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000452
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000453 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
454 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000455 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000456
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000457 QualType Ty = V->getType();
458 if (!Ty->isBlockPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000459 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000460
Ted Kremenek826a3452010-07-16 02:11:22 +0000461 const bool b = Format->getType() == "scanf";
462 if (!b && !CheckablePrintfAttr(Format, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +0000463 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000464
Anders Carlssond406bf02009-08-16 01:56:34 +0000465 bool HasVAListArg = Format->getFirstArg() == 0;
Ted Kremenek826a3452010-07-16 02:11:22 +0000466 CheckPrintfScanfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
467 HasVAListArg ? 0 : Format->getFirstArg() - 1, !b);
Anders Carlssond406bf02009-08-16 01:56:34 +0000468
469 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000470}
471
Eli Friedman276b0612011-10-11 02:20:01 +0000472ExprResult
473Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, AtomicExpr::AtomicOp Op) {
474 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
475 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedman276b0612011-10-11 02:20:01 +0000476
477 // All these operations take one of the following four forms:
478 // T __atomic_load(_Atomic(T)*, int) (loads)
479 // T* __atomic_add(_Atomic(T*)*, ptrdiff_t, int) (pointer add/sub)
480 // int __atomic_compare_exchange_strong(_Atomic(T)*, T*, T, int, int)
481 // (cmpxchg)
482 // T __atomic_exchange(_Atomic(T)*, T, int) (everything else)
483 // where T is an appropriate type, and the int paremeterss are for orderings.
484 unsigned NumVals = 1;
485 unsigned NumOrders = 1;
486 if (Op == AtomicExpr::Load) {
487 NumVals = 0;
488 } else if (Op == AtomicExpr::CmpXchgWeak || Op == AtomicExpr::CmpXchgStrong) {
489 NumVals = 2;
490 NumOrders = 2;
491 }
492
493 if (TheCall->getNumArgs() < NumVals+NumOrders+1) {
494 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
495 << 0 << NumVals+NumOrders+1 << TheCall->getNumArgs()
496 << TheCall->getCallee()->getSourceRange();
497 return ExprError();
498 } else if (TheCall->getNumArgs() > NumVals+NumOrders+1) {
499 Diag(TheCall->getArg(NumVals+NumOrders+1)->getLocStart(),
500 diag::err_typecheck_call_too_many_args)
501 << 0 << NumVals+NumOrders+1 << TheCall->getNumArgs()
502 << TheCall->getCallee()->getSourceRange();
503 return ExprError();
504 }
505
506 // Inspect the first argument of the atomic operation. This should always be
507 // a pointer to an _Atomic type.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000508 Expr *Ptr = TheCall->getArg(0);
Eli Friedman276b0612011-10-11 02:20:01 +0000509 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
510 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
511 if (!pointerType) {
512 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
513 << Ptr->getType() << Ptr->getSourceRange();
514 return ExprError();
515 }
516
517 QualType AtomTy = pointerType->getPointeeType();
518 if (!AtomTy->isAtomicType()) {
519 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
520 << Ptr->getType() << Ptr->getSourceRange();
521 return ExprError();
522 }
523 QualType ValType = AtomTy->getAs<AtomicType>()->getValueType();
524
525 if ((Op == AtomicExpr::Add || Op == AtomicExpr::Sub) &&
526 !ValType->isIntegerType() && !ValType->isPointerType()) {
527 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
528 << Ptr->getType() << Ptr->getSourceRange();
529 return ExprError();
530 }
531
532 if (!ValType->isIntegerType() &&
533 (Op == AtomicExpr::And || Op == AtomicExpr::Or || Op == AtomicExpr::Xor)){
534 Diag(DRE->getLocStart(), diag::err_atomic_op_logical_needs_atomic_int)
535 << Ptr->getType() << Ptr->getSourceRange();
536 return ExprError();
537 }
538
539 switch (ValType.getObjCLifetime()) {
540 case Qualifiers::OCL_None:
541 case Qualifiers::OCL_ExplicitNone:
542 // okay
543 break;
544
545 case Qualifiers::OCL_Weak:
546 case Qualifiers::OCL_Strong:
547 case Qualifiers::OCL_Autoreleasing:
548 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
549 << ValType << Ptr->getSourceRange();
550 return ExprError();
551 }
552
553 QualType ResultType = ValType;
554 if (Op == AtomicExpr::Store)
555 ResultType = Context.VoidTy;
556 else if (Op == AtomicExpr::CmpXchgWeak || Op == AtomicExpr::CmpXchgStrong)
557 ResultType = Context.BoolTy;
558
559 // The first argument --- the pointer --- has a fixed type; we
560 // deduce the types of the rest of the arguments accordingly. Walk
561 // the remaining arguments, converting them to the deduced value type.
562 for (unsigned i = 1; i != NumVals+NumOrders+1; ++i) {
563 ExprResult Arg = TheCall->getArg(i);
564 QualType Ty;
565 if (i < NumVals+1) {
566 // The second argument to a cmpxchg is a pointer to the data which will
567 // be exchanged. The second argument to a pointer add/subtract is the
568 // amount to add/subtract, which must be a ptrdiff_t. The third
569 // argument to a cmpxchg and the second argument in all other cases
570 // is the type of the value.
571 if (i == 1 && (Op == AtomicExpr::CmpXchgWeak ||
572 Op == AtomicExpr::CmpXchgStrong))
573 Ty = Context.getPointerType(ValType.getUnqualifiedType());
574 else if (!ValType->isIntegerType() &&
575 (Op == AtomicExpr::Add || Op == AtomicExpr::Sub))
576 Ty = Context.getPointerDiffType();
577 else
578 Ty = ValType;
579 } else {
580 // The order(s) are always converted to int.
581 Ty = Context.IntTy;
582 }
583 InitializedEntity Entity =
584 InitializedEntity::InitializeParameter(Context, Ty, false);
585 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
586 if (Arg.isInvalid())
587 return true;
588 TheCall->setArg(i, Arg.get());
589 }
590
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000591 SmallVector<Expr*, 5> SubExprs;
592 SubExprs.push_back(Ptr);
Eli Friedman276b0612011-10-11 02:20:01 +0000593 if (Op == AtomicExpr::Load) {
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000594 SubExprs.push_back(TheCall->getArg(1)); // Order
Eli Friedman276b0612011-10-11 02:20:01 +0000595 } else if (Op != AtomicExpr::CmpXchgWeak && Op != AtomicExpr::CmpXchgStrong) {
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000596 SubExprs.push_back(TheCall->getArg(2)); // Order
597 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman276b0612011-10-11 02:20:01 +0000598 } else {
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000599 SubExprs.push_back(TheCall->getArg(3)); // Order
600 SubExprs.push_back(TheCall->getArg(1)); // Val1
601 SubExprs.push_back(TheCall->getArg(2)); // Val2
602 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
Eli Friedman276b0612011-10-11 02:20:01 +0000603 }
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000604
605 return Owned(new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
606 SubExprs.data(), SubExprs.size(),
607 ResultType, Op,
608 TheCall->getRParenLoc()));
Eli Friedman276b0612011-10-11 02:20:01 +0000609}
610
611
John McCall5f8d6042011-08-27 01:09:30 +0000612/// checkBuiltinArgument - Given a call to a builtin function, perform
613/// normal type-checking on the given argument, updating the call in
614/// place. This is useful when a builtin function requires custom
615/// type-checking for some of its arguments but not necessarily all of
616/// them.
617///
618/// Returns true on error.
619static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
620 FunctionDecl *Fn = E->getDirectCallee();
621 assert(Fn && "builtin call without direct callee!");
622
623 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
624 InitializedEntity Entity =
625 InitializedEntity::InitializeParameter(S.Context, Param);
626
627 ExprResult Arg = E->getArg(0);
628 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
629 if (Arg.isInvalid())
630 return true;
631
632 E->setArg(ArgIndex, Arg.take());
633 return false;
634}
635
Chris Lattner5caa3702009-05-08 06:58:22 +0000636/// SemaBuiltinAtomicOverloaded - We have a call to a function like
637/// __sync_fetch_and_add, which is an overloaded function based on the pointer
638/// type of its first argument. The main ActOnCallExpr routines have already
639/// promoted the types of arguments because all of these calls are prototyped as
640/// void(...).
641///
642/// This function goes through and does final semantic checking for these
643/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +0000644ExprResult
645Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000646 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +0000647 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
648 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
649
650 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +0000651 if (TheCall->getNumArgs() < 1) {
652 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
653 << 0 << 1 << TheCall->getNumArgs()
654 << TheCall->getCallee()->getSourceRange();
655 return ExprError();
656 }
Mike Stump1eb44332009-09-09 15:08:12 +0000657
Chris Lattner5caa3702009-05-08 06:58:22 +0000658 // Inspect the first argument of the atomic builtin. This should always be
659 // a pointer type, whose element is an integral scalar or pointer type.
660 // Because it is a pointer type, we don't have to worry about any implicit
661 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +0000662 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +0000663 Expr *FirstArg = TheCall->getArg(0);
John McCallf85e1932011-06-15 23:02:42 +0000664 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
665 if (!pointerType) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000666 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
667 << FirstArg->getType() << FirstArg->getSourceRange();
668 return ExprError();
669 }
Mike Stump1eb44332009-09-09 15:08:12 +0000670
John McCallf85e1932011-06-15 23:02:42 +0000671 QualType ValType = pointerType->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +0000672 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +0000673 !ValType->isBlockPointerType()) {
674 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
675 << FirstArg->getType() << FirstArg->getSourceRange();
676 return ExprError();
677 }
Chris Lattner5caa3702009-05-08 06:58:22 +0000678
John McCallf85e1932011-06-15 23:02:42 +0000679 switch (ValType.getObjCLifetime()) {
680 case Qualifiers::OCL_None:
681 case Qualifiers::OCL_ExplicitNone:
682 // okay
683 break;
684
685 case Qualifiers::OCL_Weak:
686 case Qualifiers::OCL_Strong:
687 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +0000688 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCallf85e1932011-06-15 23:02:42 +0000689 << ValType << FirstArg->getSourceRange();
690 return ExprError();
691 }
692
John McCallb45ae252011-10-05 07:41:44 +0000693 // Strip any qualifiers off ValType.
694 ValType = ValType.getUnqualifiedType();
695
Chandler Carruth8d13d222010-07-18 20:54:12 +0000696 // The majority of builtins return a value, but a few have special return
697 // types, so allow them to override appropriately below.
698 QualType ResultType = ValType;
699
Chris Lattner5caa3702009-05-08 06:58:22 +0000700 // We need to figure out which concrete builtin this maps onto. For example,
701 // __sync_fetch_and_add with a 2 byte object turns into
702 // __sync_fetch_and_add_2.
703#define BUILTIN_ROW(x) \
704 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
705 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +0000706
Chris Lattner5caa3702009-05-08 06:58:22 +0000707 static const unsigned BuiltinIndices[][5] = {
708 BUILTIN_ROW(__sync_fetch_and_add),
709 BUILTIN_ROW(__sync_fetch_and_sub),
710 BUILTIN_ROW(__sync_fetch_and_or),
711 BUILTIN_ROW(__sync_fetch_and_and),
712 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +0000713
Chris Lattner5caa3702009-05-08 06:58:22 +0000714 BUILTIN_ROW(__sync_add_and_fetch),
715 BUILTIN_ROW(__sync_sub_and_fetch),
716 BUILTIN_ROW(__sync_and_and_fetch),
717 BUILTIN_ROW(__sync_or_and_fetch),
718 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +0000719
Chris Lattner5caa3702009-05-08 06:58:22 +0000720 BUILTIN_ROW(__sync_val_compare_and_swap),
721 BUILTIN_ROW(__sync_bool_compare_and_swap),
722 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner23aa9c82011-04-09 03:57:26 +0000723 BUILTIN_ROW(__sync_lock_release),
724 BUILTIN_ROW(__sync_swap)
Chris Lattner5caa3702009-05-08 06:58:22 +0000725 };
Mike Stump1eb44332009-09-09 15:08:12 +0000726#undef BUILTIN_ROW
727
Chris Lattner5caa3702009-05-08 06:58:22 +0000728 // Determine the index of the size.
729 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +0000730 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +0000731 case 1: SizeIndex = 0; break;
732 case 2: SizeIndex = 1; break;
733 case 4: SizeIndex = 2; break;
734 case 8: SizeIndex = 3; break;
735 case 16: SizeIndex = 4; break;
736 default:
Chandler Carruthd2014572010-07-09 18:59:35 +0000737 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
738 << FirstArg->getType() << FirstArg->getSourceRange();
739 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +0000740 }
Mike Stump1eb44332009-09-09 15:08:12 +0000741
Chris Lattner5caa3702009-05-08 06:58:22 +0000742 // Each of these builtins has one pointer argument, followed by some number of
743 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
744 // that we ignore. Find out which row of BuiltinIndices to read from as well
745 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +0000746 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +0000747 unsigned BuiltinIndex, NumFixed = 1;
748 switch (BuiltinID) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000749 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Chris Lattner5caa3702009-05-08 06:58:22 +0000750 case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break;
751 case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break;
752 case Builtin::BI__sync_fetch_and_or: BuiltinIndex = 2; break;
753 case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break;
754 case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000755
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000756 case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 5; break;
757 case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 6; break;
758 case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 7; break;
759 case Builtin::BI__sync_or_and_fetch: BuiltinIndex = 8; break;
760 case Builtin::BI__sync_xor_and_fetch: BuiltinIndex = 9; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000761
Chris Lattner5caa3702009-05-08 06:58:22 +0000762 case Builtin::BI__sync_val_compare_and_swap:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000763 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +0000764 NumFixed = 2;
765 break;
766 case Builtin::BI__sync_bool_compare_and_swap:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000767 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +0000768 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +0000769 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +0000770 break;
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000771 case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 12; break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000772 case Builtin::BI__sync_lock_release:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000773 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +0000774 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +0000775 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +0000776 break;
Chris Lattner23aa9c82011-04-09 03:57:26 +0000777 case Builtin::BI__sync_swap: BuiltinIndex = 14; break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000778 }
Mike Stump1eb44332009-09-09 15:08:12 +0000779
Chris Lattner5caa3702009-05-08 06:58:22 +0000780 // Now that we know how many fixed arguments we expect, first check that we
781 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +0000782 if (TheCall->getNumArgs() < 1+NumFixed) {
783 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
784 << 0 << 1+NumFixed << TheCall->getNumArgs()
785 << TheCall->getCallee()->getSourceRange();
786 return ExprError();
787 }
Mike Stump1eb44332009-09-09 15:08:12 +0000788
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000789 // Get the decl for the concrete builtin from this, we can tell what the
790 // concrete integer type we should convert to is.
791 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
792 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
793 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
Mike Stump1eb44332009-09-09 15:08:12 +0000794 FunctionDecl *NewBuiltinDecl =
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000795 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
796 TUScope, false, DRE->getLocStart()));
Chandler Carruthd2014572010-07-09 18:59:35 +0000797
John McCallf871d0c2010-08-07 06:22:56 +0000798 // The first argument --- the pointer --- has a fixed type; we
799 // deduce the types of the rest of the arguments accordingly. Walk
800 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +0000801 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley429bb272011-04-08 18:41:53 +0000802 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +0000803
Chris Lattner5caa3702009-05-08 06:58:22 +0000804 // If the argument is an implicit cast, then there was a promotion due to
805 // "...", just remove it now.
John Wiegley429bb272011-04-08 18:41:53 +0000806 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg.get())) {
Chris Lattner5caa3702009-05-08 06:58:22 +0000807 Arg = ICE->getSubExpr();
808 ICE->setSubExpr(0);
John Wiegley429bb272011-04-08 18:41:53 +0000809 TheCall->setArg(i+1, Arg.get());
Chris Lattner5caa3702009-05-08 06:58:22 +0000810 }
Mike Stump1eb44332009-09-09 15:08:12 +0000811
Chris Lattner5caa3702009-05-08 06:58:22 +0000812 // GCC does an implicit conversion to the pointer or integer ValType. This
813 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb45ae252011-10-05 07:41:44 +0000814 // Initialize the argument.
815 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
816 ValType, /*consume*/ false);
817 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley429bb272011-04-08 18:41:53 +0000818 if (Arg.isInvalid())
Chandler Carruthd2014572010-07-09 18:59:35 +0000819 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000820
Chris Lattner5caa3702009-05-08 06:58:22 +0000821 // Okay, we have something that *can* be converted to the right type. Check
822 // to see if there is a potentially weird extension going on here. This can
823 // happen when you do an atomic operation on something like an char* and
824 // pass in 42. The 42 gets converted to char. This is even more strange
825 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +0000826 // FIXME: Do this check.
John McCallb45ae252011-10-05 07:41:44 +0000827 TheCall->setArg(i+1, Arg.take());
Chris Lattner5caa3702009-05-08 06:58:22 +0000828 }
Mike Stump1eb44332009-09-09 15:08:12 +0000829
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +0000830 ASTContext& Context = this->getASTContext();
831
832 // Create a new DeclRefExpr to refer to the new decl.
833 DeclRefExpr* NewDRE = DeclRefExpr::Create(
834 Context,
835 DRE->getQualifierLoc(),
836 NewBuiltinDecl,
837 DRE->getLocation(),
838 NewBuiltinDecl->getType(),
839 DRE->getValueKind());
Mike Stump1eb44332009-09-09 15:08:12 +0000840
Chris Lattner5caa3702009-05-08 06:58:22 +0000841 // Set the callee in the CallExpr.
842 // FIXME: This leaks the original parens and implicit casts.
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +0000843 ExprResult PromotedCall = UsualUnaryConversions(NewDRE);
John Wiegley429bb272011-04-08 18:41:53 +0000844 if (PromotedCall.isInvalid())
845 return ExprError();
846 TheCall->setCallee(PromotedCall.take());
Mike Stump1eb44332009-09-09 15:08:12 +0000847
Chandler Carruthdb4325b2010-07-18 07:23:17 +0000848 // Change the result type of the call to match the original value type. This
849 // is arbitrary, but the codegen for these builtins ins design to handle it
850 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +0000851 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +0000852
853 return move(TheCallResult);
Chris Lattner5caa3702009-05-08 06:58:22 +0000854}
855
Chris Lattner69039812009-02-18 06:01:06 +0000856/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +0000857/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +0000858/// Note: It might also make sense to do the UTF-16 conversion here (would
859/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +0000860bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +0000861 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000862 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
863
Douglas Gregor5cee1192011-07-27 05:40:30 +0000864 if (!Literal || !Literal->isAscii()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000865 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
866 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000867 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000868 }
Mike Stump1eb44332009-09-09 15:08:12 +0000869
Fariborz Jahanian7da71022010-09-07 19:38:13 +0000870 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000871 StringRef String = Literal->getString();
Fariborz Jahanian7da71022010-09-07 19:38:13 +0000872 unsigned NumBytes = String.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000873 SmallVector<UTF16, 128> ToBuf(NumBytes);
Fariborz Jahanian7da71022010-09-07 19:38:13 +0000874 const UTF8 *FromPtr = (UTF8 *)String.data();
875 UTF16 *ToPtr = &ToBuf[0];
876
877 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
878 &ToPtr, ToPtr + NumBytes,
879 strictConversion);
880 // Check for conversion failure.
881 if (Result != conversionOK)
882 Diag(Arg->getLocStart(),
883 diag::warn_cfstring_truncated) << Arg->getSourceRange();
884 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000885 return false;
Chris Lattner59907c42007-08-10 20:18:51 +0000886}
887
Chris Lattnerc27c6652007-12-20 00:05:45 +0000888/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
889/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +0000890bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
891 Expr *Fn = TheCall->getCallee();
892 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +0000893 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000894 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000895 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
896 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +0000897 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000898 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +0000899 return true;
900 }
Eli Friedman56f20ae2008-12-15 22:05:35 +0000901
902 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +0000903 return Diag(TheCall->getLocEnd(),
904 diag::err_typecheck_call_too_few_args_at_least)
905 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +0000906 }
907
John McCall5f8d6042011-08-27 01:09:30 +0000908 // Type-check the first argument normally.
909 if (checkBuiltinArgument(*this, TheCall, 0))
910 return true;
911
Chris Lattnerc27c6652007-12-20 00:05:45 +0000912 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000913 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +0000914 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000915 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +0000916 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +0000917 else if (FunctionDecl *FD = getCurFunctionDecl())
918 isVariadic = FD->isVariadic();
919 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000920 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +0000921
Chris Lattnerc27c6652007-12-20 00:05:45 +0000922 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000923 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
924 return true;
925 }
Mike Stump1eb44332009-09-09 15:08:12 +0000926
Chris Lattner30ce3442007-12-19 23:59:04 +0000927 // Verify that the second argument to the builtin is the last argument of the
928 // current function or method.
929 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +0000930 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +0000931
Anders Carlsson88cf2262008-02-11 04:20:54 +0000932 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
933 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000934 // FIXME: This isn't correct for methods (results in bogus warning).
935 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +0000936 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000937 if (CurBlock)
938 LastArg = *(CurBlock->TheDecl->param_end()-1);
939 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +0000940 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000941 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000942 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000943 SecondArgIsLastNamedArgument = PV == LastArg;
944 }
945 }
Mike Stump1eb44332009-09-09 15:08:12 +0000946
Chris Lattner30ce3442007-12-19 23:59:04 +0000947 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +0000948 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +0000949 diag::warn_second_parameter_of_va_start_not_last_named_argument);
950 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +0000951}
Chris Lattner30ce3442007-12-19 23:59:04 +0000952
Chris Lattner1b9a0792007-12-20 00:26:33 +0000953/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
954/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +0000955bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
956 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +0000957 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +0000958 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +0000959 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +0000960 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000961 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000962 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000963 << SourceRange(TheCall->getArg(2)->getLocStart(),
964 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000965
John Wiegley429bb272011-04-08 18:41:53 +0000966 ExprResult OrigArg0 = TheCall->getArg(0);
967 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +0000968
Chris Lattner1b9a0792007-12-20 00:26:33 +0000969 // Do standard promotions between the two arguments, returning their common
970 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +0000971 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley429bb272011-04-08 18:41:53 +0000972 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
973 return true;
Daniel Dunbar403bc2b2009-02-19 19:28:43 +0000974
975 // Make sure any conversions are pushed back into the call; this is
976 // type safe since unordered compare builtins are declared as "_Bool
977 // foo(...)".
John Wiegley429bb272011-04-08 18:41:53 +0000978 TheCall->setArg(0, OrigArg0.get());
979 TheCall->setArg(1, OrigArg1.get());
Mike Stump1eb44332009-09-09 15:08:12 +0000980
John Wiegley429bb272011-04-08 18:41:53 +0000981 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorcde01732009-05-19 22:10:17 +0000982 return false;
983
Chris Lattner1b9a0792007-12-20 00:26:33 +0000984 // If the common type isn't a real floating type, then the arguments were
985 // invalid for this operation.
986 if (!Res->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +0000987 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000988 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley429bb272011-04-08 18:41:53 +0000989 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
990 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000991
Chris Lattner1b9a0792007-12-20 00:26:33 +0000992 return false;
993}
994
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000995/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
996/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000997/// to check everything. We expect the last argument to be a floating point
998/// value.
999bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1000 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +00001001 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001002 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001003 if (TheCall->getNumArgs() > NumArgs)
1004 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001005 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001006 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001007 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001008 (*(TheCall->arg_end()-1))->getLocEnd());
1009
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001010 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001011
Eli Friedman9ac6f622009-08-31 20:06:00 +00001012 if (OrigArg->isTypeDependent())
1013 return false;
1014
Chris Lattner81368fb2010-05-06 05:50:07 +00001015 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +00001016 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +00001017 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001018 diag::err_typecheck_call_invalid_unary_fp)
1019 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001020
Chris Lattner81368fb2010-05-06 05:50:07 +00001021 // If this is an implicit conversion from float -> double, remove it.
1022 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1023 Expr *CastArg = Cast->getSubExpr();
1024 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1025 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1026 "promotion from float to double is the only expected cast here");
1027 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +00001028 TheCall->setArg(NumArgs-1, CastArg);
1029 OrigArg = CastArg;
1030 }
1031 }
1032
Eli Friedman9ac6f622009-08-31 20:06:00 +00001033 return false;
1034}
1035
Eli Friedmand38617c2008-05-14 19:38:39 +00001036/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1037// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +00001038ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001039 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001040 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +00001041 diag::err_typecheck_call_too_few_args_at_least)
Nate Begeman37b6a572010-06-08 00:16:34 +00001042 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherd77b9a22010-04-16 04:48:22 +00001043 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001044
Nate Begeman37b6a572010-06-08 00:16:34 +00001045 // Determine which of the following types of shufflevector we're checking:
1046 // 1) unary, vector mask: (lhs, mask)
1047 // 2) binary, vector mask: (lhs, rhs, mask)
1048 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1049 QualType resType = TheCall->getArg(0)->getType();
1050 unsigned numElements = 0;
1051
Douglas Gregorcde01732009-05-19 22:10:17 +00001052 if (!TheCall->getArg(0)->isTypeDependent() &&
1053 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001054 QualType LHSType = TheCall->getArg(0)->getType();
1055 QualType RHSType = TheCall->getArg(1)->getType();
1056
1057 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001058 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001059 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001060 TheCall->getArg(1)->getLocEnd());
1061 return ExprError();
1062 }
Nate Begeman37b6a572010-06-08 00:16:34 +00001063
1064 numElements = LHSType->getAs<VectorType>()->getNumElements();
1065 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +00001066
Nate Begeman37b6a572010-06-08 00:16:34 +00001067 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1068 // with mask. If so, verify that RHS is an integer vector type with the
1069 // same number of elts as lhs.
1070 if (TheCall->getNumArgs() == 2) {
Douglas Gregorf6094622010-07-23 15:58:24 +00001071 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +00001072 RHSType->getAs<VectorType>()->getNumElements() != numElements)
1073 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
1074 << SourceRange(TheCall->getArg(1)->getLocStart(),
1075 TheCall->getArg(1)->getLocEnd());
1076 numResElements = numElements;
1077 }
1078 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001079 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001080 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001081 TheCall->getArg(1)->getLocEnd());
1082 return ExprError();
Nate Begeman37b6a572010-06-08 00:16:34 +00001083 } else if (numElements != numResElements) {
1084 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +00001085 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001086 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +00001087 }
Eli Friedmand38617c2008-05-14 19:38:39 +00001088 }
1089
1090 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001091 if (TheCall->getArg(i)->isTypeDependent() ||
1092 TheCall->getArg(i)->isValueDependent())
1093 continue;
1094
Nate Begeman37b6a572010-06-08 00:16:34 +00001095 llvm::APSInt Result(32);
1096 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1097 return ExprError(Diag(TheCall->getLocStart(),
1098 diag::err_shufflevector_nonconstant_argument)
1099 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001100
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001101 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001102 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001103 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001104 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001105 }
1106
Chris Lattner5f9e2722011-07-23 10:55:15 +00001107 SmallVector<Expr*, 32> exprs;
Eli Friedmand38617c2008-05-14 19:38:39 +00001108
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001109 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +00001110 exprs.push_back(TheCall->getArg(i));
1111 TheCall->setArg(i, 0);
1112 }
1113
Nate Begemana88dc302009-08-12 02:10:25 +00001114 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
Nate Begeman37b6a572010-06-08 00:16:34 +00001115 exprs.size(), resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001116 TheCall->getCallee()->getLocStart(),
1117 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +00001118}
Chris Lattner30ce3442007-12-19 23:59:04 +00001119
Daniel Dunbar4493f792008-07-21 22:59:13 +00001120/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1121// This is declared to take (const void*, ...) and can take two
1122// optional constant int args.
1123bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001124 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001125
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001126 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +00001127 return Diag(TheCall->getLocEnd(),
1128 diag::err_typecheck_call_too_many_args_at_most)
1129 << 0 /*function call*/ << 3 << NumArgs
1130 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001131
1132 // Argument 0 is checked for us and the remaining arguments must be
1133 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001134 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +00001135 Expr *Arg = TheCall->getArg(i);
Eric Christopher691ebc32010-04-17 02:26:23 +00001136
Eli Friedman9aef7262009-12-04 00:30:06 +00001137 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +00001138 if (SemaBuiltinConstantArg(TheCall, i, Result))
1139 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001140
Daniel Dunbar4493f792008-07-21 22:59:13 +00001141 // FIXME: gcc issues a warning and rewrites these to 0. These
1142 // seems especially odd for the third argument since the default
1143 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001144 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +00001145 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001146 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001147 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001148 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +00001149 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001150 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001151 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001152 }
1153 }
1154
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001155 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +00001156}
1157
Eric Christopher691ebc32010-04-17 02:26:23 +00001158/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1159/// TheCall is a constant expression.
1160bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1161 llvm::APSInt &Result) {
1162 Expr *Arg = TheCall->getArg(ArgNum);
1163 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1164 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1165
1166 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1167
1168 if (!Arg->isIntegerConstantExpr(Result, Context))
1169 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +00001170 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +00001171
Chris Lattner21fb98e2009-09-23 06:06:36 +00001172 return false;
1173}
1174
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001175/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1176/// int type). This simply type checks that type is one of the defined
1177/// constants (0-3).
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001178// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001179bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +00001180 llvm::APSInt Result;
1181
1182 // Check constant-ness first.
1183 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1184 return true;
1185
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001186 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001187 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001188 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1189 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001190 }
1191
1192 return false;
1193}
1194
Eli Friedman586d6a82009-05-03 06:04:26 +00001195/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +00001196/// This checks that val is a constant 1.
1197bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1198 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +00001199 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +00001200
Eric Christopher691ebc32010-04-17 02:26:23 +00001201 // TODO: This is less than ideal. Overload this to take a value.
1202 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1203 return true;
1204
1205 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +00001206 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1207 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1208
1209 return false;
1210}
1211
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001212// Handle i > 1 ? "x" : "y", recursively.
Ted Kremenek082d9362009-03-20 21:35:28 +00001213bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
1214 bool HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00001215 unsigned format_idx, unsigned firstDataArg,
Richard Trieu55733de2011-10-28 00:41:25 +00001216 bool isPrintf, bool inFunctionCall) {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001217 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +00001218 if (E->isTypeDependent() || E->isValueDependent())
1219 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001220
Peter Collingbournef111d932011-04-15 00:35:48 +00001221 E = E->IgnoreParens();
1222
Ted Kremenekd30ef872009-01-12 23:09:09 +00001223 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +00001224 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +00001225 case Stmt::ConditionalOperatorClass: {
John McCall56ca35d2011-02-17 10:25:35 +00001226 const AbstractConditionalOperator *C = cast<AbstractConditionalOperator>(E);
Ted Kremenek826a3452010-07-16 02:11:22 +00001227 return SemaCheckStringLiteral(C->getTrueExpr(), TheCall, HasVAListArg,
Richard Trieu55733de2011-10-28 00:41:25 +00001228 format_idx, firstDataArg, isPrintf,
1229 inFunctionCall)
John McCall56ca35d2011-02-17 10:25:35 +00001230 && SemaCheckStringLiteral(C->getFalseExpr(), TheCall, HasVAListArg,
Richard Trieu55733de2011-10-28 00:41:25 +00001231 format_idx, firstDataArg, isPrintf,
1232 inFunctionCall);
Ted Kremenekd30ef872009-01-12 23:09:09 +00001233 }
1234
Ted Kremenek95355bb2010-09-09 03:51:42 +00001235 case Stmt::IntegerLiteralClass:
1236 // Technically -Wformat-nonliteral does not warn about this case.
1237 // The behavior of printf and friends in this case is implementation
1238 // dependent. Ideally if the format string cannot be null then
1239 // it should have a 'nonnull' attribute in the function prototype.
1240 return true;
1241
Ted Kremenekd30ef872009-01-12 23:09:09 +00001242 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001243 E = cast<ImplicitCastExpr>(E)->getSubExpr();
1244 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001245 }
1246
John McCall56ca35d2011-02-17 10:25:35 +00001247 case Stmt::OpaqueValueExprClass:
1248 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
1249 E = src;
1250 goto tryAgain;
1251 }
1252 return false;
1253
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001254 case Stmt::PredefinedExprClass:
1255 // While __func__, etc., are technically not string literals, they
1256 // cannot contain format specifiers and thus are not a security
1257 // liability.
1258 return true;
1259
Ted Kremenek082d9362009-03-20 21:35:28 +00001260 case Stmt::DeclRefExprClass: {
1261 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001262
Ted Kremenek082d9362009-03-20 21:35:28 +00001263 // As an exception, do not flag errors for variables binding to
1264 // const string literals.
1265 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1266 bool isConstant = false;
1267 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001268
Ted Kremenek082d9362009-03-20 21:35:28 +00001269 if (const ArrayType *AT = Context.getAsArrayType(T)) {
1270 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001271 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001272 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +00001273 PT->getPointeeType().isConstant(Context);
1274 }
Mike Stump1eb44332009-09-09 15:08:12 +00001275
Ted Kremenek082d9362009-03-20 21:35:28 +00001276 if (isConstant) {
Sebastian Redl31310a22010-02-01 20:16:42 +00001277 if (const Expr *Init = VD->getAnyInitializer())
Ted Kremenek082d9362009-03-20 21:35:28 +00001278 return SemaCheckStringLiteral(Init, TheCall,
Ted Kremenek826a3452010-07-16 02:11:22 +00001279 HasVAListArg, format_idx, firstDataArg,
Richard Trieu55733de2011-10-28 00:41:25 +00001280 isPrintf, /*inFunctionCall*/false);
Ted Kremenek082d9362009-03-20 21:35:28 +00001281 }
Mike Stump1eb44332009-09-09 15:08:12 +00001282
Anders Carlssond966a552009-06-28 19:55:58 +00001283 // For vprintf* functions (i.e., HasVAListArg==true), we add a
1284 // special check to see if the format string is a function parameter
1285 // of the function calling the printf function. If the function
1286 // has an attribute indicating it is a printf-like function, then we
1287 // should suppress warnings concerning non-literals being used in a call
1288 // to a vprintf function. For example:
1289 //
1290 // void
1291 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
1292 // va_list ap;
1293 // va_start(ap, fmt);
1294 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
1295 // ...
1296 //
1297 //
1298 // FIXME: We don't have full attribute support yet, so just check to see
1299 // if the argument is a DeclRefExpr that references a parameter. We'll
1300 // add proper support for checking the attribute later.
1301 if (HasVAListArg)
1302 if (isa<ParmVarDecl>(VD))
1303 return true;
Ted Kremenek082d9362009-03-20 21:35:28 +00001304 }
Mike Stump1eb44332009-09-09 15:08:12 +00001305
Ted Kremenek082d9362009-03-20 21:35:28 +00001306 return false;
1307 }
Ted Kremenekd30ef872009-01-12 23:09:09 +00001308
Anders Carlsson8f031b32009-06-27 04:05:33 +00001309 case Stmt::CallExprClass: {
1310 const CallExpr *CE = cast<CallExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001311 if (const ImplicitCastExpr *ICE
Anders Carlsson8f031b32009-06-27 04:05:33 +00001312 = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
1313 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
1314 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001315 if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
Anders Carlsson8f031b32009-06-27 04:05:33 +00001316 unsigned ArgIndex = FA->getFormatIdx();
1317 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001318
1319 return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg,
Richard Trieu55733de2011-10-28 00:41:25 +00001320 format_idx, firstDataArg, isPrintf,
1321 inFunctionCall);
Anders Carlsson8f031b32009-06-27 04:05:33 +00001322 }
1323 }
1324 }
1325 }
Mike Stump1eb44332009-09-09 15:08:12 +00001326
Anders Carlsson8f031b32009-06-27 04:05:33 +00001327 return false;
1328 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001329 case Stmt::ObjCStringLiteralClass:
1330 case Stmt::StringLiteralClass: {
1331 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001332
Ted Kremenek082d9362009-03-20 21:35:28 +00001333 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00001334 StrE = ObjCFExpr->getString();
1335 else
Ted Kremenek082d9362009-03-20 21:35:28 +00001336 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001337
Ted Kremenekd30ef872009-01-12 23:09:09 +00001338 if (StrE) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001339 CheckFormatString(StrE, E, TheCall, HasVAListArg, format_idx,
Richard Trieu55733de2011-10-28 00:41:25 +00001340 firstDataArg, isPrintf, inFunctionCall);
Ted Kremenekd30ef872009-01-12 23:09:09 +00001341 return true;
1342 }
Mike Stump1eb44332009-09-09 15:08:12 +00001343
Ted Kremenekd30ef872009-01-12 23:09:09 +00001344 return false;
1345 }
Mike Stump1eb44332009-09-09 15:08:12 +00001346
Ted Kremenek082d9362009-03-20 21:35:28 +00001347 default:
1348 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001349 }
1350}
1351
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001352void
Mike Stump1eb44332009-09-09 15:08:12 +00001353Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewycky909a70d2011-03-25 01:44:32 +00001354 const Expr * const *ExprArgs,
1355 SourceLocation CallSiteLoc) {
Sean Huntcf807c42010-08-18 23:23:40 +00001356 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1357 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001358 i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +00001359 const Expr *ArgExpr = ExprArgs[*i];
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001360 if (ArgExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00001361 Expr::NPC_ValueDependentIsNotNull))
Nick Lewycky909a70d2011-03-25 01:44:32 +00001362 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001363 }
1364}
Ted Kremenekd30ef872009-01-12 23:09:09 +00001365
Ted Kremenek826a3452010-07-16 02:11:22 +00001366/// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar
1367/// functions) for correct use of format strings.
Chris Lattner59907c42007-08-10 20:18:51 +00001368void
Ted Kremenek826a3452010-07-16 02:11:22 +00001369Sema::CheckPrintfScanfArguments(const CallExpr *TheCall, bool HasVAListArg,
1370 unsigned format_idx, unsigned firstDataArg,
1371 bool isPrintf) {
1372
Ted Kremenek082d9362009-03-20 21:35:28 +00001373 const Expr *Fn = TheCall->getCallee();
Chris Lattner925e60d2007-12-28 05:29:59 +00001374
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001375 // The way the format attribute works in GCC, the implicit this argument
1376 // of member functions is counted. However, it doesn't appear in our own
1377 // lists, so decrement format_idx in that case.
1378 if (isa<CXXMemberCallExpr>(TheCall)) {
Chandler Carruth9263a302010-11-16 08:49:43 +00001379 const CXXMethodDecl *method_decl =
1380 dyn_cast<CXXMethodDecl>(TheCall->getCalleeDecl());
1381 if (method_decl && method_decl->isInstance()) {
1382 // Catch a format attribute mistakenly referring to the object argument.
1383 if (format_idx == 0)
1384 return;
1385 --format_idx;
1386 if(firstDataArg != 0)
1387 --firstDataArg;
1388 }
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001389 }
1390
Ted Kremenek826a3452010-07-16 02:11:22 +00001391 // CHECK: printf/scanf-like function is called with no format string.
Chris Lattner925e60d2007-12-28 05:29:59 +00001392 if (format_idx >= TheCall->getNumArgs()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001393 Diag(TheCall->getRParenLoc(), diag::warn_missing_format_string)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001394 << Fn->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001395 return;
1396 }
Mike Stump1eb44332009-09-09 15:08:12 +00001397
Ted Kremenek082d9362009-03-20 21:35:28 +00001398 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001399
Chris Lattner59907c42007-08-10 20:18:51 +00001400 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001401 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001402 // Dynamically generated format strings are difficult to
1403 // automatically vet at compile time. Requiring that format strings
1404 // are string literals: (1) permits the checking of format strings by
1405 // the compiler and thereby (2) can practically remove the source of
1406 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001407
Mike Stump1eb44332009-09-09 15:08:12 +00001408 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001409 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001410 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001411 // the same format string checking logic for both ObjC and C strings.
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001412 if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
Ted Kremenek826a3452010-07-16 02:11:22 +00001413 firstDataArg, isPrintf))
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001414 return; // Literal format string found, check done!
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001415
Chris Lattner655f1412009-04-29 04:59:47 +00001416 // If there are no arguments specified, warn with -Wformat-security, otherwise
1417 // warn only with -Wformat-nonliteral.
1418 if (TheCall->getNumArgs() == format_idx+1)
Mike Stump1eb44332009-09-09 15:08:12 +00001419 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001420 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00001421 << OrigFormatExpr->getSourceRange();
1422 else
Mike Stump1eb44332009-09-09 15:08:12 +00001423 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001424 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00001425 << OrigFormatExpr->getSourceRange();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001426}
Ted Kremenek71895b92007-08-14 17:39:48 +00001427
Ted Kremeneke0e53132010-01-28 23:39:18 +00001428namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00001429class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1430protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00001431 Sema &S;
1432 const StringLiteral *FExpr;
1433 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00001434 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001435 const unsigned NumDataArgs;
1436 const bool IsObjCLiteral;
1437 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00001438 const bool HasVAListArg;
1439 const CallExpr *TheCall;
1440 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001441 llvm::BitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00001442 bool usesPositionalArgs;
1443 bool atFirstArg;
Richard Trieu55733de2011-10-28 00:41:25 +00001444 bool inFunctionCall;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001445public:
Ted Kremenek826a3452010-07-16 02:11:22 +00001446 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00001447 const Expr *origFormatExpr, unsigned firstDataArg,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001448 unsigned numDataArgs, bool isObjCLiteral,
Ted Kremenek0d277352010-01-29 01:06:55 +00001449 const char *beg, bool hasVAListArg,
Richard Trieu55733de2011-10-28 00:41:25 +00001450 const CallExpr *theCall, unsigned formatIdx,
1451 bool inFunctionCall)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001452 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Ted Kremenek6ee76532010-03-25 03:59:12 +00001453 FirstDataArg(firstDataArg),
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001454 NumDataArgs(numDataArgs),
Ted Kremenek0d277352010-01-29 01:06:55 +00001455 IsObjCLiteral(isObjCLiteral), Beg(beg),
1456 HasVAListArg(hasVAListArg),
Ted Kremenekefaff192010-02-27 01:41:03 +00001457 TheCall(theCall), FormatIdx(formatIdx),
Richard Trieu55733de2011-10-28 00:41:25 +00001458 usesPositionalArgs(false), atFirstArg(true),
1459 inFunctionCall(inFunctionCall) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001460 CoveredArgs.resize(numDataArgs);
1461 CoveredArgs.reset();
1462 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001463
Ted Kremenek07d161f2010-01-29 01:50:07 +00001464 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001465
Ted Kremenek826a3452010-07-16 02:11:22 +00001466 void HandleIncompleteSpecifier(const char *startSpecifier,
1467 unsigned specifierLen);
1468
Ted Kremenekefaff192010-02-27 01:41:03 +00001469 virtual void HandleInvalidPosition(const char *startSpecifier,
1470 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00001471 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00001472
1473 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1474
Ted Kremeneke0e53132010-01-28 23:39:18 +00001475 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001476
Richard Trieu55733de2011-10-28 00:41:25 +00001477 template <typename Range>
1478 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
1479 const Expr *ArgumentExpr,
1480 PartialDiagnostic PDiag,
1481 SourceLocation StringLoc,
1482 bool IsStringLocation, Range StringRange,
1483 FixItHint Fixit = FixItHint());
1484
Ted Kremenek826a3452010-07-16 02:11:22 +00001485protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001486 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
1487 const char *startSpec,
1488 unsigned specifierLen,
1489 const char *csStart, unsigned csLen);
Richard Trieu55733de2011-10-28 00:41:25 +00001490
1491 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
1492 const char *startSpec,
1493 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001494
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001495 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00001496 CharSourceRange getSpecifierRange(const char *startSpecifier,
1497 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001498 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001499
Ted Kremenek0d277352010-01-29 01:06:55 +00001500 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00001501
1502 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
1503 const analyze_format_string::ConversionSpecifier &CS,
1504 const char *startSpecifier, unsigned specifierLen,
1505 unsigned argIndex);
Richard Trieu55733de2011-10-28 00:41:25 +00001506
1507 template <typename Range>
1508 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
1509 bool IsStringLocation, Range StringRange,
1510 FixItHint Fixit = FixItHint());
1511
1512 void CheckPositionalAndNonpositionalArgs(
1513 const analyze_format_string::FormatSpecifier *FS);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001514};
1515}
1516
Ted Kremenek826a3452010-07-16 02:11:22 +00001517SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00001518 return OrigFormatExpr->getSourceRange();
1519}
1520
Ted Kremenek826a3452010-07-16 02:11:22 +00001521CharSourceRange CheckFormatHandler::
1522getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00001523 SourceLocation Start = getLocationOfByte(startSpecifier);
1524 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
1525
1526 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001527 End = End.getLocWithOffset(1);
Tom Care45f9b7e2010-06-21 21:21:01 +00001528
1529 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001530}
1531
Ted Kremenek826a3452010-07-16 02:11:22 +00001532SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001533 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001534}
1535
Ted Kremenek826a3452010-07-16 02:11:22 +00001536void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
1537 unsigned specifierLen){
Richard Trieu55733de2011-10-28 00:41:25 +00001538 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
1539 getLocationOfByte(startSpecifier),
1540 /*IsStringLocation*/true,
1541 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek808015a2010-01-29 03:16:21 +00001542}
1543
Ted Kremenekefaff192010-02-27 01:41:03 +00001544void
Ted Kremenek826a3452010-07-16 02:11:22 +00001545CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
1546 analyze_format_string::PositionContext p) {
Richard Trieu55733de2011-10-28 00:41:25 +00001547 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
1548 << (unsigned) p,
1549 getLocationOfByte(startPos), /*IsStringLocation*/true,
1550 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00001551}
1552
Ted Kremenek826a3452010-07-16 02:11:22 +00001553void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00001554 unsigned posLen) {
Richard Trieu55733de2011-10-28 00:41:25 +00001555 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
1556 getLocationOfByte(startPos),
1557 /*IsStringLocation*/true,
1558 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00001559}
1560
Ted Kremenek826a3452010-07-16 02:11:22 +00001561void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Ted Kremenek0c069442011-03-15 21:18:48 +00001562 if (!IsObjCLiteral) {
1563 // The presence of a null character is likely an error.
Richard Trieu55733de2011-10-28 00:41:25 +00001564 EmitFormatDiagnostic(
1565 S.PDiag(diag::warn_printf_format_string_contains_null_char),
1566 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
1567 getFormatStringRange());
Ted Kremenek0c069442011-03-15 21:18:48 +00001568 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001569}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001570
Ted Kremenek826a3452010-07-16 02:11:22 +00001571const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
1572 return TheCall->getArg(FirstDataArg + i);
1573}
1574
1575void CheckFormatHandler::DoneProcessing() {
1576 // Does the number of data arguments exceed the number of
1577 // format conversions in the format string?
1578 if (!HasVAListArg) {
1579 // Find any arguments that weren't covered.
1580 CoveredArgs.flip();
1581 signed notCoveredArg = CoveredArgs.find_first();
1582 if (notCoveredArg >= 0) {
1583 assert((unsigned)notCoveredArg < NumDataArgs);
Richard Trieu55733de2011-10-28 00:41:25 +00001584 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
1585 getDataArg((unsigned) notCoveredArg)->getLocStart(),
1586 /*IsStringLocation*/false, getFormatStringRange());
Ted Kremenek826a3452010-07-16 02:11:22 +00001587 }
1588 }
1589}
1590
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001591bool
1592CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
1593 SourceLocation Loc,
1594 const char *startSpec,
1595 unsigned specifierLen,
1596 const char *csStart,
1597 unsigned csLen) {
1598
1599 bool keepGoing = true;
1600 if (argIndex < NumDataArgs) {
1601 // Consider the argument coverered, even though the specifier doesn't
1602 // make sense.
1603 CoveredArgs.set(argIndex);
1604 }
1605 else {
1606 // If argIndex exceeds the number of data arguments we
1607 // don't issue a warning because that is just a cascade of warnings (and
1608 // they may have intended '%%' anyway). We don't want to continue processing
1609 // the format string after this point, however, as we will like just get
1610 // gibberish when trying to match arguments.
1611 keepGoing = false;
1612 }
1613
Richard Trieu55733de2011-10-28 00:41:25 +00001614 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
1615 << StringRef(csStart, csLen),
1616 Loc, /*IsStringLocation*/true,
1617 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001618
1619 return keepGoing;
1620}
1621
Richard Trieu55733de2011-10-28 00:41:25 +00001622void
1623CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
1624 const char *startSpec,
1625 unsigned specifierLen) {
1626 EmitFormatDiagnostic(
1627 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
1628 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
1629}
1630
Ted Kremenek666a1972010-07-26 19:45:42 +00001631bool
1632CheckFormatHandler::CheckNumArgs(
1633 const analyze_format_string::FormatSpecifier &FS,
1634 const analyze_format_string::ConversionSpecifier &CS,
1635 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
1636
1637 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00001638 PartialDiagnostic PDiag = FS.usesPositionalArg()
1639 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
1640 << (argIndex+1) << NumDataArgs)
1641 : S.PDiag(diag::warn_printf_insufficient_data_args);
1642 EmitFormatDiagnostic(
1643 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
1644 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek666a1972010-07-26 19:45:42 +00001645 return false;
1646 }
1647 return true;
1648}
1649
Richard Trieu55733de2011-10-28 00:41:25 +00001650template<typename Range>
1651void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
1652 SourceLocation Loc,
1653 bool IsStringLocation,
1654 Range StringRange,
1655 FixItHint FixIt) {
1656 EmitFormatDiagnostic(S, inFunctionCall, TheCall->getArg(FormatIdx), PDiag,
1657 Loc, IsStringLocation, StringRange, FixIt);
1658}
1659
1660/// \brief If the format string is not within the funcion call, emit a note
1661/// so that the function call and string are in diagnostic messages.
1662///
1663/// \param inFunctionCall if true, the format string is within the function
1664/// call and only one diagnostic message will be produced. Otherwise, an
1665/// extra note will be emitted pointing to location of the format string.
1666///
1667/// \param ArgumentExpr the expression that is passed as the format string
1668/// argument in the function call. Used for getting locations when two
1669/// diagnostics are emitted.
1670///
1671/// \param PDiag the callee should already have provided any strings for the
1672/// diagnostic message. This function only adds locations and fixits
1673/// to diagnostics.
1674///
1675/// \param Loc primary location for diagnostic. If two diagnostics are
1676/// required, one will be at Loc and a new SourceLocation will be created for
1677/// the other one.
1678///
1679/// \param IsStringLocation if true, Loc points to the format string should be
1680/// used for the note. Otherwise, Loc points to the argument list and will
1681/// be used with PDiag.
1682///
1683/// \param StringRange some or all of the string to highlight. This is
1684/// templated so it can accept either a CharSourceRange or a SourceRange.
1685///
1686/// \param Fixit optional fix it hint for the format string.
1687template<typename Range>
1688void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
1689 const Expr *ArgumentExpr,
1690 PartialDiagnostic PDiag,
1691 SourceLocation Loc,
1692 bool IsStringLocation,
1693 Range StringRange,
1694 FixItHint FixIt) {
1695 if (InFunctionCall)
1696 S.Diag(Loc, PDiag) << StringRange << FixIt;
1697 else {
1698 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
1699 << ArgumentExpr->getSourceRange();
1700 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
1701 diag::note_format_string_defined)
1702 << StringRange << FixIt;
1703 }
1704}
1705
Ted Kremenek826a3452010-07-16 02:11:22 +00001706//===--- CHECK: Printf format string checking ------------------------------===//
1707
1708namespace {
1709class CheckPrintfHandler : public CheckFormatHandler {
1710public:
1711 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
1712 const Expr *origFormatExpr, unsigned firstDataArg,
1713 unsigned numDataArgs, bool isObjCLiteral,
1714 const char *beg, bool hasVAListArg,
Richard Trieu55733de2011-10-28 00:41:25 +00001715 const CallExpr *theCall, unsigned formatIdx,
1716 bool inFunctionCall)
Ted Kremenek826a3452010-07-16 02:11:22 +00001717 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1718 numDataArgs, isObjCLiteral, beg, hasVAListArg,
Richard Trieu55733de2011-10-28 00:41:25 +00001719 theCall, formatIdx, inFunctionCall) {}
Ted Kremenek826a3452010-07-16 02:11:22 +00001720
1721
1722 bool HandleInvalidPrintfConversionSpecifier(
1723 const analyze_printf::PrintfSpecifier &FS,
1724 const char *startSpecifier,
1725 unsigned specifierLen);
1726
1727 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
1728 const char *startSpecifier,
1729 unsigned specifierLen);
1730
1731 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
1732 const char *startSpecifier, unsigned specifierLen);
1733 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
1734 const analyze_printf::OptionalAmount &Amt,
1735 unsigned type,
1736 const char *startSpecifier, unsigned specifierLen);
1737 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
1738 const analyze_printf::OptionalFlag &flag,
1739 const char *startSpecifier, unsigned specifierLen);
1740 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
1741 const analyze_printf::OptionalFlag &ignoredFlag,
1742 const analyze_printf::OptionalFlag &flag,
1743 const char *startSpecifier, unsigned specifierLen);
1744};
1745}
1746
1747bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
1748 const analyze_printf::PrintfSpecifier &FS,
1749 const char *startSpecifier,
1750 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001751 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001752 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00001753
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001754 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1755 getLocationOfByte(CS.getStart()),
1756 startSpecifier, specifierLen,
1757 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001758}
1759
Ted Kremenek826a3452010-07-16 02:11:22 +00001760bool CheckPrintfHandler::HandleAmount(
1761 const analyze_format_string::OptionalAmount &Amt,
1762 unsigned k, const char *startSpecifier,
1763 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001764
1765 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001766 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001767 unsigned argIndex = Amt.getArgIndex();
1768 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00001769 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
1770 << k,
1771 getLocationOfByte(Amt.getStart()),
1772 /*IsStringLocation*/true,
1773 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00001774 // Don't do any more checking. We will just emit
1775 // spurious errors.
1776 return false;
1777 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001778
Ted Kremenek0d277352010-01-29 01:06:55 +00001779 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00001780 // Although not in conformance with C99, we also allow the argument to be
1781 // an 'unsigned int' as that is a reasonably safe case. GCC also
1782 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001783 CoveredArgs.set(argIndex);
1784 const Expr *Arg = getDataArg(argIndex);
Ted Kremenek0d277352010-01-29 01:06:55 +00001785 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001786
1787 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
1788 assert(ATR.isValid());
1789
1790 if (!ATR.matchesType(S.Context, T)) {
Richard Trieu55733de2011-10-28 00:41:25 +00001791 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
1792 << k << ATR.getRepresentativeType(S.Context)
1793 << T << Arg->getSourceRange(),
1794 getLocationOfByte(Amt.getStart()),
1795 /*IsStringLocation*/true,
1796 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00001797 // Don't do any more checking. We will just emit
1798 // spurious errors.
1799 return false;
1800 }
1801 }
1802 }
1803 return true;
1804}
Ted Kremenek0d277352010-01-29 01:06:55 +00001805
Tom Caree4ee9662010-06-17 19:00:27 +00001806void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00001807 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001808 const analyze_printf::OptionalAmount &Amt,
1809 unsigned type,
1810 const char *startSpecifier,
1811 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001812 const analyze_printf::PrintfConversionSpecifier &CS =
1813 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00001814
Richard Trieu55733de2011-10-28 00:41:25 +00001815 FixItHint fixit =
1816 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
1817 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
1818 Amt.getConstantLength()))
1819 : FixItHint();
1820
1821 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
1822 << type << CS.toString(),
1823 getLocationOfByte(Amt.getStart()),
1824 /*IsStringLocation*/true,
1825 getSpecifierRange(startSpecifier, specifierLen),
1826 fixit);
Tom Caree4ee9662010-06-17 19:00:27 +00001827}
1828
Ted Kremenek826a3452010-07-16 02:11:22 +00001829void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001830 const analyze_printf::OptionalFlag &flag,
1831 const char *startSpecifier,
1832 unsigned specifierLen) {
1833 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001834 const analyze_printf::PrintfConversionSpecifier &CS =
1835 FS.getConversionSpecifier();
Richard Trieu55733de2011-10-28 00:41:25 +00001836 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
1837 << flag.toString() << CS.toString(),
1838 getLocationOfByte(flag.getPosition()),
1839 /*IsStringLocation*/true,
1840 getSpecifierRange(startSpecifier, specifierLen),
1841 FixItHint::CreateRemoval(
1842 getSpecifierRange(flag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00001843}
1844
1845void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00001846 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001847 const analyze_printf::OptionalFlag &ignoredFlag,
1848 const analyze_printf::OptionalFlag &flag,
1849 const char *startSpecifier,
1850 unsigned specifierLen) {
1851 // Warn about ignored flag with a fixit removal.
Richard Trieu55733de2011-10-28 00:41:25 +00001852 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
1853 << ignoredFlag.toString() << flag.toString(),
1854 getLocationOfByte(ignoredFlag.getPosition()),
1855 /*IsStringLocation*/true,
1856 getSpecifierRange(startSpecifier, specifierLen),
1857 FixItHint::CreateRemoval(
1858 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00001859}
1860
Ted Kremeneke0e53132010-01-28 23:39:18 +00001861bool
Ted Kremenek826a3452010-07-16 02:11:22 +00001862CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001863 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001864 const char *startSpecifier,
1865 unsigned specifierLen) {
1866
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001867 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00001868 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001869 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00001870
Ted Kremenekbaa40062010-07-19 22:01:06 +00001871 if (FS.consumesDataArgument()) {
1872 if (atFirstArg) {
1873 atFirstArg = false;
1874 usesPositionalArgs = FS.usesPositionalArg();
1875 }
1876 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00001877 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
1878 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00001879 return false;
1880 }
Ted Kremenek0d277352010-01-29 01:06:55 +00001881 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001882
Ted Kremenekefaff192010-02-27 01:41:03 +00001883 // First check if the field width, precision, and conversion specifier
1884 // have matching data arguments.
1885 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
1886 startSpecifier, specifierLen)) {
1887 return false;
1888 }
1889
1890 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
1891 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001892 return false;
1893 }
1894
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001895 if (!CS.consumesDataArgument()) {
1896 // FIXME: Technically specifying a precision or field width here
1897 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001898 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001899 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001900
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001901 // Consume the argument.
1902 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00001903 if (argIndex < NumDataArgs) {
1904 // The check to see if the argIndex is valid will come later.
1905 // We set the bit here because we may exit early from this
1906 // function if we encounter some other error.
1907 CoveredArgs.set(argIndex);
1908 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001909
1910 // Check for using an Objective-C specific conversion specifier
1911 // in a non-ObjC literal.
1912 if (!IsObjCLiteral && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001913 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
1914 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001915 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001916
Tom Caree4ee9662010-06-17 19:00:27 +00001917 // Check for invalid use of field width
1918 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00001919 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00001920 startSpecifier, specifierLen);
1921 }
1922
1923 // Check for invalid use of precision
1924 if (!FS.hasValidPrecision()) {
1925 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
1926 startSpecifier, specifierLen);
1927 }
1928
1929 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00001930 if (!FS.hasValidThousandsGroupingPrefix())
1931 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001932 if (!FS.hasValidLeadingZeros())
1933 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
1934 if (!FS.hasValidPlusPrefix())
1935 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00001936 if (!FS.hasValidSpacePrefix())
1937 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001938 if (!FS.hasValidAlternativeForm())
1939 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
1940 if (!FS.hasValidLeftJustified())
1941 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
1942
1943 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00001944 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
1945 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
1946 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001947 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
1948 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
1949 startSpecifier, specifierLen);
1950
1951 // Check the length modifier is valid with the given conversion specifier.
1952 const LengthModifier &LM = FS.getLengthModifier();
1953 if (!FS.hasValidLengthModifier())
Richard Trieu55733de2011-10-28 00:41:25 +00001954 EmitFormatDiagnostic(S.PDiag(diag::warn_format_nonsensical_length)
1955 << LM.toString() << CS.toString(),
1956 getLocationOfByte(LM.getStart()),
1957 /*IsStringLocation*/true,
1958 getSpecifierRange(startSpecifier, specifierLen),
1959 FixItHint::CreateRemoval(
1960 getSpecifierRange(LM.getStart(),
1961 LM.getLength())));
Tom Caree4ee9662010-06-17 19:00:27 +00001962
1963 // Are we using '%n'?
Ted Kremenek35d353b2010-07-20 20:04:10 +00001964 if (CS.getKind() == ConversionSpecifier::nArg) {
Tom Caree4ee9662010-06-17 19:00:27 +00001965 // Issue a warning about this being a possible security issue.
Richard Trieu55733de2011-10-28 00:41:25 +00001966 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_write_back),
1967 getLocationOfByte(CS.getStart()),
1968 /*IsStringLocation*/true,
1969 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremeneke82d8042010-01-29 01:35:25 +00001970 // Continue checking the other format specifiers.
1971 return true;
1972 }
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001973
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001974 // The remaining checks depend on the data arguments.
1975 if (HasVAListArg)
1976 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001977
Ted Kremenek666a1972010-07-26 19:45:42 +00001978 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001979 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001980
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001981 // Now type check the data expression that matches the
1982 // format specifier.
1983 const Expr *Ex = getDataArg(argIndex);
1984 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context);
1985 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
1986 // Check if we didn't match because of an implicit cast from a 'char'
1987 // or 'short' to an 'int'. This is done because printf is a varargs
1988 // function.
1989 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00001990 if (ICE->getType() == S.Context.IntTy) {
1991 // All further checking is done on the subexpression.
1992 Ex = ICE->getSubExpr();
1993 if (ATR.matchesType(S.Context, Ex->getType()))
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001994 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00001995 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001996
1997 // We may be able to offer a FixItHint if it is a supported type.
1998 PrintfSpecifier fixedFS = FS;
Hans Wennborga7da2152011-10-18 08:10:06 +00001999 bool success = fixedFS.fixType(Ex->getType(), S.getLangOptions());
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002000
2001 if (success) {
2002 // Get the fix string from the fixed format specifier
2003 llvm::SmallString<128> buf;
2004 llvm::raw_svector_ostream os(buf);
2005 fixedFS.toString(os);
2006
Ted Kremenek9325eaf2010-08-24 22:24:51 +00002007 // FIXME: getRepresentativeType() perhaps should return a string
2008 // instead of a QualType to better handle when the representative
2009 // type is 'wint_t' (which is defined in the system headers).
Richard Trieu55733de2011-10-28 00:41:25 +00002010 EmitFormatDiagnostic(
2011 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2012 << ATR.getRepresentativeType(S.Context) << Ex->getType()
2013 << Ex->getSourceRange(),
2014 getLocationOfByte(CS.getStart()),
2015 /*IsStringLocation*/true,
2016 getSpecifierRange(startSpecifier, specifierLen),
2017 FixItHint::CreateReplacement(
2018 getSpecifierRange(startSpecifier, specifierLen),
2019 os.str()));
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002020 }
2021 else {
2022 S.Diag(getLocationOfByte(CS.getStart()),
2023 diag::warn_printf_conversion_argument_type_mismatch)
2024 << ATR.getRepresentativeType(S.Context) << Ex->getType()
2025 << getSpecifierRange(startSpecifier, specifierLen)
2026 << Ex->getSourceRange();
2027 }
2028 }
2029
Ted Kremeneke0e53132010-01-28 23:39:18 +00002030 return true;
2031}
2032
Ted Kremenek826a3452010-07-16 02:11:22 +00002033//===--- CHECK: Scanf format string checking ------------------------------===//
2034
2035namespace {
2036class CheckScanfHandler : public CheckFormatHandler {
2037public:
2038 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
2039 const Expr *origFormatExpr, unsigned firstDataArg,
2040 unsigned numDataArgs, bool isObjCLiteral,
2041 const char *beg, bool hasVAListArg,
Richard Trieu55733de2011-10-28 00:41:25 +00002042 const CallExpr *theCall, unsigned formatIdx,
2043 bool inFunctionCall)
Ted Kremenek826a3452010-07-16 02:11:22 +00002044 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2045 numDataArgs, isObjCLiteral, beg, hasVAListArg,
Richard Trieu55733de2011-10-28 00:41:25 +00002046 theCall, formatIdx, inFunctionCall) {}
Ted Kremenek826a3452010-07-16 02:11:22 +00002047
2048 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
2049 const char *startSpecifier,
2050 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002051
2052 bool HandleInvalidScanfConversionSpecifier(
2053 const analyze_scanf::ScanfSpecifier &FS,
2054 const char *startSpecifier,
2055 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00002056
2057 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00002058};
Ted Kremenek07d161f2010-01-29 01:50:07 +00002059}
Ted Kremeneke0e53132010-01-28 23:39:18 +00002060
Ted Kremenekb7c21012010-07-16 18:28:03 +00002061void CheckScanfHandler::HandleIncompleteScanList(const char *start,
2062 const char *end) {
Richard Trieu55733de2011-10-28 00:41:25 +00002063 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
2064 getLocationOfByte(end), /*IsStringLocation*/true,
2065 getSpecifierRange(start, end - start));
Ted Kremenekb7c21012010-07-16 18:28:03 +00002066}
2067
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002068bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
2069 const analyze_scanf::ScanfSpecifier &FS,
2070 const char *startSpecifier,
2071 unsigned specifierLen) {
2072
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002073 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002074 FS.getConversionSpecifier();
2075
2076 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2077 getLocationOfByte(CS.getStart()),
2078 startSpecifier, specifierLen,
2079 CS.getStart(), CS.getLength());
2080}
2081
Ted Kremenek826a3452010-07-16 02:11:22 +00002082bool CheckScanfHandler::HandleScanfSpecifier(
2083 const analyze_scanf::ScanfSpecifier &FS,
2084 const char *startSpecifier,
2085 unsigned specifierLen) {
2086
2087 using namespace analyze_scanf;
2088 using namespace analyze_format_string;
2089
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002090 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002091
Ted Kremenekbaa40062010-07-19 22:01:06 +00002092 // Handle case where '%' and '*' don't consume an argument. These shouldn't
2093 // be used to decide if we are using positional arguments consistently.
2094 if (FS.consumesDataArgument()) {
2095 if (atFirstArg) {
2096 atFirstArg = false;
2097 usesPositionalArgs = FS.usesPositionalArg();
2098 }
2099 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002100 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2101 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002102 return false;
2103 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002104 }
2105
2106 // Check if the field with is non-zero.
2107 const OptionalAmount &Amt = FS.getFieldWidth();
2108 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
2109 if (Amt.getConstantAmount() == 0) {
2110 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
2111 Amt.getConstantLength());
Richard Trieu55733de2011-10-28 00:41:25 +00002112 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
2113 getLocationOfByte(Amt.getStart()),
2114 /*IsStringLocation*/true, R,
2115 FixItHint::CreateRemoval(R));
Ted Kremenek826a3452010-07-16 02:11:22 +00002116 }
2117 }
2118
2119 if (!FS.consumesDataArgument()) {
2120 // FIXME: Technically specifying a precision or field width here
2121 // makes no sense. Worth issuing a warning at some point.
2122 return true;
2123 }
2124
2125 // Consume the argument.
2126 unsigned argIndex = FS.getArgIndex();
2127 if (argIndex < NumDataArgs) {
2128 // The check to see if the argIndex is valid will come later.
2129 // We set the bit here because we may exit early from this
2130 // function if we encounter some other error.
2131 CoveredArgs.set(argIndex);
2132 }
2133
Ted Kremenek1e51c202010-07-20 20:04:47 +00002134 // Check the length modifier is valid with the given conversion specifier.
2135 const LengthModifier &LM = FS.getLengthModifier();
2136 if (!FS.hasValidLengthModifier()) {
2137 S.Diag(getLocationOfByte(LM.getStart()),
2138 diag::warn_format_nonsensical_length)
2139 << LM.toString() << CS.toString()
2140 << getSpecifierRange(startSpecifier, specifierLen)
2141 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
2142 LM.getLength()));
2143 }
2144
Ted Kremenek826a3452010-07-16 02:11:22 +00002145 // The remaining checks depend on the data arguments.
2146 if (HasVAListArg)
2147 return true;
2148
Ted Kremenek666a1972010-07-26 19:45:42 +00002149 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00002150 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00002151
2152 // FIXME: Check that the argument type matches the format specifier.
2153
2154 return true;
2155}
2156
2157void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002158 const Expr *OrigFormatExpr,
2159 const CallExpr *TheCall, bool HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00002160 unsigned format_idx, unsigned firstDataArg,
Richard Trieu55733de2011-10-28 00:41:25 +00002161 bool isPrintf, bool inFunctionCall) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002162
Ted Kremeneke0e53132010-01-28 23:39:18 +00002163 // CHECK: is the format string a wide literal?
Douglas Gregor5cee1192011-07-27 05:40:30 +00002164 if (!FExpr->isAscii()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002165 CheckFormatHandler::EmitFormatDiagnostic(
2166 *this, inFunctionCall, TheCall->getArg(format_idx),
2167 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
2168 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00002169 return;
2170 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002171
Ted Kremeneke0e53132010-01-28 23:39:18 +00002172 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner5f9e2722011-07-23 10:55:15 +00002173 StringRef StrRef = FExpr->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00002174 const char *Str = StrRef.data();
2175 unsigned StrLen = StrRef.size();
Ted Kremenek4cd57912011-09-29 05:52:16 +00002176 const unsigned numDataArgs = TheCall->getNumArgs() - firstDataArg;
Ted Kremenek826a3452010-07-16 02:11:22 +00002177
Ted Kremeneke0e53132010-01-28 23:39:18 +00002178 // CHECK: empty format string?
Ted Kremenek4cd57912011-09-29 05:52:16 +00002179 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu55733de2011-10-28 00:41:25 +00002180 CheckFormatHandler::EmitFormatDiagnostic(
2181 *this, inFunctionCall, TheCall->getArg(format_idx),
2182 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
2183 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00002184 return;
2185 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002186
2187 if (isPrintf) {
2188 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Ted Kremenek4cd57912011-09-29 05:52:16 +00002189 numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr),
Richard Trieu55733de2011-10-28 00:41:25 +00002190 Str, HasVAListArg, TheCall, format_idx,
2191 inFunctionCall);
Ted Kremenek826a3452010-07-16 02:11:22 +00002192
2193 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen))
2194 H.DoneProcessing();
2195 }
2196 else {
2197 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Ted Kremenek4cd57912011-09-29 05:52:16 +00002198 numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr),
Richard Trieu55733de2011-10-28 00:41:25 +00002199 Str, HasVAListArg, TheCall, format_idx,
2200 inFunctionCall);
Ted Kremenek826a3452010-07-16 02:11:22 +00002201
2202 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen))
2203 H.DoneProcessing();
2204 }
Ted Kremenekce7024e2010-01-28 01:18:22 +00002205}
2206
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002207//===--- CHECK: Standard memory functions ---------------------------------===//
2208
Douglas Gregor2a053a32011-05-03 20:05:22 +00002209/// \brief Determine whether the given type is a dynamic class type (e.g.,
2210/// whether it has a vtable).
2211static bool isDynamicClassType(QualType T) {
2212 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
2213 if (CXXRecordDecl *Definition = Record->getDefinition())
2214 if (Definition->isDynamicClass())
2215 return true;
2216
2217 return false;
2218}
2219
Chandler Carrutha72a12f2011-06-21 23:04:20 +00002220/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth000d4282011-06-16 09:09:40 +00002221/// otherwise returns NULL.
2222static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Webere4a1c642011-06-14 16:14:58 +00002223 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth000d4282011-06-16 09:09:40 +00002224 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2225 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
2226 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00002227
Chandler Carruth000d4282011-06-16 09:09:40 +00002228 return 0;
2229}
2230
Chandler Carrutha72a12f2011-06-21 23:04:20 +00002231/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth000d4282011-06-16 09:09:40 +00002232static QualType getSizeOfArgType(const Expr* E) {
2233 if (const UnaryExprOrTypeTraitExpr *SizeOf =
2234 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2235 if (SizeOf->getKind() == clang::UETT_SizeOf)
2236 return SizeOf->getTypeOfArgument();
2237
2238 return QualType();
Nico Webere4a1c642011-06-14 16:14:58 +00002239}
2240
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002241/// \brief Check for dangerous or invalid arguments to memset().
2242///
Chandler Carruth929f0132011-06-03 06:23:57 +00002243/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002244/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
2245/// function calls.
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002246///
2247/// \param Call The call expression to diagnose.
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002248void Sema::CheckMemaccessArguments(const CallExpr *Call,
2249 CheckedMemoryFunction CMF,
2250 IdentifierInfo *FnName) {
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00002251 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor707a23e2011-06-16 17:56:04 +00002252 // we have enough arguments, and if not, abort further checking.
Nico Webercda57822011-10-13 22:30:23 +00002253 unsigned ExpectedNumArgs = (CMF == CMF_Strndup ? 2 : 3);
2254 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00002255 return;
2256
Nico Webercda57822011-10-13 22:30:23 +00002257 unsigned LastArg = (CMF == CMF_Memset || CMF == CMF_Strndup ? 1 : 2);
2258 unsigned LenArg = (CMF == CMF_Strndup ? 1 : 2);
2259 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth000d4282011-06-16 09:09:40 +00002260
2261 // We have special checking when the length is a sizeof expression.
2262 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
2263 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
2264 llvm::FoldingSetNodeID SizeOfArgID;
2265
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002266 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
2267 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00002268 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002269
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002270 QualType DestTy = Dest->getType();
2271 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
2272 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00002273
Chandler Carruth000d4282011-06-16 09:09:40 +00002274 // Never warn about void type pointers. This can be used to suppress
2275 // false positives.
2276 if (PointeeTy->isVoidType())
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002277 continue;
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002278
Chandler Carruth000d4282011-06-16 09:09:40 +00002279 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
2280 // actually comparing the expressions for equality. Because computing the
2281 // expression IDs can be expensive, we only do this if the diagnostic is
2282 // enabled.
2283 if (SizeOfArg &&
2284 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
2285 SizeOfArg->getExprLoc())) {
2286 // We only compute IDs for expressions if the warning is enabled, and
2287 // cache the sizeof arg's ID.
2288 if (SizeOfArgID == llvm::FoldingSetNodeID())
2289 SizeOfArg->Profile(SizeOfArgID, Context, true);
2290 llvm::FoldingSetNodeID DestID;
2291 Dest->Profile(DestID, Context, true);
2292 if (DestID == SizeOfArgID) {
Nico Webercda57822011-10-13 22:30:23 +00002293 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
2294 // over sizeof(src) as well.
Chandler Carruth000d4282011-06-16 09:09:40 +00002295 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
2296 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
2297 if (UnaryOp->getOpcode() == UO_AddrOf)
2298 ActionIdx = 1; // If its an address-of operator, just remove it.
2299 if (Context.getTypeSize(PointeeTy) == Context.getCharWidth())
2300 ActionIdx = 2; // If the pointee's size is sizeof(char),
2301 // suggest an explicit length.
Nico Webercda57822011-10-13 22:30:23 +00002302 unsigned DestSrcSelect = (CMF == CMF_Strndup ? 1 : ArgIdx);
Chandler Carruth000d4282011-06-16 09:09:40 +00002303 DiagRuntimeBehavior(SizeOfArg->getExprLoc(), Dest,
2304 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Nico Webercda57822011-10-13 22:30:23 +00002305 << FnName << DestSrcSelect << ActionIdx
Chandler Carruth000d4282011-06-16 09:09:40 +00002306 << Dest->getSourceRange()
2307 << SizeOfArg->getSourceRange());
2308 break;
2309 }
2310 }
2311
2312 // Also check for cases where the sizeof argument is the exact same
2313 // type as the memory argument, and where it points to a user-defined
2314 // record type.
2315 if (SizeOfArgTy != QualType()) {
2316 if (PointeeTy->isRecordType() &&
2317 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
2318 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
2319 PDiag(diag::warn_sizeof_pointer_type_memaccess)
2320 << FnName << SizeOfArgTy << ArgIdx
2321 << PointeeTy << Dest->getSourceRange()
2322 << LenExpr->getSourceRange());
2323 break;
2324 }
Nico Webere4a1c642011-06-14 16:14:58 +00002325 }
2326
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002327 // Always complain about dynamic classes.
John McCallf85e1932011-06-15 23:02:42 +00002328 if (isDynamicClassType(PointeeTy))
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00002329 DiagRuntimeBehavior(
2330 Dest->getExprLoc(), Dest,
2331 PDiag(diag::warn_dyn_class_memaccess)
2332 << (CMF == CMF_Memcmp ? ArgIdx + 2 : ArgIdx) << FnName << PointeeTy
2333 // "overwritten" if we're warning about the destination for any call
2334 // but memcmp; otherwise a verb appropriate to the call.
2335 << (ArgIdx == 0 && CMF != CMF_Memcmp ? 0 : (unsigned)CMF)
2336 << Call->getCallee()->getSourceRange());
Douglas Gregor707a23e2011-06-16 17:56:04 +00002337 else if (PointeeTy.hasNonTrivialObjCLifetime() && CMF != CMF_Memset)
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00002338 DiagRuntimeBehavior(
2339 Dest->getExprLoc(), Dest,
2340 PDiag(diag::warn_arc_object_memaccess)
2341 << ArgIdx << FnName << PointeeTy
2342 << Call->getCallee()->getSourceRange());
John McCallf85e1932011-06-15 23:02:42 +00002343 else
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002344 continue;
John McCallf85e1932011-06-15 23:02:42 +00002345
2346 DiagRuntimeBehavior(
2347 Dest->getExprLoc(), Dest,
Chandler Carruth929f0132011-06-03 06:23:57 +00002348 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002349 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
2350 break;
2351 }
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002352 }
2353}
2354
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002355// A little helper routine: ignore addition and subtraction of integer literals.
2356// This intentionally does not ignore all integer constant expressions because
2357// we don't want to remove sizeof().
2358static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
2359 Ex = Ex->IgnoreParenCasts();
2360
2361 for (;;) {
2362 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
2363 if (!BO || !BO->isAdditiveOp())
2364 break;
2365
2366 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
2367 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
2368
2369 if (isa<IntegerLiteral>(RHS))
2370 Ex = LHS;
2371 else if (isa<IntegerLiteral>(LHS))
2372 Ex = RHS;
2373 else
2374 break;
2375 }
2376
2377 return Ex;
2378}
2379
2380// Warn if the user has made the 'size' argument to strlcpy or strlcat
2381// be the size of the source, instead of the destination.
2382void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
2383 IdentifierInfo *FnName) {
2384
2385 // Don't crash if the user has the wrong number of arguments
2386 if (Call->getNumArgs() != 3)
2387 return;
2388
2389 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
2390 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
2391 const Expr *CompareWithSrc = NULL;
2392
2393 // Look for 'strlcpy(dst, x, sizeof(x))'
2394 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
2395 CompareWithSrc = Ex;
2396 else {
2397 // Look for 'strlcpy(dst, x, strlen(x))'
2398 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
2399 if (SizeCall->isBuiltinCall(Context) == Builtin::BIstrlen
2400 && SizeCall->getNumArgs() == 1)
2401 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
2402 }
2403 }
2404
2405 if (!CompareWithSrc)
2406 return;
2407
2408 // Determine if the argument to sizeof/strlen is equal to the source
2409 // argument. In principle there's all kinds of things you could do
2410 // here, for instance creating an == expression and evaluating it with
2411 // EvaluateAsBooleanCondition, but this uses a more direct technique:
2412 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
2413 if (!SrcArgDRE)
2414 return;
2415
2416 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
2417 if (!CompareWithSrcDRE ||
2418 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
2419 return;
2420
2421 const Expr *OriginalSizeArg = Call->getArg(2);
2422 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
2423 << OriginalSizeArg->getSourceRange() << FnName;
2424
2425 // Output a FIXIT hint if the destination is an array (rather than a
2426 // pointer to an array). This could be enhanced to handle some
2427 // pointers if we know the actual size, like if DstArg is 'array+2'
2428 // we could say 'sizeof(array)-2'.
2429 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Ted Kremenek8f746222011-08-18 22:48:41 +00002430 QualType DstArgTy = DstArg->getType();
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002431
Ted Kremenek8f746222011-08-18 22:48:41 +00002432 // Only handle constant-sized or VLAs, but not flexible members.
2433 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(DstArgTy)) {
2434 // Only issue the FIXIT for arrays of size > 1.
2435 if (CAT->getSize().getSExtValue() <= 1)
2436 return;
2437 } else if (!DstArgTy->isVariableArrayType()) {
2438 return;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002439 }
Ted Kremenek8f746222011-08-18 22:48:41 +00002440
2441 llvm::SmallString<128> sizeString;
2442 llvm::raw_svector_ostream OS(sizeString);
2443 OS << "sizeof(";
Douglas Gregor8987b232011-09-27 23:30:47 +00002444 DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
Ted Kremenek8f746222011-08-18 22:48:41 +00002445 OS << ")";
2446
2447 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
2448 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
2449 OS.str());
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002450}
2451
Ted Kremenek06de2762007-08-17 16:46:58 +00002452//===--- CHECK: Return Address of Stack Variable --------------------------===//
2453
Chris Lattner5f9e2722011-07-23 10:55:15 +00002454static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars);
2455static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002456
2457/// CheckReturnStackAddr - Check if a return statement returns the address
2458/// of a stack variable.
2459void
2460Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
2461 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00002462
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002463 Expr *stackE = 0;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002464 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002465
2466 // Perform checking for returned stack addresses, local blocks,
2467 // label addresses or references to temporaries.
John McCallf85e1932011-06-15 23:02:42 +00002468 if (lhsType->isPointerType() ||
2469 (!getLangOptions().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002470 stackE = EvalAddr(RetValExp, refVars);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002471 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002472 stackE = EvalVal(RetValExp, refVars);
2473 }
2474
2475 if (stackE == 0)
2476 return; // Nothing suspicious was found.
2477
2478 SourceLocation diagLoc;
2479 SourceRange diagRange;
2480 if (refVars.empty()) {
2481 diagLoc = stackE->getLocStart();
2482 diagRange = stackE->getSourceRange();
2483 } else {
2484 // We followed through a reference variable. 'stackE' contains the
2485 // problematic expression but we will warn at the return statement pointing
2486 // at the reference variable. We will later display the "trail" of
2487 // reference variables using notes.
2488 diagLoc = refVars[0]->getLocStart();
2489 diagRange = refVars[0]->getSourceRange();
2490 }
2491
2492 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
2493 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
2494 : diag::warn_ret_stack_addr)
2495 << DR->getDecl()->getDeclName() << diagRange;
2496 } else if (isa<BlockExpr>(stackE)) { // local block.
2497 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
2498 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
2499 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
2500 } else { // local temporary.
2501 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
2502 : diag::warn_ret_local_temp_addr)
2503 << diagRange;
2504 }
2505
2506 // Display the "trail" of reference variables that we followed until we
2507 // found the problematic expression using notes.
2508 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
2509 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
2510 // If this var binds to another reference var, show the range of the next
2511 // var, otherwise the var binds to the problematic expression, in which case
2512 // show the range of the expression.
2513 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
2514 : stackE->getSourceRange();
2515 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
2516 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00002517 }
2518}
2519
2520/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
2521/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002522/// to a location on the stack, a local block, an address of a label, or a
2523/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00002524/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002525/// encounter a subexpression that (1) clearly does not lead to one of the
2526/// above problematic expressions (2) is something we cannot determine leads to
2527/// a problematic expression based on such local checking.
2528///
2529/// Both EvalAddr and EvalVal follow through reference variables to evaluate
2530/// the expression that they point to. Such variables are added to the
2531/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00002532///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00002533/// EvalAddr processes expressions that are pointers that are used as
2534/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002535/// At the base case of the recursion is a check for the above problematic
2536/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00002537///
2538/// This implementation handles:
2539///
2540/// * pointer-to-pointer casts
2541/// * implicit conversions from array references to pointers
2542/// * taking the address of fields
2543/// * arbitrary interplay between "&" and "*" operators
2544/// * pointer arithmetic from an address of a stack variable
2545/// * taking the address of an array element where the array is on the stack
Chris Lattner5f9e2722011-07-23 10:55:15 +00002546static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002547 if (E->isTypeDependent())
2548 return NULL;
2549
Ted Kremenek06de2762007-08-17 16:46:58 +00002550 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00002551 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00002552 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002553 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002554 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00002555
Peter Collingbournef111d932011-04-15 00:35:48 +00002556 E = E->IgnoreParens();
2557
Ted Kremenek06de2762007-08-17 16:46:58 +00002558 // Our "symbolic interpreter" is just a dispatch off the currently
2559 // viewed AST node. We then recursively traverse the AST by calling
2560 // EvalAddr and EvalVal appropriately.
2561 switch (E->getStmtClass()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002562 case Stmt::DeclRefExprClass: {
2563 DeclRefExpr *DR = cast<DeclRefExpr>(E);
2564
2565 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
2566 // If this is a reference variable, follow through to the expression that
2567 // it points to.
2568 if (V->hasLocalStorage() &&
2569 V->getType()->isReferenceType() && V->hasInit()) {
2570 // Add the reference variable to the "trail".
2571 refVars.push_back(DR);
2572 return EvalAddr(V->getInit(), refVars);
2573 }
2574
2575 return NULL;
2576 }
Ted Kremenek06de2762007-08-17 16:46:58 +00002577
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002578 case Stmt::UnaryOperatorClass: {
2579 // The only unary operator that make sense to handle here
2580 // is AddrOf. All others don't make sense as pointers.
2581 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002582
John McCall2de56d12010-08-25 11:45:40 +00002583 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002584 return EvalVal(U->getSubExpr(), refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002585 else
Ted Kremenek06de2762007-08-17 16:46:58 +00002586 return NULL;
2587 }
Mike Stump1eb44332009-09-09 15:08:12 +00002588
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002589 case Stmt::BinaryOperatorClass: {
2590 // Handle pointer arithmetic. All other binary operators are not valid
2591 // in this context.
2592 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00002593 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00002594
John McCall2de56d12010-08-25 11:45:40 +00002595 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002596 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00002597
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002598 Expr *Base = B->getLHS();
2599
2600 // Determine which argument is the real pointer base. It could be
2601 // the RHS argument instead of the LHS.
2602 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00002603
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002604 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002605 return EvalAddr(Base, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002606 }
Steve Naroff61f40a22008-09-10 19:17:48 +00002607
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002608 // For conditional operators we need to see if either the LHS or RHS are
2609 // valid DeclRefExpr*s. If one of them is valid, we return it.
2610 case Stmt::ConditionalOperatorClass: {
2611 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002612
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002613 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00002614 if (Expr *lhsExpr = C->getLHS()) {
2615 // In C++, we can have a throw-expression, which has 'void' type.
2616 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002617 if (Expr* LHS = EvalAddr(lhsExpr, refVars))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00002618 return LHS;
2619 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002620
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00002621 // In C++, we can have a throw-expression, which has 'void' type.
2622 if (C->getRHS()->getType()->isVoidType())
2623 return NULL;
2624
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002625 return EvalAddr(C->getRHS(), refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002626 }
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002627
2628 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00002629 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002630 return E; // local block.
2631 return NULL;
2632
2633 case Stmt::AddrLabelExprClass:
2634 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00002635
Ted Kremenek54b52742008-08-07 00:49:01 +00002636 // For casts, we need to handle conversions from arrays to
2637 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00002638 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002639 case Stmt::CStyleCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00002640 case Stmt::CXXFunctionalCastExprClass:
2641 case Stmt::ObjCBridgedCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002642 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenek54b52742008-08-07 00:49:01 +00002643 QualType T = SubExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002644
Steve Naroffdd972f22008-09-05 22:11:13 +00002645 if (SubExpr->getType()->isPointerType() ||
2646 SubExpr->getType()->isBlockPointerType() ||
2647 SubExpr->getType()->isObjCQualifiedIdType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002648 return EvalAddr(SubExpr, refVars);
Ted Kremenek54b52742008-08-07 00:49:01 +00002649 else if (T->isArrayType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002650 return EvalVal(SubExpr, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002651 else
Ted Kremenek54b52742008-08-07 00:49:01 +00002652 return 0;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002653 }
Mike Stump1eb44332009-09-09 15:08:12 +00002654
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002655 // C++ casts. For dynamic casts, static casts, and const casts, we
2656 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor49badde2008-10-27 19:41:14 +00002657 // through the cast. In the case the dynamic cast doesn't fail (and
2658 // return NULL), we take the conservative route and report cases
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002659 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor49badde2008-10-27 19:41:14 +00002660 // FIXME: The comment about is wrong; we're not always converting
2661 // from pointer to pointer. I'm guessing that this code should also
Mike Stump1eb44332009-09-09 15:08:12 +00002662 // handle references to objects.
2663 case Stmt::CXXStaticCastExprClass:
2664 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00002665 case Stmt::CXXConstCastExprClass:
2666 case Stmt::CXXReinterpretCastExprClass: {
2667 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffdd972f22008-09-05 22:11:13 +00002668 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002669 return EvalAddr(S, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002670 else
2671 return NULL;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002672 }
Mike Stump1eb44332009-09-09 15:08:12 +00002673
Douglas Gregor03e80032011-06-21 17:03:29 +00002674 case Stmt::MaterializeTemporaryExprClass:
2675 if (Expr *Result = EvalAddr(
2676 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
2677 refVars))
2678 return Result;
2679
2680 return E;
2681
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002682 // Everything else: we simply don't reason about them.
2683 default:
2684 return NULL;
2685 }
Ted Kremenek06de2762007-08-17 16:46:58 +00002686}
Mike Stump1eb44332009-09-09 15:08:12 +00002687
Ted Kremenek06de2762007-08-17 16:46:58 +00002688
2689/// EvalVal - This function is complements EvalAddr in the mutual recursion.
2690/// See the comments for EvalAddr for more details.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002691static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002692do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00002693 // We should only be called for evaluating non-pointer expressions, or
2694 // expressions with a pointer type that are not used as references but instead
2695 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00002696
Ted Kremenek06de2762007-08-17 16:46:58 +00002697 // Our "symbolic interpreter" is just a dispatch off the currently
2698 // viewed AST node. We then recursively traverse the AST by calling
2699 // EvalAddr and EvalVal appropriately.
Peter Collingbournef111d932011-04-15 00:35:48 +00002700
2701 E = E->IgnoreParens();
Ted Kremenek06de2762007-08-17 16:46:58 +00002702 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002703 case Stmt::ImplicitCastExprClass: {
2704 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00002705 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002706 E = IE->getSubExpr();
2707 continue;
2708 }
2709 return NULL;
2710 }
2711
Douglas Gregora2813ce2009-10-23 18:54:35 +00002712 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002713 // When we hit a DeclRefExpr we are looking at code that refers to a
2714 // variable's name. If it's not a reference variable we check if it has
2715 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00002716 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002717
Ted Kremenek06de2762007-08-17 16:46:58 +00002718 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002719 if (V->hasLocalStorage()) {
2720 if (!V->getType()->isReferenceType())
2721 return DR;
2722
2723 // Reference variable, follow through to the expression that
2724 // it points to.
2725 if (V->hasInit()) {
2726 // Add the reference variable to the "trail".
2727 refVars.push_back(DR);
2728 return EvalVal(V->getInit(), refVars);
2729 }
2730 }
Mike Stump1eb44332009-09-09 15:08:12 +00002731
Ted Kremenek06de2762007-08-17 16:46:58 +00002732 return NULL;
2733 }
Mike Stump1eb44332009-09-09 15:08:12 +00002734
Ted Kremenek06de2762007-08-17 16:46:58 +00002735 case Stmt::UnaryOperatorClass: {
2736 // The only unary operator that make sense to handle here
2737 // is Deref. All others don't resolve to a "name." This includes
2738 // handling all sorts of rvalues passed to a unary operator.
2739 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002740
John McCall2de56d12010-08-25 11:45:40 +00002741 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002742 return EvalAddr(U->getSubExpr(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002743
2744 return NULL;
2745 }
Mike Stump1eb44332009-09-09 15:08:12 +00002746
Ted Kremenek06de2762007-08-17 16:46:58 +00002747 case Stmt::ArraySubscriptExprClass: {
2748 // Array subscripts are potential references to data on the stack. We
2749 // retrieve the DeclRefExpr* for the array variable if it indeed
2750 // has local storage.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002751 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002752 }
Mike Stump1eb44332009-09-09 15:08:12 +00002753
Ted Kremenek06de2762007-08-17 16:46:58 +00002754 case Stmt::ConditionalOperatorClass: {
2755 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002756 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00002757 ConditionalOperator *C = cast<ConditionalOperator>(E);
2758
Anders Carlsson39073232007-11-30 19:04:31 +00002759 // Handle the GNU extension for missing LHS.
2760 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002761 if (Expr *LHS = EvalVal(lhsExpr, refVars))
Anders Carlsson39073232007-11-30 19:04:31 +00002762 return LHS;
2763
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002764 return EvalVal(C->getRHS(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002765 }
Mike Stump1eb44332009-09-09 15:08:12 +00002766
Ted Kremenek06de2762007-08-17 16:46:58 +00002767 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00002768 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00002769 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002770
Ted Kremenek06de2762007-08-17 16:46:58 +00002771 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00002772 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00002773 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00002774
2775 // Check whether the member type is itself a reference, in which case
2776 // we're not going to refer to the member, but to what the member refers to.
2777 if (M->getMemberDecl()->getType()->isReferenceType())
2778 return NULL;
2779
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002780 return EvalVal(M->getBase(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002781 }
Mike Stump1eb44332009-09-09 15:08:12 +00002782
Douglas Gregor03e80032011-06-21 17:03:29 +00002783 case Stmt::MaterializeTemporaryExprClass:
2784 if (Expr *Result = EvalVal(
2785 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
2786 refVars))
2787 return Result;
2788
2789 return E;
2790
Ted Kremenek06de2762007-08-17 16:46:58 +00002791 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002792 // Check that we don't return or take the address of a reference to a
2793 // temporary. This is only useful in C++.
2794 if (!E->isTypeDependent() && E->isRValue())
2795 return E;
2796
2797 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00002798 return NULL;
2799 }
Ted Kremenek68957a92010-08-04 20:01:07 +00002800} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00002801}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002802
2803//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
2804
2805/// Check for comparisons of floating point operands using != and ==.
2806/// Issue a warning if these are no self-comparisons, as they are not likely
2807/// to do what the programmer intended.
Richard Trieudd225092011-09-15 21:56:47 +00002808void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002809 bool EmitWarning = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002810
Richard Trieudd225092011-09-15 21:56:47 +00002811 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
2812 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002813
2814 // Special case: check for x == x (which is OK).
2815 // Do not emit warnings for such cases.
2816 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
2817 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
2818 if (DRL->getDecl() == DRR->getDecl())
2819 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002820
2821
Ted Kremenek1b500bb2007-11-29 00:59:04 +00002822 // Special case: check for comparisons against literals that can be exactly
2823 // represented by APFloat. In such cases, do not emit a warning. This
2824 // is a heuristic: often comparison against such literals are used to
2825 // detect if a value in a variable has not changed. This clearly can
2826 // lead to false negatives.
2827 if (EmitWarning) {
2828 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
2829 if (FLL->isExact())
2830 EmitWarning = false;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002831 } else
Ted Kremenek1b500bb2007-11-29 00:59:04 +00002832 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
2833 if (FLR->isExact())
2834 EmitWarning = false;
2835 }
2836 }
Mike Stump1eb44332009-09-09 15:08:12 +00002837
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002838 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002839 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002840 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00002841 if (CL->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002842 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002843
Sebastian Redl0eb23302009-01-19 00:08:26 +00002844 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002845 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00002846 if (CR->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002847 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002848
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002849 // Emit the diagnostic.
2850 if (EmitWarning)
Richard Trieudd225092011-09-15 21:56:47 +00002851 Diag(Loc, diag::warn_floatingpoint_eq)
2852 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002853}
John McCallba26e582010-01-04 23:21:16 +00002854
John McCallf2370c92010-01-06 05:24:50 +00002855//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
2856//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00002857
John McCallf2370c92010-01-06 05:24:50 +00002858namespace {
John McCallba26e582010-01-04 23:21:16 +00002859
John McCallf2370c92010-01-06 05:24:50 +00002860/// Structure recording the 'active' range of an integer-valued
2861/// expression.
2862struct IntRange {
2863 /// The number of bits active in the int.
2864 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00002865
John McCallf2370c92010-01-06 05:24:50 +00002866 /// True if the int is known not to have negative values.
2867 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00002868
John McCallf2370c92010-01-06 05:24:50 +00002869 IntRange(unsigned Width, bool NonNegative)
2870 : Width(Width), NonNegative(NonNegative)
2871 {}
John McCallba26e582010-01-04 23:21:16 +00002872
John McCall1844a6e2010-11-10 23:38:19 +00002873 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00002874 static IntRange forBoolType() {
2875 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00002876 }
2877
John McCall1844a6e2010-11-10 23:38:19 +00002878 /// Returns the range of an opaque value of the given integral type.
2879 static IntRange forValueOfType(ASTContext &C, QualType T) {
2880 return forValueOfCanonicalType(C,
2881 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00002882 }
2883
John McCall1844a6e2010-11-10 23:38:19 +00002884 /// Returns the range of an opaque value of a canonical integral type.
2885 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00002886 assert(T->isCanonicalUnqualified());
2887
2888 if (const VectorType *VT = dyn_cast<VectorType>(T))
2889 T = VT->getElementType().getTypePtr();
2890 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2891 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00002892
John McCall091f23f2010-11-09 22:22:12 +00002893 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00002894 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
2895 EnumDecl *Enum = ET->getDecl();
John McCall5e1cdac2011-10-07 06:10:15 +00002896 if (!Enum->isCompleteDefinition())
John McCall091f23f2010-11-09 22:22:12 +00002897 return IntRange(C.getIntWidth(QualType(T, 0)), false);
2898
John McCall323ed742010-05-06 08:58:33 +00002899 unsigned NumPositive = Enum->getNumPositiveBits();
2900 unsigned NumNegative = Enum->getNumNegativeBits();
2901
2902 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
2903 }
John McCallf2370c92010-01-06 05:24:50 +00002904
2905 const BuiltinType *BT = cast<BuiltinType>(T);
2906 assert(BT->isInteger());
2907
2908 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2909 }
2910
John McCall1844a6e2010-11-10 23:38:19 +00002911 /// Returns the "target" range of a canonical integral type, i.e.
2912 /// the range of values expressible in the type.
2913 ///
2914 /// This matches forValueOfCanonicalType except that enums have the
2915 /// full range of their type, not the range of their enumerators.
2916 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
2917 assert(T->isCanonicalUnqualified());
2918
2919 if (const VectorType *VT = dyn_cast<VectorType>(T))
2920 T = VT->getElementType().getTypePtr();
2921 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2922 T = CT->getElementType().getTypePtr();
2923 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor69ff26b2011-09-08 23:29:05 +00002924 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall1844a6e2010-11-10 23:38:19 +00002925
2926 const BuiltinType *BT = cast<BuiltinType>(T);
2927 assert(BT->isInteger());
2928
2929 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2930 }
2931
2932 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00002933 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00002934 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00002935 L.NonNegative && R.NonNegative);
2936 }
2937
John McCall1844a6e2010-11-10 23:38:19 +00002938 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00002939 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00002940 return IntRange(std::min(L.Width, R.Width),
2941 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00002942 }
2943};
2944
2945IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
2946 if (value.isSigned() && value.isNegative())
2947 return IntRange(value.getMinSignedBits(), false);
2948
2949 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00002950 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00002951
2952 // isNonNegative() just checks the sign bit without considering
2953 // signedness.
2954 return IntRange(value.getActiveBits(), true);
2955}
2956
John McCall0acc3112010-01-06 22:57:21 +00002957IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
John McCallf2370c92010-01-06 05:24:50 +00002958 unsigned MaxWidth) {
2959 if (result.isInt())
2960 return GetValueRange(C, result.getInt(), MaxWidth);
2961
2962 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00002963 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
2964 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
2965 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
2966 R = IntRange::join(R, El);
2967 }
John McCallf2370c92010-01-06 05:24:50 +00002968 return R;
2969 }
2970
2971 if (result.isComplexInt()) {
2972 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
2973 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
2974 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00002975 }
2976
2977 // This can happen with lossless casts to intptr_t of "based" lvalues.
2978 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00002979 // FIXME: The only reason we need to pass the type in here is to get
2980 // the sign right on this one case. It would be nice if APValue
2981 // preserved this.
John McCallf2370c92010-01-06 05:24:50 +00002982 assert(result.isLValue());
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00002983 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall51313c32010-01-04 23:31:57 +00002984}
John McCallf2370c92010-01-06 05:24:50 +00002985
2986/// Pseudo-evaluate the given integer expression, estimating the
2987/// range of values it might take.
2988///
2989/// \param MaxWidth - the width to which the value will be truncated
2990IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
2991 E = E->IgnoreParens();
2992
2993 // Try a full evaluation first.
2994 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00002995 if (E->EvaluateAsRValue(result, C))
John McCall0acc3112010-01-06 22:57:21 +00002996 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00002997
2998 // I think we only want to look through implicit casts here; if the
2999 // user has an explicit widening cast, we should treat the value as
3000 // being of the new, wider type.
3001 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall2de56d12010-08-25 11:45:40 +00003002 if (CE->getCastKind() == CK_NoOp)
John McCallf2370c92010-01-06 05:24:50 +00003003 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
3004
John McCall1844a6e2010-11-10 23:38:19 +00003005 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
John McCallf2370c92010-01-06 05:24:50 +00003006
John McCall2de56d12010-08-25 11:45:40 +00003007 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00003008
John McCallf2370c92010-01-06 05:24:50 +00003009 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00003010 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00003011 return OutputTypeRange;
3012
3013 IntRange SubRange
3014 = GetExprRange(C, CE->getSubExpr(),
3015 std::min(MaxWidth, OutputTypeRange.Width));
3016
3017 // Bail out if the subexpr's range is as wide as the cast type.
3018 if (SubRange.Width >= OutputTypeRange.Width)
3019 return OutputTypeRange;
3020
3021 // Otherwise, we take the smaller width, and we're non-negative if
3022 // either the output type or the subexpr is.
3023 return IntRange(SubRange.Width,
3024 SubRange.NonNegative || OutputTypeRange.NonNegative);
3025 }
3026
3027 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3028 // If we can fold the condition, just take that operand.
3029 bool CondResult;
3030 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
3031 return GetExprRange(C, CondResult ? CO->getTrueExpr()
3032 : CO->getFalseExpr(),
3033 MaxWidth);
3034
3035 // Otherwise, conservatively merge.
3036 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
3037 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
3038 return IntRange::join(L, R);
3039 }
3040
3041 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3042 switch (BO->getOpcode()) {
3043
3044 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00003045 case BO_LAnd:
3046 case BO_LOr:
3047 case BO_LT:
3048 case BO_GT:
3049 case BO_LE:
3050 case BO_GE:
3051 case BO_EQ:
3052 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00003053 return IntRange::forBoolType();
3054
John McCall862ff872011-07-13 06:35:24 +00003055 // The type of the assignments is the type of the LHS, so the RHS
3056 // is not necessarily the same type.
John McCall2de56d12010-08-25 11:45:40 +00003057 case BO_MulAssign:
3058 case BO_DivAssign:
3059 case BO_RemAssign:
3060 case BO_AddAssign:
3061 case BO_SubAssign:
John McCall862ff872011-07-13 06:35:24 +00003062 case BO_XorAssign:
3063 case BO_OrAssign:
3064 // TODO: bitfields?
John McCall1844a6e2010-11-10 23:38:19 +00003065 return IntRange::forValueOfType(C, E->getType());
John McCallc0cd21d2010-02-23 19:22:29 +00003066
John McCall862ff872011-07-13 06:35:24 +00003067 // Simple assignments just pass through the RHS, which will have
3068 // been coerced to the LHS type.
3069 case BO_Assign:
3070 // TODO: bitfields?
3071 return GetExprRange(C, BO->getRHS(), MaxWidth);
3072
John McCallf2370c92010-01-06 05:24:50 +00003073 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00003074 case BO_PtrMemD:
3075 case BO_PtrMemI:
John McCall1844a6e2010-11-10 23:38:19 +00003076 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003077
John McCall60fad452010-01-06 22:07:33 +00003078 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00003079 case BO_And:
3080 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00003081 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
3082 GetExprRange(C, BO->getRHS(), MaxWidth));
3083
John McCallf2370c92010-01-06 05:24:50 +00003084 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00003085 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00003086 // ...except that we want to treat '1 << (blah)' as logically
3087 // positive. It's an important idiom.
3088 if (IntegerLiteral *I
3089 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
3090 if (I->getValue() == 1) {
John McCall1844a6e2010-11-10 23:38:19 +00003091 IntRange R = IntRange::forValueOfType(C, E->getType());
John McCall3aae6092010-04-07 01:14:35 +00003092 return IntRange(R.Width, /*NonNegative*/ true);
3093 }
3094 }
3095 // fallthrough
3096
John McCall2de56d12010-08-25 11:45:40 +00003097 case BO_ShlAssign:
John McCall1844a6e2010-11-10 23:38:19 +00003098 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003099
John McCall60fad452010-01-06 22:07:33 +00003100 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00003101 case BO_Shr:
3102 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00003103 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3104
3105 // If the shift amount is a positive constant, drop the width by
3106 // that much.
3107 llvm::APSInt shift;
3108 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
3109 shift.isNonNegative()) {
3110 unsigned zext = shift.getZExtValue();
3111 if (zext >= L.Width)
3112 L.Width = (L.NonNegative ? 0 : 1);
3113 else
3114 L.Width -= zext;
3115 }
3116
3117 return L;
3118 }
3119
3120 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00003121 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00003122 return GetExprRange(C, BO->getRHS(), MaxWidth);
3123
John McCall60fad452010-01-06 22:07:33 +00003124 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00003125 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00003126 if (BO->getLHS()->getType()->isPointerType())
John McCall1844a6e2010-11-10 23:38:19 +00003127 return IntRange::forValueOfType(C, E->getType());
John McCall00fe7612011-07-14 22:39:48 +00003128 break;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003129
John McCall00fe7612011-07-14 22:39:48 +00003130 // The width of a division result is mostly determined by the size
3131 // of the LHS.
3132 case BO_Div: {
3133 // Don't 'pre-truncate' the operands.
3134 unsigned opWidth = C.getIntWidth(E->getType());
3135 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3136
3137 // If the divisor is constant, use that.
3138 llvm::APSInt divisor;
3139 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
3140 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
3141 if (log2 >= L.Width)
3142 L.Width = (L.NonNegative ? 0 : 1);
3143 else
3144 L.Width = std::min(L.Width - log2, MaxWidth);
3145 return L;
3146 }
3147
3148 // Otherwise, just use the LHS's width.
3149 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3150 return IntRange(L.Width, L.NonNegative && R.NonNegative);
3151 }
3152
3153 // The result of a remainder can't be larger than the result of
3154 // either side.
3155 case BO_Rem: {
3156 // Don't 'pre-truncate' the operands.
3157 unsigned opWidth = C.getIntWidth(E->getType());
3158 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3159 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3160
3161 IntRange meet = IntRange::meet(L, R);
3162 meet.Width = std::min(meet.Width, MaxWidth);
3163 return meet;
3164 }
3165
3166 // The default behavior is okay for these.
3167 case BO_Mul:
3168 case BO_Add:
3169 case BO_Xor:
3170 case BO_Or:
John McCallf2370c92010-01-06 05:24:50 +00003171 break;
3172 }
3173
John McCall00fe7612011-07-14 22:39:48 +00003174 // The default case is to treat the operation as if it were closed
3175 // on the narrowest type that encompasses both operands.
John McCallf2370c92010-01-06 05:24:50 +00003176 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3177 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
3178 return IntRange::join(L, R);
3179 }
3180
3181 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
3182 switch (UO->getOpcode()) {
3183 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00003184 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00003185 return IntRange::forBoolType();
3186
3187 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00003188 case UO_Deref:
3189 case UO_AddrOf: // should be impossible
John McCall1844a6e2010-11-10 23:38:19 +00003190 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003191
3192 default:
3193 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
3194 }
3195 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003196
3197 if (dyn_cast<OffsetOfExpr>(E)) {
John McCall1844a6e2010-11-10 23:38:19 +00003198 IntRange::forValueOfType(C, E->getType());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003199 }
John McCallf2370c92010-01-06 05:24:50 +00003200
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003201 if (FieldDecl *BitField = E->getBitField())
3202 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00003203 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCallf2370c92010-01-06 05:24:50 +00003204
John McCall1844a6e2010-11-10 23:38:19 +00003205 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003206}
John McCall51313c32010-01-04 23:31:57 +00003207
John McCall323ed742010-05-06 08:58:33 +00003208IntRange GetExprRange(ASTContext &C, Expr *E) {
3209 return GetExprRange(C, E, C.getIntWidth(E->getType()));
3210}
3211
John McCall51313c32010-01-04 23:31:57 +00003212/// Checks whether the given value, which currently has the given
3213/// source semantics, has the same value when coerced through the
3214/// target semantics.
John McCallf2370c92010-01-06 05:24:50 +00003215bool IsSameFloatAfterCast(const llvm::APFloat &value,
3216 const llvm::fltSemantics &Src,
3217 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00003218 llvm::APFloat truncated = value;
3219
3220 bool ignored;
3221 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
3222 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
3223
3224 return truncated.bitwiseIsEqual(value);
3225}
3226
3227/// Checks whether the given value, which currently has the given
3228/// source semantics, has the same value when coerced through the
3229/// target semantics.
3230///
3231/// The value might be a vector of floats (or a complex number).
John McCallf2370c92010-01-06 05:24:50 +00003232bool IsSameFloatAfterCast(const APValue &value,
3233 const llvm::fltSemantics &Src,
3234 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00003235 if (value.isFloat())
3236 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
3237
3238 if (value.isVector()) {
3239 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
3240 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
3241 return false;
3242 return true;
3243 }
3244
3245 assert(value.isComplexFloat());
3246 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
3247 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
3248}
3249
John McCallb4eb64d2010-10-08 02:01:28 +00003250void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00003251
Ted Kremeneke3b159c2010-09-23 21:43:44 +00003252static bool IsZero(Sema &S, Expr *E) {
3253 // Suppress cases where we are comparing against an enum constant.
3254 if (const DeclRefExpr *DR =
3255 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
3256 if (isa<EnumConstantDecl>(DR->getDecl()))
3257 return false;
3258
3259 // Suppress cases where the '0' value is expanded from a macro.
3260 if (E->getLocStart().isMacroID())
3261 return false;
3262
John McCall323ed742010-05-06 08:58:33 +00003263 llvm::APSInt Value;
3264 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
3265}
3266
John McCall372e1032010-10-06 00:25:24 +00003267static bool HasEnumType(Expr *E) {
3268 // Strip off implicit integral promotions.
3269 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00003270 if (ICE->getCastKind() != CK_IntegralCast &&
3271 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00003272 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00003273 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00003274 }
3275
3276 return E->getType()->isEnumeralType();
3277}
3278
John McCall323ed742010-05-06 08:58:33 +00003279void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00003280 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00003281 if (E->isValueDependent())
3282 return;
3283
John McCall2de56d12010-08-25 11:45:40 +00003284 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00003285 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003286 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00003287 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00003288 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00003289 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003290 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00003291 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00003292 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00003293 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003294 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00003295 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00003296 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00003297 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003298 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00003299 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
3300 }
3301}
3302
3303/// Analyze the operands of the given comparison. Implements the
3304/// fallback case from AnalyzeComparison.
3305void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00003306 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
3307 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00003308}
John McCall51313c32010-01-04 23:31:57 +00003309
John McCallba26e582010-01-04 23:21:16 +00003310/// \brief Implements -Wsign-compare.
3311///
Richard Trieudd225092011-09-15 21:56:47 +00003312/// \param E the binary operator to check for warnings
John McCall323ed742010-05-06 08:58:33 +00003313void AnalyzeComparison(Sema &S, BinaryOperator *E) {
3314 // The type the comparison is being performed in.
3315 QualType T = E->getLHS()->getType();
3316 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
3317 && "comparison with mismatched types");
John McCallba26e582010-01-04 23:21:16 +00003318
John McCall323ed742010-05-06 08:58:33 +00003319 // We don't do anything special if this isn't an unsigned integral
3320 // comparison: we're only interested in integral comparisons, and
3321 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00003322 //
3323 // We also don't care about value-dependent expressions or expressions
3324 // whose result is a constant.
3325 if (!T->hasUnsignedIntegerRepresentation()
3326 || E->isValueDependent() || E->isIntegerConstantExpr(S.Context))
John McCall323ed742010-05-06 08:58:33 +00003327 return AnalyzeImpConvsInComparison(S, E);
John McCallf2370c92010-01-06 05:24:50 +00003328
Richard Trieudd225092011-09-15 21:56:47 +00003329 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
3330 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
John McCallba26e582010-01-04 23:21:16 +00003331
John McCall323ed742010-05-06 08:58:33 +00003332 // Check to see if one of the (unmodified) operands is of different
3333 // signedness.
3334 Expr *signedOperand, *unsignedOperand;
Richard Trieudd225092011-09-15 21:56:47 +00003335 if (LHS->getType()->hasSignedIntegerRepresentation()) {
3336 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00003337 "unsigned comparison between two signed integer expressions?");
Richard Trieudd225092011-09-15 21:56:47 +00003338 signedOperand = LHS;
3339 unsignedOperand = RHS;
3340 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
3341 signedOperand = RHS;
3342 unsignedOperand = LHS;
John McCallba26e582010-01-04 23:21:16 +00003343 } else {
John McCall323ed742010-05-06 08:58:33 +00003344 CheckTrivialUnsignedComparison(S, E);
3345 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00003346 }
3347
John McCall323ed742010-05-06 08:58:33 +00003348 // Otherwise, calculate the effective range of the signed operand.
3349 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00003350
John McCall323ed742010-05-06 08:58:33 +00003351 // Go ahead and analyze implicit conversions in the operands. Note
3352 // that we skip the implicit conversions on both sides.
Richard Trieudd225092011-09-15 21:56:47 +00003353 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
3354 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00003355
John McCall323ed742010-05-06 08:58:33 +00003356 // If the signed range is non-negative, -Wsign-compare won't fire,
3357 // but we should still check for comparisons which are always true
3358 // or false.
3359 if (signedRange.NonNegative)
3360 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00003361
3362 // For (in)equality comparisons, if the unsigned operand is a
3363 // constant which cannot collide with a overflowed signed operand,
3364 // then reinterpreting the signed operand as unsigned will not
3365 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00003366 if (E->isEqualityOp()) {
3367 unsigned comparisonWidth = S.Context.getIntWidth(T);
3368 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00003369
John McCall323ed742010-05-06 08:58:33 +00003370 // We should never be unable to prove that the unsigned operand is
3371 // non-negative.
3372 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
3373
3374 if (unsignedRange.Width < comparisonWidth)
3375 return;
3376 }
3377
3378 S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison)
Richard Trieudd225092011-09-15 21:56:47 +00003379 << LHS->getType() << RHS->getType()
3380 << LHS->getSourceRange() << RHS->getSourceRange();
John McCallba26e582010-01-04 23:21:16 +00003381}
3382
John McCall15d7d122010-11-11 03:21:53 +00003383/// Analyzes an attempt to assign the given value to a bitfield.
3384///
3385/// Returns true if there was something fishy about the attempt.
3386bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
3387 SourceLocation InitLoc) {
3388 assert(Bitfield->isBitField());
3389 if (Bitfield->isInvalidDecl())
3390 return false;
3391
John McCall91b60142010-11-11 05:33:51 +00003392 // White-list bool bitfields.
3393 if (Bitfield->getType()->isBooleanType())
3394 return false;
3395
Douglas Gregor46ff3032011-02-04 13:09:01 +00003396 // Ignore value- or type-dependent expressions.
3397 if (Bitfield->getBitWidth()->isValueDependent() ||
3398 Bitfield->getBitWidth()->isTypeDependent() ||
3399 Init->isValueDependent() ||
3400 Init->isTypeDependent())
3401 return false;
3402
John McCall15d7d122010-11-11 03:21:53 +00003403 Expr *OriginalInit = Init->IgnoreParenImpCasts();
3404
John McCall15d7d122010-11-11 03:21:53 +00003405 Expr::EvalResult InitValue;
Richard Smith51f47082011-10-29 00:50:52 +00003406 if (!OriginalInit->EvaluateAsRValue(InitValue, S.Context) ||
John McCall15d7d122010-11-11 03:21:53 +00003407 !InitValue.Val.isInt())
3408 return false;
3409
3410 const llvm::APSInt &Value = InitValue.Val.getInt();
3411 unsigned OriginalWidth = Value.getBitWidth();
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003412 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall15d7d122010-11-11 03:21:53 +00003413
3414 if (OriginalWidth <= FieldWidth)
3415 return false;
3416
Jay Foad9f71a8f2010-12-07 08:25:34 +00003417 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
John McCall15d7d122010-11-11 03:21:53 +00003418
3419 // It's fairly common to write values into signed bitfields
3420 // that, if sign-extended, would end up becoming a different
3421 // value. We don't want to warn about that.
3422 if (Value.isSigned() && Value.isNegative())
Jay Foad9f71a8f2010-12-07 08:25:34 +00003423 TruncatedValue = TruncatedValue.sext(OriginalWidth);
John McCall15d7d122010-11-11 03:21:53 +00003424 else
Jay Foad9f71a8f2010-12-07 08:25:34 +00003425 TruncatedValue = TruncatedValue.zext(OriginalWidth);
John McCall15d7d122010-11-11 03:21:53 +00003426
3427 if (Value == TruncatedValue)
3428 return false;
3429
3430 std::string PrettyValue = Value.toString(10);
3431 std::string PrettyTrunc = TruncatedValue.toString(10);
3432
3433 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
3434 << PrettyValue << PrettyTrunc << OriginalInit->getType()
3435 << Init->getSourceRange();
3436
3437 return true;
3438}
3439
John McCallbeb22aa2010-11-09 23:24:47 +00003440/// Analyze the given simple or compound assignment for warning-worthy
3441/// operations.
3442void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
3443 // Just recurse on the LHS.
3444 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
3445
3446 // We want to recurse on the RHS as normal unless we're assigning to
3447 // a bitfield.
3448 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
John McCall15d7d122010-11-11 03:21:53 +00003449 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
3450 E->getOperatorLoc())) {
3451 // Recurse, ignoring any implicit conversions on the RHS.
3452 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
3453 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00003454 }
3455 }
3456
3457 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
3458}
3459
John McCall51313c32010-01-04 23:31:57 +00003460/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00003461void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
3462 SourceLocation CContext, unsigned diag) {
3463 S.Diag(E->getExprLoc(), diag)
3464 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
3465}
3466
Chandler Carruthe1b02e02011-04-05 06:47:57 +00003467/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
3468void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
3469 unsigned diag) {
3470 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag);
3471}
3472
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003473/// Diagnose an implicit cast from a literal expression. Does not warn when the
3474/// cast wouldn't lose information.
Chandler Carruthf65076e2011-04-10 08:36:24 +00003475void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
3476 SourceLocation CContext) {
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003477 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruthf65076e2011-04-10 08:36:24 +00003478 bool isExact = false;
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003479 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00003480 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
3481 T->hasUnsignedIntegerRepresentation());
3482 if (Value.convertToInteger(IntegerValue,
Chandler Carruthf65076e2011-04-10 08:36:24 +00003483 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003484 == llvm::APFloat::opOK && isExact)
Chandler Carruthf65076e2011-04-10 08:36:24 +00003485 return;
3486
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003487 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
3488 << FL->getType() << T << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruthf65076e2011-04-10 08:36:24 +00003489}
3490
John McCall091f23f2010-11-09 22:22:12 +00003491std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
3492 if (!Range.Width) return "0";
3493
3494 llvm::APSInt ValueInRange = Value;
3495 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00003496 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00003497 return ValueInRange.toString(10);
3498}
3499
Ted Kremenekef9ff882011-03-10 20:03:42 +00003500static bool isFromSystemMacro(Sema &S, SourceLocation loc) {
3501 SourceManager &smgr = S.Context.getSourceManager();
3502 return loc.isMacroID() && smgr.isInSystemHeader(smgr.getSpellingLoc(loc));
3503}
Chandler Carruthf65076e2011-04-10 08:36:24 +00003504
John McCall323ed742010-05-06 08:58:33 +00003505void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00003506 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00003507 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00003508
John McCall323ed742010-05-06 08:58:33 +00003509 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
3510 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
3511 if (Source == Target) return;
3512 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00003513
Chandler Carruth108f7562011-07-26 05:40:03 +00003514 // If the conversion context location is invalid don't complain. We also
3515 // don't want to emit a warning if the issue occurs from the expansion of
3516 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
3517 // delay this check as long as possible. Once we detect we are in that
3518 // scenario, we just return.
Ted Kremenekef9ff882011-03-10 20:03:42 +00003519 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00003520 return;
3521
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00003522 // Diagnose implicit casts to bool.
3523 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
3524 if (isa<StringLiteral>(E))
3525 // Warn on string literal to bool. Checks for string literals in logical
3526 // expressions, for instances, assert(0 && "error here"), is prevented
3527 // by a check in AnalyzeImplicitConversions().
3528 return DiagnoseImpCast(S, E, T, CC,
3529 diag::warn_impcast_string_literal_to_bool);
David Blaikiee37cdc42011-09-29 04:06:47 +00003530 return; // Other casts to bool are not checked.
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00003531 }
John McCall51313c32010-01-04 23:31:57 +00003532
3533 // Strip vector types.
3534 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003535 if (!isa<VectorType>(Target)) {
3536 if (isFromSystemMacro(S, CC))
3537 return;
John McCallb4eb64d2010-10-08 02:01:28 +00003538 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00003539 }
Chris Lattnerb792b302011-06-14 04:51:15 +00003540
3541 // If the vector cast is cast between two vectors of the same size, it is
3542 // a bitcast, not a conversion.
3543 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
3544 return;
John McCall51313c32010-01-04 23:31:57 +00003545
3546 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
3547 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
3548 }
3549
3550 // Strip complex types.
3551 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003552 if (!isa<ComplexType>(Target)) {
3553 if (isFromSystemMacro(S, CC))
3554 return;
3555
John McCallb4eb64d2010-10-08 02:01:28 +00003556 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00003557 }
John McCall51313c32010-01-04 23:31:57 +00003558
3559 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
3560 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
3561 }
3562
3563 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
3564 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
3565
3566 // If the source is floating point...
3567 if (SourceBT && SourceBT->isFloatingPoint()) {
3568 // ...and the target is floating point...
3569 if (TargetBT && TargetBT->isFloatingPoint()) {
3570 // ...then warn if we're dropping FP rank.
3571
3572 // Builtin FP kinds are ordered by increasing FP rank.
3573 if (SourceBT->getKind() > TargetBT->getKind()) {
3574 // Don't warn about float constants that are precisely
3575 // representable in the target type.
3576 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00003577 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00003578 // Value might be a float, a float vector, or a float complex.
3579 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00003580 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
3581 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00003582 return;
3583 }
3584
Ted Kremenekef9ff882011-03-10 20:03:42 +00003585 if (isFromSystemMacro(S, CC))
3586 return;
3587
John McCallb4eb64d2010-10-08 02:01:28 +00003588 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00003589 }
3590 return;
3591 }
3592
Ted Kremenekef9ff882011-03-10 20:03:42 +00003593 // If the target is integral, always warn.
Chandler Carrutha5b93322011-02-17 11:05:49 +00003594 if ((TargetBT && TargetBT->isInteger())) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003595 if (isFromSystemMacro(S, CC))
3596 return;
3597
Chandler Carrutha5b93322011-02-17 11:05:49 +00003598 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay634c8af2011-09-08 22:30:47 +00003599 // We also want to warn on, e.g., "int i = -1.234"
3600 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
3601 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
3602 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
3603
Chandler Carruthf65076e2011-04-10 08:36:24 +00003604 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
3605 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00003606 } else {
3607 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
3608 }
3609 }
John McCall51313c32010-01-04 23:31:57 +00003610
3611 return;
3612 }
3613
John McCallf2370c92010-01-06 05:24:50 +00003614 if (!Source->isIntegerType() || !Target->isIntegerType())
John McCall51313c32010-01-04 23:31:57 +00003615 return;
3616
Richard Trieu1838ca52011-05-29 19:59:02 +00003617 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
3618 == Expr::NPCK_GNUNull) && Target->isIntegerType()) {
3619 S.Diag(E->getExprLoc(), diag::warn_impcast_null_pointer_to_integer)
3620 << E->getSourceRange() << clang::SourceRange(CC);
3621 return;
3622 }
3623
John McCall323ed742010-05-06 08:58:33 +00003624 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00003625 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00003626
3627 if (SourceRange.Width > TargetRange.Width) {
John McCall091f23f2010-11-09 22:22:12 +00003628 // If the source is a constant, use a default-on diagnostic.
3629 // TODO: this should happen for bitfield stores, too.
3630 llvm::APSInt Value(32);
3631 if (E->isIntegerConstantExpr(Value, S.Context)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003632 if (isFromSystemMacro(S, CC))
3633 return;
3634
John McCall091f23f2010-11-09 22:22:12 +00003635 std::string PrettySourceValue = Value.toString(10);
3636 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
3637
Ted Kremenek5e745da2011-10-22 02:37:33 +00003638 S.DiagRuntimeBehavior(E->getExprLoc(), E,
3639 S.PDiag(diag::warn_impcast_integer_precision_constant)
3640 << PrettySourceValue << PrettyTargetValue
3641 << E->getType() << T << E->getSourceRange()
3642 << clang::SourceRange(CC));
John McCall091f23f2010-11-09 22:22:12 +00003643 return;
3644 }
3645
Chris Lattnerb792b302011-06-14 04:51:15 +00003646 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
Ted Kremenekef9ff882011-03-10 20:03:42 +00003647 if (isFromSystemMacro(S, CC))
3648 return;
3649
John McCallf2370c92010-01-06 05:24:50 +00003650 if (SourceRange.Width == 64 && TargetRange.Width == 32)
John McCallb4eb64d2010-10-08 02:01:28 +00003651 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32);
3652 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00003653 }
3654
3655 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
3656 (!TargetRange.NonNegative && SourceRange.NonNegative &&
3657 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003658
3659 if (isFromSystemMacro(S, CC))
3660 return;
3661
John McCall323ed742010-05-06 08:58:33 +00003662 unsigned DiagID = diag::warn_impcast_integer_sign;
3663
3664 // Traditionally, gcc has warned about this under -Wsign-compare.
3665 // We also want to warn about it in -Wconversion.
3666 // So if -Wconversion is off, use a completely identical diagnostic
3667 // in the sign-compare group.
3668 // The conditional-checking code will
3669 if (ICContext) {
3670 DiagID = diag::warn_impcast_integer_sign_conditional;
3671 *ICContext = true;
3672 }
3673
John McCallb4eb64d2010-10-08 02:01:28 +00003674 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00003675 }
3676
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003677 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00003678 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
3679 // type, to give us better diagnostics.
3680 QualType SourceType = E->getType();
3681 if (!S.getLangOptions().CPlusPlus) {
3682 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3683 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3684 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
3685 SourceType = S.Context.getTypeDeclType(Enum);
3686 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
3687 }
3688 }
3689
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003690 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
3691 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
3692 if ((SourceEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00003693 SourceEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003694 (TargetEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00003695 TargetEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00003696 SourceEnum != TargetEnum) {
3697 if (isFromSystemMacro(S, CC))
3698 return;
3699
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00003700 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003701 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00003702 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003703
John McCall51313c32010-01-04 23:31:57 +00003704 return;
3705}
3706
John McCall323ed742010-05-06 08:58:33 +00003707void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T);
3708
3709void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00003710 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00003711 E = E->IgnoreParenImpCasts();
3712
3713 if (isa<ConditionalOperator>(E))
3714 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T);
3715
John McCallb4eb64d2010-10-08 02:01:28 +00003716 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00003717 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00003718 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00003719 return;
3720}
3721
3722void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00003723 SourceLocation CC = E->getQuestionLoc();
3724
3725 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00003726
3727 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00003728 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
3729 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00003730
3731 // If -Wconversion would have warned about either of the candidates
3732 // for a signedness conversion to the context type...
3733 if (!Suspicious) return;
3734
3735 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003736 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
3737 CC))
John McCall323ed742010-05-06 08:58:33 +00003738 return;
3739
John McCall323ed742010-05-06 08:58:33 +00003740 // ...then check whether it would have warned about either of the
3741 // candidates for a signedness conversion to the condition type.
Richard Trieu52541612011-07-21 02:46:28 +00003742 if (E->getType() == T) return;
3743
3744 Suspicious = false;
3745 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
3746 E->getType(), CC, &Suspicious);
3747 if (!Suspicious)
3748 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00003749 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00003750}
3751
3752/// AnalyzeImplicitConversions - Find and report any interesting
3753/// implicit conversions in the given expression. There are a couple
3754/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00003755void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00003756 QualType T = OrigE->getType();
3757 Expr *E = OrigE->IgnoreParenImpCasts();
3758
Douglas Gregorf8b6e152011-10-10 17:38:18 +00003759 if (E->isTypeDependent() || E->isValueDependent())
3760 return;
3761
John McCall323ed742010-05-06 08:58:33 +00003762 // For conditional operators, we analyze the arguments as if they
3763 // were being fed directly into the output.
3764 if (isa<ConditionalOperator>(E)) {
3765 ConditionalOperator *CO = cast<ConditionalOperator>(E);
3766 CheckConditionalOperator(S, CO, T);
3767 return;
3768 }
3769
3770 // Go ahead and check any implicit conversions we might have skipped.
3771 // The non-canonical typecheck is just an optimization;
3772 // CheckImplicitConversion will filter out dead implicit conversions.
3773 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00003774 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00003775
3776 // Now continue drilling into this expression.
3777
3778 // Skip past explicit casts.
3779 if (isa<ExplicitCastExpr>(E)) {
3780 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00003781 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00003782 }
3783
John McCallbeb22aa2010-11-09 23:24:47 +00003784 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3785 // Do a somewhat different check with comparison operators.
3786 if (BO->isComparisonOp())
3787 return AnalyzeComparison(S, BO);
3788
3789 // And with assignments and compound assignments.
3790 if (BO->isAssignmentOp())
3791 return AnalyzeAssignment(S, BO);
3792 }
John McCall323ed742010-05-06 08:58:33 +00003793
3794 // These break the otherwise-useful invariant below. Fortunately,
3795 // we don't really need to recurse into them, because any internal
3796 // expressions should have been analyzed already when they were
3797 // built into statements.
3798 if (isa<StmtExpr>(E)) return;
3799
3800 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003801 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00003802
3803 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00003804 CC = E->getExprLoc();
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00003805 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
3806 bool IsLogicalOperator = BO && BO->isLogicalOp();
3807 for (Stmt::child_range I = E->children(); I; ++I) {
3808 Expr *ChildExpr = cast<Expr>(*I);
3809 if (IsLogicalOperator &&
3810 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
3811 // Ignore checking string literals that are in logical operators.
3812 continue;
3813 AnalyzeImplicitConversions(S, ChildExpr, CC);
3814 }
John McCall323ed742010-05-06 08:58:33 +00003815}
3816
3817} // end anonymous namespace
3818
3819/// Diagnoses "dangerous" implicit conversions within the given
3820/// expression (which is a full expression). Implements -Wconversion
3821/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00003822///
3823/// \param CC the "context" location of the implicit conversion, i.e.
3824/// the most location of the syntactic entity requiring the implicit
3825/// conversion
3826void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00003827 // Don't diagnose in unevaluated contexts.
3828 if (ExprEvalContexts.back().Context == Sema::Unevaluated)
3829 return;
3830
3831 // Don't diagnose for value- or type-dependent expressions.
3832 if (E->isTypeDependent() || E->isValueDependent())
3833 return;
3834
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003835 // Check for array bounds violations in cases where the check isn't triggered
3836 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
3837 // ArraySubscriptExpr is on the RHS of a variable initialization.
3838 CheckArrayAccess(E);
3839
John McCallb4eb64d2010-10-08 02:01:28 +00003840 // This is not the right CC for (e.g.) a variable initialization.
3841 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00003842}
3843
John McCall15d7d122010-11-11 03:21:53 +00003844void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
3845 FieldDecl *BitField,
3846 Expr *Init) {
3847 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
3848}
3849
Mike Stumpf8c49212010-01-21 03:59:47 +00003850/// CheckParmsForFunctionDef - Check that the parameters of the given
3851/// function are appropriate for the definition of a function. This
3852/// takes care of any checks that cannot be performed on the
3853/// declaration itself, e.g., that the types of each of the function
3854/// parameters are complete.
Douglas Gregor82aa7132010-11-01 18:37:59 +00003855bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
3856 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00003857 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00003858 for (; P != PEnd; ++P) {
3859 ParmVarDecl *Param = *P;
3860
Mike Stumpf8c49212010-01-21 03:59:47 +00003861 // C99 6.7.5.3p4: the parameters in a parameter type list in a
3862 // function declarator that is part of a function definition of
3863 // that function shall not have incomplete type.
3864 //
3865 // This is also C++ [dcl.fct]p6.
3866 if (!Param->isInvalidDecl() &&
3867 RequireCompleteType(Param->getLocation(), Param->getType(),
3868 diag::err_typecheck_decl_incomplete_type)) {
3869 Param->setInvalidDecl();
3870 HasInvalidParm = true;
3871 }
3872
3873 // C99 6.9.1p5: If the declarator includes a parameter type list, the
3874 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00003875 if (CheckParameterNames &&
3876 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00003877 !Param->isImplicit() &&
3878 !getLangOptions().CPlusPlus)
3879 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00003880
3881 // C99 6.7.5.3p12:
3882 // If the function declarator is not part of a definition of that
3883 // function, parameters may have incomplete type and may use the [*]
3884 // notation in their sequences of declarator specifiers to specify
3885 // variable length array types.
3886 QualType PType = Param->getOriginalType();
3887 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
3888 if (AT->getSizeModifier() == ArrayType::Star) {
3889 // FIXME: This diagnosic should point the the '[*]' if source-location
3890 // information is added for it.
3891 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
3892 }
3893 }
Mike Stumpf8c49212010-01-21 03:59:47 +00003894 }
3895
3896 return HasInvalidParm;
3897}
John McCallb7f4ffe2010-08-12 21:44:57 +00003898
3899/// CheckCastAlign - Implements -Wcast-align, which warns when a
3900/// pointer cast increases the alignment requirements.
3901void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
3902 // This is actually a lot of work to potentially be doing on every
3903 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003904 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
3905 TRange.getBegin())
David Blaikied6471f72011-09-25 23:23:43 +00003906 == DiagnosticsEngine::Ignored)
John McCallb7f4ffe2010-08-12 21:44:57 +00003907 return;
3908
3909 // Ignore dependent types.
3910 if (T->isDependentType() || Op->getType()->isDependentType())
3911 return;
3912
3913 // Require that the destination be a pointer type.
3914 const PointerType *DestPtr = T->getAs<PointerType>();
3915 if (!DestPtr) return;
3916
3917 // If the destination has alignment 1, we're done.
3918 QualType DestPointee = DestPtr->getPointeeType();
3919 if (DestPointee->isIncompleteType()) return;
3920 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
3921 if (DestAlign.isOne()) return;
3922
3923 // Require that the source be a pointer type.
3924 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
3925 if (!SrcPtr) return;
3926 QualType SrcPointee = SrcPtr->getPointeeType();
3927
3928 // Whitelist casts from cv void*. We already implicitly
3929 // whitelisted casts to cv void*, since they have alignment 1.
3930 // Also whitelist casts involving incomplete types, which implicitly
3931 // includes 'void'.
3932 if (SrcPointee->isIncompleteType()) return;
3933
3934 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
3935 if (SrcAlign >= DestAlign) return;
3936
3937 Diag(TRange.getBegin(), diag::warn_cast_align)
3938 << Op->getType() << T
3939 << static_cast<unsigned>(SrcAlign.getQuantity())
3940 << static_cast<unsigned>(DestAlign.getQuantity())
3941 << TRange << Op->getSourceRange();
3942}
3943
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003944static const Type* getElementType(const Expr *BaseExpr) {
3945 const Type* EltType = BaseExpr->getType().getTypePtr();
3946 if (EltType->isAnyPointerType())
3947 return EltType->getPointeeType().getTypePtr();
3948 else if (EltType->isArrayType())
3949 return EltType->getBaseElementTypeUnsafe();
3950 return EltType;
3951}
3952
Chandler Carruthc2684342011-08-05 09:10:50 +00003953/// \brief Check whether this array fits the idiom of a size-one tail padded
3954/// array member of a struct.
3955///
3956/// We avoid emitting out-of-bounds access warnings for such arrays as they are
3957/// commonly used to emulate flexible arrays in C89 code.
3958static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
3959 const NamedDecl *ND) {
3960 if (Size != 1 || !ND) return false;
3961
3962 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
3963 if (!FD) return false;
3964
3965 // Don't consider sizes resulting from macro expansions or template argument
3966 // substitution to form C89 tail-padded arrays.
3967 ConstantArrayTypeLoc TL =
3968 cast<ConstantArrayTypeLoc>(FD->getTypeSourceInfo()->getTypeLoc());
3969 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(TL.getSizeExpr());
3970 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
3971 return false;
3972
3973 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
3974 if (!RD || !RD->isStruct())
3975 return false;
3976
Benjamin Kramer22d4fed2011-08-06 03:04:42 +00003977 // See if this is the last field decl in the record.
3978 const Decl *D = FD;
3979 while ((D = D->getNextDeclInContext()))
3980 if (isa<FieldDecl>(D))
3981 return false;
3982 return true;
Chandler Carruthc2684342011-08-05 09:10:50 +00003983}
3984
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003985void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
3986 bool isSubscript, bool AllowOnePastEnd) {
3987 const Type* EffectiveType = getElementType(BaseExpr);
3988 BaseExpr = BaseExpr->IgnoreParenCasts();
3989 IndexExpr = IndexExpr->IgnoreParenCasts();
3990
Chandler Carruth34064582011-02-17 20:55:08 +00003991 const ConstantArrayType *ArrayTy =
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003992 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00003993 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00003994 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00003995
Chandler Carruth34064582011-02-17 20:55:08 +00003996 if (IndexExpr->isValueDependent())
Ted Kremeneka0125d82011-02-16 01:57:07 +00003997 return;
Chandler Carruth34064582011-02-17 20:55:08 +00003998 llvm::APSInt index;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003999 if (!IndexExpr->isIntegerConstantExpr(index, Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00004000 return;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00004001
Chandler Carruthba447122011-08-05 08:07:29 +00004002 const NamedDecl *ND = NULL;
Chandler Carruthba447122011-08-05 08:07:29 +00004003 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
4004 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruthc2684342011-08-05 09:10:50 +00004005 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruthba447122011-08-05 08:07:29 +00004006 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruthba447122011-08-05 08:07:29 +00004007
Ted Kremenek9e060ca2011-02-23 23:06:04 +00004008 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00004009 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00004010 if (!size.isStrictlyPositive())
4011 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004012
4013 const Type* BaseType = getElementType(BaseExpr);
Nico Weberde5998f2011-09-17 22:59:41 +00004014 if (BaseType != EffectiveType) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004015 // Make sure we're comparing apples to apples when comparing index to size
4016 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
4017 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhraind10f4bc2011-08-10 19:47:25 +00004018 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhrain18f16972011-08-10 18:49:28 +00004019 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004020 if (ptrarith_typesize != array_typesize) {
4021 // There's a cast to a different size type involved
4022 uint64_t ratio = array_typesize / ptrarith_typesize;
4023 // TODO: Be smarter about handling cases where array_typesize is not a
4024 // multiple of ptrarith_typesize
4025 if (ptrarith_typesize * ratio == array_typesize)
4026 size *= llvm::APInt(size.getBitWidth(), ratio);
4027 }
4028 }
4029
Chandler Carruth34064582011-02-17 20:55:08 +00004030 if (size.getBitWidth() > index.getBitWidth())
4031 index = index.sext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00004032 else if (size.getBitWidth() < index.getBitWidth())
4033 size = size.sext(index.getBitWidth());
4034
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004035 // For array subscripting the index must be less than size, but for pointer
4036 // arithmetic also allow the index (offset) to be equal to size since
4037 // computing the next address after the end of the array is legal and
4038 // commonly done e.g. in C++ iterators and range-based for loops.
4039 if (AllowOnePastEnd ? index.sle(size) : index.slt(size))
Chandler Carruthba447122011-08-05 08:07:29 +00004040 return;
4041
4042 // Also don't warn for arrays of size 1 which are members of some
4043 // structure. These are often used to approximate flexible arrays in C89
4044 // code.
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004045 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00004046 return;
Chandler Carruth34064582011-02-17 20:55:08 +00004047
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004048 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
4049 if (isSubscript)
4050 DiagID = diag::warn_array_index_exceeds_bounds;
4051
4052 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
4053 PDiag(DiagID) << index.toString(10, true)
4054 << size.toString(10, true)
4055 << (unsigned)size.getLimitedValue(~0U)
4056 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00004057 } else {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004058 unsigned DiagID = diag::warn_array_index_precedes_bounds;
4059 if (!isSubscript) {
4060 DiagID = diag::warn_ptr_arith_precedes_bounds;
4061 if (index.isNegative()) index = -index;
4062 }
4063
4064 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
4065 PDiag(DiagID) << index.toString(10, true)
4066 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00004067 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00004068
Chandler Carruth35001ca2011-02-17 21:10:52 +00004069 if (ND)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004070 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
4071 PDiag(diag::note_array_index_out_of_bounds)
4072 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00004073}
4074
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004075void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004076 int AllowOnePastEnd = 0;
4077 while (expr) {
4078 expr = expr->IgnoreParenImpCasts();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004079 switch (expr->getStmtClass()) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004080 case Stmt::ArraySubscriptExprClass: {
4081 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
4082 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), true,
4083 AllowOnePastEnd > 0);
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004084 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004085 }
4086 case Stmt::UnaryOperatorClass: {
4087 // Only unwrap the * and & unary operators
4088 const UnaryOperator *UO = cast<UnaryOperator>(expr);
4089 expr = UO->getSubExpr();
4090 switch (UO->getOpcode()) {
4091 case UO_AddrOf:
4092 AllowOnePastEnd++;
4093 break;
4094 case UO_Deref:
4095 AllowOnePastEnd--;
4096 break;
4097 default:
4098 return;
4099 }
4100 break;
4101 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004102 case Stmt::ConditionalOperatorClass: {
4103 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
4104 if (const Expr *lhs = cond->getLHS())
4105 CheckArrayAccess(lhs);
4106 if (const Expr *rhs = cond->getRHS())
4107 CheckArrayAccess(rhs);
4108 return;
4109 }
4110 default:
4111 return;
4112 }
Peter Collingbournef111d932011-04-15 00:35:48 +00004113 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004114}
John McCallf85e1932011-06-15 23:02:42 +00004115
4116//===--- CHECK: Objective-C retain cycles ----------------------------------//
4117
4118namespace {
4119 struct RetainCycleOwner {
4120 RetainCycleOwner() : Variable(0), Indirect(false) {}
4121 VarDecl *Variable;
4122 SourceRange Range;
4123 SourceLocation Loc;
4124 bool Indirect;
4125
4126 void setLocsFrom(Expr *e) {
4127 Loc = e->getExprLoc();
4128 Range = e->getSourceRange();
4129 }
4130 };
4131}
4132
4133/// Consider whether capturing the given variable can possibly lead to
4134/// a retain cycle.
4135static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
4136 // In ARC, it's captured strongly iff the variable has __strong
4137 // lifetime. In MRR, it's captured strongly if the variable is
4138 // __block and has an appropriate type.
4139 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
4140 return false;
4141
4142 owner.Variable = var;
4143 owner.setLocsFrom(ref);
4144 return true;
4145}
4146
4147static bool findRetainCycleOwner(Expr *e, RetainCycleOwner &owner) {
4148 while (true) {
4149 e = e->IgnoreParens();
4150 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
4151 switch (cast->getCastKind()) {
4152 case CK_BitCast:
4153 case CK_LValueBitCast:
4154 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00004155 case CK_ARCReclaimReturnedObject:
John McCallf85e1932011-06-15 23:02:42 +00004156 e = cast->getSubExpr();
4157 continue;
4158
John McCallf85e1932011-06-15 23:02:42 +00004159 default:
4160 return false;
4161 }
4162 }
4163
4164 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
4165 ObjCIvarDecl *ivar = ref->getDecl();
4166 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
4167 return false;
4168
4169 // Try to find a retain cycle in the base.
4170 if (!findRetainCycleOwner(ref->getBase(), owner))
4171 return false;
4172
4173 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
4174 owner.Indirect = true;
4175 return true;
4176 }
4177
4178 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
4179 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
4180 if (!var) return false;
4181 return considerVariable(var, ref, owner);
4182 }
4183
4184 if (BlockDeclRefExpr *ref = dyn_cast<BlockDeclRefExpr>(e)) {
4185 owner.Variable = ref->getDecl();
4186 owner.setLocsFrom(ref);
4187 return true;
4188 }
4189
4190 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
4191 if (member->isArrow()) return false;
4192
4193 // Don't count this as an indirect ownership.
4194 e = member->getBase();
4195 continue;
4196 }
4197
John McCall4b9c2d22011-11-06 09:01:30 +00004198 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
4199 // Only pay attention to pseudo-objects on property references.
4200 ObjCPropertyRefExpr *pre
4201 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
4202 ->IgnoreParens());
4203 if (!pre) return false;
4204 if (pre->isImplicitProperty()) return false;
4205 ObjCPropertyDecl *property = pre->getExplicitProperty();
4206 if (!property->isRetaining() &&
4207 !(property->getPropertyIvarDecl() &&
4208 property->getPropertyIvarDecl()->getType()
4209 .getObjCLifetime() == Qualifiers::OCL_Strong))
4210 return false;
4211
4212 owner.Indirect = true;
4213 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
4214 ->getSourceExpr());
4215 continue;
4216 }
4217
John McCallf85e1932011-06-15 23:02:42 +00004218 // Array ivars?
4219
4220 return false;
4221 }
4222}
4223
4224namespace {
4225 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
4226 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
4227 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
4228 Variable(variable), Capturer(0) {}
4229
4230 VarDecl *Variable;
4231 Expr *Capturer;
4232
4233 void VisitDeclRefExpr(DeclRefExpr *ref) {
4234 if (ref->getDecl() == Variable && !Capturer)
4235 Capturer = ref;
4236 }
4237
4238 void VisitBlockDeclRefExpr(BlockDeclRefExpr *ref) {
4239 if (ref->getDecl() == Variable && !Capturer)
4240 Capturer = ref;
4241 }
4242
4243 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
4244 if (Capturer) return;
4245 Visit(ref->getBase());
4246 if (Capturer && ref->isFreeIvar())
4247 Capturer = ref;
4248 }
4249
4250 void VisitBlockExpr(BlockExpr *block) {
4251 // Look inside nested blocks
4252 if (block->getBlockDecl()->capturesVariable(Variable))
4253 Visit(block->getBlockDecl()->getBody());
4254 }
4255 };
4256}
4257
4258/// Check whether the given argument is a block which captures a
4259/// variable.
4260static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
4261 assert(owner.Variable && owner.Loc.isValid());
4262
4263 e = e->IgnoreParenCasts();
4264 BlockExpr *block = dyn_cast<BlockExpr>(e);
4265 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
4266 return 0;
4267
4268 FindCaptureVisitor visitor(S.Context, owner.Variable);
4269 visitor.Visit(block->getBlockDecl()->getBody());
4270 return visitor.Capturer;
4271}
4272
4273static void diagnoseRetainCycle(Sema &S, Expr *capturer,
4274 RetainCycleOwner &owner) {
4275 assert(capturer);
4276 assert(owner.Variable && owner.Loc.isValid());
4277
4278 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
4279 << owner.Variable << capturer->getSourceRange();
4280 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
4281 << owner.Indirect << owner.Range;
4282}
4283
4284/// Check for a keyword selector that starts with the word 'add' or
4285/// 'set'.
4286static bool isSetterLikeSelector(Selector sel) {
4287 if (sel.isUnarySelector()) return false;
4288
Chris Lattner5f9e2722011-07-23 10:55:15 +00004289 StringRef str = sel.getNameForSlot(0);
John McCallf85e1932011-06-15 23:02:42 +00004290 while (!str.empty() && str.front() == '_') str = str.substr(1);
4291 if (str.startswith("set") || str.startswith("add"))
4292 str = str.substr(3);
4293 else
4294 return false;
4295
4296 if (str.empty()) return true;
4297 return !islower(str.front());
4298}
4299
4300/// Check a message send to see if it's likely to cause a retain cycle.
4301void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
4302 // Only check instance methods whose selector looks like a setter.
4303 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
4304 return;
4305
4306 // Try to find a variable that the receiver is strongly owned by.
4307 RetainCycleOwner owner;
4308 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
4309 if (!findRetainCycleOwner(msg->getInstanceReceiver(), owner))
4310 return;
4311 } else {
4312 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
4313 owner.Variable = getCurMethodDecl()->getSelfDecl();
4314 owner.Loc = msg->getSuperLoc();
4315 owner.Range = msg->getSuperLoc();
4316 }
4317
4318 // Check whether the receiver is captured by any of the arguments.
4319 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
4320 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
4321 return diagnoseRetainCycle(*this, capturer, owner);
4322}
4323
4324/// Check a property assign to see if it's likely to cause a retain cycle.
4325void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
4326 RetainCycleOwner owner;
4327 if (!findRetainCycleOwner(receiver, owner))
4328 return;
4329
4330 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
4331 diagnoseRetainCycle(*this, capturer, owner);
4332}
4333
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004334bool Sema::checkUnsafeAssigns(SourceLocation Loc,
John McCallf85e1932011-06-15 23:02:42 +00004335 QualType LHS, Expr *RHS) {
4336 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
4337 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004338 return false;
4339 // strip off any implicit cast added to get to the one arc-specific
4340 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00004341 if (cast->getCastKind() == CK_ARCConsumeObject) {
John McCallf85e1932011-06-15 23:02:42 +00004342 Diag(Loc, diag::warn_arc_retained_assign)
4343 << (LT == Qualifiers::OCL_ExplicitNone)
4344 << RHS->getSourceRange();
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004345 return true;
4346 }
4347 RHS = cast->getSubExpr();
4348 }
4349 return false;
John McCallf85e1932011-06-15 23:02:42 +00004350}
4351
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004352void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
4353 Expr *LHS, Expr *RHS) {
4354 QualType LHSType = LHS->getType();
4355 if (checkUnsafeAssigns(Loc, LHSType, RHS))
4356 return;
4357 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
4358 // FIXME. Check for other life times.
4359 if (LT != Qualifiers::OCL_None)
4360 return;
4361
John McCall3c3b7f92011-10-25 17:37:35 +00004362 if (ObjCPropertyRefExpr *PRE
4363 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens())) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004364 if (PRE->isImplicitProperty())
4365 return;
4366 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
4367 if (!PD)
4368 return;
4369
4370 unsigned Attributes = PD->getPropertyAttributes();
4371 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign)
4372 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00004373 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004374 Diag(Loc, diag::warn_arc_retained_property_assign)
4375 << RHS->getSourceRange();
4376 return;
4377 }
4378 RHS = cast->getSubExpr();
4379 }
4380 }
4381}