blob: f3bc273d99433ff7df4c745de861a710d3ccf829 [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"
Richard Smith831421f2012-06-25 20:30:08 +000019#include "clang/Sema/Lookup.h"
John McCall781472f2010-08-25 08:40:02 +000020#include "clang/Sema/ScopeInfo.h"
Ted Kremenek826a3452010-07-16 02:11:22 +000021#include "clang/Analysis/Analyses/FormatString.h"
Chris Lattner59907c42007-08-10 20:18:51 +000022#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000023#include "clang/AST/CharUnits.h"
John McCall384aff82010-08-25 07:42:41 +000024#include "clang/AST/DeclCXX.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000025#include "clang/AST/DeclObjC.h"
David Blaikiebe0ee872012-05-15 16:56:36 +000026#include "clang/AST/Expr.h"
Ted Kremenek23245122007-08-20 16:18:38 +000027#include "clang/AST/ExprCXX.h"
Ted Kremenek7ff22b22008-06-16 18:00:42 +000028#include "clang/AST/ExprObjC.h"
John McCallf85e1932011-06-15 23:02:42 +000029#include "clang/AST/EvaluatedExprVisitor.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000030#include "clang/AST/DeclObjC.h"
31#include "clang/AST/StmtCXX.h"
32#include "clang/AST/StmtObjC.h"
Chris Lattner59907c42007-08-10 20:18:51 +000033#include "clang/Lex/Preprocessor.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000034#include "llvm/ADT/BitVector.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000035#include "llvm/ADT/SmallString.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000036#include "llvm/ADT/STLExtras.h"
Tom Care3bfc5f42010-06-09 04:11:11 +000037#include "llvm/Support/raw_ostream.h"
Eric Christopher691ebc32010-04-17 02:26:23 +000038#include "clang/Basic/TargetBuiltins.h"
Nate Begeman26a31422010-06-08 02:47:44 +000039#include "clang/Basic/TargetInfo.h"
Fariborz Jahanian7da71022010-09-07 19:38:13 +000040#include "clang/Basic/ConvertUTF.h"
Zhongxing Xua1f3dba2009-05-20 01:55:10 +000041#include <limits>
Chris Lattner59907c42007-08-10 20:18:51 +000042using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000043using namespace sema;
Chris Lattner59907c42007-08-10 20:18:51 +000044
Chris Lattner60800082009-02-18 17:49:48 +000045SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
46 unsigned ByteNo) const {
Chris Lattner08f92e32010-11-17 07:37:15 +000047 return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +000048 PP.getLangOpts(), PP.getTargetInfo());
Chris Lattner60800082009-02-18 17:49:48 +000049}
50
John McCall8e10f3b2011-02-26 05:39:39 +000051/// Checks that a call expression's argument count is the desired number.
52/// This is useful when doing custom type-checking. Returns true on error.
53static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
54 unsigned argCount = call->getNumArgs();
55 if (argCount == desiredArgCount) return false;
56
57 if (argCount < desiredArgCount)
58 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
59 << 0 /*function call*/ << desiredArgCount << argCount
60 << call->getSourceRange();
61
62 // Highlight all the excess arguments.
63 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
64 call->getArg(argCount - 1)->getLocEnd());
65
66 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
67 << 0 /*function call*/ << desiredArgCount << argCount
68 << call->getArg(1)->getSourceRange();
69}
70
Julien Lerougee5939212012-04-28 17:39:16 +000071/// Check that the first argument to __builtin_annotation is an integer
72/// and the second argument is a non-wide string literal.
73static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
74 if (checkArgCount(S, TheCall, 2))
75 return true;
76
77 // First argument should be an integer.
78 Expr *ValArg = TheCall->getArg(0);
79 QualType Ty = ValArg->getType();
80 if (!Ty->isIntegerType()) {
81 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
82 << ValArg->getSourceRange();
Julien Lerouge77f68bb2011-09-09 22:41:49 +000083 return true;
84 }
Julien Lerougee5939212012-04-28 17:39:16 +000085
86 // Second argument should be a constant string.
87 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
88 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
89 if (!Literal || !Literal->isAscii()) {
90 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
91 << StrArg->getSourceRange();
92 return true;
93 }
94
95 TheCall->setType(Ty);
Julien Lerouge77f68bb2011-09-09 22:41:49 +000096 return false;
97}
98
John McCall60d7b3a2010-08-24 06:29:42 +000099ExprResult
Anders Carlssond406bf02009-08-16 01:56:34 +0000100Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
John McCall60d7b3a2010-08-24 06:29:42 +0000101 ExprResult TheCallResult(Owned(TheCall));
Douglas Gregor2def4832008-11-17 20:34:05 +0000102
Chris Lattner946928f2010-10-01 23:23:24 +0000103 // Find out if any arguments are required to be integer constant expressions.
104 unsigned ICEArguments = 0;
105 ASTContext::GetBuiltinTypeError Error;
106 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
107 if (Error != ASTContext::GE_None)
108 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
109
110 // If any arguments are required to be ICE's, check and diagnose.
111 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
112 // Skip arguments not required to be ICE's.
113 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
114
115 llvm::APSInt Result;
116 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
117 return true;
118 ICEArguments &= ~(1 << ArgNo);
119 }
120
Anders Carlssond406bf02009-08-16 01:56:34 +0000121 switch (BuiltinID) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000122 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +0000123 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +0000124 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner69039812009-02-18 06:01:06 +0000125 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000126 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000127 break;
Ted Kremenek49ff7a12008-07-09 17:58:53 +0000128 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +0000129 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000130 if (SemaBuiltinVAStart(TheCall))
131 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000132 break;
Chris Lattner1b9a0792007-12-20 00:26:33 +0000133 case Builtin::BI__builtin_isgreater:
134 case Builtin::BI__builtin_isgreaterequal:
135 case Builtin::BI__builtin_isless:
136 case Builtin::BI__builtin_islessequal:
137 case Builtin::BI__builtin_islessgreater:
138 case Builtin::BI__builtin_isunordered:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000139 if (SemaBuiltinUnorderedCompare(TheCall))
140 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000141 break;
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000142 case Builtin::BI__builtin_fpclassify:
143 if (SemaBuiltinFPClassification(TheCall, 6))
144 return ExprError();
145 break;
Eli Friedman9ac6f622009-08-31 20:06:00 +0000146 case Builtin::BI__builtin_isfinite:
147 case Builtin::BI__builtin_isinf:
148 case Builtin::BI__builtin_isinf_sign:
149 case Builtin::BI__builtin_isnan:
150 case Builtin::BI__builtin_isnormal:
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000151 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman9ac6f622009-08-31 20:06:00 +0000152 return ExprError();
153 break;
Eli Friedmand38617c2008-05-14 19:38:39 +0000154 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000155 return SemaBuiltinShuffleVector(TheCall);
156 // TheCall will be freed by the smart pointer here, but that's fine, since
157 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000158 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000159 if (SemaBuiltinPrefetch(TheCall))
160 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000161 break;
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000162 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000163 if (SemaBuiltinObjectSize(TheCall))
164 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000165 break;
Eli Friedmand875fed2009-05-03 04:46:36 +0000166 case Builtin::BI__builtin_longjmp:
167 if (SemaBuiltinLongjmp(TheCall))
168 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000169 break;
John McCall8e10f3b2011-02-26 05:39:39 +0000170
171 case Builtin::BI__builtin_classify_type:
172 if (checkArgCount(*this, TheCall, 1)) return true;
173 TheCall->setType(Context.IntTy);
174 break;
Chris Lattner75c29a02010-10-12 17:47:42 +0000175 case Builtin::BI__builtin_constant_p:
John McCall8e10f3b2011-02-26 05:39:39 +0000176 if (checkArgCount(*this, TheCall, 1)) return true;
177 TheCall->setType(Context.IntTy);
Chris Lattner75c29a02010-10-12 17:47:42 +0000178 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000179 case Builtin::BI__sync_fetch_and_add:
Douglas Gregora9766412011-11-28 16:30:08 +0000180 case Builtin::BI__sync_fetch_and_add_1:
181 case Builtin::BI__sync_fetch_and_add_2:
182 case Builtin::BI__sync_fetch_and_add_4:
183 case Builtin::BI__sync_fetch_and_add_8:
184 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000185 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregora9766412011-11-28 16:30:08 +0000186 case Builtin::BI__sync_fetch_and_sub_1:
187 case Builtin::BI__sync_fetch_and_sub_2:
188 case Builtin::BI__sync_fetch_and_sub_4:
189 case Builtin::BI__sync_fetch_and_sub_8:
190 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000191 case Builtin::BI__sync_fetch_and_or:
Douglas Gregora9766412011-11-28 16:30:08 +0000192 case Builtin::BI__sync_fetch_and_or_1:
193 case Builtin::BI__sync_fetch_and_or_2:
194 case Builtin::BI__sync_fetch_and_or_4:
195 case Builtin::BI__sync_fetch_and_or_8:
196 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000197 case Builtin::BI__sync_fetch_and_and:
Douglas Gregora9766412011-11-28 16:30:08 +0000198 case Builtin::BI__sync_fetch_and_and_1:
199 case Builtin::BI__sync_fetch_and_and_2:
200 case Builtin::BI__sync_fetch_and_and_4:
201 case Builtin::BI__sync_fetch_and_and_8:
202 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000203 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregora9766412011-11-28 16:30:08 +0000204 case Builtin::BI__sync_fetch_and_xor_1:
205 case Builtin::BI__sync_fetch_and_xor_2:
206 case Builtin::BI__sync_fetch_and_xor_4:
207 case Builtin::BI__sync_fetch_and_xor_8:
208 case Builtin::BI__sync_fetch_and_xor_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000209 case Builtin::BI__sync_add_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000210 case Builtin::BI__sync_add_and_fetch_1:
211 case Builtin::BI__sync_add_and_fetch_2:
212 case Builtin::BI__sync_add_and_fetch_4:
213 case Builtin::BI__sync_add_and_fetch_8:
214 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000215 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000216 case Builtin::BI__sync_sub_and_fetch_1:
217 case Builtin::BI__sync_sub_and_fetch_2:
218 case Builtin::BI__sync_sub_and_fetch_4:
219 case Builtin::BI__sync_sub_and_fetch_8:
220 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000221 case Builtin::BI__sync_and_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000222 case Builtin::BI__sync_and_and_fetch_1:
223 case Builtin::BI__sync_and_and_fetch_2:
224 case Builtin::BI__sync_and_and_fetch_4:
225 case Builtin::BI__sync_and_and_fetch_8:
226 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000227 case Builtin::BI__sync_or_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000228 case Builtin::BI__sync_or_and_fetch_1:
229 case Builtin::BI__sync_or_and_fetch_2:
230 case Builtin::BI__sync_or_and_fetch_4:
231 case Builtin::BI__sync_or_and_fetch_8:
232 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000233 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000234 case Builtin::BI__sync_xor_and_fetch_1:
235 case Builtin::BI__sync_xor_and_fetch_2:
236 case Builtin::BI__sync_xor_and_fetch_4:
237 case Builtin::BI__sync_xor_and_fetch_8:
238 case Builtin::BI__sync_xor_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000239 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000240 case Builtin::BI__sync_val_compare_and_swap_1:
241 case Builtin::BI__sync_val_compare_and_swap_2:
242 case Builtin::BI__sync_val_compare_and_swap_4:
243 case Builtin::BI__sync_val_compare_and_swap_8:
244 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000245 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000246 case Builtin::BI__sync_bool_compare_and_swap_1:
247 case Builtin::BI__sync_bool_compare_and_swap_2:
248 case Builtin::BI__sync_bool_compare_and_swap_4:
249 case Builtin::BI__sync_bool_compare_and_swap_8:
250 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000251 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregora9766412011-11-28 16:30:08 +0000252 case Builtin::BI__sync_lock_test_and_set_1:
253 case Builtin::BI__sync_lock_test_and_set_2:
254 case Builtin::BI__sync_lock_test_and_set_4:
255 case Builtin::BI__sync_lock_test_and_set_8:
256 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000257 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +0000258 case Builtin::BI__sync_lock_release_1:
259 case Builtin::BI__sync_lock_release_2:
260 case Builtin::BI__sync_lock_release_4:
261 case Builtin::BI__sync_lock_release_8:
262 case Builtin::BI__sync_lock_release_16:
Chris Lattner23aa9c82011-04-09 03:57:26 +0000263 case Builtin::BI__sync_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000264 case Builtin::BI__sync_swap_1:
265 case Builtin::BI__sync_swap_2:
266 case Builtin::BI__sync_swap_4:
267 case Builtin::BI__sync_swap_8:
268 case Builtin::BI__sync_swap_16:
Chandler Carruthd2014572010-07-09 18:59:35 +0000269 return SemaBuiltinAtomicOverloaded(move(TheCallResult));
Richard Smithff34d402012-04-12 05:08:17 +0000270#define BUILTIN(ID, TYPE, ATTRS)
271#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
272 case Builtin::BI##ID: \
273 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::AO##ID);
274#include "clang/Basic/Builtins.def"
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000275 case Builtin::BI__builtin_annotation:
Julien Lerougee5939212012-04-28 17:39:16 +0000276 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000277 return ExprError();
278 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000279 }
280
281 // Since the target specific builtins for each arch overlap, only check those
282 // of the arch we are compiling for.
283 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000284 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman26a31422010-06-08 02:47:44 +0000285 case llvm::Triple::arm:
286 case llvm::Triple::thumb:
287 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
288 return ExprError();
289 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000290 default:
291 break;
292 }
293 }
294
295 return move(TheCallResult);
296}
297
Nate Begeman61eecf52010-06-14 05:21:25 +0000298// Get the valid immediate range for the specified NEON type code.
299static unsigned RFT(unsigned t, bool shift = false) {
Bob Wilsonda95f732011-11-08 01:16:11 +0000300 NeonTypeFlags Type(t);
301 int IsQuad = Type.isQuad();
302 switch (Type.getEltType()) {
303 case NeonTypeFlags::Int8:
304 case NeonTypeFlags::Poly8:
305 return shift ? 7 : (8 << IsQuad) - 1;
306 case NeonTypeFlags::Int16:
307 case NeonTypeFlags::Poly16:
308 return shift ? 15 : (4 << IsQuad) - 1;
309 case NeonTypeFlags::Int32:
310 return shift ? 31 : (2 << IsQuad) - 1;
311 case NeonTypeFlags::Int64:
312 return shift ? 63 : (1 << IsQuad) - 1;
313 case NeonTypeFlags::Float16:
314 assert(!shift && "cannot shift float types!");
315 return (4 << IsQuad) - 1;
316 case NeonTypeFlags::Float32:
317 assert(!shift && "cannot shift float types!");
318 return (2 << IsQuad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000319 }
David Blaikie7530c032012-01-17 06:56:22 +0000320 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman61eecf52010-06-14 05:21:25 +0000321}
322
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000323/// getNeonEltType - Return the QualType corresponding to the elements of
324/// the vector type specified by the NeonTypeFlags. This is used to check
325/// the pointer arguments for Neon load/store intrinsics.
326static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context) {
327 switch (Flags.getEltType()) {
328 case NeonTypeFlags::Int8:
329 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
330 case NeonTypeFlags::Int16:
331 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
332 case NeonTypeFlags::Int32:
333 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
334 case NeonTypeFlags::Int64:
335 return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy;
336 case NeonTypeFlags::Poly8:
337 return Context.SignedCharTy;
338 case NeonTypeFlags::Poly16:
339 return Context.ShortTy;
340 case NeonTypeFlags::Float16:
341 return Context.UnsignedShortTy;
342 case NeonTypeFlags::Float32:
343 return Context.FloatTy;
344 }
David Blaikie7530c032012-01-17 06:56:22 +0000345 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000346}
347
Nate Begeman26a31422010-06-08 02:47:44 +0000348bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000349 llvm::APSInt Result;
350
Nate Begeman0d15c532010-06-13 04:47:52 +0000351 unsigned mask = 0;
Nate Begeman61eecf52010-06-14 05:21:25 +0000352 unsigned TV = 0;
Bob Wilson46482552011-11-16 21:32:23 +0000353 int PtrArgNum = -1;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000354 bool HasConstPtr = false;
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000355 switch (BuiltinID) {
Nate Begemana23326b2010-06-17 04:17:01 +0000356#define GET_NEON_OVERLOAD_CHECK
357#include "clang/Basic/arm_neon.inc"
358#undef GET_NEON_OVERLOAD_CHECK
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000359 }
360
Nate Begeman0d15c532010-06-13 04:47:52 +0000361 // For NEON intrinsics which are overloaded on vector element type, validate
362 // the immediate which specifies which variant to emit.
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000363 unsigned ImmArg = TheCall->getNumArgs()-1;
Nate Begeman0d15c532010-06-13 04:47:52 +0000364 if (mask) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000365 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
Nate Begeman0d15c532010-06-13 04:47:52 +0000366 return true;
367
Bob Wilsonda95f732011-11-08 01:16:11 +0000368 TV = Result.getLimitedValue(64);
369 if ((TV > 63) || (mask & (1 << TV)) == 0)
Nate Begeman0d15c532010-06-13 04:47:52 +0000370 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000371 << TheCall->getArg(ImmArg)->getSourceRange();
372 }
373
Bob Wilson46482552011-11-16 21:32:23 +0000374 if (PtrArgNum >= 0) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000375 // Check that pointer arguments have the specified type.
Bob Wilson46482552011-11-16 21:32:23 +0000376 Expr *Arg = TheCall->getArg(PtrArgNum);
377 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
378 Arg = ICE->getSubExpr();
379 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
380 QualType RHSTy = RHS.get()->getType();
381 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context);
382 if (HasConstPtr)
383 EltTy = EltTy.withConst();
384 QualType LHSTy = Context.getPointerType(EltTy);
385 AssignConvertType ConvTy;
386 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
387 if (RHS.isInvalid())
388 return true;
389 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
390 RHS.get(), AA_Assigning))
391 return true;
Nate Begeman0d15c532010-06-13 04:47:52 +0000392 }
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000393
Nate Begeman0d15c532010-06-13 04:47:52 +0000394 // For NEON intrinsics which take an immediate value as part of the
395 // instruction, range check them here.
Nate Begeman61eecf52010-06-14 05:21:25 +0000396 unsigned i = 0, l = 0, u = 0;
Nate Begeman0d15c532010-06-13 04:47:52 +0000397 switch (BuiltinID) {
398 default: return false;
Nate Begemanbb37f502010-07-29 22:48:34 +0000399 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
400 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begeman99c40bb2010-08-03 21:32:34 +0000401 case ARM::BI__builtin_arm_vcvtr_f:
402 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Nate Begemana23326b2010-06-17 04:17:01 +0000403#define GET_NEON_IMMEDIATE_CHECK
404#include "clang/Basic/arm_neon.inc"
405#undef GET_NEON_IMMEDIATE_CHECK
Nate Begeman0d15c532010-06-13 04:47:52 +0000406 };
407
Douglas Gregor592a4232012-06-29 01:05:22 +0000408 // We can't check the value of a dependent argument.
409 if (TheCall->getArg(i)->isTypeDependent() ||
410 TheCall->getArg(i)->isValueDependent())
411 return false;
412
Nate Begeman61eecf52010-06-14 05:21:25 +0000413 // Check that the immediate argument is actually a constant.
Nate Begeman0d15c532010-06-13 04:47:52 +0000414 if (SemaBuiltinConstantArg(TheCall, i, Result))
415 return true;
416
Nate Begeman61eecf52010-06-14 05:21:25 +0000417 // Range check against the upper/lower values for this isntruction.
Nate Begeman0d15c532010-06-13 04:47:52 +0000418 unsigned Val = Result.getZExtValue();
Nate Begeman61eecf52010-06-14 05:21:25 +0000419 if (Val < l || Val > (u + l))
Nate Begeman0d15c532010-06-13 04:47:52 +0000420 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramer476d8b82010-08-11 14:47:12 +0000421 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begeman0d15c532010-06-13 04:47:52 +0000422
Nate Begeman99c40bb2010-08-03 21:32:34 +0000423 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman26a31422010-06-08 02:47:44 +0000424 return false;
Anders Carlssond406bf02009-08-16 01:56:34 +0000425}
Daniel Dunbarde454282008-10-02 18:44:07 +0000426
Richard Smith831421f2012-06-25 20:30:08 +0000427/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
428/// parameter with the FormatAttr's correct format_idx and firstDataArg.
429/// Returns true when the format fits the function and the FormatStringInfo has
430/// been populated.
431bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
432 FormatStringInfo *FSI) {
433 FSI->HasVAListArg = Format->getFirstArg() == 0;
434 FSI->FormatIdx = Format->getFormatIdx() - 1;
435 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssond406bf02009-08-16 01:56:34 +0000436
Richard Smith831421f2012-06-25 20:30:08 +0000437 // The way the format attribute works in GCC, the implicit this argument
438 // of member functions is counted. However, it doesn't appear in our own
439 // lists, so decrement format_idx in that case.
440 if (IsCXXMember) {
441 if(FSI->FormatIdx == 0)
442 return false;
443 --FSI->FormatIdx;
444 if (FSI->FirstDataArg != 0)
445 --FSI->FirstDataArg;
446 }
447 return true;
448}
Mike Stump1eb44332009-09-09 15:08:12 +0000449
Richard Smith831421f2012-06-25 20:30:08 +0000450/// Handles the checks for format strings, non-POD arguments to vararg
451/// functions, and NULL arguments passed to non-NULL parameters.
452void Sema::checkCall(NamedDecl *FDecl, Expr **Args,
453 unsigned NumArgs,
454 unsigned NumProtoArgs,
455 bool IsMemberFunction,
456 SourceLocation Loc,
457 SourceRange Range,
458 VariadicCallType CallType) {
Daniel Dunbarde454282008-10-02 18:44:07 +0000459 // FIXME: This mechanism should be abstracted to be less fragile and
460 // more efficient. For example, just map function ids to custom
461 // handlers.
462
Ted Kremenekc82faca2010-09-09 04:33:05 +0000463 // Printf and scanf checking.
Richard Smith831421f2012-06-25 20:30:08 +0000464 bool HandledFormatString = false;
Ted Kremenekc82faca2010-09-09 04:33:05 +0000465 for (specific_attr_iterator<FormatAttr>
Richard Smith831421f2012-06-25 20:30:08 +0000466 I = FDecl->specific_attr_begin<FormatAttr>(),
467 E = FDecl->specific_attr_end<FormatAttr>(); I != E ; ++I)
468 if (CheckFormatArguments(*I, Args, NumArgs, IsMemberFunction, Loc, Range))
469 HandledFormatString = true;
470
471 // Refuse POD arguments that weren't caught by the format string
472 // checks above.
473 if (!HandledFormatString && CallType != VariadicDoesNotApply)
474 for (unsigned ArgIdx = NumProtoArgs; ArgIdx < NumArgs; ++ArgIdx)
475 variadicArgumentPODCheck(Args[ArgIdx], CallType);
Mike Stump1eb44332009-09-09 15:08:12 +0000476
Ted Kremenekc82faca2010-09-09 04:33:05 +0000477 for (specific_attr_iterator<NonNullAttr>
Richard Smith831421f2012-06-25 20:30:08 +0000478 I = FDecl->specific_attr_begin<NonNullAttr>(),
479 E = FDecl->specific_attr_end<NonNullAttr>(); I != E; ++I)
480 CheckNonNullArguments(*I, Args, Loc);
481}
482
483/// CheckConstructorCall - Check a constructor call for correctness and safety
484/// properties not enforced by the C type system.
485void Sema::CheckConstructorCall(FunctionDecl *FDecl, Expr **Args,
486 unsigned NumArgs,
487 const FunctionProtoType *Proto,
488 SourceLocation Loc) {
489 VariadicCallType CallType =
490 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
491 checkCall(FDecl, Args, NumArgs, Proto->getNumArgs(),
492 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
493}
494
495/// CheckFunctionCall - Check a direct function call for various correctness
496/// and safety properties not strictly enforced by the C type system.
497bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
498 const FunctionProtoType *Proto) {
499 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall);
500 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
501 TheCall->getCallee());
502 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
503 checkCall(FDecl, TheCall->getArgs(), TheCall->getNumArgs(), NumProtoArgs,
504 IsMemberFunction, TheCall->getRParenLoc(),
505 TheCall->getCallee()->getSourceRange(), CallType);
506
507 IdentifierInfo *FnInfo = FDecl->getIdentifier();
508 // None of the checks below are needed for functions that don't have
509 // simple names (e.g., C++ conversion functions).
510 if (!FnInfo)
511 return false;
Sebastian Redl0eb23302009-01-19 00:08:26 +0000512
Anna Zaks0a151a12012-01-17 00:37:07 +0000513 unsigned CMId = FDecl->getMemoryFunctionKind();
514 if (CMId == 0)
Anna Zaksd9b859a2012-01-13 21:52:01 +0000515 return false;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000516
Anna Zaksd9b859a2012-01-13 21:52:01 +0000517 // Handle memory setting and copying functions.
Anna Zaks0a151a12012-01-17 00:37:07 +0000518 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000519 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaksc36bedc2012-02-01 19:08:57 +0000520 else if (CMId == Builtin::BIstrncat)
521 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaksd9b859a2012-01-13 21:52:01 +0000522 else
Anna Zaks0a151a12012-01-17 00:37:07 +0000523 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth7ccc95b2011-04-27 07:05:31 +0000524
Anders Carlssond406bf02009-08-16 01:56:34 +0000525 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000526}
527
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000528bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
529 Expr **Args, unsigned NumArgs) {
Richard Smith831421f2012-06-25 20:30:08 +0000530 VariadicCallType CallType =
531 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000532
Richard Smith831421f2012-06-25 20:30:08 +0000533 checkCall(Method, Args, NumArgs, Method->param_size(),
534 /*IsMemberFunction=*/false,
535 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000536
537 return false;
538}
539
Richard Smith831421f2012-06-25 20:30:08 +0000540bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall,
541 const FunctionProtoType *Proto) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000542 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
543 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000544 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000545
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000546 QualType Ty = V->getType();
547 if (!Ty->isBlockPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000548 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000549
Richard Smith831421f2012-06-25 20:30:08 +0000550 VariadicCallType CallType =
551 Proto && Proto->isVariadic() ? VariadicBlock : VariadicDoesNotApply ;
552 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
Anders Carlssond406bf02009-08-16 01:56:34 +0000553
Richard Smith831421f2012-06-25 20:30:08 +0000554 checkCall(NDecl, TheCall->getArgs(), TheCall->getNumArgs(),
555 NumProtoArgs, /*IsMemberFunction=*/false,
556 TheCall->getRParenLoc(),
557 TheCall->getCallee()->getSourceRange(), CallType);
558
Anders Carlssond406bf02009-08-16 01:56:34 +0000559 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000560}
561
Richard Smithff34d402012-04-12 05:08:17 +0000562ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
563 AtomicExpr::AtomicOp Op) {
Eli Friedman276b0612011-10-11 02:20:01 +0000564 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
565 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedman276b0612011-10-11 02:20:01 +0000566
Richard Smithff34d402012-04-12 05:08:17 +0000567 // All these operations take one of the following forms:
568 enum {
569 // C __c11_atomic_init(A *, C)
570 Init,
571 // C __c11_atomic_load(A *, int)
572 Load,
573 // void __atomic_load(A *, CP, int)
574 Copy,
575 // C __c11_atomic_add(A *, M, int)
576 Arithmetic,
577 // C __atomic_exchange_n(A *, CP, int)
578 Xchg,
579 // void __atomic_exchange(A *, C *, CP, int)
580 GNUXchg,
581 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
582 C11CmpXchg,
583 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
584 GNUCmpXchg
585 } Form = Init;
586 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
587 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
588 // where:
589 // C is an appropriate type,
590 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
591 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
592 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
593 // the int parameters are for orderings.
Eli Friedman276b0612011-10-11 02:20:01 +0000594
Richard Smithff34d402012-04-12 05:08:17 +0000595 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
596 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
597 && "need to update code for modified C11 atomics");
598 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
599 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
600 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
601 Op == AtomicExpr::AO__atomic_store_n ||
602 Op == AtomicExpr::AO__atomic_exchange_n ||
603 Op == AtomicExpr::AO__atomic_compare_exchange_n;
604 bool IsAddSub = false;
605
606 switch (Op) {
607 case AtomicExpr::AO__c11_atomic_init:
608 Form = Init;
609 break;
610
611 case AtomicExpr::AO__c11_atomic_load:
612 case AtomicExpr::AO__atomic_load_n:
613 Form = Load;
614 break;
615
616 case AtomicExpr::AO__c11_atomic_store:
617 case AtomicExpr::AO__atomic_load:
618 case AtomicExpr::AO__atomic_store:
619 case AtomicExpr::AO__atomic_store_n:
620 Form = Copy;
621 break;
622
623 case AtomicExpr::AO__c11_atomic_fetch_add:
624 case AtomicExpr::AO__c11_atomic_fetch_sub:
625 case AtomicExpr::AO__atomic_fetch_add:
626 case AtomicExpr::AO__atomic_fetch_sub:
627 case AtomicExpr::AO__atomic_add_fetch:
628 case AtomicExpr::AO__atomic_sub_fetch:
629 IsAddSub = true;
630 // Fall through.
631 case AtomicExpr::AO__c11_atomic_fetch_and:
632 case AtomicExpr::AO__c11_atomic_fetch_or:
633 case AtomicExpr::AO__c11_atomic_fetch_xor:
634 case AtomicExpr::AO__atomic_fetch_and:
635 case AtomicExpr::AO__atomic_fetch_or:
636 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smith51b92402012-04-13 06:31:38 +0000637 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithff34d402012-04-12 05:08:17 +0000638 case AtomicExpr::AO__atomic_and_fetch:
639 case AtomicExpr::AO__atomic_or_fetch:
640 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smith51b92402012-04-13 06:31:38 +0000641 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithff34d402012-04-12 05:08:17 +0000642 Form = Arithmetic;
643 break;
644
645 case AtomicExpr::AO__c11_atomic_exchange:
646 case AtomicExpr::AO__atomic_exchange_n:
647 Form = Xchg;
648 break;
649
650 case AtomicExpr::AO__atomic_exchange:
651 Form = GNUXchg;
652 break;
653
654 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
655 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
656 Form = C11CmpXchg;
657 break;
658
659 case AtomicExpr::AO__atomic_compare_exchange:
660 case AtomicExpr::AO__atomic_compare_exchange_n:
661 Form = GNUCmpXchg;
662 break;
663 }
664
665 // Check we have the right number of arguments.
666 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedman276b0612011-10-11 02:20:01 +0000667 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithff34d402012-04-12 05:08:17 +0000668 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +0000669 << TheCall->getCallee()->getSourceRange();
670 return ExprError();
Richard Smithff34d402012-04-12 05:08:17 +0000671 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
672 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedman276b0612011-10-11 02:20:01 +0000673 diag::err_typecheck_call_too_many_args)
Richard Smithff34d402012-04-12 05:08:17 +0000674 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +0000675 << TheCall->getCallee()->getSourceRange();
676 return ExprError();
677 }
678
Richard Smithff34d402012-04-12 05:08:17 +0000679 // Inspect the first argument of the atomic operation.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000680 Expr *Ptr = TheCall->getArg(0);
Eli Friedman276b0612011-10-11 02:20:01 +0000681 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
682 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
683 if (!pointerType) {
Richard Smithff34d402012-04-12 05:08:17 +0000684 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedman276b0612011-10-11 02:20:01 +0000685 << Ptr->getType() << Ptr->getSourceRange();
686 return ExprError();
687 }
688
Richard Smithff34d402012-04-12 05:08:17 +0000689 // For a __c11 builtin, this should be a pointer to an _Atomic type.
690 QualType AtomTy = pointerType->getPointeeType(); // 'A'
691 QualType ValType = AtomTy; // 'C'
692 if (IsC11) {
693 if (!AtomTy->isAtomicType()) {
694 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
695 << Ptr->getType() << Ptr->getSourceRange();
696 return ExprError();
697 }
698 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedman276b0612011-10-11 02:20:01 +0000699 }
Eli Friedman276b0612011-10-11 02:20:01 +0000700
Richard Smithff34d402012-04-12 05:08:17 +0000701 // For an arithmetic operation, the implied arithmetic must be well-formed.
702 if (Form == Arithmetic) {
703 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
704 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
705 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
706 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
707 return ExprError();
708 }
709 if (!IsAddSub && !ValType->isIntegerType()) {
710 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
711 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
712 return ExprError();
713 }
714 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
715 // For __atomic_*_n operations, the value type must be a scalar integral or
716 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedman276b0612011-10-11 02:20:01 +0000717 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithff34d402012-04-12 05:08:17 +0000718 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
719 return ExprError();
720 }
721
722 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context)) {
723 // For GNU atomics, require a trivially-copyable type. This is not part of
724 // the GNU atomics specification, but we enforce it for sanity.
725 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedman276b0612011-10-11 02:20:01 +0000726 << Ptr->getType() << Ptr->getSourceRange();
727 return ExprError();
728 }
729
Richard Smithff34d402012-04-12 05:08:17 +0000730 // FIXME: For any builtin other than a load, the ValType must not be
731 // const-qualified.
Eli Friedman276b0612011-10-11 02:20:01 +0000732
733 switch (ValType.getObjCLifetime()) {
734 case Qualifiers::OCL_None:
735 case Qualifiers::OCL_ExplicitNone:
736 // okay
737 break;
738
739 case Qualifiers::OCL_Weak:
740 case Qualifiers::OCL_Strong:
741 case Qualifiers::OCL_Autoreleasing:
Richard Smithff34d402012-04-12 05:08:17 +0000742 // FIXME: Can this happen? By this point, ValType should be known
743 // to be trivially copyable.
Eli Friedman276b0612011-10-11 02:20:01 +0000744 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
745 << ValType << Ptr->getSourceRange();
746 return ExprError();
747 }
748
749 QualType ResultType = ValType;
Richard Smithff34d402012-04-12 05:08:17 +0000750 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedman276b0612011-10-11 02:20:01 +0000751 ResultType = Context.VoidTy;
Richard Smithff34d402012-04-12 05:08:17 +0000752 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedman276b0612011-10-11 02:20:01 +0000753 ResultType = Context.BoolTy;
754
Richard Smithff34d402012-04-12 05:08:17 +0000755 // The type of a parameter passed 'by value'. In the GNU atomics, such
756 // arguments are actually passed as pointers.
757 QualType ByValType = ValType; // 'CP'
758 if (!IsC11 && !IsN)
759 ByValType = Ptr->getType();
760
Eli Friedman276b0612011-10-11 02:20:01 +0000761 // The first argument --- the pointer --- has a fixed type; we
762 // deduce the types of the rest of the arguments accordingly. Walk
763 // the remaining arguments, converting them to the deduced value type.
Richard Smithff34d402012-04-12 05:08:17 +0000764 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedman276b0612011-10-11 02:20:01 +0000765 QualType Ty;
Richard Smithff34d402012-04-12 05:08:17 +0000766 if (i < NumVals[Form] + 1) {
767 switch (i) {
768 case 1:
769 // The second argument is the non-atomic operand. For arithmetic, this
770 // is always passed by value, and for a compare_exchange it is always
771 // passed by address. For the rest, GNU uses by-address and C11 uses
772 // by-value.
773 assert(Form != Load);
774 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
775 Ty = ValType;
776 else if (Form == Copy || Form == Xchg)
777 Ty = ByValType;
778 else if (Form == Arithmetic)
779 Ty = Context.getPointerDiffType();
780 else
781 Ty = Context.getPointerType(ValType.getUnqualifiedType());
782 break;
783 case 2:
784 // The third argument to compare_exchange / GNU exchange is a
785 // (pointer to a) desired value.
786 Ty = ByValType;
787 break;
788 case 3:
789 // The fourth argument to GNU compare_exchange is a 'weak' flag.
790 Ty = Context.BoolTy;
791 break;
792 }
Eli Friedman276b0612011-10-11 02:20:01 +0000793 } else {
794 // The order(s) are always converted to int.
795 Ty = Context.IntTy;
796 }
Richard Smithff34d402012-04-12 05:08:17 +0000797
Eli Friedman276b0612011-10-11 02:20:01 +0000798 InitializedEntity Entity =
799 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithff34d402012-04-12 05:08:17 +0000800 ExprResult Arg = TheCall->getArg(i);
Eli Friedman276b0612011-10-11 02:20:01 +0000801 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
802 if (Arg.isInvalid())
803 return true;
804 TheCall->setArg(i, Arg.get());
805 }
806
Richard Smithff34d402012-04-12 05:08:17 +0000807 // Permute the arguments into a 'consistent' order.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000808 SmallVector<Expr*, 5> SubExprs;
809 SubExprs.push_back(Ptr);
Richard Smithff34d402012-04-12 05:08:17 +0000810 switch (Form) {
811 case Init:
812 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnall7a7ee302012-01-16 17:27:18 +0000813 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +0000814 break;
815 case Load:
816 SubExprs.push_back(TheCall->getArg(1)); // Order
817 break;
818 case Copy:
819 case Arithmetic:
820 case Xchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000821 SubExprs.push_back(TheCall->getArg(2)); // Order
822 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +0000823 break;
824 case GNUXchg:
825 // Note, AtomicExpr::getVal2() has a special case for this atomic.
826 SubExprs.push_back(TheCall->getArg(3)); // Order
827 SubExprs.push_back(TheCall->getArg(1)); // Val1
828 SubExprs.push_back(TheCall->getArg(2)); // Val2
829 break;
830 case C11CmpXchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000831 SubExprs.push_back(TheCall->getArg(3)); // Order
832 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000833 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall2ebb98a2012-03-29 17:58:59 +0000834 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithff34d402012-04-12 05:08:17 +0000835 break;
836 case GNUCmpXchg:
837 SubExprs.push_back(TheCall->getArg(4)); // Order
838 SubExprs.push_back(TheCall->getArg(1)); // Val1
839 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
840 SubExprs.push_back(TheCall->getArg(2)); // Val2
841 SubExprs.push_back(TheCall->getArg(3)); // Weak
842 break;
Eli Friedman276b0612011-10-11 02:20:01 +0000843 }
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000844
845 return Owned(new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
846 SubExprs.data(), SubExprs.size(),
847 ResultType, Op,
848 TheCall->getRParenLoc()));
Eli Friedman276b0612011-10-11 02:20:01 +0000849}
850
851
John McCall5f8d6042011-08-27 01:09:30 +0000852/// checkBuiltinArgument - Given a call to a builtin function, perform
853/// normal type-checking on the given argument, updating the call in
854/// place. This is useful when a builtin function requires custom
855/// type-checking for some of its arguments but not necessarily all of
856/// them.
857///
858/// Returns true on error.
859static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
860 FunctionDecl *Fn = E->getDirectCallee();
861 assert(Fn && "builtin call without direct callee!");
862
863 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
864 InitializedEntity Entity =
865 InitializedEntity::InitializeParameter(S.Context, Param);
866
867 ExprResult Arg = E->getArg(0);
868 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
869 if (Arg.isInvalid())
870 return true;
871
872 E->setArg(ArgIndex, Arg.take());
873 return false;
874}
875
Chris Lattner5caa3702009-05-08 06:58:22 +0000876/// SemaBuiltinAtomicOverloaded - We have a call to a function like
877/// __sync_fetch_and_add, which is an overloaded function based on the pointer
878/// type of its first argument. The main ActOnCallExpr routines have already
879/// promoted the types of arguments because all of these calls are prototyped as
880/// void(...).
881///
882/// This function goes through and does final semantic checking for these
883/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +0000884ExprResult
885Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000886 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +0000887 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
888 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
889
890 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +0000891 if (TheCall->getNumArgs() < 1) {
892 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
893 << 0 << 1 << TheCall->getNumArgs()
894 << TheCall->getCallee()->getSourceRange();
895 return ExprError();
896 }
Mike Stump1eb44332009-09-09 15:08:12 +0000897
Chris Lattner5caa3702009-05-08 06:58:22 +0000898 // Inspect the first argument of the atomic builtin. This should always be
899 // a pointer type, whose element is an integral scalar or pointer type.
900 // Because it is a pointer type, we don't have to worry about any implicit
901 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +0000902 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +0000903 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman8c382062012-01-23 02:35:22 +0000904 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
905 if (FirstArgResult.isInvalid())
906 return ExprError();
907 FirstArg = FirstArgResult.take();
908 TheCall->setArg(0, FirstArg);
909
John McCallf85e1932011-06-15 23:02:42 +0000910 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
911 if (!pointerType) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000912 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
913 << FirstArg->getType() << FirstArg->getSourceRange();
914 return ExprError();
915 }
Mike Stump1eb44332009-09-09 15:08:12 +0000916
John McCallf85e1932011-06-15 23:02:42 +0000917 QualType ValType = pointerType->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +0000918 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +0000919 !ValType->isBlockPointerType()) {
920 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
921 << FirstArg->getType() << FirstArg->getSourceRange();
922 return ExprError();
923 }
Chris Lattner5caa3702009-05-08 06:58:22 +0000924
John McCallf85e1932011-06-15 23:02:42 +0000925 switch (ValType.getObjCLifetime()) {
926 case Qualifiers::OCL_None:
927 case Qualifiers::OCL_ExplicitNone:
928 // okay
929 break;
930
931 case Qualifiers::OCL_Weak:
932 case Qualifiers::OCL_Strong:
933 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +0000934 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCallf85e1932011-06-15 23:02:42 +0000935 << ValType << FirstArg->getSourceRange();
936 return ExprError();
937 }
938
John McCallb45ae252011-10-05 07:41:44 +0000939 // Strip any qualifiers off ValType.
940 ValType = ValType.getUnqualifiedType();
941
Chandler Carruth8d13d222010-07-18 20:54:12 +0000942 // The majority of builtins return a value, but a few have special return
943 // types, so allow them to override appropriately below.
944 QualType ResultType = ValType;
945
Chris Lattner5caa3702009-05-08 06:58:22 +0000946 // We need to figure out which concrete builtin this maps onto. For example,
947 // __sync_fetch_and_add with a 2 byte object turns into
948 // __sync_fetch_and_add_2.
949#define BUILTIN_ROW(x) \
950 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
951 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +0000952
Chris Lattner5caa3702009-05-08 06:58:22 +0000953 static const unsigned BuiltinIndices[][5] = {
954 BUILTIN_ROW(__sync_fetch_and_add),
955 BUILTIN_ROW(__sync_fetch_and_sub),
956 BUILTIN_ROW(__sync_fetch_and_or),
957 BUILTIN_ROW(__sync_fetch_and_and),
958 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +0000959
Chris Lattner5caa3702009-05-08 06:58:22 +0000960 BUILTIN_ROW(__sync_add_and_fetch),
961 BUILTIN_ROW(__sync_sub_and_fetch),
962 BUILTIN_ROW(__sync_and_and_fetch),
963 BUILTIN_ROW(__sync_or_and_fetch),
964 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +0000965
Chris Lattner5caa3702009-05-08 06:58:22 +0000966 BUILTIN_ROW(__sync_val_compare_and_swap),
967 BUILTIN_ROW(__sync_bool_compare_and_swap),
968 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner23aa9c82011-04-09 03:57:26 +0000969 BUILTIN_ROW(__sync_lock_release),
970 BUILTIN_ROW(__sync_swap)
Chris Lattner5caa3702009-05-08 06:58:22 +0000971 };
Mike Stump1eb44332009-09-09 15:08:12 +0000972#undef BUILTIN_ROW
973
Chris Lattner5caa3702009-05-08 06:58:22 +0000974 // Determine the index of the size.
975 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +0000976 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +0000977 case 1: SizeIndex = 0; break;
978 case 2: SizeIndex = 1; break;
979 case 4: SizeIndex = 2; break;
980 case 8: SizeIndex = 3; break;
981 case 16: SizeIndex = 4; break;
982 default:
Chandler Carruthd2014572010-07-09 18:59:35 +0000983 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
984 << FirstArg->getType() << FirstArg->getSourceRange();
985 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +0000986 }
Mike Stump1eb44332009-09-09 15:08:12 +0000987
Chris Lattner5caa3702009-05-08 06:58:22 +0000988 // Each of these builtins has one pointer argument, followed by some number of
989 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
990 // that we ignore. Find out which row of BuiltinIndices to read from as well
991 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +0000992 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +0000993 unsigned BuiltinIndex, NumFixed = 1;
994 switch (BuiltinID) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000995 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregora9766412011-11-28 16:30:08 +0000996 case Builtin::BI__sync_fetch_and_add:
997 case Builtin::BI__sync_fetch_and_add_1:
998 case Builtin::BI__sync_fetch_and_add_2:
999 case Builtin::BI__sync_fetch_and_add_4:
1000 case Builtin::BI__sync_fetch_and_add_8:
1001 case Builtin::BI__sync_fetch_and_add_16:
1002 BuiltinIndex = 0;
1003 break;
1004
1005 case Builtin::BI__sync_fetch_and_sub:
1006 case Builtin::BI__sync_fetch_and_sub_1:
1007 case Builtin::BI__sync_fetch_and_sub_2:
1008 case Builtin::BI__sync_fetch_and_sub_4:
1009 case Builtin::BI__sync_fetch_and_sub_8:
1010 case Builtin::BI__sync_fetch_and_sub_16:
1011 BuiltinIndex = 1;
1012 break;
1013
1014 case Builtin::BI__sync_fetch_and_or:
1015 case Builtin::BI__sync_fetch_and_or_1:
1016 case Builtin::BI__sync_fetch_and_or_2:
1017 case Builtin::BI__sync_fetch_and_or_4:
1018 case Builtin::BI__sync_fetch_and_or_8:
1019 case Builtin::BI__sync_fetch_and_or_16:
1020 BuiltinIndex = 2;
1021 break;
1022
1023 case Builtin::BI__sync_fetch_and_and:
1024 case Builtin::BI__sync_fetch_and_and_1:
1025 case Builtin::BI__sync_fetch_and_and_2:
1026 case Builtin::BI__sync_fetch_and_and_4:
1027 case Builtin::BI__sync_fetch_and_and_8:
1028 case Builtin::BI__sync_fetch_and_and_16:
1029 BuiltinIndex = 3;
1030 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001031
Douglas Gregora9766412011-11-28 16:30:08 +00001032 case Builtin::BI__sync_fetch_and_xor:
1033 case Builtin::BI__sync_fetch_and_xor_1:
1034 case Builtin::BI__sync_fetch_and_xor_2:
1035 case Builtin::BI__sync_fetch_and_xor_4:
1036 case Builtin::BI__sync_fetch_and_xor_8:
1037 case Builtin::BI__sync_fetch_and_xor_16:
1038 BuiltinIndex = 4;
1039 break;
1040
1041 case Builtin::BI__sync_add_and_fetch:
1042 case Builtin::BI__sync_add_and_fetch_1:
1043 case Builtin::BI__sync_add_and_fetch_2:
1044 case Builtin::BI__sync_add_and_fetch_4:
1045 case Builtin::BI__sync_add_and_fetch_8:
1046 case Builtin::BI__sync_add_and_fetch_16:
1047 BuiltinIndex = 5;
1048 break;
1049
1050 case Builtin::BI__sync_sub_and_fetch:
1051 case Builtin::BI__sync_sub_and_fetch_1:
1052 case Builtin::BI__sync_sub_and_fetch_2:
1053 case Builtin::BI__sync_sub_and_fetch_4:
1054 case Builtin::BI__sync_sub_and_fetch_8:
1055 case Builtin::BI__sync_sub_and_fetch_16:
1056 BuiltinIndex = 6;
1057 break;
1058
1059 case Builtin::BI__sync_and_and_fetch:
1060 case Builtin::BI__sync_and_and_fetch_1:
1061 case Builtin::BI__sync_and_and_fetch_2:
1062 case Builtin::BI__sync_and_and_fetch_4:
1063 case Builtin::BI__sync_and_and_fetch_8:
1064 case Builtin::BI__sync_and_and_fetch_16:
1065 BuiltinIndex = 7;
1066 break;
1067
1068 case Builtin::BI__sync_or_and_fetch:
1069 case Builtin::BI__sync_or_and_fetch_1:
1070 case Builtin::BI__sync_or_and_fetch_2:
1071 case Builtin::BI__sync_or_and_fetch_4:
1072 case Builtin::BI__sync_or_and_fetch_8:
1073 case Builtin::BI__sync_or_and_fetch_16:
1074 BuiltinIndex = 8;
1075 break;
1076
1077 case Builtin::BI__sync_xor_and_fetch:
1078 case Builtin::BI__sync_xor_and_fetch_1:
1079 case Builtin::BI__sync_xor_and_fetch_2:
1080 case Builtin::BI__sync_xor_and_fetch_4:
1081 case Builtin::BI__sync_xor_and_fetch_8:
1082 case Builtin::BI__sync_xor_and_fetch_16:
1083 BuiltinIndex = 9;
1084 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001085
Chris Lattner5caa3702009-05-08 06:58:22 +00001086 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001087 case Builtin::BI__sync_val_compare_and_swap_1:
1088 case Builtin::BI__sync_val_compare_and_swap_2:
1089 case Builtin::BI__sync_val_compare_and_swap_4:
1090 case Builtin::BI__sync_val_compare_and_swap_8:
1091 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001092 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +00001093 NumFixed = 2;
1094 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001095
Chris Lattner5caa3702009-05-08 06:58:22 +00001096 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001097 case Builtin::BI__sync_bool_compare_and_swap_1:
1098 case Builtin::BI__sync_bool_compare_and_swap_2:
1099 case Builtin::BI__sync_bool_compare_and_swap_4:
1100 case Builtin::BI__sync_bool_compare_and_swap_8:
1101 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001102 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +00001103 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001104 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001105 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001106
1107 case Builtin::BI__sync_lock_test_and_set:
1108 case Builtin::BI__sync_lock_test_and_set_1:
1109 case Builtin::BI__sync_lock_test_and_set_2:
1110 case Builtin::BI__sync_lock_test_and_set_4:
1111 case Builtin::BI__sync_lock_test_and_set_8:
1112 case Builtin::BI__sync_lock_test_and_set_16:
1113 BuiltinIndex = 12;
1114 break;
1115
Chris Lattner5caa3702009-05-08 06:58:22 +00001116 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +00001117 case Builtin::BI__sync_lock_release_1:
1118 case Builtin::BI__sync_lock_release_2:
1119 case Builtin::BI__sync_lock_release_4:
1120 case Builtin::BI__sync_lock_release_8:
1121 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001122 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +00001123 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001124 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001125 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001126
1127 case Builtin::BI__sync_swap:
1128 case Builtin::BI__sync_swap_1:
1129 case Builtin::BI__sync_swap_2:
1130 case Builtin::BI__sync_swap_4:
1131 case Builtin::BI__sync_swap_8:
1132 case Builtin::BI__sync_swap_16:
1133 BuiltinIndex = 14;
1134 break;
Chris Lattner5caa3702009-05-08 06:58:22 +00001135 }
Mike Stump1eb44332009-09-09 15:08:12 +00001136
Chris Lattner5caa3702009-05-08 06:58:22 +00001137 // Now that we know how many fixed arguments we expect, first check that we
1138 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +00001139 if (TheCall->getNumArgs() < 1+NumFixed) {
1140 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1141 << 0 << 1+NumFixed << TheCall->getNumArgs()
1142 << TheCall->getCallee()->getSourceRange();
1143 return ExprError();
1144 }
Mike Stump1eb44332009-09-09 15:08:12 +00001145
Chris Lattnere7ac0a92009-05-08 15:36:58 +00001146 // Get the decl for the concrete builtin from this, we can tell what the
1147 // concrete integer type we should convert to is.
1148 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1149 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
1150 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
Mike Stump1eb44332009-09-09 15:08:12 +00001151 FunctionDecl *NewBuiltinDecl =
Chris Lattnere7ac0a92009-05-08 15:36:58 +00001152 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
1153 TUScope, false, DRE->getLocStart()));
Chandler Carruthd2014572010-07-09 18:59:35 +00001154
John McCallf871d0c2010-08-07 06:22:56 +00001155 // The first argument --- the pointer --- has a fixed type; we
1156 // deduce the types of the rest of the arguments accordingly. Walk
1157 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +00001158 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley429bb272011-04-08 18:41:53 +00001159 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +00001160
Chris Lattner5caa3702009-05-08 06:58:22 +00001161 // GCC does an implicit conversion to the pointer or integer ValType. This
1162 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb45ae252011-10-05 07:41:44 +00001163 // Initialize the argument.
1164 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1165 ValType, /*consume*/ false);
1166 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley429bb272011-04-08 18:41:53 +00001167 if (Arg.isInvalid())
Chandler Carruthd2014572010-07-09 18:59:35 +00001168 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001169
Chris Lattner5caa3702009-05-08 06:58:22 +00001170 // Okay, we have something that *can* be converted to the right type. Check
1171 // to see if there is a potentially weird extension going on here. This can
1172 // happen when you do an atomic operation on something like an char* and
1173 // pass in 42. The 42 gets converted to char. This is even more strange
1174 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +00001175 // FIXME: Do this check.
John McCallb45ae252011-10-05 07:41:44 +00001176 TheCall->setArg(i+1, Arg.take());
Chris Lattner5caa3702009-05-08 06:58:22 +00001177 }
Mike Stump1eb44332009-09-09 15:08:12 +00001178
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001179 ASTContext& Context = this->getASTContext();
1180
1181 // Create a new DeclRefExpr to refer to the new decl.
1182 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1183 Context,
1184 DRE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001185 SourceLocation(),
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001186 NewBuiltinDecl,
John McCallf4b88a42012-03-10 09:33:50 +00001187 /*enclosing*/ false,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001188 DRE->getLocation(),
1189 NewBuiltinDecl->getType(),
1190 DRE->getValueKind());
Mike Stump1eb44332009-09-09 15:08:12 +00001191
Chris Lattner5caa3702009-05-08 06:58:22 +00001192 // Set the callee in the CallExpr.
1193 // FIXME: This leaks the original parens and implicit casts.
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001194 ExprResult PromotedCall = UsualUnaryConversions(NewDRE);
John Wiegley429bb272011-04-08 18:41:53 +00001195 if (PromotedCall.isInvalid())
1196 return ExprError();
1197 TheCall->setCallee(PromotedCall.take());
Mike Stump1eb44332009-09-09 15:08:12 +00001198
Chandler Carruthdb4325b2010-07-18 07:23:17 +00001199 // Change the result type of the call to match the original value type. This
1200 // is arbitrary, but the codegen for these builtins ins design to handle it
1201 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +00001202 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +00001203
1204 return move(TheCallResult);
Chris Lattner5caa3702009-05-08 06:58:22 +00001205}
1206
Chris Lattner69039812009-02-18 06:01:06 +00001207/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +00001208/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +00001209/// Note: It might also make sense to do the UTF-16 conversion here (would
1210/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +00001211bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +00001212 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +00001213 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1214
Douglas Gregor5cee1192011-07-27 05:40:30 +00001215 if (!Literal || !Literal->isAscii()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001216 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1217 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001218 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +00001219 }
Mike Stump1eb44332009-09-09 15:08:12 +00001220
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001221 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001222 StringRef String = Literal->getString();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001223 unsigned NumBytes = String.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001224 SmallVector<UTF16, 128> ToBuf(NumBytes);
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001225 const UTF8 *FromPtr = (UTF8 *)String.data();
1226 UTF16 *ToPtr = &ToBuf[0];
1227
1228 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1229 &ToPtr, ToPtr + NumBytes,
1230 strictConversion);
1231 // Check for conversion failure.
1232 if (Result != conversionOK)
1233 Diag(Arg->getLocStart(),
1234 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1235 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001236 return false;
Chris Lattner59907c42007-08-10 20:18:51 +00001237}
1238
Chris Lattnerc27c6652007-12-20 00:05:45 +00001239/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1240/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +00001241bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1242 Expr *Fn = TheCall->getCallee();
1243 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +00001244 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001245 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001246 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1247 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +00001248 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001249 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +00001250 return true;
1251 }
Eli Friedman56f20ae2008-12-15 22:05:35 +00001252
1253 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +00001254 return Diag(TheCall->getLocEnd(),
1255 diag::err_typecheck_call_too_few_args_at_least)
1256 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +00001257 }
1258
John McCall5f8d6042011-08-27 01:09:30 +00001259 // Type-check the first argument normally.
1260 if (checkBuiltinArgument(*this, TheCall, 0))
1261 return true;
1262
Chris Lattnerc27c6652007-12-20 00:05:45 +00001263 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001264 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +00001265 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001266 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +00001267 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +00001268 else if (FunctionDecl *FD = getCurFunctionDecl())
1269 isVariadic = FD->isVariadic();
1270 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001271 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +00001272
Chris Lattnerc27c6652007-12-20 00:05:45 +00001273 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001274 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1275 return true;
1276 }
Mike Stump1eb44332009-09-09 15:08:12 +00001277
Chris Lattner30ce3442007-12-19 23:59:04 +00001278 // Verify that the second argument to the builtin is the last argument of the
1279 // current function or method.
1280 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +00001281 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001282
Anders Carlsson88cf2262008-02-11 04:20:54 +00001283 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1284 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001285 // FIXME: This isn't correct for methods (results in bogus warning).
1286 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +00001287 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001288 if (CurBlock)
1289 LastArg = *(CurBlock->TheDecl->param_end()-1);
1290 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +00001291 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001292 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001293 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001294 SecondArgIsLastNamedArgument = PV == LastArg;
1295 }
1296 }
Mike Stump1eb44332009-09-09 15:08:12 +00001297
Chris Lattner30ce3442007-12-19 23:59:04 +00001298 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001299 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +00001300 diag::warn_second_parameter_of_va_start_not_last_named_argument);
1301 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +00001302}
Chris Lattner30ce3442007-12-19 23:59:04 +00001303
Chris Lattner1b9a0792007-12-20 00:26:33 +00001304/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1305/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +00001306bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1307 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +00001308 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001309 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +00001310 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +00001311 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001312 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001313 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001314 << SourceRange(TheCall->getArg(2)->getLocStart(),
1315 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001316
John Wiegley429bb272011-04-08 18:41:53 +00001317 ExprResult OrigArg0 = TheCall->getArg(0);
1318 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +00001319
Chris Lattner1b9a0792007-12-20 00:26:33 +00001320 // Do standard promotions between the two arguments, returning their common
1321 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +00001322 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley429bb272011-04-08 18:41:53 +00001323 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1324 return true;
Daniel Dunbar403bc2b2009-02-19 19:28:43 +00001325
1326 // Make sure any conversions are pushed back into the call; this is
1327 // type safe since unordered compare builtins are declared as "_Bool
1328 // foo(...)".
John Wiegley429bb272011-04-08 18:41:53 +00001329 TheCall->setArg(0, OrigArg0.get());
1330 TheCall->setArg(1, OrigArg1.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001331
John Wiegley429bb272011-04-08 18:41:53 +00001332 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorcde01732009-05-19 22:10:17 +00001333 return false;
1334
Chris Lattner1b9a0792007-12-20 00:26:33 +00001335 // If the common type isn't a real floating type, then the arguments were
1336 // invalid for this operation.
Eli Friedman860a3192012-06-16 02:19:17 +00001337 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +00001338 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001339 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley429bb272011-04-08 18:41:53 +00001340 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1341 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001342
Chris Lattner1b9a0792007-12-20 00:26:33 +00001343 return false;
1344}
1345
Benjamin Kramere771a7a2010-02-15 22:42:31 +00001346/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1347/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001348/// to check everything. We expect the last argument to be a floating point
1349/// value.
1350bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1351 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +00001352 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001353 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001354 if (TheCall->getNumArgs() > NumArgs)
1355 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001356 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001357 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001358 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001359 (*(TheCall->arg_end()-1))->getLocEnd());
1360
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001361 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001362
Eli Friedman9ac6f622009-08-31 20:06:00 +00001363 if (OrigArg->isTypeDependent())
1364 return false;
1365
Chris Lattner81368fb2010-05-06 05:50:07 +00001366 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +00001367 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +00001368 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001369 diag::err_typecheck_call_invalid_unary_fp)
1370 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001371
Chris Lattner81368fb2010-05-06 05:50:07 +00001372 // If this is an implicit conversion from float -> double, remove it.
1373 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1374 Expr *CastArg = Cast->getSubExpr();
1375 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1376 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1377 "promotion from float to double is the only expected cast here");
1378 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +00001379 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner81368fb2010-05-06 05:50:07 +00001380 }
1381 }
1382
Eli Friedman9ac6f622009-08-31 20:06:00 +00001383 return false;
1384}
1385
Eli Friedmand38617c2008-05-14 19:38:39 +00001386/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1387// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +00001388ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001389 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001390 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +00001391 diag::err_typecheck_call_too_few_args_at_least)
Nate Begeman37b6a572010-06-08 00:16:34 +00001392 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherd77b9a22010-04-16 04:48:22 +00001393 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001394
Nate Begeman37b6a572010-06-08 00:16:34 +00001395 // Determine which of the following types of shufflevector we're checking:
1396 // 1) unary, vector mask: (lhs, mask)
1397 // 2) binary, vector mask: (lhs, rhs, mask)
1398 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1399 QualType resType = TheCall->getArg(0)->getType();
1400 unsigned numElements = 0;
1401
Douglas Gregorcde01732009-05-19 22:10:17 +00001402 if (!TheCall->getArg(0)->isTypeDependent() &&
1403 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001404 QualType LHSType = TheCall->getArg(0)->getType();
1405 QualType RHSType = TheCall->getArg(1)->getType();
1406
1407 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001408 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001409 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001410 TheCall->getArg(1)->getLocEnd());
1411 return ExprError();
1412 }
Nate Begeman37b6a572010-06-08 00:16:34 +00001413
1414 numElements = LHSType->getAs<VectorType>()->getNumElements();
1415 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +00001416
Nate Begeman37b6a572010-06-08 00:16:34 +00001417 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1418 // with mask. If so, verify that RHS is an integer vector type with the
1419 // same number of elts as lhs.
1420 if (TheCall->getNumArgs() == 2) {
Douglas Gregorf6094622010-07-23 15:58:24 +00001421 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +00001422 RHSType->getAs<VectorType>()->getNumElements() != numElements)
1423 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
1424 << SourceRange(TheCall->getArg(1)->getLocStart(),
1425 TheCall->getArg(1)->getLocEnd());
1426 numResElements = numElements;
1427 }
1428 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001429 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001430 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001431 TheCall->getArg(1)->getLocEnd());
1432 return ExprError();
Nate Begeman37b6a572010-06-08 00:16:34 +00001433 } else if (numElements != numResElements) {
1434 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +00001435 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001436 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +00001437 }
Eli Friedmand38617c2008-05-14 19:38:39 +00001438 }
1439
1440 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001441 if (TheCall->getArg(i)->isTypeDependent() ||
1442 TheCall->getArg(i)->isValueDependent())
1443 continue;
1444
Nate Begeman37b6a572010-06-08 00:16:34 +00001445 llvm::APSInt Result(32);
1446 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1447 return ExprError(Diag(TheCall->getLocStart(),
1448 diag::err_shufflevector_nonconstant_argument)
1449 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001450
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001451 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001452 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001453 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001454 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001455 }
1456
Chris Lattner5f9e2722011-07-23 10:55:15 +00001457 SmallVector<Expr*, 32> exprs;
Eli Friedmand38617c2008-05-14 19:38:39 +00001458
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001459 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +00001460 exprs.push_back(TheCall->getArg(i));
1461 TheCall->setArg(i, 0);
1462 }
1463
Nate Begemana88dc302009-08-12 02:10:25 +00001464 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
Nate Begeman37b6a572010-06-08 00:16:34 +00001465 exprs.size(), resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001466 TheCall->getCallee()->getLocStart(),
1467 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +00001468}
Chris Lattner30ce3442007-12-19 23:59:04 +00001469
Daniel Dunbar4493f792008-07-21 22:59:13 +00001470/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1471// This is declared to take (const void*, ...) and can take two
1472// optional constant int args.
1473bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001474 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001475
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001476 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +00001477 return Diag(TheCall->getLocEnd(),
1478 diag::err_typecheck_call_too_many_args_at_most)
1479 << 0 /*function call*/ << 3 << NumArgs
1480 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001481
1482 // Argument 0 is checked for us and the remaining arguments must be
1483 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001484 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +00001485 Expr *Arg = TheCall->getArg(i);
Douglas Gregor592a4232012-06-29 01:05:22 +00001486
1487 // We can't check the value of a dependent argument.
1488 if (Arg->isTypeDependent() || Arg->isValueDependent())
1489 continue;
1490
Eli Friedman9aef7262009-12-04 00:30:06 +00001491 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +00001492 if (SemaBuiltinConstantArg(TheCall, i, Result))
1493 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001494
Daniel Dunbar4493f792008-07-21 22:59:13 +00001495 // FIXME: gcc issues a warning and rewrites these to 0. These
1496 // seems especially odd for the third argument since the default
1497 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001498 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +00001499 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001500 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001501 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001502 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +00001503 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001504 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001505 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001506 }
1507 }
1508
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001509 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +00001510}
1511
Eric Christopher691ebc32010-04-17 02:26:23 +00001512/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1513/// TheCall is a constant expression.
1514bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1515 llvm::APSInt &Result) {
1516 Expr *Arg = TheCall->getArg(ArgNum);
1517 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1518 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1519
1520 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1521
1522 if (!Arg->isIntegerConstantExpr(Result, Context))
1523 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +00001524 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +00001525
Chris Lattner21fb98e2009-09-23 06:06:36 +00001526 return false;
1527}
1528
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001529/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1530/// int type). This simply type checks that type is one of the defined
1531/// constants (0-3).
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001532// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001533bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +00001534 llvm::APSInt Result;
Douglas Gregor592a4232012-06-29 01:05:22 +00001535
1536 // We can't check the value of a dependent argument.
1537 if (TheCall->getArg(1)->isTypeDependent() ||
1538 TheCall->getArg(1)->isValueDependent())
1539 return false;
1540
Eric Christopher691ebc32010-04-17 02:26:23 +00001541 // Check constant-ness first.
1542 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1543 return true;
1544
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001545 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001546 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001547 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1548 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001549 }
1550
1551 return false;
1552}
1553
Eli Friedman586d6a82009-05-03 06:04:26 +00001554/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +00001555/// This checks that val is a constant 1.
1556bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1557 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +00001558 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +00001559
Eric Christopher691ebc32010-04-17 02:26:23 +00001560 // TODO: This is less than ideal. Overload this to take a value.
1561 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1562 return true;
1563
1564 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +00001565 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1566 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1567
1568 return false;
1569}
1570
Richard Smith831421f2012-06-25 20:30:08 +00001571// Determine if an expression is a string literal or constant string.
1572// If this function returns false on the arguments to a function expecting a
1573// format string, we will usually need to emit a warning.
1574// True string literals are then checked by CheckFormatString.
1575Sema::StringLiteralCheckType
1576Sema::checkFormatStringExpr(const Expr *E, Expr **Args,
1577 unsigned NumArgs, bool HasVAListArg,
1578 unsigned format_idx, unsigned firstDataArg,
1579 FormatStringType Type, bool inFunctionCall) {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001580 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +00001581 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith831421f2012-06-25 20:30:08 +00001582 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001583
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001584 E = E->IgnoreParenCasts();
Peter Collingbournef111d932011-04-15 00:35:48 +00001585
David Blaikiea73cdcb2012-02-10 21:07:25 +00001586 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
1587 // Technically -Wformat-nonliteral does not warn about this case.
1588 // The behavior of printf and friends in this case is implementation
1589 // dependent. Ideally if the format string cannot be null then
1590 // it should have a 'nonnull' attribute in the function prototype.
Richard Smith831421f2012-06-25 20:30:08 +00001591 return SLCT_CheckedLiteral;
David Blaikiea73cdcb2012-02-10 21:07:25 +00001592
Ted Kremenekd30ef872009-01-12 23:09:09 +00001593 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +00001594 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +00001595 case Stmt::ConditionalOperatorClass: {
Richard Smith831421f2012-06-25 20:30:08 +00001596 // The expression is a literal if both sub-expressions were, and it was
1597 // completely checked only if both sub-expressions were checked.
1598 const AbstractConditionalOperator *C =
1599 cast<AbstractConditionalOperator>(E);
1600 StringLiteralCheckType Left =
1601 checkFormatStringExpr(C->getTrueExpr(), Args, NumArgs,
1602 HasVAListArg, format_idx, firstDataArg,
1603 Type, inFunctionCall);
1604 if (Left == SLCT_NotALiteral)
1605 return SLCT_NotALiteral;
1606 StringLiteralCheckType Right =
1607 checkFormatStringExpr(C->getFalseExpr(), Args, NumArgs,
1608 HasVAListArg, format_idx, firstDataArg,
1609 Type, inFunctionCall);
1610 return Left < Right ? Left : Right;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001611 }
1612
1613 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001614 E = cast<ImplicitCastExpr>(E)->getSubExpr();
1615 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001616 }
1617
John McCall56ca35d2011-02-17 10:25:35 +00001618 case Stmt::OpaqueValueExprClass:
1619 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
1620 E = src;
1621 goto tryAgain;
1622 }
Richard Smith831421f2012-06-25 20:30:08 +00001623 return SLCT_NotALiteral;
John McCall56ca35d2011-02-17 10:25:35 +00001624
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001625 case Stmt::PredefinedExprClass:
1626 // While __func__, etc., are technically not string literals, they
1627 // cannot contain format specifiers and thus are not a security
1628 // liability.
Richard Smith831421f2012-06-25 20:30:08 +00001629 return SLCT_UncheckedLiteral;
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001630
Ted Kremenek082d9362009-03-20 21:35:28 +00001631 case Stmt::DeclRefExprClass: {
1632 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001633
Ted Kremenek082d9362009-03-20 21:35:28 +00001634 // As an exception, do not flag errors for variables binding to
1635 // const string literals.
1636 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1637 bool isConstant = false;
1638 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001639
Ted Kremenek082d9362009-03-20 21:35:28 +00001640 if (const ArrayType *AT = Context.getAsArrayType(T)) {
1641 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001642 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001643 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +00001644 PT->getPointeeType().isConstant(Context);
Jean-Daniel Dupase98e5b52012-01-25 10:35:33 +00001645 } else if (T->isObjCObjectPointerType()) {
1646 // In ObjC, there is usually no "const ObjectPointer" type,
1647 // so don't check if the pointee type is constant.
1648 isConstant = T.isConstant(Context);
Ted Kremenek082d9362009-03-20 21:35:28 +00001649 }
Mike Stump1eb44332009-09-09 15:08:12 +00001650
Ted Kremenek082d9362009-03-20 21:35:28 +00001651 if (isConstant) {
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00001652 if (const Expr *Init = VD->getAnyInitializer()) {
1653 // Look through initializers like const char c[] = { "foo" }
1654 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
1655 if (InitList->isStringLiteralInit())
1656 Init = InitList->getInit(0)->IgnoreParenImpCasts();
1657 }
Richard Smith831421f2012-06-25 20:30:08 +00001658 return checkFormatStringExpr(Init, Args, NumArgs,
1659 HasVAListArg, format_idx,
1660 firstDataArg, Type,
1661 /*inFunctionCall*/false);
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00001662 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001663 }
Mike Stump1eb44332009-09-09 15:08:12 +00001664
Anders Carlssond966a552009-06-28 19:55:58 +00001665 // For vprintf* functions (i.e., HasVAListArg==true), we add a
1666 // special check to see if the format string is a function parameter
1667 // of the function calling the printf function. If the function
1668 // has an attribute indicating it is a printf-like function, then we
1669 // should suppress warnings concerning non-literals being used in a call
1670 // to a vprintf function. For example:
1671 //
1672 // void
1673 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
1674 // va_list ap;
1675 // va_start(ap, fmt);
1676 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
1677 // ...
1678 //
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00001679 if (HasVAListArg) {
1680 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
1681 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
1682 int PVIndex = PV->getFunctionScopeIndex() + 1;
1683 for (specific_attr_iterator<FormatAttr>
1684 i = ND->specific_attr_begin<FormatAttr>(),
1685 e = ND->specific_attr_end<FormatAttr>(); i != e ; ++i) {
1686 FormatAttr *PVFormat = *i;
1687 // adjust for implicit parameter
1688 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
1689 if (MD->isInstance())
1690 ++PVIndex;
1691 // We also check if the formats are compatible.
1692 // We can't pass a 'scanf' string to a 'printf' function.
1693 if (PVIndex == PVFormat->getFormatIdx() &&
1694 Type == GetFormatStringType(PVFormat))
Richard Smith831421f2012-06-25 20:30:08 +00001695 return SLCT_UncheckedLiteral;
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00001696 }
1697 }
1698 }
1699 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001700 }
Mike Stump1eb44332009-09-09 15:08:12 +00001701
Richard Smith831421f2012-06-25 20:30:08 +00001702 return SLCT_NotALiteral;
Ted Kremenek082d9362009-03-20 21:35:28 +00001703 }
Ted Kremenekd30ef872009-01-12 23:09:09 +00001704
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001705 case Stmt::CallExprClass:
1706 case Stmt::CXXMemberCallExprClass: {
Anders Carlsson8f031b32009-06-27 04:05:33 +00001707 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001708 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
1709 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
1710 unsigned ArgIndex = FA->getFormatIdx();
1711 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
1712 if (MD->isInstance())
1713 --ArgIndex;
1714 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001715
Richard Smith831421f2012-06-25 20:30:08 +00001716 return checkFormatStringExpr(Arg, Args, NumArgs,
1717 HasVAListArg, format_idx, firstDataArg,
1718 Type, inFunctionCall);
Jordan Rose50687312012-06-04 23:52:23 +00001719 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
1720 unsigned BuiltinID = FD->getBuiltinID();
1721 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
1722 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
1723 const Expr *Arg = CE->getArg(0);
Richard Smith831421f2012-06-25 20:30:08 +00001724 return checkFormatStringExpr(Arg, Args, NumArgs,
1725 HasVAListArg, format_idx,
1726 firstDataArg, Type, inFunctionCall);
Jordan Rose50687312012-06-04 23:52:23 +00001727 }
Anders Carlsson8f031b32009-06-27 04:05:33 +00001728 }
1729 }
Mike Stump1eb44332009-09-09 15:08:12 +00001730
Richard Smith831421f2012-06-25 20:30:08 +00001731 return SLCT_NotALiteral;
Anders Carlsson8f031b32009-06-27 04:05:33 +00001732 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001733 case Stmt::ObjCStringLiteralClass:
1734 case Stmt::StringLiteralClass: {
1735 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001736
Ted Kremenek082d9362009-03-20 21:35:28 +00001737 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00001738 StrE = ObjCFExpr->getString();
1739 else
Ted Kremenek082d9362009-03-20 21:35:28 +00001740 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001741
Ted Kremenekd30ef872009-01-12 23:09:09 +00001742 if (StrE) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001743 CheckFormatString(StrE, E, Args, NumArgs, HasVAListArg, format_idx,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001744 firstDataArg, Type, inFunctionCall);
Richard Smith831421f2012-06-25 20:30:08 +00001745 return SLCT_CheckedLiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001746 }
Mike Stump1eb44332009-09-09 15:08:12 +00001747
Richard Smith831421f2012-06-25 20:30:08 +00001748 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001749 }
Mike Stump1eb44332009-09-09 15:08:12 +00001750
Ted Kremenek082d9362009-03-20 21:35:28 +00001751 default:
Richard Smith831421f2012-06-25 20:30:08 +00001752 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001753 }
1754}
1755
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001756void
Mike Stump1eb44332009-09-09 15:08:12 +00001757Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewycky909a70d2011-03-25 01:44:32 +00001758 const Expr * const *ExprArgs,
1759 SourceLocation CallSiteLoc) {
Sean Huntcf807c42010-08-18 23:23:40 +00001760 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1761 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001762 i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +00001763 const Expr *ArgExpr = ExprArgs[*i];
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001764 if (ArgExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00001765 Expr::NPC_ValueDependentIsNotNull))
Nick Lewycky909a70d2011-03-25 01:44:32 +00001766 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001767 }
1768}
Ted Kremenekd30ef872009-01-12 23:09:09 +00001769
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001770Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
1771 return llvm::StringSwitch<FormatStringType>(Format->getType())
1772 .Case("scanf", FST_Scanf)
1773 .Cases("printf", "printf0", FST_Printf)
1774 .Cases("NSString", "CFString", FST_NSString)
1775 .Case("strftime", FST_Strftime)
1776 .Case("strfmon", FST_Strfmon)
1777 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
1778 .Default(FST_Unknown);
1779}
1780
Ted Kremenek826a3452010-07-16 02:11:22 +00001781/// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar
1782/// functions) for correct use of format strings.
Richard Smith831421f2012-06-25 20:30:08 +00001783/// Returns true if a format string has been fully checked.
1784bool Sema::CheckFormatArguments(const FormatAttr *Format, CallExpr *TheCall) {
1785 bool IsCXXMember = isa<CXXMemberCallExpr>(TheCall);
1786 return CheckFormatArguments(Format, TheCall->getArgs(),
1787 TheCall->getNumArgs(),
1788 IsCXXMember, TheCall->getRParenLoc(),
1789 TheCall->getCallee()->getSourceRange());
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001790}
1791
Richard Smith831421f2012-06-25 20:30:08 +00001792bool Sema::CheckFormatArguments(const FormatAttr *Format, Expr **Args,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001793 unsigned NumArgs, bool IsCXXMember,
1794 SourceLocation Loc, SourceRange Range) {
Richard Smith831421f2012-06-25 20:30:08 +00001795 FormatStringInfo FSI;
1796 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
1797 return CheckFormatArguments(Args, NumArgs, FSI.HasVAListArg, FSI.FormatIdx,
1798 FSI.FirstDataArg, GetFormatStringType(Format),
1799 Loc, Range);
1800 return false;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001801}
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001802
Richard Smith831421f2012-06-25 20:30:08 +00001803bool Sema::CheckFormatArguments(Expr **Args, unsigned NumArgs,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001804 bool HasVAListArg, unsigned format_idx,
1805 unsigned firstDataArg, FormatStringType Type,
1806 SourceLocation Loc, SourceRange Range) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001807 // CHECK: printf/scanf-like function is called with no format string.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001808 if (format_idx >= NumArgs) {
1809 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith831421f2012-06-25 20:30:08 +00001810 return false;
Ted Kremenek71895b92007-08-14 17:39:48 +00001811 }
Mike Stump1eb44332009-09-09 15:08:12 +00001812
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001813 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001814
Chris Lattner59907c42007-08-10 20:18:51 +00001815 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001816 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001817 // Dynamically generated format strings are difficult to
1818 // automatically vet at compile time. Requiring that format strings
1819 // are string literals: (1) permits the checking of format strings by
1820 // the compiler and thereby (2) can practically remove the source of
1821 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001822
Mike Stump1eb44332009-09-09 15:08:12 +00001823 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001824 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001825 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001826 // the same format string checking logic for both ObjC and C strings.
Richard Smith831421f2012-06-25 20:30:08 +00001827 StringLiteralCheckType CT =
1828 checkFormatStringExpr(OrigFormatExpr, Args, NumArgs, HasVAListArg,
1829 format_idx, firstDataArg, Type);
1830 if (CT != SLCT_NotALiteral)
1831 // Literal format string found, check done!
1832 return CT == SLCT_CheckedLiteral;
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001833
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00001834 // Strftime is particular as it always uses a single 'time' argument,
1835 // so it is safe to pass a non-literal string.
1836 if (Type == FST_Strftime)
Richard Smith831421f2012-06-25 20:30:08 +00001837 return false;
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00001838
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00001839 // Do not emit diag when the string param is a macro expansion and the
1840 // format is either NSString or CFString. This is a hack to prevent
1841 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
1842 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupasdc170202012-05-04 21:08:08 +00001843 if (Type == FST_NSString &&
1844 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith831421f2012-06-25 20:30:08 +00001845 return false;
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00001846
Chris Lattner655f1412009-04-29 04:59:47 +00001847 // If there are no arguments specified, warn with -Wformat-security, otherwise
1848 // warn only with -Wformat-nonliteral.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001849 if (NumArgs == format_idx+1)
1850 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001851 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00001852 << OrigFormatExpr->getSourceRange();
1853 else
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001854 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001855 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00001856 << OrigFormatExpr->getSourceRange();
Richard Smith831421f2012-06-25 20:30:08 +00001857 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001858}
Ted Kremenek71895b92007-08-14 17:39:48 +00001859
Ted Kremeneke0e53132010-01-28 23:39:18 +00001860namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00001861class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1862protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00001863 Sema &S;
1864 const StringLiteral *FExpr;
1865 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00001866 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001867 const unsigned NumDataArgs;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001868 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00001869 const bool HasVAListArg;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001870 const Expr * const *Args;
1871 const unsigned NumArgs;
Ted Kremenek0d277352010-01-29 01:06:55 +00001872 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001873 llvm::BitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00001874 bool usesPositionalArgs;
1875 bool atFirstArg;
Richard Trieu55733de2011-10-28 00:41:25 +00001876 bool inFunctionCall;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001877public:
Ted Kremenek826a3452010-07-16 02:11:22 +00001878 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00001879 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00001880 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001881 Expr **args, unsigned numArgs,
1882 unsigned formatIdx, bool inFunctionCall)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001883 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose50687312012-06-04 23:52:23 +00001884 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
1885 Beg(beg), HasVAListArg(hasVAListArg),
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001886 Args(args), NumArgs(numArgs), FormatIdx(formatIdx),
Richard Trieu55733de2011-10-28 00:41:25 +00001887 usesPositionalArgs(false), atFirstArg(true),
1888 inFunctionCall(inFunctionCall) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001889 CoveredArgs.resize(numDataArgs);
1890 CoveredArgs.reset();
1891 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001892
Ted Kremenek07d161f2010-01-29 01:50:07 +00001893 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001894
Ted Kremenek826a3452010-07-16 02:11:22 +00001895 void HandleIncompleteSpecifier(const char *startSpecifier,
1896 unsigned specifierLen);
Hans Wennborg76517422012-02-22 10:17:01 +00001897
1898 void HandleNonStandardLengthModifier(
1899 const analyze_format_string::LengthModifier &LM,
1900 const char *startSpecifier, unsigned specifierLen);
1901
1902 void HandleNonStandardConversionSpecifier(
1903 const analyze_format_string::ConversionSpecifier &CS,
1904 const char *startSpecifier, unsigned specifierLen);
1905
1906 void HandleNonStandardConversionSpecification(
1907 const analyze_format_string::LengthModifier &LM,
1908 const analyze_format_string::ConversionSpecifier &CS,
1909 const char *startSpecifier, unsigned specifierLen);
1910
Hans Wennborgf8562642012-03-09 10:10:54 +00001911 virtual void HandlePosition(const char *startPos, unsigned posLen);
1912
Ted Kremenekefaff192010-02-27 01:41:03 +00001913 virtual void HandleInvalidPosition(const char *startSpecifier,
1914 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00001915 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00001916
1917 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1918
Ted Kremeneke0e53132010-01-28 23:39:18 +00001919 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001920
Richard Trieu55733de2011-10-28 00:41:25 +00001921 template <typename Range>
1922 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
1923 const Expr *ArgumentExpr,
1924 PartialDiagnostic PDiag,
1925 SourceLocation StringLoc,
1926 bool IsStringLocation, Range StringRange,
1927 FixItHint Fixit = FixItHint());
1928
Ted Kremenek826a3452010-07-16 02:11:22 +00001929protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001930 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
1931 const char *startSpec,
1932 unsigned specifierLen,
1933 const char *csStart, unsigned csLen);
Richard Trieu55733de2011-10-28 00:41:25 +00001934
1935 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
1936 const char *startSpec,
1937 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001938
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001939 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00001940 CharSourceRange getSpecifierRange(const char *startSpecifier,
1941 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001942 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001943
Ted Kremenek0d277352010-01-29 01:06:55 +00001944 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00001945
1946 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
1947 const analyze_format_string::ConversionSpecifier &CS,
1948 const char *startSpecifier, unsigned specifierLen,
1949 unsigned argIndex);
Richard Trieu55733de2011-10-28 00:41:25 +00001950
1951 template <typename Range>
1952 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
1953 bool IsStringLocation, Range StringRange,
1954 FixItHint Fixit = FixItHint());
1955
1956 void CheckPositionalAndNonpositionalArgs(
1957 const analyze_format_string::FormatSpecifier *FS);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001958};
1959}
1960
Ted Kremenek826a3452010-07-16 02:11:22 +00001961SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00001962 return OrigFormatExpr->getSourceRange();
1963}
1964
Ted Kremenek826a3452010-07-16 02:11:22 +00001965CharSourceRange CheckFormatHandler::
1966getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00001967 SourceLocation Start = getLocationOfByte(startSpecifier);
1968 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
1969
1970 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001971 End = End.getLocWithOffset(1);
Tom Care45f9b7e2010-06-21 21:21:01 +00001972
1973 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001974}
1975
Ted Kremenek826a3452010-07-16 02:11:22 +00001976SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001977 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001978}
1979
Ted Kremenek826a3452010-07-16 02:11:22 +00001980void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
1981 unsigned specifierLen){
Richard Trieu55733de2011-10-28 00:41:25 +00001982 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
1983 getLocationOfByte(startSpecifier),
1984 /*IsStringLocation*/true,
1985 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek808015a2010-01-29 03:16:21 +00001986}
1987
Hans Wennborg76517422012-02-22 10:17:01 +00001988void CheckFormatHandler::HandleNonStandardLengthModifier(
1989 const analyze_format_string::LengthModifier &LM,
1990 const char *startSpecifier, unsigned specifierLen) {
1991 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) << LM.toString()
Hans Wennborgf8562642012-03-09 10:10:54 +00001992 << 0,
Hans Wennborg76517422012-02-22 10:17:01 +00001993 getLocationOfByte(LM.getStart()),
1994 /*IsStringLocation*/true,
1995 getSpecifierRange(startSpecifier, specifierLen));
1996}
1997
1998void CheckFormatHandler::HandleNonStandardConversionSpecifier(
1999 const analyze_format_string::ConversionSpecifier &CS,
2000 const char *startSpecifier, unsigned specifierLen) {
2001 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) << CS.toString()
Hans Wennborgf8562642012-03-09 10:10:54 +00002002 << 1,
Hans Wennborg76517422012-02-22 10:17:01 +00002003 getLocationOfByte(CS.getStart()),
2004 /*IsStringLocation*/true,
2005 getSpecifierRange(startSpecifier, specifierLen));
2006}
2007
2008void CheckFormatHandler::HandleNonStandardConversionSpecification(
2009 const analyze_format_string::LengthModifier &LM,
2010 const analyze_format_string::ConversionSpecifier &CS,
2011 const char *startSpecifier, unsigned specifierLen) {
2012 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_conversion_spec)
2013 << LM.toString() << CS.toString(),
2014 getLocationOfByte(LM.getStart()),
2015 /*IsStringLocation*/true,
2016 getSpecifierRange(startSpecifier, specifierLen));
2017}
2018
Hans Wennborgf8562642012-03-09 10:10:54 +00002019void CheckFormatHandler::HandlePosition(const char *startPos,
2020 unsigned posLen) {
2021 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2022 getLocationOfByte(startPos),
2023 /*IsStringLocation*/true,
2024 getSpecifierRange(startPos, posLen));
2025}
2026
Ted Kremenekefaff192010-02-27 01:41:03 +00002027void
Ted Kremenek826a3452010-07-16 02:11:22 +00002028CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2029 analyze_format_string::PositionContext p) {
Richard Trieu55733de2011-10-28 00:41:25 +00002030 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2031 << (unsigned) p,
2032 getLocationOfByte(startPos), /*IsStringLocation*/true,
2033 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00002034}
2035
Ted Kremenek826a3452010-07-16 02:11:22 +00002036void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00002037 unsigned posLen) {
Richard Trieu55733de2011-10-28 00:41:25 +00002038 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2039 getLocationOfByte(startPos),
2040 /*IsStringLocation*/true,
2041 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00002042}
2043
Ted Kremenek826a3452010-07-16 02:11:22 +00002044void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose50687312012-06-04 23:52:23 +00002045 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0c069442011-03-15 21:18:48 +00002046 // The presence of a null character is likely an error.
Richard Trieu55733de2011-10-28 00:41:25 +00002047 EmitFormatDiagnostic(
2048 S.PDiag(diag::warn_printf_format_string_contains_null_char),
2049 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2050 getFormatStringRange());
Ted Kremenek0c069442011-03-15 21:18:48 +00002051 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002052}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002053
Ted Kremenek826a3452010-07-16 02:11:22 +00002054const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002055 return Args[FirstDataArg + i];
Ted Kremenek826a3452010-07-16 02:11:22 +00002056}
2057
2058void CheckFormatHandler::DoneProcessing() {
2059 // Does the number of data arguments exceed the number of
2060 // format conversions in the format string?
2061 if (!HasVAListArg) {
2062 // Find any arguments that weren't covered.
2063 CoveredArgs.flip();
2064 signed notCoveredArg = CoveredArgs.find_first();
2065 if (notCoveredArg >= 0) {
2066 assert((unsigned)notCoveredArg < NumDataArgs);
Bob Wilsonc03f2df2012-05-03 19:47:19 +00002067 SourceLocation Loc = getDataArg((unsigned) notCoveredArg)->getLocStart();
2068 if (!S.getSourceManager().isInSystemMacro(Loc)) {
2069 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2070 Loc,
2071 /*IsStringLocation*/false, getFormatStringRange());
2072 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002073 }
2074 }
2075}
2076
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002077bool
2078CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2079 SourceLocation Loc,
2080 const char *startSpec,
2081 unsigned specifierLen,
2082 const char *csStart,
2083 unsigned csLen) {
2084
2085 bool keepGoing = true;
2086 if (argIndex < NumDataArgs) {
2087 // Consider the argument coverered, even though the specifier doesn't
2088 // make sense.
2089 CoveredArgs.set(argIndex);
2090 }
2091 else {
2092 // If argIndex exceeds the number of data arguments we
2093 // don't issue a warning because that is just a cascade of warnings (and
2094 // they may have intended '%%' anyway). We don't want to continue processing
2095 // the format string after this point, however, as we will like just get
2096 // gibberish when trying to match arguments.
2097 keepGoing = false;
2098 }
2099
Richard Trieu55733de2011-10-28 00:41:25 +00002100 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2101 << StringRef(csStart, csLen),
2102 Loc, /*IsStringLocation*/true,
2103 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002104
2105 return keepGoing;
2106}
2107
Richard Trieu55733de2011-10-28 00:41:25 +00002108void
2109CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2110 const char *startSpec,
2111 unsigned specifierLen) {
2112 EmitFormatDiagnostic(
2113 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2114 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2115}
2116
Ted Kremenek666a1972010-07-26 19:45:42 +00002117bool
2118CheckFormatHandler::CheckNumArgs(
2119 const analyze_format_string::FormatSpecifier &FS,
2120 const analyze_format_string::ConversionSpecifier &CS,
2121 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2122
2123 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002124 PartialDiagnostic PDiag = FS.usesPositionalArg()
2125 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2126 << (argIndex+1) << NumDataArgs)
2127 : S.PDiag(diag::warn_printf_insufficient_data_args);
2128 EmitFormatDiagnostic(
2129 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2130 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek666a1972010-07-26 19:45:42 +00002131 return false;
2132 }
2133 return true;
2134}
2135
Richard Trieu55733de2011-10-28 00:41:25 +00002136template<typename Range>
2137void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2138 SourceLocation Loc,
2139 bool IsStringLocation,
2140 Range StringRange,
2141 FixItHint FixIt) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002142 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu55733de2011-10-28 00:41:25 +00002143 Loc, IsStringLocation, StringRange, FixIt);
2144}
2145
2146/// \brief If the format string is not within the funcion call, emit a note
2147/// so that the function call and string are in diagnostic messages.
2148///
2149/// \param inFunctionCall if true, the format string is within the function
2150/// call and only one diagnostic message will be produced. Otherwise, an
2151/// extra note will be emitted pointing to location of the format string.
2152///
2153/// \param ArgumentExpr the expression that is passed as the format string
2154/// argument in the function call. Used for getting locations when two
2155/// diagnostics are emitted.
2156///
2157/// \param PDiag the callee should already have provided any strings for the
2158/// diagnostic message. This function only adds locations and fixits
2159/// to diagnostics.
2160///
2161/// \param Loc primary location for diagnostic. If two diagnostics are
2162/// required, one will be at Loc and a new SourceLocation will be created for
2163/// the other one.
2164///
2165/// \param IsStringLocation if true, Loc points to the format string should be
2166/// used for the note. Otherwise, Loc points to the argument list and will
2167/// be used with PDiag.
2168///
2169/// \param StringRange some or all of the string to highlight. This is
2170/// templated so it can accept either a CharSourceRange or a SourceRange.
2171///
2172/// \param Fixit optional fix it hint for the format string.
2173template<typename Range>
2174void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2175 const Expr *ArgumentExpr,
2176 PartialDiagnostic PDiag,
2177 SourceLocation Loc,
2178 bool IsStringLocation,
2179 Range StringRange,
2180 FixItHint FixIt) {
2181 if (InFunctionCall)
2182 S.Diag(Loc, PDiag) << StringRange << FixIt;
2183 else {
2184 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2185 << ArgumentExpr->getSourceRange();
2186 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2187 diag::note_format_string_defined)
2188 << StringRange << FixIt;
2189 }
2190}
2191
Ted Kremenek826a3452010-07-16 02:11:22 +00002192//===--- CHECK: Printf format string checking ------------------------------===//
2193
2194namespace {
2195class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose50687312012-06-04 23:52:23 +00002196 bool ObjCContext;
Ted Kremenek826a3452010-07-16 02:11:22 +00002197public:
2198 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2199 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002200 unsigned numDataArgs, bool isObjC,
Ted Kremenek826a3452010-07-16 02:11:22 +00002201 const char *beg, bool hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002202 Expr **Args, unsigned NumArgs,
2203 unsigned formatIdx, bool inFunctionCall)
Ted Kremenek826a3452010-07-16 02:11:22 +00002204 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002205 numDataArgs, beg, hasVAListArg, Args, NumArgs,
2206 formatIdx, inFunctionCall), ObjCContext(isObjC) {}
Ted Kremenek826a3452010-07-16 02:11:22 +00002207
2208
2209 bool HandleInvalidPrintfConversionSpecifier(
2210 const analyze_printf::PrintfSpecifier &FS,
2211 const char *startSpecifier,
2212 unsigned specifierLen);
2213
2214 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2215 const char *startSpecifier,
2216 unsigned specifierLen);
Richard Smith831421f2012-06-25 20:30:08 +00002217 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2218 const char *StartSpecifier,
2219 unsigned SpecifierLen,
2220 const Expr *E);
2221
Ted Kremenek826a3452010-07-16 02:11:22 +00002222 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2223 const char *startSpecifier, unsigned specifierLen);
2224 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2225 const analyze_printf::OptionalAmount &Amt,
2226 unsigned type,
2227 const char *startSpecifier, unsigned specifierLen);
2228 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2229 const analyze_printf::OptionalFlag &flag,
2230 const char *startSpecifier, unsigned specifierLen);
2231 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2232 const analyze_printf::OptionalFlag &ignoredFlag,
2233 const analyze_printf::OptionalFlag &flag,
2234 const char *startSpecifier, unsigned specifierLen);
Richard Smith831421f2012-06-25 20:30:08 +00002235 bool checkForCStrMembers(const analyze_printf::ArgTypeResult &ATR,
2236 const Expr *E, const CharSourceRange &CSR);
2237
Ted Kremenek826a3452010-07-16 02:11:22 +00002238};
2239}
2240
2241bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2242 const analyze_printf::PrintfSpecifier &FS,
2243 const char *startSpecifier,
2244 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002245 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002246 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002247
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002248 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2249 getLocationOfByte(CS.getStart()),
2250 startSpecifier, specifierLen,
2251 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00002252}
2253
Ted Kremenek826a3452010-07-16 02:11:22 +00002254bool CheckPrintfHandler::HandleAmount(
2255 const analyze_format_string::OptionalAmount &Amt,
2256 unsigned k, const char *startSpecifier,
2257 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002258
2259 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002260 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002261 unsigned argIndex = Amt.getArgIndex();
2262 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002263 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2264 << k,
2265 getLocationOfByte(Amt.getStart()),
2266 /*IsStringLocation*/true,
2267 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002268 // Don't do any more checking. We will just emit
2269 // spurious errors.
2270 return false;
2271 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002272
Ted Kremenek0d277352010-01-29 01:06:55 +00002273 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00002274 // Although not in conformance with C99, we also allow the argument to be
2275 // an 'unsigned int' as that is a reasonably safe case. GCC also
2276 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002277 CoveredArgs.set(argIndex);
2278 const Expr *Arg = getDataArg(argIndex);
Ted Kremenek0d277352010-01-29 01:06:55 +00002279 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002280
2281 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
2282 assert(ATR.isValid());
2283
2284 if (!ATR.matchesType(S.Context, T)) {
Richard Trieu55733de2011-10-28 00:41:25 +00002285 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborga792aff2011-12-07 10:33:11 +00002286 << k << ATR.getRepresentativeTypeName(S.Context)
Richard Trieu55733de2011-10-28 00:41:25 +00002287 << T << Arg->getSourceRange(),
2288 getLocationOfByte(Amt.getStart()),
2289 /*IsStringLocation*/true,
2290 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002291 // Don't do any more checking. We will just emit
2292 // spurious errors.
2293 return false;
2294 }
2295 }
2296 }
2297 return true;
2298}
Ted Kremenek0d277352010-01-29 01:06:55 +00002299
Tom Caree4ee9662010-06-17 19:00:27 +00002300void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00002301 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002302 const analyze_printf::OptionalAmount &Amt,
2303 unsigned type,
2304 const char *startSpecifier,
2305 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002306 const analyze_printf::PrintfConversionSpecifier &CS =
2307 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00002308
Richard Trieu55733de2011-10-28 00:41:25 +00002309 FixItHint fixit =
2310 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2311 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2312 Amt.getConstantLength()))
2313 : FixItHint();
2314
2315 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2316 << type << CS.toString(),
2317 getLocationOfByte(Amt.getStart()),
2318 /*IsStringLocation*/true,
2319 getSpecifierRange(startSpecifier, specifierLen),
2320 fixit);
Tom Caree4ee9662010-06-17 19:00:27 +00002321}
2322
Ted Kremenek826a3452010-07-16 02:11:22 +00002323void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002324 const analyze_printf::OptionalFlag &flag,
2325 const char *startSpecifier,
2326 unsigned specifierLen) {
2327 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002328 const analyze_printf::PrintfConversionSpecifier &CS =
2329 FS.getConversionSpecifier();
Richard Trieu55733de2011-10-28 00:41:25 +00002330 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2331 << flag.toString() << CS.toString(),
2332 getLocationOfByte(flag.getPosition()),
2333 /*IsStringLocation*/true,
2334 getSpecifierRange(startSpecifier, specifierLen),
2335 FixItHint::CreateRemoval(
2336 getSpecifierRange(flag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002337}
2338
2339void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00002340 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002341 const analyze_printf::OptionalFlag &ignoredFlag,
2342 const analyze_printf::OptionalFlag &flag,
2343 const char *startSpecifier,
2344 unsigned specifierLen) {
2345 // Warn about ignored flag with a fixit removal.
Richard Trieu55733de2011-10-28 00:41:25 +00002346 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2347 << ignoredFlag.toString() << flag.toString(),
2348 getLocationOfByte(ignoredFlag.getPosition()),
2349 /*IsStringLocation*/true,
2350 getSpecifierRange(startSpecifier, specifierLen),
2351 FixItHint::CreateRemoval(
2352 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002353}
2354
Richard Smith831421f2012-06-25 20:30:08 +00002355// Determines if the specified is a C++ class or struct containing
2356// a member with the specified name and kind (e.g. a CXXMethodDecl named
2357// "c_str()").
2358template<typename MemberKind>
2359static llvm::SmallPtrSet<MemberKind*, 1>
2360CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
2361 const RecordType *RT = Ty->getAs<RecordType>();
2362 llvm::SmallPtrSet<MemberKind*, 1> Results;
2363
2364 if (!RT)
2365 return Results;
2366 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
2367 if (!RD)
2368 return Results;
2369
2370 LookupResult R(S, &S.PP.getIdentifierTable().get(Name), SourceLocation(),
2371 Sema::LookupMemberName);
2372
2373 // We just need to include all members of the right kind turned up by the
2374 // filter, at this point.
2375 if (S.LookupQualifiedName(R, RT->getDecl()))
2376 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2377 NamedDecl *decl = (*I)->getUnderlyingDecl();
2378 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
2379 Results.insert(FK);
2380 }
2381 return Results;
2382}
2383
2384// Check if a (w)string was passed when a (w)char* was needed, and offer a
2385// better diagnostic if so. ATR is assumed to be valid.
2386// Returns true when a c_str() conversion method is found.
2387bool CheckPrintfHandler::checkForCStrMembers(
2388 const analyze_printf::ArgTypeResult &ATR, const Expr *E,
2389 const CharSourceRange &CSR) {
2390 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2391
2392 MethodSet Results =
2393 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
2394
2395 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2396 MI != ME; ++MI) {
2397 const CXXMethodDecl *Method = *MI;
2398 if (Method->getNumParams() == 0 &&
2399 ATR.matchesType(S.Context, Method->getResultType())) {
2400 // FIXME: Suggest parens if the expression needs them.
2401 SourceLocation EndLoc =
2402 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd());
2403 S.Diag(E->getLocStart(), diag::note_printf_c_str)
2404 << "c_str()"
2405 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
2406 return true;
2407 }
2408 }
2409
2410 return false;
2411}
2412
Ted Kremeneke0e53132010-01-28 23:39:18 +00002413bool
Ted Kremenek826a3452010-07-16 02:11:22 +00002414CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00002415 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00002416 const char *startSpecifier,
2417 unsigned specifierLen) {
2418
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002419 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00002420 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002421 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00002422
Ted Kremenekbaa40062010-07-19 22:01:06 +00002423 if (FS.consumesDataArgument()) {
2424 if (atFirstArg) {
2425 atFirstArg = false;
2426 usesPositionalArgs = FS.usesPositionalArg();
2427 }
2428 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002429 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2430 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002431 return false;
2432 }
Ted Kremenek0d277352010-01-29 01:06:55 +00002433 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002434
Ted Kremenekefaff192010-02-27 01:41:03 +00002435 // First check if the field width, precision, and conversion specifier
2436 // have matching data arguments.
2437 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2438 startSpecifier, specifierLen)) {
2439 return false;
2440 }
2441
2442 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2443 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002444 return false;
2445 }
2446
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002447 if (!CS.consumesDataArgument()) {
2448 // FIXME: Technically specifying a precision or field width here
2449 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002450 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002451 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002452
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002453 // Consume the argument.
2454 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00002455 if (argIndex < NumDataArgs) {
2456 // The check to see if the argIndex is valid will come later.
2457 // We set the bit here because we may exit early from this
2458 // function if we encounter some other error.
2459 CoveredArgs.set(argIndex);
2460 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002461
2462 // Check for using an Objective-C specific conversion specifier
2463 // in a non-ObjC literal.
Jordan Rose50687312012-06-04 23:52:23 +00002464 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002465 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
2466 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002467 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002468
Tom Caree4ee9662010-06-17 19:00:27 +00002469 // Check for invalid use of field width
2470 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002471 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00002472 startSpecifier, specifierLen);
2473 }
2474
2475 // Check for invalid use of precision
2476 if (!FS.hasValidPrecision()) {
2477 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
2478 startSpecifier, specifierLen);
2479 }
2480
2481 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00002482 if (!FS.hasValidThousandsGroupingPrefix())
2483 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002484 if (!FS.hasValidLeadingZeros())
2485 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
2486 if (!FS.hasValidPlusPrefix())
2487 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00002488 if (!FS.hasValidSpacePrefix())
2489 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002490 if (!FS.hasValidAlternativeForm())
2491 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
2492 if (!FS.hasValidLeftJustified())
2493 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
2494
2495 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00002496 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
2497 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
2498 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002499 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
2500 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
2501 startSpecifier, specifierLen);
2502
2503 // Check the length modifier is valid with the given conversion specifier.
2504 const LengthModifier &LM = FS.getLengthModifier();
2505 if (!FS.hasValidLengthModifier())
Richard Trieu55733de2011-10-28 00:41:25 +00002506 EmitFormatDiagnostic(S.PDiag(diag::warn_format_nonsensical_length)
2507 << LM.toString() << CS.toString(),
2508 getLocationOfByte(LM.getStart()),
2509 /*IsStringLocation*/true,
2510 getSpecifierRange(startSpecifier, specifierLen),
2511 FixItHint::CreateRemoval(
2512 getSpecifierRange(LM.getStart(),
2513 LM.getLength())));
Hans Wennborg76517422012-02-22 10:17:01 +00002514 if (!FS.hasStandardLengthModifier())
2515 HandleNonStandardLengthModifier(LM, startSpecifier, specifierLen);
David Blaikie4e4d0842012-03-11 07:00:24 +00002516 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
Hans Wennborg76517422012-02-22 10:17:01 +00002517 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
2518 if (!FS.hasStandardLengthConversionCombination())
2519 HandleNonStandardConversionSpecification(LM, CS, startSpecifier,
2520 specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002521
2522 // Are we using '%n'?
Ted Kremenek35d353b2010-07-20 20:04:10 +00002523 if (CS.getKind() == ConversionSpecifier::nArg) {
Tom Caree4ee9662010-06-17 19:00:27 +00002524 // Issue a warning about this being a possible security issue.
Richard Trieu55733de2011-10-28 00:41:25 +00002525 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_write_back),
2526 getLocationOfByte(CS.getStart()),
2527 /*IsStringLocation*/true,
2528 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremeneke82d8042010-01-29 01:35:25 +00002529 // Continue checking the other format specifiers.
2530 return true;
2531 }
Ted Kremenek5c41ee82010-02-11 09:27:41 +00002532
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002533 // The remaining checks depend on the data arguments.
2534 if (HasVAListArg)
2535 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002536
Ted Kremenek666a1972010-07-26 19:45:42 +00002537 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002538 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002539
Richard Smith831421f2012-06-25 20:30:08 +00002540 return checkFormatExpr(FS, startSpecifier, specifierLen,
2541 getDataArg(argIndex));
2542}
2543
2544bool
2545CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2546 const char *StartSpecifier,
2547 unsigned SpecifierLen,
2548 const Expr *E) {
2549 using namespace analyze_format_string;
2550 using namespace analyze_printf;
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002551 // Now type check the data expression that matches the
2552 // format specifier.
Nico Weber339b9072012-01-31 01:43:25 +00002553 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context,
Jordan Rose50687312012-06-04 23:52:23 +00002554 ObjCContext);
Richard Smith831421f2012-06-25 20:30:08 +00002555 if (ATR.isValid() && !ATR.matchesType(S.Context, E->getType())) {
Jordan Roseee0259d2012-06-04 22:48:57 +00002556 // Look through argument promotions for our error message's reported type.
2557 // This includes the integral and floating promotions, but excludes array
2558 // and function pointer decay; seeing that an argument intended to be a
2559 // string has type 'char [6]' is probably more confusing than 'char *'.
Richard Smith831421f2012-06-25 20:30:08 +00002560 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Jordan Roseee0259d2012-06-04 22:48:57 +00002561 if (ICE->getCastKind() == CK_IntegralCast ||
2562 ICE->getCastKind() == CK_FloatingCast) {
Richard Smith831421f2012-06-25 20:30:08 +00002563 E = ICE->getSubExpr();
Jordan Roseee0259d2012-06-04 22:48:57 +00002564
2565 // Check if we didn't match because of an implicit cast from a 'char'
2566 // or 'short' to an 'int'. This is done because printf is a varargs
2567 // function.
2568 if (ICE->getType() == S.Context.IntTy ||
2569 ICE->getType() == S.Context.UnsignedIntTy) {
2570 // All further checking is done on the subexpression.
Richard Smith831421f2012-06-25 20:30:08 +00002571 if (ATR.matchesType(S.Context, E->getType()))
Jordan Roseee0259d2012-06-04 22:48:57 +00002572 return true;
2573 }
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00002574 }
Jordan Roseee0259d2012-06-04 22:48:57 +00002575 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002576
2577 // We may be able to offer a FixItHint if it is a supported type.
2578 PrintfSpecifier fixedFS = FS;
Richard Smith831421f2012-06-25 20:30:08 +00002579 bool success = fixedFS.fixType(E->getType(), S.getLangOpts(),
Jordan Rose50687312012-06-04 23:52:23 +00002580 S.Context, ObjCContext);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002581
2582 if (success) {
2583 // Get the fix string from the fixed format specifier
Jordan Roseee0259d2012-06-04 22:48:57 +00002584 SmallString<16> buf;
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002585 llvm::raw_svector_ostream os(buf);
2586 fixedFS.toString(os);
2587
Richard Trieu55733de2011-10-28 00:41:25 +00002588 EmitFormatDiagnostic(
2589 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Richard Smith831421f2012-06-25 20:30:08 +00002590 << ATR.getRepresentativeTypeName(S.Context) << E->getType()
2591 << E->getSourceRange(),
2592 E->getLocStart(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00002593 /*IsStringLocation*/false,
Richard Smith831421f2012-06-25 20:30:08 +00002594 getSpecifierRange(StartSpecifier, SpecifierLen),
Richard Trieu55733de2011-10-28 00:41:25 +00002595 FixItHint::CreateReplacement(
Richard Smith831421f2012-06-25 20:30:08 +00002596 getSpecifierRange(StartSpecifier, SpecifierLen),
Richard Trieu55733de2011-10-28 00:41:25 +00002597 os.str()));
Richard Smith831421f2012-06-25 20:30:08 +00002598 } else {
2599 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
2600 SpecifierLen);
2601 // Since the warning for passing non-POD types to variadic functions
2602 // was deferred until now, we emit a warning for non-POD
2603 // arguments here.
2604 if (S.isValidVarArgType(E->getType()) == Sema::VAK_Invalid) {
2605 EmitFormatDiagnostic(
2606 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
2607 << S.getLangOpts().CPlusPlus0x
2608 << E->getType()
2609 << ATR.getRepresentativeTypeName(S.Context)
2610 << CSR
2611 << E->getSourceRange(),
2612 E->getLocStart(), /*IsStringLocation*/false, CSR);
2613
2614 checkForCStrMembers(ATR, E, CSR);
2615 } else
2616 EmitFormatDiagnostic(
2617 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2618 << ATR.getRepresentativeTypeName(S.Context) << E->getType()
2619 << CSR
2620 << E->getSourceRange(),
2621 E->getLocStart(), /*IsStringLocation*/false, CSR);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002622 }
2623 }
2624
Ted Kremeneke0e53132010-01-28 23:39:18 +00002625 return true;
2626}
2627
Ted Kremenek826a3452010-07-16 02:11:22 +00002628//===--- CHECK: Scanf format string checking ------------------------------===//
2629
2630namespace {
2631class CheckScanfHandler : public CheckFormatHandler {
2632public:
2633 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
2634 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002635 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002636 Expr **Args, unsigned NumArgs,
2637 unsigned formatIdx, bool inFunctionCall)
Ted Kremenek826a3452010-07-16 02:11:22 +00002638 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002639 numDataArgs, beg, hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002640 Args, NumArgs, formatIdx, inFunctionCall) {}
Ted Kremenek826a3452010-07-16 02:11:22 +00002641
2642 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
2643 const char *startSpecifier,
2644 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002645
2646 bool HandleInvalidScanfConversionSpecifier(
2647 const analyze_scanf::ScanfSpecifier &FS,
2648 const char *startSpecifier,
2649 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00002650
2651 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00002652};
Ted Kremenek07d161f2010-01-29 01:50:07 +00002653}
Ted Kremeneke0e53132010-01-28 23:39:18 +00002654
Ted Kremenekb7c21012010-07-16 18:28:03 +00002655void CheckScanfHandler::HandleIncompleteScanList(const char *start,
2656 const char *end) {
Richard Trieu55733de2011-10-28 00:41:25 +00002657 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
2658 getLocationOfByte(end), /*IsStringLocation*/true,
2659 getSpecifierRange(start, end - start));
Ted Kremenekb7c21012010-07-16 18:28:03 +00002660}
2661
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002662bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
2663 const analyze_scanf::ScanfSpecifier &FS,
2664 const char *startSpecifier,
2665 unsigned specifierLen) {
2666
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002667 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002668 FS.getConversionSpecifier();
2669
2670 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2671 getLocationOfByte(CS.getStart()),
2672 startSpecifier, specifierLen,
2673 CS.getStart(), CS.getLength());
2674}
2675
Ted Kremenek826a3452010-07-16 02:11:22 +00002676bool CheckScanfHandler::HandleScanfSpecifier(
2677 const analyze_scanf::ScanfSpecifier &FS,
2678 const char *startSpecifier,
2679 unsigned specifierLen) {
2680
2681 using namespace analyze_scanf;
2682 using namespace analyze_format_string;
2683
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002684 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002685
Ted Kremenekbaa40062010-07-19 22:01:06 +00002686 // Handle case where '%' and '*' don't consume an argument. These shouldn't
2687 // be used to decide if we are using positional arguments consistently.
2688 if (FS.consumesDataArgument()) {
2689 if (atFirstArg) {
2690 atFirstArg = false;
2691 usesPositionalArgs = FS.usesPositionalArg();
2692 }
2693 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002694 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2695 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002696 return false;
2697 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002698 }
2699
2700 // Check if the field with is non-zero.
2701 const OptionalAmount &Amt = FS.getFieldWidth();
2702 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
2703 if (Amt.getConstantAmount() == 0) {
2704 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
2705 Amt.getConstantLength());
Richard Trieu55733de2011-10-28 00:41:25 +00002706 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
2707 getLocationOfByte(Amt.getStart()),
2708 /*IsStringLocation*/true, R,
2709 FixItHint::CreateRemoval(R));
Ted Kremenek826a3452010-07-16 02:11:22 +00002710 }
2711 }
2712
2713 if (!FS.consumesDataArgument()) {
2714 // FIXME: Technically specifying a precision or field width here
2715 // makes no sense. Worth issuing a warning at some point.
2716 return true;
2717 }
2718
2719 // Consume the argument.
2720 unsigned argIndex = FS.getArgIndex();
2721 if (argIndex < NumDataArgs) {
2722 // The check to see if the argIndex is valid will come later.
2723 // We set the bit here because we may exit early from this
2724 // function if we encounter some other error.
2725 CoveredArgs.set(argIndex);
2726 }
2727
Ted Kremenek1e51c202010-07-20 20:04:47 +00002728 // Check the length modifier is valid with the given conversion specifier.
2729 const LengthModifier &LM = FS.getLengthModifier();
2730 if (!FS.hasValidLengthModifier()) {
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00002731 const CharSourceRange &R = getSpecifierRange(LM.getStart(), LM.getLength());
2732 EmitFormatDiagnostic(S.PDiag(diag::warn_format_nonsensical_length)
2733 << LM.toString() << CS.toString()
2734 << getSpecifierRange(startSpecifier, specifierLen),
2735 getLocationOfByte(LM.getStart()),
2736 /*IsStringLocation*/true, R,
2737 FixItHint::CreateRemoval(R));
Ted Kremenek1e51c202010-07-20 20:04:47 +00002738 }
2739
Hans Wennborg76517422012-02-22 10:17:01 +00002740 if (!FS.hasStandardLengthModifier())
2741 HandleNonStandardLengthModifier(LM, startSpecifier, specifierLen);
David Blaikie4e4d0842012-03-11 07:00:24 +00002742 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
Hans Wennborg76517422012-02-22 10:17:01 +00002743 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
2744 if (!FS.hasStandardLengthConversionCombination())
2745 HandleNonStandardConversionSpecification(LM, CS, startSpecifier,
2746 specifierLen);
2747
Ted Kremenek826a3452010-07-16 02:11:22 +00002748 // The remaining checks depend on the data arguments.
2749 if (HasVAListArg)
2750 return true;
2751
Ted Kremenek666a1972010-07-26 19:45:42 +00002752 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00002753 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00002754
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002755 // Check that the argument type matches the format specifier.
2756 const Expr *Ex = getDataArg(argIndex);
2757 const analyze_scanf::ScanfArgTypeResult &ATR = FS.getArgType(S.Context);
2758 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
2759 ScanfSpecifier fixedFS = FS;
David Blaikie4e4d0842012-03-11 07:00:24 +00002760 bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(),
Hans Wennborgbe6126a2012-02-15 09:59:46 +00002761 S.Context);
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002762
2763 if (success) {
2764 // Get the fix string from the fixed format specifier.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002765 SmallString<128> buf;
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002766 llvm::raw_svector_ostream os(buf);
2767 fixedFS.toString(os);
2768
2769 EmitFormatDiagnostic(
2770 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2771 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
2772 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00002773 Ex->getLocStart(),
2774 /*IsStringLocation*/false,
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002775 getSpecifierRange(startSpecifier, specifierLen),
2776 FixItHint::CreateReplacement(
2777 getSpecifierRange(startSpecifier, specifierLen),
2778 os.str()));
2779 } else {
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00002780 EmitFormatDiagnostic(
2781 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002782 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00002783 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00002784 Ex->getLocStart(),
2785 /*IsStringLocation*/false,
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00002786 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002787 }
2788 }
2789
Ted Kremenek826a3452010-07-16 02:11:22 +00002790 return true;
2791}
2792
2793void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002794 const Expr *OrigFormatExpr,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002795 Expr **Args, unsigned NumArgs,
2796 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002797 unsigned firstDataArg, FormatStringType Type,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002798 bool inFunctionCall) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002799
Ted Kremeneke0e53132010-01-28 23:39:18 +00002800 // CHECK: is the format string a wide literal?
Richard Smithdf9ef1b2012-06-13 05:37:23 +00002801 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002802 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002803 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00002804 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
2805 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00002806 return;
2807 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002808
Ted Kremeneke0e53132010-01-28 23:39:18 +00002809 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner5f9e2722011-07-23 10:55:15 +00002810 StringRef StrRef = FExpr->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00002811 const char *Str = StrRef.data();
2812 unsigned StrLen = StrRef.size();
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002813 const unsigned numDataArgs = NumArgs - firstDataArg;
Ted Kremenek826a3452010-07-16 02:11:22 +00002814
Ted Kremeneke0e53132010-01-28 23:39:18 +00002815 // CHECK: empty format string?
Ted Kremenek4cd57912011-09-29 05:52:16 +00002816 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu55733de2011-10-28 00:41:25 +00002817 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002818 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00002819 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
2820 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00002821 return;
2822 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002823
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002824 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002825 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002826 numDataArgs, (Type == FST_NSString),
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002827 Str, HasVAListArg, Args, NumArgs, format_idx,
Richard Trieu55733de2011-10-28 00:41:25 +00002828 inFunctionCall);
Ted Kremenek826a3452010-07-16 02:11:22 +00002829
Hans Wennborgd02deeb2011-12-15 10:25:47 +00002830 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
David Blaikie4e4d0842012-03-11 07:00:24 +00002831 getLangOpts()))
Ted Kremenek826a3452010-07-16 02:11:22 +00002832 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002833 } else if (Type == FST_Scanf) {
Jordan Rose50687312012-06-04 23:52:23 +00002834 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002835 Str, HasVAListArg, Args, NumArgs, format_idx,
Richard Trieu55733de2011-10-28 00:41:25 +00002836 inFunctionCall);
Ted Kremenek826a3452010-07-16 02:11:22 +00002837
Hans Wennborgd02deeb2011-12-15 10:25:47 +00002838 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
David Blaikie4e4d0842012-03-11 07:00:24 +00002839 getLangOpts()))
Ted Kremenek826a3452010-07-16 02:11:22 +00002840 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002841 } // TODO: handle other formats
Ted Kremenekce7024e2010-01-28 01:18:22 +00002842}
2843
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002844//===--- CHECK: Standard memory functions ---------------------------------===//
2845
Douglas Gregor2a053a32011-05-03 20:05:22 +00002846/// \brief Determine whether the given type is a dynamic class type (e.g.,
2847/// whether it has a vtable).
2848static bool isDynamicClassType(QualType T) {
2849 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
2850 if (CXXRecordDecl *Definition = Record->getDefinition())
2851 if (Definition->isDynamicClass())
2852 return true;
2853
2854 return false;
2855}
2856
Chandler Carrutha72a12f2011-06-21 23:04:20 +00002857/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth000d4282011-06-16 09:09:40 +00002858/// otherwise returns NULL.
2859static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Webere4a1c642011-06-14 16:14:58 +00002860 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth000d4282011-06-16 09:09:40 +00002861 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2862 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
2863 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00002864
Chandler Carruth000d4282011-06-16 09:09:40 +00002865 return 0;
2866}
2867
Chandler Carrutha72a12f2011-06-21 23:04:20 +00002868/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth000d4282011-06-16 09:09:40 +00002869static QualType getSizeOfArgType(const Expr* E) {
2870 if (const UnaryExprOrTypeTraitExpr *SizeOf =
2871 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2872 if (SizeOf->getKind() == clang::UETT_SizeOf)
2873 return SizeOf->getTypeOfArgument();
2874
2875 return QualType();
Nico Webere4a1c642011-06-14 16:14:58 +00002876}
2877
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002878/// \brief Check for dangerous or invalid arguments to memset().
2879///
Chandler Carruth929f0132011-06-03 06:23:57 +00002880/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002881/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
2882/// function calls.
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002883///
2884/// \param Call The call expression to diagnose.
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002885void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks0a151a12012-01-17 00:37:07 +00002886 unsigned BId,
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002887 IdentifierInfo *FnName) {
Anna Zaks0a151a12012-01-17 00:37:07 +00002888 assert(BId != 0);
2889
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00002890 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor707a23e2011-06-16 17:56:04 +00002891 // we have enough arguments, and if not, abort further checking.
Anna Zaks0a151a12012-01-17 00:37:07 +00002892 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Webercda57822011-10-13 22:30:23 +00002893 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00002894 return;
2895
Anna Zaks0a151a12012-01-17 00:37:07 +00002896 unsigned LastArg = (BId == Builtin::BImemset ||
2897 BId == Builtin::BIstrndup ? 1 : 2);
2898 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Webercda57822011-10-13 22:30:23 +00002899 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth000d4282011-06-16 09:09:40 +00002900
2901 // We have special checking when the length is a sizeof expression.
2902 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
2903 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
2904 llvm::FoldingSetNodeID SizeOfArgID;
2905
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002906 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
2907 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00002908 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002909
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002910 QualType DestTy = Dest->getType();
2911 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
2912 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00002913
Chandler Carruth000d4282011-06-16 09:09:40 +00002914 // Never warn about void type pointers. This can be used to suppress
2915 // false positives.
2916 if (PointeeTy->isVoidType())
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002917 continue;
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002918
Chandler Carruth000d4282011-06-16 09:09:40 +00002919 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
2920 // actually comparing the expressions for equality. Because computing the
2921 // expression IDs can be expensive, we only do this if the diagnostic is
2922 // enabled.
2923 if (SizeOfArg &&
2924 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
2925 SizeOfArg->getExprLoc())) {
2926 // We only compute IDs for expressions if the warning is enabled, and
2927 // cache the sizeof arg's ID.
2928 if (SizeOfArgID == llvm::FoldingSetNodeID())
2929 SizeOfArg->Profile(SizeOfArgID, Context, true);
2930 llvm::FoldingSetNodeID DestID;
2931 Dest->Profile(DestID, Context, true);
2932 if (DestID == SizeOfArgID) {
Nico Webercda57822011-10-13 22:30:23 +00002933 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
2934 // over sizeof(src) as well.
Chandler Carruth000d4282011-06-16 09:09:40 +00002935 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks6fcb3722012-05-30 00:34:21 +00002936 StringRef ReadableName = FnName->getName();
2937
Chandler Carruth000d4282011-06-16 09:09:40 +00002938 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaks90c78322012-05-30 23:14:52 +00002939 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth000d4282011-06-16 09:09:40 +00002940 ActionIdx = 1; // If its an address-of operator, just remove it.
2941 if (Context.getTypeSize(PointeeTy) == Context.getCharWidth())
2942 ActionIdx = 2; // If the pointee's size is sizeof(char),
2943 // suggest an explicit length.
Anna Zaks6fcb3722012-05-30 00:34:21 +00002944
2945 // If the function is defined as a builtin macro, do not show macro
2946 // expansion.
2947 SourceLocation SL = SizeOfArg->getExprLoc();
2948 SourceRange DSR = Dest->getSourceRange();
2949 SourceRange SSR = SizeOfArg->getSourceRange();
2950 SourceManager &SM = PP.getSourceManager();
2951
2952 if (SM.isMacroArgExpansion(SL)) {
2953 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
2954 SL = SM.getSpellingLoc(SL);
2955 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
2956 SM.getSpellingLoc(DSR.getEnd()));
2957 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
2958 SM.getSpellingLoc(SSR.getEnd()));
2959 }
2960
Anna Zaks90c78322012-05-30 23:14:52 +00002961 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth000d4282011-06-16 09:09:40 +00002962 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks6fcb3722012-05-30 00:34:21 +00002963 << ReadableName
Anna Zaks90c78322012-05-30 23:14:52 +00002964 << PointeeTy
2965 << DestTy
Anna Zaks6fcb3722012-05-30 00:34:21 +00002966 << DSR
Anna Zaks90c78322012-05-30 23:14:52 +00002967 << SSR);
2968 DiagRuntimeBehavior(SL, SizeOfArg,
2969 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
2970 << ActionIdx
2971 << SSR);
2972
Chandler Carruth000d4282011-06-16 09:09:40 +00002973 break;
2974 }
2975 }
2976
2977 // Also check for cases where the sizeof argument is the exact same
2978 // type as the memory argument, and where it points to a user-defined
2979 // record type.
2980 if (SizeOfArgTy != QualType()) {
2981 if (PointeeTy->isRecordType() &&
2982 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
2983 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
2984 PDiag(diag::warn_sizeof_pointer_type_memaccess)
2985 << FnName << SizeOfArgTy << ArgIdx
2986 << PointeeTy << Dest->getSourceRange()
2987 << LenExpr->getSourceRange());
2988 break;
2989 }
Nico Webere4a1c642011-06-14 16:14:58 +00002990 }
2991
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002992 // Always complain about dynamic classes.
Anna Zaks0a151a12012-01-17 00:37:07 +00002993 if (isDynamicClassType(PointeeTy)) {
2994
2995 unsigned OperationType = 0;
2996 // "overwritten" if we're warning about the destination for any call
2997 // but memcmp; otherwise a verb appropriate to the call.
2998 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
2999 if (BId == Builtin::BImemcpy)
3000 OperationType = 1;
3001 else if(BId == Builtin::BImemmove)
3002 OperationType = 2;
3003 else if (BId == Builtin::BImemcmp)
3004 OperationType = 3;
3005 }
3006
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003007 DiagRuntimeBehavior(
3008 Dest->getExprLoc(), Dest,
3009 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks0a151a12012-01-17 00:37:07 +00003010 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Anna Zaksd9b859a2012-01-13 21:52:01 +00003011 << FnName << PointeeTy
Anna Zaks0a151a12012-01-17 00:37:07 +00003012 << OperationType
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003013 << Call->getCallee()->getSourceRange());
Anna Zaks0a151a12012-01-17 00:37:07 +00003014 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
3015 BId != Builtin::BImemset)
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003016 DiagRuntimeBehavior(
3017 Dest->getExprLoc(), Dest,
3018 PDiag(diag::warn_arc_object_memaccess)
3019 << ArgIdx << FnName << PointeeTy
3020 << Call->getCallee()->getSourceRange());
John McCallf85e1932011-06-15 23:02:42 +00003021 else
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003022 continue;
John McCallf85e1932011-06-15 23:02:42 +00003023
3024 DiagRuntimeBehavior(
3025 Dest->getExprLoc(), Dest,
Chandler Carruth929f0132011-06-03 06:23:57 +00003026 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003027 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
3028 break;
3029 }
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003030 }
3031}
3032
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003033// A little helper routine: ignore addition and subtraction of integer literals.
3034// This intentionally does not ignore all integer constant expressions because
3035// we don't want to remove sizeof().
3036static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
3037 Ex = Ex->IgnoreParenCasts();
3038
3039 for (;;) {
3040 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
3041 if (!BO || !BO->isAdditiveOp())
3042 break;
3043
3044 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
3045 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
3046
3047 if (isa<IntegerLiteral>(RHS))
3048 Ex = LHS;
3049 else if (isa<IntegerLiteral>(LHS))
3050 Ex = RHS;
3051 else
3052 break;
3053 }
3054
3055 return Ex;
3056}
3057
3058// Warn if the user has made the 'size' argument to strlcpy or strlcat
3059// be the size of the source, instead of the destination.
3060void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
3061 IdentifierInfo *FnName) {
3062
3063 // Don't crash if the user has the wrong number of arguments
3064 if (Call->getNumArgs() != 3)
3065 return;
3066
3067 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
3068 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
3069 const Expr *CompareWithSrc = NULL;
3070
3071 // Look for 'strlcpy(dst, x, sizeof(x))'
3072 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
3073 CompareWithSrc = Ex;
3074 else {
3075 // Look for 'strlcpy(dst, x, strlen(x))'
3076 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Richard Smith180f4792011-11-10 06:34:14 +00003077 if (SizeCall->isBuiltinCall() == Builtin::BIstrlen
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003078 && SizeCall->getNumArgs() == 1)
3079 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
3080 }
3081 }
3082
3083 if (!CompareWithSrc)
3084 return;
3085
3086 // Determine if the argument to sizeof/strlen is equal to the source
3087 // argument. In principle there's all kinds of things you could do
3088 // here, for instance creating an == expression and evaluating it with
3089 // EvaluateAsBooleanCondition, but this uses a more direct technique:
3090 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
3091 if (!SrcArgDRE)
3092 return;
3093
3094 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
3095 if (!CompareWithSrcDRE ||
3096 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
3097 return;
3098
3099 const Expr *OriginalSizeArg = Call->getArg(2);
3100 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
3101 << OriginalSizeArg->getSourceRange() << FnName;
3102
3103 // Output a FIXIT hint if the destination is an array (rather than a
3104 // pointer to an array). This could be enhanced to handle some
3105 // pointers if we know the actual size, like if DstArg is 'array+2'
3106 // we could say 'sizeof(array)-2'.
3107 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Ted Kremenek8f746222011-08-18 22:48:41 +00003108 QualType DstArgTy = DstArg->getType();
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003109
Ted Kremenek8f746222011-08-18 22:48:41 +00003110 // Only handle constant-sized or VLAs, but not flexible members.
3111 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(DstArgTy)) {
3112 // Only issue the FIXIT for arrays of size > 1.
3113 if (CAT->getSize().getSExtValue() <= 1)
3114 return;
3115 } else if (!DstArgTy->isVariableArrayType()) {
3116 return;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003117 }
Ted Kremenek8f746222011-08-18 22:48:41 +00003118
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003119 SmallString<128> sizeString;
Ted Kremenek8f746222011-08-18 22:48:41 +00003120 llvm::raw_svector_ostream OS(sizeString);
3121 OS << "sizeof(";
Douglas Gregor8987b232011-09-27 23:30:47 +00003122 DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
Ted Kremenek8f746222011-08-18 22:48:41 +00003123 OS << ")";
3124
3125 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
3126 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
3127 OS.str());
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003128}
3129
Anna Zaksc36bedc2012-02-01 19:08:57 +00003130/// Check if two expressions refer to the same declaration.
3131static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
3132 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
3133 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
3134 return D1->getDecl() == D2->getDecl();
3135 return false;
3136}
3137
3138static const Expr *getStrlenExprArg(const Expr *E) {
3139 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
3140 const FunctionDecl *FD = CE->getDirectCallee();
3141 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
3142 return 0;
3143 return CE->getArg(0)->IgnoreParenCasts();
3144 }
3145 return 0;
3146}
3147
3148// Warn on anti-patterns as the 'size' argument to strncat.
3149// The correct size argument should look like following:
3150// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
3151void Sema::CheckStrncatArguments(const CallExpr *CE,
3152 IdentifierInfo *FnName) {
3153 // Don't crash if the user has the wrong number of arguments.
3154 if (CE->getNumArgs() < 3)
3155 return;
3156 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
3157 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
3158 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
3159
3160 // Identify common expressions, which are wrongly used as the size argument
3161 // to strncat and may lead to buffer overflows.
3162 unsigned PatternType = 0;
3163 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
3164 // - sizeof(dst)
3165 if (referToTheSameDecl(SizeOfArg, DstArg))
3166 PatternType = 1;
3167 // - sizeof(src)
3168 else if (referToTheSameDecl(SizeOfArg, SrcArg))
3169 PatternType = 2;
3170 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
3171 if (BE->getOpcode() == BO_Sub) {
3172 const Expr *L = BE->getLHS()->IgnoreParenCasts();
3173 const Expr *R = BE->getRHS()->IgnoreParenCasts();
3174 // - sizeof(dst) - strlen(dst)
3175 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
3176 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
3177 PatternType = 1;
3178 // - sizeof(src) - (anything)
3179 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
3180 PatternType = 2;
3181 }
3182 }
3183
3184 if (PatternType == 0)
3185 return;
3186
Anna Zaksafdb0412012-02-03 01:27:37 +00003187 // Generate the diagnostic.
3188 SourceLocation SL = LenArg->getLocStart();
3189 SourceRange SR = LenArg->getSourceRange();
3190 SourceManager &SM = PP.getSourceManager();
3191
3192 // If the function is defined as a builtin macro, do not show macro expansion.
3193 if (SM.isMacroArgExpansion(SL)) {
3194 SL = SM.getSpellingLoc(SL);
3195 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
3196 SM.getSpellingLoc(SR.getEnd()));
3197 }
3198
Anna Zaksc36bedc2012-02-01 19:08:57 +00003199 if (PatternType == 1)
Anna Zaksafdb0412012-02-03 01:27:37 +00003200 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003201 else
Anna Zaksafdb0412012-02-03 01:27:37 +00003202 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003203
3204 // Output a FIXIT hint if the destination is an array (rather than a
3205 // pointer to an array). This could be enhanced to handle some
3206 // pointers if we know the actual size, like if DstArg is 'array+2'
3207 // we could say 'sizeof(array)-2'.
3208 QualType DstArgTy = DstArg->getType();
3209
3210 // Only handle constant-sized or VLAs, but not flexible members.
3211 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(DstArgTy)) {
3212 // Only issue the FIXIT for arrays of size > 1.
3213 if (CAT->getSize().getSExtValue() <= 1)
3214 return;
3215 } else if (!DstArgTy->isVariableArrayType()) {
3216 return;
3217 }
3218
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003219 SmallString<128> sizeString;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003220 llvm::raw_svector_ostream OS(sizeString);
3221 OS << "sizeof(";
3222 DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
3223 OS << ") - ";
3224 OS << "strlen(";
3225 DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
3226 OS << ") - 1";
3227
Anna Zaksafdb0412012-02-03 01:27:37 +00003228 Diag(SL, diag::note_strncat_wrong_size)
3229 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003230}
3231
Ted Kremenek06de2762007-08-17 16:46:58 +00003232//===--- CHECK: Return Address of Stack Variable --------------------------===//
3233
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003234static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3235 Decl *ParentDecl);
3236static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
3237 Decl *ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003238
3239/// CheckReturnStackAddr - Check if a return statement returns the address
3240/// of a stack variable.
3241void
3242Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
3243 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00003244
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003245 Expr *stackE = 0;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003246 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003247
3248 // Perform checking for returned stack addresses, local blocks,
3249 // label addresses or references to temporaries.
John McCallf85e1932011-06-15 23:02:42 +00003250 if (lhsType->isPointerType() ||
David Blaikie4e4d0842012-03-11 07:00:24 +00003251 (!getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003252 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003253 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003254 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003255 }
3256
3257 if (stackE == 0)
3258 return; // Nothing suspicious was found.
3259
3260 SourceLocation diagLoc;
3261 SourceRange diagRange;
3262 if (refVars.empty()) {
3263 diagLoc = stackE->getLocStart();
3264 diagRange = stackE->getSourceRange();
3265 } else {
3266 // We followed through a reference variable. 'stackE' contains the
3267 // problematic expression but we will warn at the return statement pointing
3268 // at the reference variable. We will later display the "trail" of
3269 // reference variables using notes.
3270 diagLoc = refVars[0]->getLocStart();
3271 diagRange = refVars[0]->getSourceRange();
3272 }
3273
3274 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
3275 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
3276 : diag::warn_ret_stack_addr)
3277 << DR->getDecl()->getDeclName() << diagRange;
3278 } else if (isa<BlockExpr>(stackE)) { // local block.
3279 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
3280 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
3281 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
3282 } else { // local temporary.
3283 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
3284 : diag::warn_ret_local_temp_addr)
3285 << diagRange;
3286 }
3287
3288 // Display the "trail" of reference variables that we followed until we
3289 // found the problematic expression using notes.
3290 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
3291 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
3292 // If this var binds to another reference var, show the range of the next
3293 // var, otherwise the var binds to the problematic expression, in which case
3294 // show the range of the expression.
3295 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
3296 : stackE->getSourceRange();
3297 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
3298 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00003299 }
3300}
3301
3302/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
3303/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003304/// to a location on the stack, a local block, an address of a label, or a
3305/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00003306/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003307/// encounter a subexpression that (1) clearly does not lead to one of the
3308/// above problematic expressions (2) is something we cannot determine leads to
3309/// a problematic expression based on such local checking.
3310///
3311/// Both EvalAddr and EvalVal follow through reference variables to evaluate
3312/// the expression that they point to. Such variables are added to the
3313/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00003314///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00003315/// EvalAddr processes expressions that are pointers that are used as
3316/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003317/// At the base case of the recursion is a check for the above problematic
3318/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00003319///
3320/// This implementation handles:
3321///
3322/// * pointer-to-pointer casts
3323/// * implicit conversions from array references to pointers
3324/// * taking the address of fields
3325/// * arbitrary interplay between "&" and "*" operators
3326/// * pointer arithmetic from an address of a stack variable
3327/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003328static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3329 Decl *ParentDecl) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003330 if (E->isTypeDependent())
3331 return NULL;
3332
Ted Kremenek06de2762007-08-17 16:46:58 +00003333 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00003334 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00003335 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003336 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003337 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00003338
Peter Collingbournef111d932011-04-15 00:35:48 +00003339 E = E->IgnoreParens();
3340
Ted Kremenek06de2762007-08-17 16:46:58 +00003341 // Our "symbolic interpreter" is just a dispatch off the currently
3342 // viewed AST node. We then recursively traverse the AST by calling
3343 // EvalAddr and EvalVal appropriately.
3344 switch (E->getStmtClass()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003345 case Stmt::DeclRefExprClass: {
3346 DeclRefExpr *DR = cast<DeclRefExpr>(E);
3347
3348 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
3349 // If this is a reference variable, follow through to the expression that
3350 // it points to.
3351 if (V->hasLocalStorage() &&
3352 V->getType()->isReferenceType() && V->hasInit()) {
3353 // Add the reference variable to the "trail".
3354 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003355 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003356 }
3357
3358 return NULL;
3359 }
Ted Kremenek06de2762007-08-17 16:46:58 +00003360
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003361 case Stmt::UnaryOperatorClass: {
3362 // The only unary operator that make sense to handle here
3363 // is AddrOf. All others don't make sense as pointers.
3364 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003365
John McCall2de56d12010-08-25 11:45:40 +00003366 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003367 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003368 else
Ted Kremenek06de2762007-08-17 16:46:58 +00003369 return NULL;
3370 }
Mike Stump1eb44332009-09-09 15:08:12 +00003371
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003372 case Stmt::BinaryOperatorClass: {
3373 // Handle pointer arithmetic. All other binary operators are not valid
3374 // in this context.
3375 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00003376 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00003377
John McCall2de56d12010-08-25 11:45:40 +00003378 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003379 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00003380
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003381 Expr *Base = B->getLHS();
3382
3383 // Determine which argument is the real pointer base. It could be
3384 // the RHS argument instead of the LHS.
3385 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00003386
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003387 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003388 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003389 }
Steve Naroff61f40a22008-09-10 19:17:48 +00003390
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003391 // For conditional operators we need to see if either the LHS or RHS are
3392 // valid DeclRefExpr*s. If one of them is valid, we return it.
3393 case Stmt::ConditionalOperatorClass: {
3394 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003395
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003396 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003397 if (Expr *lhsExpr = C->getLHS()) {
3398 // In C++, we can have a throw-expression, which has 'void' type.
3399 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003400 if (Expr* LHS = EvalAddr(lhsExpr, refVars, ParentDecl))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003401 return LHS;
3402 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003403
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003404 // In C++, we can have a throw-expression, which has 'void' type.
3405 if (C->getRHS()->getType()->isVoidType())
3406 return NULL;
3407
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003408 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003409 }
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003410
3411 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00003412 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003413 return E; // local block.
3414 return NULL;
3415
3416 case Stmt::AddrLabelExprClass:
3417 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00003418
John McCall80ee6e82011-11-10 05:35:25 +00003419 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003420 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
3421 ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00003422
Ted Kremenek54b52742008-08-07 00:49:01 +00003423 // For casts, we need to handle conversions from arrays to
3424 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00003425 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00003426 case Stmt::CStyleCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00003427 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8b9414e2012-02-23 23:04:32 +00003428 case Stmt::ObjCBridgedCastExprClass:
Mike Stump1eb44332009-09-09 15:08:12 +00003429 case Stmt::CXXStaticCastExprClass:
3430 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00003431 case Stmt::CXXConstCastExprClass:
3432 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8b9414e2012-02-23 23:04:32 +00003433 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
3434 switch (cast<CastExpr>(E)->getCastKind()) {
3435 case CK_BitCast:
3436 case CK_LValueToRValue:
3437 case CK_NoOp:
3438 case CK_BaseToDerived:
3439 case CK_DerivedToBase:
3440 case CK_UncheckedDerivedToBase:
3441 case CK_Dynamic:
3442 case CK_CPointerToObjCPointerCast:
3443 case CK_BlockPointerToObjCPointerCast:
3444 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003445 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00003446
3447 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003448 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00003449
3450 default:
3451 return 0;
3452 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003453 }
Mike Stump1eb44332009-09-09 15:08:12 +00003454
Douglas Gregor03e80032011-06-21 17:03:29 +00003455 case Stmt::MaterializeTemporaryExprClass:
3456 if (Expr *Result = EvalAddr(
3457 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003458 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00003459 return Result;
3460
3461 return E;
3462
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003463 // Everything else: we simply don't reason about them.
3464 default:
3465 return NULL;
3466 }
Ted Kremenek06de2762007-08-17 16:46:58 +00003467}
Mike Stump1eb44332009-09-09 15:08:12 +00003468
Ted Kremenek06de2762007-08-17 16:46:58 +00003469
3470/// EvalVal - This function is complements EvalAddr in the mutual recursion.
3471/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003472static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3473 Decl *ParentDecl) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003474do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00003475 // We should only be called for evaluating non-pointer expressions, or
3476 // expressions with a pointer type that are not used as references but instead
3477 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00003478
Ted Kremenek06de2762007-08-17 16:46:58 +00003479 // Our "symbolic interpreter" is just a dispatch off the currently
3480 // viewed AST node. We then recursively traverse the AST by calling
3481 // EvalAddr and EvalVal appropriately.
Peter Collingbournef111d932011-04-15 00:35:48 +00003482
3483 E = E->IgnoreParens();
Ted Kremenek06de2762007-08-17 16:46:58 +00003484 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003485 case Stmt::ImplicitCastExprClass: {
3486 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00003487 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003488 E = IE->getSubExpr();
3489 continue;
3490 }
3491 return NULL;
3492 }
3493
John McCall80ee6e82011-11-10 05:35:25 +00003494 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003495 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00003496
Douglas Gregora2813ce2009-10-23 18:54:35 +00003497 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003498 // When we hit a DeclRefExpr we are looking at code that refers to a
3499 // variable's name. If it's not a reference variable we check if it has
3500 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00003501 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003502
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003503 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
3504 // Check if it refers to itself, e.g. "int& i = i;".
3505 if (V == ParentDecl)
3506 return DR;
3507
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003508 if (V->hasLocalStorage()) {
3509 if (!V->getType()->isReferenceType())
3510 return DR;
3511
3512 // Reference variable, follow through to the expression that
3513 // it points to.
3514 if (V->hasInit()) {
3515 // Add the reference variable to the "trail".
3516 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003517 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003518 }
3519 }
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003520 }
Mike Stump1eb44332009-09-09 15:08:12 +00003521
Ted Kremenek06de2762007-08-17 16:46:58 +00003522 return NULL;
3523 }
Mike Stump1eb44332009-09-09 15:08:12 +00003524
Ted Kremenek06de2762007-08-17 16:46:58 +00003525 case Stmt::UnaryOperatorClass: {
3526 // The only unary operator that make sense to handle here
3527 // is Deref. All others don't resolve to a "name." This includes
3528 // handling all sorts of rvalues passed to a unary operator.
3529 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003530
John McCall2de56d12010-08-25 11:45:40 +00003531 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003532 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003533
3534 return NULL;
3535 }
Mike Stump1eb44332009-09-09 15:08:12 +00003536
Ted Kremenek06de2762007-08-17 16:46:58 +00003537 case Stmt::ArraySubscriptExprClass: {
3538 // Array subscripts are potential references to data on the stack. We
3539 // retrieve the DeclRefExpr* for the array variable if it indeed
3540 // has local storage.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003541 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003542 }
Mike Stump1eb44332009-09-09 15:08:12 +00003543
Ted Kremenek06de2762007-08-17 16:46:58 +00003544 case Stmt::ConditionalOperatorClass: {
3545 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003546 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00003547 ConditionalOperator *C = cast<ConditionalOperator>(E);
3548
Anders Carlsson39073232007-11-30 19:04:31 +00003549 // Handle the GNU extension for missing LHS.
3550 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003551 if (Expr *LHS = EvalVal(lhsExpr, refVars, ParentDecl))
Anders Carlsson39073232007-11-30 19:04:31 +00003552 return LHS;
3553
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003554 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003555 }
Mike Stump1eb44332009-09-09 15:08:12 +00003556
Ted Kremenek06de2762007-08-17 16:46:58 +00003557 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00003558 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00003559 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003560
Ted Kremenek06de2762007-08-17 16:46:58 +00003561 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00003562 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00003563 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00003564
3565 // Check whether the member type is itself a reference, in which case
3566 // we're not going to refer to the member, but to what the member refers to.
3567 if (M->getMemberDecl()->getType()->isReferenceType())
3568 return NULL;
3569
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003570 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003571 }
Mike Stump1eb44332009-09-09 15:08:12 +00003572
Douglas Gregor03e80032011-06-21 17:03:29 +00003573 case Stmt::MaterializeTemporaryExprClass:
3574 if (Expr *Result = EvalVal(
3575 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003576 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00003577 return Result;
3578
3579 return E;
3580
Ted Kremenek06de2762007-08-17 16:46:58 +00003581 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003582 // Check that we don't return or take the address of a reference to a
3583 // temporary. This is only useful in C++.
3584 if (!E->isTypeDependent() && E->isRValue())
3585 return E;
3586
3587 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00003588 return NULL;
3589 }
Ted Kremenek68957a92010-08-04 20:01:07 +00003590} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00003591}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003592
3593//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
3594
3595/// Check for comparisons of floating point operands using != and ==.
3596/// Issue a warning if these are no self-comparisons, as they are not likely
3597/// to do what the programmer intended.
Richard Trieudd225092011-09-15 21:56:47 +00003598void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003599 bool EmitWarning = true;
Mike Stump1eb44332009-09-09 15:08:12 +00003600
Richard Trieudd225092011-09-15 21:56:47 +00003601 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
3602 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003603
3604 // Special case: check for x == x (which is OK).
3605 // Do not emit warnings for such cases.
3606 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
3607 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
3608 if (DRL->getDecl() == DRR->getDecl())
3609 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003610
3611
Ted Kremenek1b500bb2007-11-29 00:59:04 +00003612 // Special case: check for comparisons against literals that can be exactly
3613 // represented by APFloat. In such cases, do not emit a warning. This
3614 // is a heuristic: often comparison against such literals are used to
3615 // detect if a value in a variable has not changed. This clearly can
3616 // lead to false negatives.
3617 if (EmitWarning) {
3618 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
3619 if (FLL->isExact())
3620 EmitWarning = false;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003621 } else
Ted Kremenek1b500bb2007-11-29 00:59:04 +00003622 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
3623 if (FLR->isExact())
3624 EmitWarning = false;
3625 }
3626 }
Mike Stump1eb44332009-09-09 15:08:12 +00003627
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003628 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003629 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003630 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Richard Smith180f4792011-11-10 06:34:14 +00003631 if (CL->isBuiltinCall())
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003632 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003633
Sebastian Redl0eb23302009-01-19 00:08:26 +00003634 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003635 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Richard Smith180f4792011-11-10 06:34:14 +00003636 if (CR->isBuiltinCall())
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003637 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003638
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003639 // Emit the diagnostic.
3640 if (EmitWarning)
Richard Trieudd225092011-09-15 21:56:47 +00003641 Diag(Loc, diag::warn_floatingpoint_eq)
3642 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003643}
John McCallba26e582010-01-04 23:21:16 +00003644
John McCallf2370c92010-01-06 05:24:50 +00003645//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
3646//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00003647
John McCallf2370c92010-01-06 05:24:50 +00003648namespace {
John McCallba26e582010-01-04 23:21:16 +00003649
John McCallf2370c92010-01-06 05:24:50 +00003650/// Structure recording the 'active' range of an integer-valued
3651/// expression.
3652struct IntRange {
3653 /// The number of bits active in the int.
3654 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00003655
John McCallf2370c92010-01-06 05:24:50 +00003656 /// True if the int is known not to have negative values.
3657 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00003658
John McCallf2370c92010-01-06 05:24:50 +00003659 IntRange(unsigned Width, bool NonNegative)
3660 : Width(Width), NonNegative(NonNegative)
3661 {}
John McCallba26e582010-01-04 23:21:16 +00003662
John McCall1844a6e2010-11-10 23:38:19 +00003663 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00003664 static IntRange forBoolType() {
3665 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00003666 }
3667
John McCall1844a6e2010-11-10 23:38:19 +00003668 /// Returns the range of an opaque value of the given integral type.
3669 static IntRange forValueOfType(ASTContext &C, QualType T) {
3670 return forValueOfCanonicalType(C,
3671 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00003672 }
3673
John McCall1844a6e2010-11-10 23:38:19 +00003674 /// Returns the range of an opaque value of a canonical integral type.
3675 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00003676 assert(T->isCanonicalUnqualified());
3677
3678 if (const VectorType *VT = dyn_cast<VectorType>(T))
3679 T = VT->getElementType().getTypePtr();
3680 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
3681 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00003682
John McCall091f23f2010-11-09 22:22:12 +00003683 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00003684 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
3685 EnumDecl *Enum = ET->getDecl();
John McCall5e1cdac2011-10-07 06:10:15 +00003686 if (!Enum->isCompleteDefinition())
John McCall091f23f2010-11-09 22:22:12 +00003687 return IntRange(C.getIntWidth(QualType(T, 0)), false);
3688
John McCall323ed742010-05-06 08:58:33 +00003689 unsigned NumPositive = Enum->getNumPositiveBits();
3690 unsigned NumNegative = Enum->getNumNegativeBits();
3691
3692 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
3693 }
John McCallf2370c92010-01-06 05:24:50 +00003694
3695 const BuiltinType *BT = cast<BuiltinType>(T);
3696 assert(BT->isInteger());
3697
3698 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
3699 }
3700
John McCall1844a6e2010-11-10 23:38:19 +00003701 /// Returns the "target" range of a canonical integral type, i.e.
3702 /// the range of values expressible in the type.
3703 ///
3704 /// This matches forValueOfCanonicalType except that enums have the
3705 /// full range of their type, not the range of their enumerators.
3706 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
3707 assert(T->isCanonicalUnqualified());
3708
3709 if (const VectorType *VT = dyn_cast<VectorType>(T))
3710 T = VT->getElementType().getTypePtr();
3711 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
3712 T = CT->getElementType().getTypePtr();
3713 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor69ff26b2011-09-08 23:29:05 +00003714 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall1844a6e2010-11-10 23:38:19 +00003715
3716 const BuiltinType *BT = cast<BuiltinType>(T);
3717 assert(BT->isInteger());
3718
3719 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
3720 }
3721
3722 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00003723 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00003724 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00003725 L.NonNegative && R.NonNegative);
3726 }
3727
John McCall1844a6e2010-11-10 23:38:19 +00003728 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00003729 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00003730 return IntRange(std::min(L.Width, R.Width),
3731 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00003732 }
3733};
3734
Ted Kremenek0692a192012-01-31 05:37:37 +00003735static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
3736 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00003737 if (value.isSigned() && value.isNegative())
3738 return IntRange(value.getMinSignedBits(), false);
3739
3740 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00003741 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00003742
3743 // isNonNegative() just checks the sign bit without considering
3744 // signedness.
3745 return IntRange(value.getActiveBits(), true);
3746}
3747
Ted Kremenek0692a192012-01-31 05:37:37 +00003748static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
3749 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00003750 if (result.isInt())
3751 return GetValueRange(C, result.getInt(), MaxWidth);
3752
3753 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00003754 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
3755 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
3756 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
3757 R = IntRange::join(R, El);
3758 }
John McCallf2370c92010-01-06 05:24:50 +00003759 return R;
3760 }
3761
3762 if (result.isComplexInt()) {
3763 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
3764 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
3765 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00003766 }
3767
3768 // This can happen with lossless casts to intptr_t of "based" lvalues.
3769 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00003770 // FIXME: The only reason we need to pass the type in here is to get
3771 // the sign right on this one case. It would be nice if APValue
3772 // preserved this.
Eli Friedman65639282012-01-04 23:13:47 +00003773 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00003774 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall51313c32010-01-04 23:31:57 +00003775}
John McCallf2370c92010-01-06 05:24:50 +00003776
3777/// Pseudo-evaluate the given integer expression, estimating the
3778/// range of values it might take.
3779///
3780/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek0692a192012-01-31 05:37:37 +00003781static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00003782 E = E->IgnoreParens();
3783
3784 // Try a full evaluation first.
3785 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00003786 if (E->EvaluateAsRValue(result, C))
John McCall0acc3112010-01-06 22:57:21 +00003787 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00003788
3789 // I think we only want to look through implicit casts here; if the
3790 // user has an explicit widening cast, we should treat the value as
3791 // being of the new, wider type.
3792 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedmanb17ee5b2011-12-15 02:41:52 +00003793 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCallf2370c92010-01-06 05:24:50 +00003794 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
3795
John McCall1844a6e2010-11-10 23:38:19 +00003796 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
John McCallf2370c92010-01-06 05:24:50 +00003797
John McCall2de56d12010-08-25 11:45:40 +00003798 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00003799
John McCallf2370c92010-01-06 05:24:50 +00003800 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00003801 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00003802 return OutputTypeRange;
3803
3804 IntRange SubRange
3805 = GetExprRange(C, CE->getSubExpr(),
3806 std::min(MaxWidth, OutputTypeRange.Width));
3807
3808 // Bail out if the subexpr's range is as wide as the cast type.
3809 if (SubRange.Width >= OutputTypeRange.Width)
3810 return OutputTypeRange;
3811
3812 // Otherwise, we take the smaller width, and we're non-negative if
3813 // either the output type or the subexpr is.
3814 return IntRange(SubRange.Width,
3815 SubRange.NonNegative || OutputTypeRange.NonNegative);
3816 }
3817
3818 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3819 // If we can fold the condition, just take that operand.
3820 bool CondResult;
3821 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
3822 return GetExprRange(C, CondResult ? CO->getTrueExpr()
3823 : CO->getFalseExpr(),
3824 MaxWidth);
3825
3826 // Otherwise, conservatively merge.
3827 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
3828 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
3829 return IntRange::join(L, R);
3830 }
3831
3832 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3833 switch (BO->getOpcode()) {
3834
3835 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00003836 case BO_LAnd:
3837 case BO_LOr:
3838 case BO_LT:
3839 case BO_GT:
3840 case BO_LE:
3841 case BO_GE:
3842 case BO_EQ:
3843 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00003844 return IntRange::forBoolType();
3845
John McCall862ff872011-07-13 06:35:24 +00003846 // The type of the assignments is the type of the LHS, so the RHS
3847 // is not necessarily the same type.
John McCall2de56d12010-08-25 11:45:40 +00003848 case BO_MulAssign:
3849 case BO_DivAssign:
3850 case BO_RemAssign:
3851 case BO_AddAssign:
3852 case BO_SubAssign:
John McCall862ff872011-07-13 06:35:24 +00003853 case BO_XorAssign:
3854 case BO_OrAssign:
3855 // TODO: bitfields?
John McCall1844a6e2010-11-10 23:38:19 +00003856 return IntRange::forValueOfType(C, E->getType());
John McCallc0cd21d2010-02-23 19:22:29 +00003857
John McCall862ff872011-07-13 06:35:24 +00003858 // Simple assignments just pass through the RHS, which will have
3859 // been coerced to the LHS type.
3860 case BO_Assign:
3861 // TODO: bitfields?
3862 return GetExprRange(C, BO->getRHS(), MaxWidth);
3863
John McCallf2370c92010-01-06 05:24:50 +00003864 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00003865 case BO_PtrMemD:
3866 case BO_PtrMemI:
John McCall1844a6e2010-11-10 23:38:19 +00003867 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003868
John McCall60fad452010-01-06 22:07:33 +00003869 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00003870 case BO_And:
3871 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00003872 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
3873 GetExprRange(C, BO->getRHS(), MaxWidth));
3874
John McCallf2370c92010-01-06 05:24:50 +00003875 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00003876 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00003877 // ...except that we want to treat '1 << (blah)' as logically
3878 // positive. It's an important idiom.
3879 if (IntegerLiteral *I
3880 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
3881 if (I->getValue() == 1) {
John McCall1844a6e2010-11-10 23:38:19 +00003882 IntRange R = IntRange::forValueOfType(C, E->getType());
John McCall3aae6092010-04-07 01:14:35 +00003883 return IntRange(R.Width, /*NonNegative*/ true);
3884 }
3885 }
3886 // fallthrough
3887
John McCall2de56d12010-08-25 11:45:40 +00003888 case BO_ShlAssign:
John McCall1844a6e2010-11-10 23:38:19 +00003889 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003890
John McCall60fad452010-01-06 22:07:33 +00003891 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00003892 case BO_Shr:
3893 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00003894 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3895
3896 // If the shift amount is a positive constant, drop the width by
3897 // that much.
3898 llvm::APSInt shift;
3899 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
3900 shift.isNonNegative()) {
3901 unsigned zext = shift.getZExtValue();
3902 if (zext >= L.Width)
3903 L.Width = (L.NonNegative ? 0 : 1);
3904 else
3905 L.Width -= zext;
3906 }
3907
3908 return L;
3909 }
3910
3911 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00003912 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00003913 return GetExprRange(C, BO->getRHS(), MaxWidth);
3914
John McCall60fad452010-01-06 22:07:33 +00003915 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00003916 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00003917 if (BO->getLHS()->getType()->isPointerType())
John McCall1844a6e2010-11-10 23:38:19 +00003918 return IntRange::forValueOfType(C, E->getType());
John McCall00fe7612011-07-14 22:39:48 +00003919 break;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003920
John McCall00fe7612011-07-14 22:39:48 +00003921 // The width of a division result is mostly determined by the size
3922 // of the LHS.
3923 case BO_Div: {
3924 // Don't 'pre-truncate' the operands.
3925 unsigned opWidth = C.getIntWidth(E->getType());
3926 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3927
3928 // If the divisor is constant, use that.
3929 llvm::APSInt divisor;
3930 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
3931 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
3932 if (log2 >= L.Width)
3933 L.Width = (L.NonNegative ? 0 : 1);
3934 else
3935 L.Width = std::min(L.Width - log2, MaxWidth);
3936 return L;
3937 }
3938
3939 // Otherwise, just use the LHS's width.
3940 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3941 return IntRange(L.Width, L.NonNegative && R.NonNegative);
3942 }
3943
3944 // The result of a remainder can't be larger than the result of
3945 // either side.
3946 case BO_Rem: {
3947 // Don't 'pre-truncate' the operands.
3948 unsigned opWidth = C.getIntWidth(E->getType());
3949 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3950 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3951
3952 IntRange meet = IntRange::meet(L, R);
3953 meet.Width = std::min(meet.Width, MaxWidth);
3954 return meet;
3955 }
3956
3957 // The default behavior is okay for these.
3958 case BO_Mul:
3959 case BO_Add:
3960 case BO_Xor:
3961 case BO_Or:
John McCallf2370c92010-01-06 05:24:50 +00003962 break;
3963 }
3964
John McCall00fe7612011-07-14 22:39:48 +00003965 // The default case is to treat the operation as if it were closed
3966 // on the narrowest type that encompasses both operands.
John McCallf2370c92010-01-06 05:24:50 +00003967 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3968 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
3969 return IntRange::join(L, R);
3970 }
3971
3972 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
3973 switch (UO->getOpcode()) {
3974 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00003975 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00003976 return IntRange::forBoolType();
3977
3978 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00003979 case UO_Deref:
3980 case UO_AddrOf: // should be impossible
John McCall1844a6e2010-11-10 23:38:19 +00003981 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003982
3983 default:
3984 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
3985 }
3986 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003987
3988 if (dyn_cast<OffsetOfExpr>(E)) {
John McCall1844a6e2010-11-10 23:38:19 +00003989 IntRange::forValueOfType(C, E->getType());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003990 }
John McCallf2370c92010-01-06 05:24:50 +00003991
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003992 if (FieldDecl *BitField = E->getBitField())
3993 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00003994 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCallf2370c92010-01-06 05:24:50 +00003995
John McCall1844a6e2010-11-10 23:38:19 +00003996 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003997}
John McCall51313c32010-01-04 23:31:57 +00003998
Ted Kremenek0692a192012-01-31 05:37:37 +00003999static IntRange GetExprRange(ASTContext &C, Expr *E) {
John McCall323ed742010-05-06 08:58:33 +00004000 return GetExprRange(C, E, C.getIntWidth(E->getType()));
4001}
4002
John McCall51313c32010-01-04 23:31:57 +00004003/// Checks whether the given value, which currently has the given
4004/// source semantics, has the same value when coerced through the
4005/// target semantics.
Ted Kremenek0692a192012-01-31 05:37:37 +00004006static bool IsSameFloatAfterCast(const llvm::APFloat &value,
4007 const llvm::fltSemantics &Src,
4008 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00004009 llvm::APFloat truncated = value;
4010
4011 bool ignored;
4012 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
4013 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
4014
4015 return truncated.bitwiseIsEqual(value);
4016}
4017
4018/// Checks whether the given value, which currently has the given
4019/// source semantics, has the same value when coerced through the
4020/// target semantics.
4021///
4022/// The value might be a vector of floats (or a complex number).
Ted Kremenek0692a192012-01-31 05:37:37 +00004023static bool IsSameFloatAfterCast(const APValue &value,
4024 const llvm::fltSemantics &Src,
4025 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00004026 if (value.isFloat())
4027 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
4028
4029 if (value.isVector()) {
4030 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
4031 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
4032 return false;
4033 return true;
4034 }
4035
4036 assert(value.isComplexFloat());
4037 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
4038 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
4039}
4040
Ted Kremenek0692a192012-01-31 05:37:37 +00004041static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00004042
Ted Kremeneke3b159c2010-09-23 21:43:44 +00004043static bool IsZero(Sema &S, Expr *E) {
4044 // Suppress cases where we are comparing against an enum constant.
4045 if (const DeclRefExpr *DR =
4046 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
4047 if (isa<EnumConstantDecl>(DR->getDecl()))
4048 return false;
4049
4050 // Suppress cases where the '0' value is expanded from a macro.
4051 if (E->getLocStart().isMacroID())
4052 return false;
4053
John McCall323ed742010-05-06 08:58:33 +00004054 llvm::APSInt Value;
4055 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
4056}
4057
John McCall372e1032010-10-06 00:25:24 +00004058static bool HasEnumType(Expr *E) {
4059 // Strip off implicit integral promotions.
4060 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00004061 if (ICE->getCastKind() != CK_IntegralCast &&
4062 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00004063 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00004064 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00004065 }
4066
4067 return E->getType()->isEnumeralType();
4068}
4069
Ted Kremenek0692a192012-01-31 05:37:37 +00004070static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00004071 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00004072 if (E->isValueDependent())
4073 return;
4074
John McCall2de56d12010-08-25 11:45:40 +00004075 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00004076 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004077 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00004078 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004079 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00004080 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004081 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00004082 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004083 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00004084 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004085 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00004086 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004087 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00004088 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004089 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00004090 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4091 }
4092}
4093
4094/// Analyze the operands of the given comparison. Implements the
4095/// fallback case from AnalyzeComparison.
Ted Kremenek0692a192012-01-31 05:37:37 +00004096static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00004097 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
4098 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00004099}
John McCall51313c32010-01-04 23:31:57 +00004100
John McCallba26e582010-01-04 23:21:16 +00004101/// \brief Implements -Wsign-compare.
4102///
Richard Trieudd225092011-09-15 21:56:47 +00004103/// \param E the binary operator to check for warnings
Ted Kremenek0692a192012-01-31 05:37:37 +00004104static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCall323ed742010-05-06 08:58:33 +00004105 // The type the comparison is being performed in.
4106 QualType T = E->getLHS()->getType();
4107 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
4108 && "comparison with mismatched types");
John McCallba26e582010-01-04 23:21:16 +00004109
John McCall323ed742010-05-06 08:58:33 +00004110 // We don't do anything special if this isn't an unsigned integral
4111 // comparison: we're only interested in integral comparisons, and
4112 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00004113 //
4114 // We also don't care about value-dependent expressions or expressions
4115 // whose result is a constant.
4116 if (!T->hasUnsignedIntegerRepresentation()
4117 || E->isValueDependent() || E->isIntegerConstantExpr(S.Context))
John McCall323ed742010-05-06 08:58:33 +00004118 return AnalyzeImpConvsInComparison(S, E);
John McCallf2370c92010-01-06 05:24:50 +00004119
Richard Trieudd225092011-09-15 21:56:47 +00004120 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
4121 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
John McCallba26e582010-01-04 23:21:16 +00004122
John McCall323ed742010-05-06 08:58:33 +00004123 // Check to see if one of the (unmodified) operands is of different
4124 // signedness.
4125 Expr *signedOperand, *unsignedOperand;
Richard Trieudd225092011-09-15 21:56:47 +00004126 if (LHS->getType()->hasSignedIntegerRepresentation()) {
4127 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00004128 "unsigned comparison between two signed integer expressions?");
Richard Trieudd225092011-09-15 21:56:47 +00004129 signedOperand = LHS;
4130 unsignedOperand = RHS;
4131 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
4132 signedOperand = RHS;
4133 unsignedOperand = LHS;
John McCallba26e582010-01-04 23:21:16 +00004134 } else {
John McCall323ed742010-05-06 08:58:33 +00004135 CheckTrivialUnsignedComparison(S, E);
4136 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004137 }
4138
John McCall323ed742010-05-06 08:58:33 +00004139 // Otherwise, calculate the effective range of the signed operand.
4140 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00004141
John McCall323ed742010-05-06 08:58:33 +00004142 // Go ahead and analyze implicit conversions in the operands. Note
4143 // that we skip the implicit conversions on both sides.
Richard Trieudd225092011-09-15 21:56:47 +00004144 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
4145 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00004146
John McCall323ed742010-05-06 08:58:33 +00004147 // If the signed range is non-negative, -Wsign-compare won't fire,
4148 // but we should still check for comparisons which are always true
4149 // or false.
4150 if (signedRange.NonNegative)
4151 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004152
4153 // For (in)equality comparisons, if the unsigned operand is a
4154 // constant which cannot collide with a overflowed signed operand,
4155 // then reinterpreting the signed operand as unsigned will not
4156 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00004157 if (E->isEqualityOp()) {
4158 unsigned comparisonWidth = S.Context.getIntWidth(T);
4159 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00004160
John McCall323ed742010-05-06 08:58:33 +00004161 // We should never be unable to prove that the unsigned operand is
4162 // non-negative.
4163 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
4164
4165 if (unsignedRange.Width < comparisonWidth)
4166 return;
4167 }
4168
Douglas Gregor6d3b93d2012-05-01 01:53:49 +00004169 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
4170 S.PDiag(diag::warn_mixed_sign_comparison)
4171 << LHS->getType() << RHS->getType()
4172 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallba26e582010-01-04 23:21:16 +00004173}
4174
John McCall15d7d122010-11-11 03:21:53 +00004175/// Analyzes an attempt to assign the given value to a bitfield.
4176///
4177/// Returns true if there was something fishy about the attempt.
Ted Kremenek0692a192012-01-31 05:37:37 +00004178static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
4179 SourceLocation InitLoc) {
John McCall15d7d122010-11-11 03:21:53 +00004180 assert(Bitfield->isBitField());
4181 if (Bitfield->isInvalidDecl())
4182 return false;
4183
John McCall91b60142010-11-11 05:33:51 +00004184 // White-list bool bitfields.
4185 if (Bitfield->getType()->isBooleanType())
4186 return false;
4187
Douglas Gregor46ff3032011-02-04 13:09:01 +00004188 // Ignore value- or type-dependent expressions.
4189 if (Bitfield->getBitWidth()->isValueDependent() ||
4190 Bitfield->getBitWidth()->isTypeDependent() ||
4191 Init->isValueDependent() ||
4192 Init->isTypeDependent())
4193 return false;
4194
John McCall15d7d122010-11-11 03:21:53 +00004195 Expr *OriginalInit = Init->IgnoreParenImpCasts();
4196
Richard Smith80d4b552011-12-28 19:48:30 +00004197 llvm::APSInt Value;
4198 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall15d7d122010-11-11 03:21:53 +00004199 return false;
4200
John McCall15d7d122010-11-11 03:21:53 +00004201 unsigned OriginalWidth = Value.getBitWidth();
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004202 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall15d7d122010-11-11 03:21:53 +00004203
4204 if (OriginalWidth <= FieldWidth)
4205 return false;
4206
Eli Friedman3a643af2012-01-26 23:11:39 +00004207 // Compute the value which the bitfield will contain.
Jay Foad9f71a8f2010-12-07 08:25:34 +00004208 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedman3a643af2012-01-26 23:11:39 +00004209 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall15d7d122010-11-11 03:21:53 +00004210
Eli Friedman3a643af2012-01-26 23:11:39 +00004211 // Check whether the stored value is equal to the original value.
4212 TruncatedValue = TruncatedValue.extend(OriginalWidth);
John McCall15d7d122010-11-11 03:21:53 +00004213 if (Value == TruncatedValue)
4214 return false;
4215
Eli Friedman3a643af2012-01-26 23:11:39 +00004216 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedman34ff0622012-02-02 00:40:20 +00004217 // therefore don't strictly fit into a signed bitfield of width 1.
4218 if (FieldWidth == 1 && Value == 1)
Eli Friedman3a643af2012-01-26 23:11:39 +00004219 return false;
4220
John McCall15d7d122010-11-11 03:21:53 +00004221 std::string PrettyValue = Value.toString(10);
4222 std::string PrettyTrunc = TruncatedValue.toString(10);
4223
4224 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
4225 << PrettyValue << PrettyTrunc << OriginalInit->getType()
4226 << Init->getSourceRange();
4227
4228 return true;
4229}
4230
John McCallbeb22aa2010-11-09 23:24:47 +00004231/// Analyze the given simple or compound assignment for warning-worthy
4232/// operations.
Ted Kremenek0692a192012-01-31 05:37:37 +00004233static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCallbeb22aa2010-11-09 23:24:47 +00004234 // Just recurse on the LHS.
4235 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
4236
4237 // We want to recurse on the RHS as normal unless we're assigning to
4238 // a bitfield.
4239 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
John McCall15d7d122010-11-11 03:21:53 +00004240 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
4241 E->getOperatorLoc())) {
4242 // Recurse, ignoring any implicit conversions on the RHS.
4243 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
4244 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00004245 }
4246 }
4247
4248 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
4249}
4250
John McCall51313c32010-01-04 23:31:57 +00004251/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00004252static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00004253 SourceLocation CContext, unsigned diag,
4254 bool pruneControlFlow = false) {
4255 if (pruneControlFlow) {
4256 S.DiagRuntimeBehavior(E->getExprLoc(), E,
4257 S.PDiag(diag)
4258 << SourceType << T << E->getSourceRange()
4259 << SourceRange(CContext));
4260 return;
4261 }
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004262 S.Diag(E->getExprLoc(), diag)
4263 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
4264}
4265
Chandler Carruthe1b02e02011-04-05 06:47:57 +00004266/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00004267static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00004268 SourceLocation CContext, unsigned diag,
4269 bool pruneControlFlow = false) {
4270 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruthe1b02e02011-04-05 06:47:57 +00004271}
4272
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004273/// Diagnose an implicit cast from a literal expression. Does not warn when the
4274/// cast wouldn't lose information.
Chandler Carruthf65076e2011-04-10 08:36:24 +00004275void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
4276 SourceLocation CContext) {
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004277 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruthf65076e2011-04-10 08:36:24 +00004278 bool isExact = false;
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004279 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00004280 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
4281 T->hasUnsignedIntegerRepresentation());
4282 if (Value.convertToInteger(IntegerValue,
Chandler Carruthf65076e2011-04-10 08:36:24 +00004283 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004284 == llvm::APFloat::opOK && isExact)
Chandler Carruthf65076e2011-04-10 08:36:24 +00004285 return;
4286
David Blaikiebe0ee872012-05-15 16:56:36 +00004287 SmallString<16> PrettySourceValue;
4288 Value.toString(PrettySourceValue);
David Blaikiede7e7b82012-05-15 17:18:27 +00004289 SmallString<16> PrettyTargetValue;
David Blaikiebe0ee872012-05-15 16:56:36 +00004290 if (T->isSpecificBuiltinType(BuiltinType::Bool))
4291 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
4292 else
David Blaikiede7e7b82012-05-15 17:18:27 +00004293 IntegerValue.toString(PrettyTargetValue);
David Blaikiebe0ee872012-05-15 16:56:36 +00004294
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004295 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikiebe0ee872012-05-15 16:56:36 +00004296 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
4297 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruthf65076e2011-04-10 08:36:24 +00004298}
4299
John McCall091f23f2010-11-09 22:22:12 +00004300std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
4301 if (!Range.Width) return "0";
4302
4303 llvm::APSInt ValueInRange = Value;
4304 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00004305 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00004306 return ValueInRange.toString(10);
4307}
4308
John McCall323ed742010-05-06 08:58:33 +00004309void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00004310 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00004311 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00004312
John McCall323ed742010-05-06 08:58:33 +00004313 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
4314 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
4315 if (Source == Target) return;
4316 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00004317
Chandler Carruth108f7562011-07-26 05:40:03 +00004318 // If the conversion context location is invalid don't complain. We also
4319 // don't want to emit a warning if the issue occurs from the expansion of
4320 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
4321 // delay this check as long as possible. Once we detect we are in that
4322 // scenario, we just return.
Ted Kremenekef9ff882011-03-10 20:03:42 +00004323 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00004324 return;
4325
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004326 // Diagnose implicit casts to bool.
4327 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
4328 if (isa<StringLiteral>(E))
4329 // Warn on string literal to bool. Checks for string literals in logical
4330 // expressions, for instances, assert(0 && "error here"), is prevented
4331 // by a check in AnalyzeImplicitConversions().
4332 return DiagnoseImpCast(S, E, T, CC,
4333 diag::warn_impcast_string_literal_to_bool);
Lang Hamese14ca9f2011-12-05 20:49:50 +00004334 if (Source->isFunctionType()) {
4335 // Warn on function to bool. Checks free functions and static member
4336 // functions. Weakly imported functions are excluded from the check,
4337 // since it's common to test their value to check whether the linker
4338 // found a definition for them.
4339 ValueDecl *D = 0;
4340 if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
4341 D = R->getDecl();
4342 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
4343 D = M->getMemberDecl();
4344 }
4345
4346 if (D && !D->isWeak()) {
Richard Trieu26b45d82011-12-06 04:48:01 +00004347 if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
4348 S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
4349 << F << E->getSourceRange() << SourceRange(CC);
David Blaikie2def7732011-12-09 21:42:37 +00004350 S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
4351 << FixItHint::CreateInsertion(E->getExprLoc(), "&");
4352 QualType ReturnType;
4353 UnresolvedSet<4> NonTemplateOverloads;
4354 S.isExprCallable(*E, ReturnType, NonTemplateOverloads);
4355 if (!ReturnType.isNull()
4356 && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
4357 S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
4358 << FixItHint::CreateInsertion(
4359 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu26b45d82011-12-06 04:48:01 +00004360 return;
4361 }
Lang Hamese14ca9f2011-12-05 20:49:50 +00004362 }
4363 }
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004364 }
John McCall51313c32010-01-04 23:31:57 +00004365
4366 // Strip vector types.
4367 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004368 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004369 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004370 return;
John McCallb4eb64d2010-10-08 02:01:28 +00004371 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004372 }
Chris Lattnerb792b302011-06-14 04:51:15 +00004373
4374 // If the vector cast is cast between two vectors of the same size, it is
4375 // a bitcast, not a conversion.
4376 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
4377 return;
John McCall51313c32010-01-04 23:31:57 +00004378
4379 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
4380 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
4381 }
4382
4383 // Strip complex types.
4384 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004385 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004386 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004387 return;
4388
John McCallb4eb64d2010-10-08 02:01:28 +00004389 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004390 }
John McCall51313c32010-01-04 23:31:57 +00004391
4392 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
4393 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
4394 }
4395
4396 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
4397 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
4398
4399 // If the source is floating point...
4400 if (SourceBT && SourceBT->isFloatingPoint()) {
4401 // ...and the target is floating point...
4402 if (TargetBT && TargetBT->isFloatingPoint()) {
4403 // ...then warn if we're dropping FP rank.
4404
4405 // Builtin FP kinds are ordered by increasing FP rank.
4406 if (SourceBT->getKind() > TargetBT->getKind()) {
4407 // Don't warn about float constants that are precisely
4408 // representable in the target type.
4409 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00004410 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00004411 // Value might be a float, a float vector, or a float complex.
4412 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00004413 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
4414 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00004415 return;
4416 }
4417
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004418 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004419 return;
4420
John McCallb4eb64d2010-10-08 02:01:28 +00004421 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00004422 }
4423 return;
4424 }
4425
Ted Kremenekef9ff882011-03-10 20:03:42 +00004426 // If the target is integral, always warn.
David Blaikiebe0ee872012-05-15 16:56:36 +00004427 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004428 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004429 return;
4430
Chandler Carrutha5b93322011-02-17 11:05:49 +00004431 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay634c8af2011-09-08 22:30:47 +00004432 // We also want to warn on, e.g., "int i = -1.234"
4433 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
4434 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
4435 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
4436
Chandler Carruthf65076e2011-04-10 08:36:24 +00004437 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
4438 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00004439 } else {
4440 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
4441 }
4442 }
John McCall51313c32010-01-04 23:31:57 +00004443
4444 return;
4445 }
4446
Richard Trieu1838ca52011-05-29 19:59:02 +00004447 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
David Blaikieb26331b2012-06-19 21:19:06 +00004448 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
David Blaikie28a5f0c2012-06-21 18:51:10 +00004449 && !Target->isBlockPointerType() && !Target->isMemberPointerType()) {
David Blaikieb1360492012-03-16 20:30:12 +00004450 SourceLocation Loc = E->getSourceRange().getBegin();
4451 if (Loc.isMacroID())
4452 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
David Blaikie9fb1ac52012-05-15 21:57:38 +00004453 if (!Loc.isMacroID() || CC.isMacroID())
4454 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
4455 << T << clang::SourceRange(CC)
4456 << FixItHint::CreateReplacement(Loc, S.getFixItZeroLiteralForType(T));
Richard Trieu1838ca52011-05-29 19:59:02 +00004457 }
4458
David Blaikieb26331b2012-06-19 21:19:06 +00004459 if (!Source->isIntegerType() || !Target->isIntegerType())
4460 return;
4461
David Blaikiebe0ee872012-05-15 16:56:36 +00004462 // TODO: remove this early return once the false positives for constant->bool
4463 // in templates, macros, etc, are reduced or removed.
4464 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
4465 return;
4466
John McCall323ed742010-05-06 08:58:33 +00004467 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00004468 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00004469
4470 if (SourceRange.Width > TargetRange.Width) {
John McCall091f23f2010-11-09 22:22:12 +00004471 // If the source is a constant, use a default-on diagnostic.
4472 // TODO: this should happen for bitfield stores, too.
4473 llvm::APSInt Value(32);
4474 if (E->isIntegerConstantExpr(Value, S.Context)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004475 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004476 return;
4477
John McCall091f23f2010-11-09 22:22:12 +00004478 std::string PrettySourceValue = Value.toString(10);
4479 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
4480
Ted Kremenek5e745da2011-10-22 02:37:33 +00004481 S.DiagRuntimeBehavior(E->getExprLoc(), E,
4482 S.PDiag(diag::warn_impcast_integer_precision_constant)
4483 << PrettySourceValue << PrettyTargetValue
4484 << E->getType() << T << E->getSourceRange()
4485 << clang::SourceRange(CC));
John McCall091f23f2010-11-09 22:22:12 +00004486 return;
4487 }
4488
Chris Lattnerb792b302011-06-14 04:51:15 +00004489 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004490 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004491 return;
4492
David Blaikie37050842012-04-12 22:40:54 +00004493 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaksc36bedc2012-02-01 19:08:57 +00004494 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
4495 /* pruneControlFlow */ true);
John McCallb4eb64d2010-10-08 02:01:28 +00004496 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00004497 }
4498
4499 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
4500 (!TargetRange.NonNegative && SourceRange.NonNegative &&
4501 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004502
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004503 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004504 return;
4505
John McCall323ed742010-05-06 08:58:33 +00004506 unsigned DiagID = diag::warn_impcast_integer_sign;
4507
4508 // Traditionally, gcc has warned about this under -Wsign-compare.
4509 // We also want to warn about it in -Wconversion.
4510 // So if -Wconversion is off, use a completely identical diagnostic
4511 // in the sign-compare group.
4512 // The conditional-checking code will
4513 if (ICContext) {
4514 DiagID = diag::warn_impcast_integer_sign_conditional;
4515 *ICContext = true;
4516 }
4517
John McCallb4eb64d2010-10-08 02:01:28 +00004518 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00004519 }
4520
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004521 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004522 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
4523 // type, to give us better diagnostics.
4524 QualType SourceType = E->getType();
David Blaikie4e4d0842012-03-11 07:00:24 +00004525 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004526 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
4527 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
4528 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
4529 SourceType = S.Context.getTypeDeclType(Enum);
4530 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
4531 }
4532 }
4533
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004534 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
4535 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
4536 if ((SourceEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00004537 SourceEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004538 (TargetEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00004539 TargetEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00004540 SourceEnum != TargetEnum) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004541 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004542 return;
4543
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004544 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004545 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004546 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004547
John McCall51313c32010-01-04 23:31:57 +00004548 return;
4549}
4550
David Blaikie9fb1ac52012-05-15 21:57:38 +00004551void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
4552 SourceLocation CC, QualType T);
John McCall323ed742010-05-06 08:58:33 +00004553
4554void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00004555 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00004556 E = E->IgnoreParenImpCasts();
4557
4558 if (isa<ConditionalOperator>(E))
David Blaikie9fb1ac52012-05-15 21:57:38 +00004559 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCall323ed742010-05-06 08:58:33 +00004560
John McCallb4eb64d2010-10-08 02:01:28 +00004561 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00004562 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00004563 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00004564 return;
4565}
4566
David Blaikie9fb1ac52012-05-15 21:57:38 +00004567void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
4568 SourceLocation CC, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00004569 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00004570
4571 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00004572 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
4573 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00004574
4575 // If -Wconversion would have warned about either of the candidates
4576 // for a signedness conversion to the context type...
4577 if (!Suspicious) return;
4578
4579 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00004580 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
4581 CC))
John McCall323ed742010-05-06 08:58:33 +00004582 return;
4583
John McCall323ed742010-05-06 08:58:33 +00004584 // ...then check whether it would have warned about either of the
4585 // candidates for a signedness conversion to the condition type.
Richard Trieu52541612011-07-21 02:46:28 +00004586 if (E->getType() == T) return;
4587
4588 Suspicious = false;
4589 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
4590 E->getType(), CC, &Suspicious);
4591 if (!Suspicious)
4592 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00004593 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00004594}
4595
4596/// AnalyzeImplicitConversions - Find and report any interesting
4597/// implicit conversions in the given expression. There are a couple
4598/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00004599void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00004600 QualType T = OrigE->getType();
4601 Expr *E = OrigE->IgnoreParenImpCasts();
4602
Douglas Gregorf8b6e152011-10-10 17:38:18 +00004603 if (E->isTypeDependent() || E->isValueDependent())
4604 return;
4605
John McCall323ed742010-05-06 08:58:33 +00004606 // For conditional operators, we analyze the arguments as if they
4607 // were being fed directly into the output.
4608 if (isa<ConditionalOperator>(E)) {
4609 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie9fb1ac52012-05-15 21:57:38 +00004610 CheckConditionalOperator(S, CO, CC, T);
John McCall323ed742010-05-06 08:58:33 +00004611 return;
4612 }
4613
4614 // Go ahead and check any implicit conversions we might have skipped.
4615 // The non-canonical typecheck is just an optimization;
4616 // CheckImplicitConversion will filter out dead implicit conversions.
4617 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00004618 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00004619
4620 // Now continue drilling into this expression.
4621
4622 // Skip past explicit casts.
4623 if (isa<ExplicitCastExpr>(E)) {
4624 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00004625 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00004626 }
4627
John McCallbeb22aa2010-11-09 23:24:47 +00004628 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4629 // Do a somewhat different check with comparison operators.
4630 if (BO->isComparisonOp())
4631 return AnalyzeComparison(S, BO);
4632
Eli Friedman0fa06382012-01-26 23:34:06 +00004633 // And with simple assignments.
4634 if (BO->getOpcode() == BO_Assign)
John McCallbeb22aa2010-11-09 23:24:47 +00004635 return AnalyzeAssignment(S, BO);
4636 }
John McCall323ed742010-05-06 08:58:33 +00004637
4638 // These break the otherwise-useful invariant below. Fortunately,
4639 // we don't really need to recurse into them, because any internal
4640 // expressions should have been analyzed already when they were
4641 // built into statements.
4642 if (isa<StmtExpr>(E)) return;
4643
4644 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004645 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00004646
4647 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00004648 CC = E->getExprLoc();
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004649 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
4650 bool IsLogicalOperator = BO && BO->isLogicalOp();
4651 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor54042f12012-02-09 10:18:50 +00004652 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor503384f2012-02-09 00:47:04 +00004653 if (!ChildExpr)
4654 continue;
4655
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004656 if (IsLogicalOperator &&
4657 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
4658 // Ignore checking string literals that are in logical operators.
4659 continue;
4660 AnalyzeImplicitConversions(S, ChildExpr, CC);
4661 }
John McCall323ed742010-05-06 08:58:33 +00004662}
4663
4664} // end anonymous namespace
4665
4666/// Diagnoses "dangerous" implicit conversions within the given
4667/// expression (which is a full expression). Implements -Wconversion
4668/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00004669///
4670/// \param CC the "context" location of the implicit conversion, i.e.
4671/// the most location of the syntactic entity requiring the implicit
4672/// conversion
4673void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00004674 // Don't diagnose in unevaluated contexts.
4675 if (ExprEvalContexts.back().Context == Sema::Unevaluated)
4676 return;
4677
4678 // Don't diagnose for value- or type-dependent expressions.
4679 if (E->isTypeDependent() || E->isValueDependent())
4680 return;
4681
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004682 // Check for array bounds violations in cases where the check isn't triggered
4683 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
4684 // ArraySubscriptExpr is on the RHS of a variable initialization.
4685 CheckArrayAccess(E);
4686
John McCallb4eb64d2010-10-08 02:01:28 +00004687 // This is not the right CC for (e.g.) a variable initialization.
4688 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00004689}
4690
John McCall15d7d122010-11-11 03:21:53 +00004691void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
4692 FieldDecl *BitField,
4693 Expr *Init) {
4694 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
4695}
4696
Mike Stumpf8c49212010-01-21 03:59:47 +00004697/// CheckParmsForFunctionDef - Check that the parameters of the given
4698/// function are appropriate for the definition of a function. This
4699/// takes care of any checks that cannot be performed on the
4700/// declaration itself, e.g., that the types of each of the function
4701/// parameters are complete.
Douglas Gregor82aa7132010-11-01 18:37:59 +00004702bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
4703 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00004704 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00004705 for (; P != PEnd; ++P) {
4706 ParmVarDecl *Param = *P;
4707
Mike Stumpf8c49212010-01-21 03:59:47 +00004708 // C99 6.7.5.3p4: the parameters in a parameter type list in a
4709 // function declarator that is part of a function definition of
4710 // that function shall not have incomplete type.
4711 //
4712 // This is also C++ [dcl.fct]p6.
4713 if (!Param->isInvalidDecl() &&
4714 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00004715 diag::err_typecheck_decl_incomplete_type)) {
Mike Stumpf8c49212010-01-21 03:59:47 +00004716 Param->setInvalidDecl();
4717 HasInvalidParm = true;
4718 }
4719
4720 // C99 6.9.1p5: If the declarator includes a parameter type list, the
4721 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00004722 if (CheckParameterNames &&
4723 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00004724 !Param->isImplicit() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00004725 !getLangOpts().CPlusPlus)
Mike Stumpf8c49212010-01-21 03:59:47 +00004726 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00004727
4728 // C99 6.7.5.3p12:
4729 // If the function declarator is not part of a definition of that
4730 // function, parameters may have incomplete type and may use the [*]
4731 // notation in their sequences of declarator specifiers to specify
4732 // variable length array types.
4733 QualType PType = Param->getOriginalType();
4734 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
4735 if (AT->getSizeModifier() == ArrayType::Star) {
4736 // FIXME: This diagnosic should point the the '[*]' if source-location
4737 // information is added for it.
4738 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
4739 }
4740 }
Mike Stumpf8c49212010-01-21 03:59:47 +00004741 }
4742
4743 return HasInvalidParm;
4744}
John McCallb7f4ffe2010-08-12 21:44:57 +00004745
4746/// CheckCastAlign - Implements -Wcast-align, which warns when a
4747/// pointer cast increases the alignment requirements.
4748void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
4749 // This is actually a lot of work to potentially be doing on every
4750 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00004751 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
4752 TRange.getBegin())
David Blaikied6471f72011-09-25 23:23:43 +00004753 == DiagnosticsEngine::Ignored)
John McCallb7f4ffe2010-08-12 21:44:57 +00004754 return;
4755
4756 // Ignore dependent types.
4757 if (T->isDependentType() || Op->getType()->isDependentType())
4758 return;
4759
4760 // Require that the destination be a pointer type.
4761 const PointerType *DestPtr = T->getAs<PointerType>();
4762 if (!DestPtr) return;
4763
4764 // If the destination has alignment 1, we're done.
4765 QualType DestPointee = DestPtr->getPointeeType();
4766 if (DestPointee->isIncompleteType()) return;
4767 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
4768 if (DestAlign.isOne()) return;
4769
4770 // Require that the source be a pointer type.
4771 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
4772 if (!SrcPtr) return;
4773 QualType SrcPointee = SrcPtr->getPointeeType();
4774
4775 // Whitelist casts from cv void*. We already implicitly
4776 // whitelisted casts to cv void*, since they have alignment 1.
4777 // Also whitelist casts involving incomplete types, which implicitly
4778 // includes 'void'.
4779 if (SrcPointee->isIncompleteType()) return;
4780
4781 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
4782 if (SrcAlign >= DestAlign) return;
4783
4784 Diag(TRange.getBegin(), diag::warn_cast_align)
4785 << Op->getType() << T
4786 << static_cast<unsigned>(SrcAlign.getQuantity())
4787 << static_cast<unsigned>(DestAlign.getQuantity())
4788 << TRange << Op->getSourceRange();
4789}
4790
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004791static const Type* getElementType(const Expr *BaseExpr) {
4792 const Type* EltType = BaseExpr->getType().getTypePtr();
4793 if (EltType->isAnyPointerType())
4794 return EltType->getPointeeType().getTypePtr();
4795 else if (EltType->isArrayType())
4796 return EltType->getBaseElementTypeUnsafe();
4797 return EltType;
4798}
4799
Chandler Carruthc2684342011-08-05 09:10:50 +00004800/// \brief Check whether this array fits the idiom of a size-one tail padded
4801/// array member of a struct.
4802///
4803/// We avoid emitting out-of-bounds access warnings for such arrays as they are
4804/// commonly used to emulate flexible arrays in C89 code.
4805static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
4806 const NamedDecl *ND) {
4807 if (Size != 1 || !ND) return false;
4808
4809 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
4810 if (!FD) return false;
4811
4812 // Don't consider sizes resulting from macro expansions or template argument
4813 // substitution to form C89 tail-padded arrays.
Sean Callanand2cf3482012-05-04 18:22:53 +00004814
4815 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00004816 while (TInfo) {
4817 TypeLoc TL = TInfo->getTypeLoc();
4818 // Look through typedefs.
4819 const TypedefTypeLoc *TTL = dyn_cast<TypedefTypeLoc>(&TL);
4820 if (TTL) {
4821 const TypedefNameDecl *TDL = TTL->getTypedefNameDecl();
4822 TInfo = TDL->getTypeSourceInfo();
4823 continue;
4824 }
4825 ConstantArrayTypeLoc CTL = cast<ConstantArrayTypeLoc>(TL);
4826 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Sean Callanand2cf3482012-05-04 18:22:53 +00004827 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
4828 return false;
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00004829 break;
Sean Callanand2cf3482012-05-04 18:22:53 +00004830 }
Chandler Carruthc2684342011-08-05 09:10:50 +00004831
4832 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gay381711c2011-11-29 22:43:53 +00004833 if (!RD) return false;
4834 if (RD->isUnion()) return false;
4835 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
4836 if (!CRD->isStandardLayout()) return false;
4837 }
Chandler Carruthc2684342011-08-05 09:10:50 +00004838
Benjamin Kramer22d4fed2011-08-06 03:04:42 +00004839 // See if this is the last field decl in the record.
4840 const Decl *D = FD;
4841 while ((D = D->getNextDeclInContext()))
4842 if (isa<FieldDecl>(D))
4843 return false;
4844 return true;
Chandler Carruthc2684342011-08-05 09:10:50 +00004845}
4846
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004847void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004848 const ArraySubscriptExpr *ASE,
Richard Smith25b009a2011-12-16 19:31:14 +00004849 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman92b670e2012-02-27 21:21:40 +00004850 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004851 if (IndexExpr->isValueDependent())
4852 return;
4853
Matt Beaumont-Gay8ef8f432011-12-12 22:35:02 +00004854 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004855 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth34064582011-02-17 20:55:08 +00004856 const ConstantArrayType *ArrayTy =
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004857 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00004858 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00004859 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00004860
Chandler Carruth34064582011-02-17 20:55:08 +00004861 llvm::APSInt index;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004862 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00004863 return;
Richard Smith25b009a2011-12-16 19:31:14 +00004864 if (IndexNegated)
4865 index = -index;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00004866
Chandler Carruthba447122011-08-05 08:07:29 +00004867 const NamedDecl *ND = NULL;
Chandler Carruthba447122011-08-05 08:07:29 +00004868 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
4869 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruthc2684342011-08-05 09:10:50 +00004870 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruthba447122011-08-05 08:07:29 +00004871 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruthba447122011-08-05 08:07:29 +00004872
Ted Kremenek9e060ca2011-02-23 23:06:04 +00004873 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00004874 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00004875 if (!size.isStrictlyPositive())
4876 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004877
4878 const Type* BaseType = getElementType(BaseExpr);
Nico Weberde5998f2011-09-17 22:59:41 +00004879 if (BaseType != EffectiveType) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004880 // Make sure we're comparing apples to apples when comparing index to size
4881 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
4882 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhraind10f4bc2011-08-10 19:47:25 +00004883 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhrain18f16972011-08-10 18:49:28 +00004884 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004885 if (ptrarith_typesize != array_typesize) {
4886 // There's a cast to a different size type involved
4887 uint64_t ratio = array_typesize / ptrarith_typesize;
4888 // TODO: Be smarter about handling cases where array_typesize is not a
4889 // multiple of ptrarith_typesize
4890 if (ptrarith_typesize * ratio == array_typesize)
4891 size *= llvm::APInt(size.getBitWidth(), ratio);
4892 }
4893 }
4894
Chandler Carruth34064582011-02-17 20:55:08 +00004895 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00004896 index = index.zext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00004897 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00004898 size = size.zext(index.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00004899
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004900 // For array subscripting the index must be less than size, but for pointer
4901 // arithmetic also allow the index (offset) to be equal to size since
4902 // computing the next address after the end of the array is legal and
4903 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman92b670e2012-02-27 21:21:40 +00004904 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruthba447122011-08-05 08:07:29 +00004905 return;
4906
4907 // Also don't warn for arrays of size 1 which are members of some
4908 // structure. These are often used to approximate flexible arrays in C89
4909 // code.
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004910 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00004911 return;
Chandler Carruth34064582011-02-17 20:55:08 +00004912
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004913 // Suppress the warning if the subscript expression (as identified by the
4914 // ']' location) and the index expression are both from macro expansions
4915 // within a system header.
4916 if (ASE) {
4917 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
4918 ASE->getRBracketLoc());
4919 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
4920 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
4921 IndexExpr->getLocStart());
4922 if (SourceMgr.isFromSameFile(RBracketLoc, IndexLoc))
4923 return;
4924 }
4925 }
4926
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004927 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004928 if (ASE)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004929 DiagID = diag::warn_array_index_exceeds_bounds;
4930
4931 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
4932 PDiag(DiagID) << index.toString(10, true)
4933 << size.toString(10, true)
4934 << (unsigned)size.getLimitedValue(~0U)
4935 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00004936 } else {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004937 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004938 if (!ASE) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004939 DiagID = diag::warn_ptr_arith_precedes_bounds;
4940 if (index.isNegative()) index = -index;
4941 }
4942
4943 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
4944 PDiag(DiagID) << index.toString(10, true)
4945 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00004946 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00004947
Matt Beaumont-Gaycfbc5b52011-11-29 19:27:11 +00004948 if (!ND) {
4949 // Try harder to find a NamedDecl to point at in the note.
4950 while (const ArraySubscriptExpr *ASE =
4951 dyn_cast<ArraySubscriptExpr>(BaseExpr))
4952 BaseExpr = ASE->getBase()->IgnoreParenCasts();
4953 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
4954 ND = dyn_cast<NamedDecl>(DRE->getDecl());
4955 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
4956 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
4957 }
4958
Chandler Carruth35001ca2011-02-17 21:10:52 +00004959 if (ND)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004960 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
4961 PDiag(diag::note_array_index_out_of_bounds)
4962 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00004963}
4964
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004965void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004966 int AllowOnePastEnd = 0;
4967 while (expr) {
4968 expr = expr->IgnoreParenImpCasts();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004969 switch (expr->getStmtClass()) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004970 case Stmt::ArraySubscriptExprClass: {
4971 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004972 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004973 AllowOnePastEnd > 0);
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004974 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004975 }
4976 case Stmt::UnaryOperatorClass: {
4977 // Only unwrap the * and & unary operators
4978 const UnaryOperator *UO = cast<UnaryOperator>(expr);
4979 expr = UO->getSubExpr();
4980 switch (UO->getOpcode()) {
4981 case UO_AddrOf:
4982 AllowOnePastEnd++;
4983 break;
4984 case UO_Deref:
4985 AllowOnePastEnd--;
4986 break;
4987 default:
4988 return;
4989 }
4990 break;
4991 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004992 case Stmt::ConditionalOperatorClass: {
4993 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
4994 if (const Expr *lhs = cond->getLHS())
4995 CheckArrayAccess(lhs);
4996 if (const Expr *rhs = cond->getRHS())
4997 CheckArrayAccess(rhs);
4998 return;
4999 }
5000 default:
5001 return;
5002 }
Peter Collingbournef111d932011-04-15 00:35:48 +00005003 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00005004}
John McCallf85e1932011-06-15 23:02:42 +00005005
5006//===--- CHECK: Objective-C retain cycles ----------------------------------//
5007
5008namespace {
5009 struct RetainCycleOwner {
5010 RetainCycleOwner() : Variable(0), Indirect(false) {}
5011 VarDecl *Variable;
5012 SourceRange Range;
5013 SourceLocation Loc;
5014 bool Indirect;
5015
5016 void setLocsFrom(Expr *e) {
5017 Loc = e->getExprLoc();
5018 Range = e->getSourceRange();
5019 }
5020 };
5021}
5022
5023/// Consider whether capturing the given variable can possibly lead to
5024/// a retain cycle.
5025static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
5026 // In ARC, it's captured strongly iff the variable has __strong
5027 // lifetime. In MRR, it's captured strongly if the variable is
5028 // __block and has an appropriate type.
5029 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
5030 return false;
5031
5032 owner.Variable = var;
5033 owner.setLocsFrom(ref);
5034 return true;
5035}
5036
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00005037static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCallf85e1932011-06-15 23:02:42 +00005038 while (true) {
5039 e = e->IgnoreParens();
5040 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
5041 switch (cast->getCastKind()) {
5042 case CK_BitCast:
5043 case CK_LValueBitCast:
5044 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00005045 case CK_ARCReclaimReturnedObject:
John McCallf85e1932011-06-15 23:02:42 +00005046 e = cast->getSubExpr();
5047 continue;
5048
John McCallf85e1932011-06-15 23:02:42 +00005049 default:
5050 return false;
5051 }
5052 }
5053
5054 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
5055 ObjCIvarDecl *ivar = ref->getDecl();
5056 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
5057 return false;
5058
5059 // Try to find a retain cycle in the base.
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00005060 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCallf85e1932011-06-15 23:02:42 +00005061 return false;
5062
5063 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
5064 owner.Indirect = true;
5065 return true;
5066 }
5067
5068 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
5069 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
5070 if (!var) return false;
5071 return considerVariable(var, ref, owner);
5072 }
5073
John McCallf85e1932011-06-15 23:02:42 +00005074 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
5075 if (member->isArrow()) return false;
5076
5077 // Don't count this as an indirect ownership.
5078 e = member->getBase();
5079 continue;
5080 }
5081
John McCall4b9c2d22011-11-06 09:01:30 +00005082 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
5083 // Only pay attention to pseudo-objects on property references.
5084 ObjCPropertyRefExpr *pre
5085 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
5086 ->IgnoreParens());
5087 if (!pre) return false;
5088 if (pre->isImplicitProperty()) return false;
5089 ObjCPropertyDecl *property = pre->getExplicitProperty();
5090 if (!property->isRetaining() &&
5091 !(property->getPropertyIvarDecl() &&
5092 property->getPropertyIvarDecl()->getType()
5093 .getObjCLifetime() == Qualifiers::OCL_Strong))
5094 return false;
5095
5096 owner.Indirect = true;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00005097 if (pre->isSuperReceiver()) {
5098 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
5099 if (!owner.Variable)
5100 return false;
5101 owner.Loc = pre->getLocation();
5102 owner.Range = pre->getSourceRange();
5103 return true;
5104 }
John McCall4b9c2d22011-11-06 09:01:30 +00005105 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
5106 ->getSourceExpr());
5107 continue;
5108 }
5109
John McCallf85e1932011-06-15 23:02:42 +00005110 // Array ivars?
5111
5112 return false;
5113 }
5114}
5115
5116namespace {
5117 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
5118 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
5119 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
5120 Variable(variable), Capturer(0) {}
5121
5122 VarDecl *Variable;
5123 Expr *Capturer;
5124
5125 void VisitDeclRefExpr(DeclRefExpr *ref) {
5126 if (ref->getDecl() == Variable && !Capturer)
5127 Capturer = ref;
5128 }
5129
John McCallf85e1932011-06-15 23:02:42 +00005130 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
5131 if (Capturer) return;
5132 Visit(ref->getBase());
5133 if (Capturer && ref->isFreeIvar())
5134 Capturer = ref;
5135 }
5136
5137 void VisitBlockExpr(BlockExpr *block) {
5138 // Look inside nested blocks
5139 if (block->getBlockDecl()->capturesVariable(Variable))
5140 Visit(block->getBlockDecl()->getBody());
5141 }
5142 };
5143}
5144
5145/// Check whether the given argument is a block which captures a
5146/// variable.
5147static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
5148 assert(owner.Variable && owner.Loc.isValid());
5149
5150 e = e->IgnoreParenCasts();
5151 BlockExpr *block = dyn_cast<BlockExpr>(e);
5152 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
5153 return 0;
5154
5155 FindCaptureVisitor visitor(S.Context, owner.Variable);
5156 visitor.Visit(block->getBlockDecl()->getBody());
5157 return visitor.Capturer;
5158}
5159
5160static void diagnoseRetainCycle(Sema &S, Expr *capturer,
5161 RetainCycleOwner &owner) {
5162 assert(capturer);
5163 assert(owner.Variable && owner.Loc.isValid());
5164
5165 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
5166 << owner.Variable << capturer->getSourceRange();
5167 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
5168 << owner.Indirect << owner.Range;
5169}
5170
5171/// Check for a keyword selector that starts with the word 'add' or
5172/// 'set'.
5173static bool isSetterLikeSelector(Selector sel) {
5174 if (sel.isUnarySelector()) return false;
5175
Chris Lattner5f9e2722011-07-23 10:55:15 +00005176 StringRef str = sel.getNameForSlot(0);
John McCallf85e1932011-06-15 23:02:42 +00005177 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00005178 if (str.startswith("set"))
John McCallf85e1932011-06-15 23:02:42 +00005179 str = str.substr(3);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00005180 else if (str.startswith("add")) {
5181 // Specially whitelist 'addOperationWithBlock:'.
5182 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
5183 return false;
5184 str = str.substr(3);
5185 }
John McCallf85e1932011-06-15 23:02:42 +00005186 else
5187 return false;
5188
5189 if (str.empty()) return true;
5190 return !islower(str.front());
5191}
5192
5193/// Check a message send to see if it's likely to cause a retain cycle.
5194void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
5195 // Only check instance methods whose selector looks like a setter.
5196 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
5197 return;
5198
5199 // Try to find a variable that the receiver is strongly owned by.
5200 RetainCycleOwner owner;
5201 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00005202 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCallf85e1932011-06-15 23:02:42 +00005203 return;
5204 } else {
5205 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
5206 owner.Variable = getCurMethodDecl()->getSelfDecl();
5207 owner.Loc = msg->getSuperLoc();
5208 owner.Range = msg->getSuperLoc();
5209 }
5210
5211 // Check whether the receiver is captured by any of the arguments.
5212 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
5213 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
5214 return diagnoseRetainCycle(*this, capturer, owner);
5215}
5216
5217/// Check a property assign to see if it's likely to cause a retain cycle.
5218void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
5219 RetainCycleOwner owner;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00005220 if (!findRetainCycleOwner(*this, receiver, owner))
John McCallf85e1932011-06-15 23:02:42 +00005221 return;
5222
5223 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
5224 diagnoseRetainCycle(*this, capturer, owner);
5225}
5226
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005227bool Sema::checkUnsafeAssigns(SourceLocation Loc,
John McCallf85e1932011-06-15 23:02:42 +00005228 QualType LHS, Expr *RHS) {
5229 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
5230 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005231 return false;
5232 // strip off any implicit cast added to get to the one arc-specific
5233 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00005234 if (cast->getCastKind() == CK_ARCConsumeObject) {
John McCallf85e1932011-06-15 23:02:42 +00005235 Diag(Loc, diag::warn_arc_retained_assign)
5236 << (LT == Qualifiers::OCL_ExplicitNone)
5237 << RHS->getSourceRange();
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005238 return true;
5239 }
5240 RHS = cast->getSubExpr();
5241 }
5242 return false;
John McCallf85e1932011-06-15 23:02:42 +00005243}
5244
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005245void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
5246 Expr *LHS, Expr *RHS) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00005247 QualType LHSType;
5248 // PropertyRef on LHS type need be directly obtained from
5249 // its declaration as it has a PsuedoType.
5250 ObjCPropertyRefExpr *PRE
5251 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
5252 if (PRE && !PRE->isImplicitProperty()) {
5253 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
5254 if (PD)
5255 LHSType = PD->getType();
5256 }
5257
5258 if (LHSType.isNull())
5259 LHSType = LHS->getType();
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005260 if (checkUnsafeAssigns(Loc, LHSType, RHS))
5261 return;
5262 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
5263 // FIXME. Check for other life times.
5264 if (LT != Qualifiers::OCL_None)
5265 return;
5266
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00005267 if (PRE) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005268 if (PRE->isImplicitProperty())
5269 return;
5270 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
5271 if (!PD)
5272 return;
5273
5274 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00005275 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
5276 // when 'assign' attribute was not explicitly specified
5277 // by user, ignore it and rely on property type itself
5278 // for lifetime info.
5279 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
5280 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
5281 LHSType->isObjCRetainableType())
5282 return;
5283
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005284 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00005285 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005286 Diag(Loc, diag::warn_arc_retained_property_assign)
5287 << RHS->getSourceRange();
5288 return;
5289 }
5290 RHS = cast->getSubExpr();
5291 }
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00005292 }
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005293 }
5294}
Dmitri Gribenko625bb562012-02-14 22:14:32 +00005295
5296//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
5297
5298namespace {
5299bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
5300 SourceLocation StmtLoc,
5301 const NullStmt *Body) {
5302 // Do not warn if the body is a macro that expands to nothing, e.g:
5303 //
5304 // #define CALL(x)
5305 // if (condition)
5306 // CALL(0);
5307 //
5308 if (Body->hasLeadingEmptyMacro())
5309 return false;
5310
5311 // Get line numbers of statement and body.
5312 bool StmtLineInvalid;
5313 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
5314 &StmtLineInvalid);
5315 if (StmtLineInvalid)
5316 return false;
5317
5318 bool BodyLineInvalid;
5319 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
5320 &BodyLineInvalid);
5321 if (BodyLineInvalid)
5322 return false;
5323
5324 // Warn if null statement and body are on the same line.
5325 if (StmtLine != BodyLine)
5326 return false;
5327
5328 return true;
5329}
5330} // Unnamed namespace
5331
5332void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
5333 const Stmt *Body,
5334 unsigned DiagID) {
5335 // Since this is a syntactic check, don't emit diagnostic for template
5336 // instantiations, this just adds noise.
5337 if (CurrentInstantiationScope)
5338 return;
5339
5340 // The body should be a null statement.
5341 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
5342 if (!NBody)
5343 return;
5344
5345 // Do the usual checks.
5346 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
5347 return;
5348
5349 Diag(NBody->getSemiLoc(), DiagID);
5350 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
5351}
5352
5353void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
5354 const Stmt *PossibleBody) {
5355 assert(!CurrentInstantiationScope); // Ensured by caller
5356
5357 SourceLocation StmtLoc;
5358 const Stmt *Body;
5359 unsigned DiagID;
5360 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
5361 StmtLoc = FS->getRParenLoc();
5362 Body = FS->getBody();
5363 DiagID = diag::warn_empty_for_body;
5364 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
5365 StmtLoc = WS->getCond()->getSourceRange().getEnd();
5366 Body = WS->getBody();
5367 DiagID = diag::warn_empty_while_body;
5368 } else
5369 return; // Neither `for' nor `while'.
5370
5371 // The body should be a null statement.
5372 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
5373 if (!NBody)
5374 return;
5375
5376 // Skip expensive checks if diagnostic is disabled.
5377 if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
5378 DiagnosticsEngine::Ignored)
5379 return;
5380
5381 // Do the usual checks.
5382 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
5383 return;
5384
5385 // `for(...);' and `while(...);' are popular idioms, so in order to keep
5386 // noise level low, emit diagnostics only if for/while is followed by a
5387 // CompoundStmt, e.g.:
5388 // for (int i = 0; i < n; i++);
5389 // {
5390 // a(i);
5391 // }
5392 // or if for/while is followed by a statement with more indentation
5393 // than for/while itself:
5394 // for (int i = 0; i < n; i++);
5395 // a(i);
5396 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
5397 if (!ProbableTypo) {
5398 bool BodyColInvalid;
5399 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
5400 PossibleBody->getLocStart(),
5401 &BodyColInvalid);
5402 if (BodyColInvalid)
5403 return;
5404
5405 bool StmtColInvalid;
5406 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
5407 S->getLocStart(),
5408 &StmtColInvalid);
5409 if (StmtColInvalid)
5410 return;
5411
5412 if (BodyCol > StmtCol)
5413 ProbableTypo = true;
5414 }
5415
5416 if (ProbableTypo) {
5417 Diag(NBody->getSemiLoc(), DiagID);
5418 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
5419 }
5420}