blob: 9454a751550d9173e80cafabb0e396581856e79d [file] [log] [blame]
Chris Lattner59907c42007-08-10 20:18:51 +00001//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner59907c42007-08-10 20:18:51 +00007//
8//===----------------------------------------------------------------------===//
9//
Mike Stump1eb44332009-09-09 15:08:12 +000010// This file implements extra semantic analysis beyond what is enforced
Chris Lattner59907c42007-08-10 20:18:51 +000011// by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
John McCall5f8d6042011-08-27 01:09:30 +000015#include "clang/Sema/Initialization.h"
Douglas Gregore737f502010-08-12 20:07:10 +000016#include "clang/Sema/Sema.h"
John McCall2d887082010-08-25 22:03:47 +000017#include "clang/Sema/SemaInternal.h"
Eli Friedman276b0612011-10-11 02:20:01 +000018#include "clang/Sema/Initialization.h"
John McCall781472f2010-08-25 08:40:02 +000019#include "clang/Sema/ScopeInfo.h"
Ted Kremenek826a3452010-07-16 02:11:22 +000020#include "clang/Analysis/Analyses/FormatString.h"
Chris Lattner59907c42007-08-10 20:18:51 +000021#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000022#include "clang/AST/CharUnits.h"
John McCall384aff82010-08-25 07:42:41 +000023#include "clang/AST/DeclCXX.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000024#include "clang/AST/DeclObjC.h"
Ted Kremenek23245122007-08-20 16:18:38 +000025#include "clang/AST/ExprCXX.h"
Ted Kremenek7ff22b22008-06-16 18:00:42 +000026#include "clang/AST/ExprObjC.h"
John McCallf85e1932011-06-15 23:02:42 +000027#include "clang/AST/EvaluatedExprVisitor.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000028#include "clang/AST/DeclObjC.h"
29#include "clang/AST/StmtCXX.h"
30#include "clang/AST/StmtObjC.h"
Chris Lattner59907c42007-08-10 20:18:51 +000031#include "clang/Lex/Preprocessor.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000032#include "llvm/ADT/BitVector.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000033#include "llvm/ADT/SmallString.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000034#include "llvm/ADT/STLExtras.h"
Tom Care3bfc5f42010-06-09 04:11:11 +000035#include "llvm/Support/raw_ostream.h"
Eric Christopher691ebc32010-04-17 02:26:23 +000036#include "clang/Basic/TargetBuiltins.h"
Nate Begeman26a31422010-06-08 02:47:44 +000037#include "clang/Basic/TargetInfo.h"
Fariborz Jahanian7da71022010-09-07 19:38:13 +000038#include "clang/Basic/ConvertUTF.h"
Zhongxing Xua1f3dba2009-05-20 01:55:10 +000039#include <limits>
Chris Lattner59907c42007-08-10 20:18:51 +000040using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000041using namespace sema;
Chris Lattner59907c42007-08-10 20:18:51 +000042
Chris Lattner60800082009-02-18 17:49:48 +000043SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
44 unsigned ByteNo) const {
Chris Lattner08f92e32010-11-17 07:37:15 +000045 return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
46 PP.getLangOptions(), PP.getTargetInfo());
Chris Lattner60800082009-02-18 17:49:48 +000047}
48
John McCall8e10f3b2011-02-26 05:39:39 +000049/// Checks that a call expression's argument count is the desired number.
50/// This is useful when doing custom type-checking. Returns true on error.
51static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
52 unsigned argCount = call->getNumArgs();
53 if (argCount == desiredArgCount) return false;
54
55 if (argCount < desiredArgCount)
56 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
57 << 0 /*function call*/ << desiredArgCount << argCount
58 << call->getSourceRange();
59
60 // Highlight all the excess arguments.
61 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
62 call->getArg(argCount - 1)->getLocEnd());
63
64 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
65 << 0 /*function call*/ << desiredArgCount << argCount
66 << call->getArg(1)->getSourceRange();
67}
68
Julien Lerouge77f68bb2011-09-09 22:41:49 +000069/// CheckBuiltinAnnotationString - Checks that string argument to the builtin
70/// annotation is a non wide string literal.
71static bool CheckBuiltinAnnotationString(Sema &S, Expr *Arg) {
72 Arg = Arg->IgnoreParenCasts();
73 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
74 if (!Literal || !Literal->isAscii()) {
75 S.Diag(Arg->getLocStart(), diag::err_builtin_annotation_not_string_constant)
76 << Arg->getSourceRange();
77 return true;
78 }
79 return false;
80}
81
John McCall60d7b3a2010-08-24 06:29:42 +000082ExprResult
Anders Carlssond406bf02009-08-16 01:56:34 +000083Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
John McCall60d7b3a2010-08-24 06:29:42 +000084 ExprResult TheCallResult(Owned(TheCall));
Douglas Gregor2def4832008-11-17 20:34:05 +000085
Chris Lattner946928f2010-10-01 23:23:24 +000086 // Find out if any arguments are required to be integer constant expressions.
87 unsigned ICEArguments = 0;
88 ASTContext::GetBuiltinTypeError Error;
89 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
90 if (Error != ASTContext::GE_None)
91 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
92
93 // If any arguments are required to be ICE's, check and diagnose.
94 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
95 // Skip arguments not required to be ICE's.
96 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
97
98 llvm::APSInt Result;
99 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
100 return true;
101 ICEArguments &= ~(1 << ArgNo);
102 }
103
Anders Carlssond406bf02009-08-16 01:56:34 +0000104 switch (BuiltinID) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000105 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +0000106 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +0000107 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner69039812009-02-18 06:01:06 +0000108 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000109 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000110 break;
Ted Kremenek49ff7a12008-07-09 17:58:53 +0000111 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +0000112 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000113 if (SemaBuiltinVAStart(TheCall))
114 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000115 break;
Chris Lattner1b9a0792007-12-20 00:26:33 +0000116 case Builtin::BI__builtin_isgreater:
117 case Builtin::BI__builtin_isgreaterequal:
118 case Builtin::BI__builtin_isless:
119 case Builtin::BI__builtin_islessequal:
120 case Builtin::BI__builtin_islessgreater:
121 case Builtin::BI__builtin_isunordered:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000122 if (SemaBuiltinUnorderedCompare(TheCall))
123 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000124 break;
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000125 case Builtin::BI__builtin_fpclassify:
126 if (SemaBuiltinFPClassification(TheCall, 6))
127 return ExprError();
128 break;
Eli Friedman9ac6f622009-08-31 20:06:00 +0000129 case Builtin::BI__builtin_isfinite:
130 case Builtin::BI__builtin_isinf:
131 case Builtin::BI__builtin_isinf_sign:
132 case Builtin::BI__builtin_isnan:
133 case Builtin::BI__builtin_isnormal:
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000134 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman9ac6f622009-08-31 20:06:00 +0000135 return ExprError();
136 break;
Eli Friedmand38617c2008-05-14 19:38:39 +0000137 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000138 return SemaBuiltinShuffleVector(TheCall);
139 // TheCall will be freed by the smart pointer here, but that's fine, since
140 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000141 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000142 if (SemaBuiltinPrefetch(TheCall))
143 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000144 break;
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000145 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000146 if (SemaBuiltinObjectSize(TheCall))
147 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000148 break;
Eli Friedmand875fed2009-05-03 04:46:36 +0000149 case Builtin::BI__builtin_longjmp:
150 if (SemaBuiltinLongjmp(TheCall))
151 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000152 break;
John McCall8e10f3b2011-02-26 05:39:39 +0000153
154 case Builtin::BI__builtin_classify_type:
155 if (checkArgCount(*this, TheCall, 1)) return true;
156 TheCall->setType(Context.IntTy);
157 break;
Chris Lattner75c29a02010-10-12 17:47:42 +0000158 case Builtin::BI__builtin_constant_p:
John McCall8e10f3b2011-02-26 05:39:39 +0000159 if (checkArgCount(*this, TheCall, 1)) return true;
160 TheCall->setType(Context.IntTy);
Chris Lattner75c29a02010-10-12 17:47:42 +0000161 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000162 case Builtin::BI__sync_fetch_and_add:
Douglas Gregora9766412011-11-28 16:30:08 +0000163 case Builtin::BI__sync_fetch_and_add_1:
164 case Builtin::BI__sync_fetch_and_add_2:
165 case Builtin::BI__sync_fetch_and_add_4:
166 case Builtin::BI__sync_fetch_and_add_8:
167 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000168 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregora9766412011-11-28 16:30:08 +0000169 case Builtin::BI__sync_fetch_and_sub_1:
170 case Builtin::BI__sync_fetch_and_sub_2:
171 case Builtin::BI__sync_fetch_and_sub_4:
172 case Builtin::BI__sync_fetch_and_sub_8:
173 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000174 case Builtin::BI__sync_fetch_and_or:
Douglas Gregora9766412011-11-28 16:30:08 +0000175 case Builtin::BI__sync_fetch_and_or_1:
176 case Builtin::BI__sync_fetch_and_or_2:
177 case Builtin::BI__sync_fetch_and_or_4:
178 case Builtin::BI__sync_fetch_and_or_8:
179 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000180 case Builtin::BI__sync_fetch_and_and:
Douglas Gregora9766412011-11-28 16:30:08 +0000181 case Builtin::BI__sync_fetch_and_and_1:
182 case Builtin::BI__sync_fetch_and_and_2:
183 case Builtin::BI__sync_fetch_and_and_4:
184 case Builtin::BI__sync_fetch_and_and_8:
185 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000186 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregora9766412011-11-28 16:30:08 +0000187 case Builtin::BI__sync_fetch_and_xor_1:
188 case Builtin::BI__sync_fetch_and_xor_2:
189 case Builtin::BI__sync_fetch_and_xor_4:
190 case Builtin::BI__sync_fetch_and_xor_8:
191 case Builtin::BI__sync_fetch_and_xor_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000192 case Builtin::BI__sync_add_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000193 case Builtin::BI__sync_add_and_fetch_1:
194 case Builtin::BI__sync_add_and_fetch_2:
195 case Builtin::BI__sync_add_and_fetch_4:
196 case Builtin::BI__sync_add_and_fetch_8:
197 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000198 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000199 case Builtin::BI__sync_sub_and_fetch_1:
200 case Builtin::BI__sync_sub_and_fetch_2:
201 case Builtin::BI__sync_sub_and_fetch_4:
202 case Builtin::BI__sync_sub_and_fetch_8:
203 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000204 case Builtin::BI__sync_and_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000205 case Builtin::BI__sync_and_and_fetch_1:
206 case Builtin::BI__sync_and_and_fetch_2:
207 case Builtin::BI__sync_and_and_fetch_4:
208 case Builtin::BI__sync_and_and_fetch_8:
209 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000210 case Builtin::BI__sync_or_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000211 case Builtin::BI__sync_or_and_fetch_1:
212 case Builtin::BI__sync_or_and_fetch_2:
213 case Builtin::BI__sync_or_and_fetch_4:
214 case Builtin::BI__sync_or_and_fetch_8:
215 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000216 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000217 case Builtin::BI__sync_xor_and_fetch_1:
218 case Builtin::BI__sync_xor_and_fetch_2:
219 case Builtin::BI__sync_xor_and_fetch_4:
220 case Builtin::BI__sync_xor_and_fetch_8:
221 case Builtin::BI__sync_xor_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000222 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000223 case Builtin::BI__sync_val_compare_and_swap_1:
224 case Builtin::BI__sync_val_compare_and_swap_2:
225 case Builtin::BI__sync_val_compare_and_swap_4:
226 case Builtin::BI__sync_val_compare_and_swap_8:
227 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000228 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000229 case Builtin::BI__sync_bool_compare_and_swap_1:
230 case Builtin::BI__sync_bool_compare_and_swap_2:
231 case Builtin::BI__sync_bool_compare_and_swap_4:
232 case Builtin::BI__sync_bool_compare_and_swap_8:
233 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000234 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregora9766412011-11-28 16:30:08 +0000235 case Builtin::BI__sync_lock_test_and_set_1:
236 case Builtin::BI__sync_lock_test_and_set_2:
237 case Builtin::BI__sync_lock_test_and_set_4:
238 case Builtin::BI__sync_lock_test_and_set_8:
239 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000240 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +0000241 case Builtin::BI__sync_lock_release_1:
242 case Builtin::BI__sync_lock_release_2:
243 case Builtin::BI__sync_lock_release_4:
244 case Builtin::BI__sync_lock_release_8:
245 case Builtin::BI__sync_lock_release_16:
Chris Lattner23aa9c82011-04-09 03:57:26 +0000246 case Builtin::BI__sync_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000247 case Builtin::BI__sync_swap_1:
248 case Builtin::BI__sync_swap_2:
249 case Builtin::BI__sync_swap_4:
250 case Builtin::BI__sync_swap_8:
251 case Builtin::BI__sync_swap_16:
Chandler Carruthd2014572010-07-09 18:59:35 +0000252 return SemaBuiltinAtomicOverloaded(move(TheCallResult));
Eli Friedman276b0612011-10-11 02:20:01 +0000253 case Builtin::BI__atomic_load:
254 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Load);
255 case Builtin::BI__atomic_store:
256 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Store);
David Chisnall7a7ee302012-01-16 17:27:18 +0000257 case Builtin::BI__atomic_init:
258 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Init);
Eli Friedman276b0612011-10-11 02:20:01 +0000259 case Builtin::BI__atomic_exchange:
260 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Xchg);
261 case Builtin::BI__atomic_compare_exchange_strong:
262 return SemaAtomicOpsOverloaded(move(TheCallResult),
263 AtomicExpr::CmpXchgStrong);
264 case Builtin::BI__atomic_compare_exchange_weak:
265 return SemaAtomicOpsOverloaded(move(TheCallResult),
266 AtomicExpr::CmpXchgWeak);
267 case Builtin::BI__atomic_fetch_add:
268 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Add);
269 case Builtin::BI__atomic_fetch_sub:
270 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Sub);
271 case Builtin::BI__atomic_fetch_and:
272 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::And);
273 case Builtin::BI__atomic_fetch_or:
274 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Or);
275 case Builtin::BI__atomic_fetch_xor:
276 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Xor);
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000277 case Builtin::BI__builtin_annotation:
278 if (CheckBuiltinAnnotationString(*this, TheCall->getArg(1)))
279 return ExprError();
280 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000281 }
282
283 // Since the target specific builtins for each arch overlap, only check those
284 // of the arch we are compiling for.
285 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000286 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman26a31422010-06-08 02:47:44 +0000287 case llvm::Triple::arm:
288 case llvm::Triple::thumb:
289 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
290 return ExprError();
291 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000292 default:
293 break;
294 }
295 }
296
297 return move(TheCallResult);
298}
299
Nate Begeman61eecf52010-06-14 05:21:25 +0000300// Get the valid immediate range for the specified NEON type code.
301static unsigned RFT(unsigned t, bool shift = false) {
Bob Wilsonda95f732011-11-08 01:16:11 +0000302 NeonTypeFlags Type(t);
303 int IsQuad = Type.isQuad();
304 switch (Type.getEltType()) {
305 case NeonTypeFlags::Int8:
306 case NeonTypeFlags::Poly8:
307 return shift ? 7 : (8 << IsQuad) - 1;
308 case NeonTypeFlags::Int16:
309 case NeonTypeFlags::Poly16:
310 return shift ? 15 : (4 << IsQuad) - 1;
311 case NeonTypeFlags::Int32:
312 return shift ? 31 : (2 << IsQuad) - 1;
313 case NeonTypeFlags::Int64:
314 return shift ? 63 : (1 << IsQuad) - 1;
315 case NeonTypeFlags::Float16:
316 assert(!shift && "cannot shift float types!");
317 return (4 << IsQuad) - 1;
318 case NeonTypeFlags::Float32:
319 assert(!shift && "cannot shift float types!");
320 return (2 << IsQuad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000321 }
David Blaikie7530c032012-01-17 06:56:22 +0000322 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman61eecf52010-06-14 05:21:25 +0000323}
324
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000325/// getNeonEltType - Return the QualType corresponding to the elements of
326/// the vector type specified by the NeonTypeFlags. This is used to check
327/// the pointer arguments for Neon load/store intrinsics.
328static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context) {
329 switch (Flags.getEltType()) {
330 case NeonTypeFlags::Int8:
331 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
332 case NeonTypeFlags::Int16:
333 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
334 case NeonTypeFlags::Int32:
335 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
336 case NeonTypeFlags::Int64:
337 return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy;
338 case NeonTypeFlags::Poly8:
339 return Context.SignedCharTy;
340 case NeonTypeFlags::Poly16:
341 return Context.ShortTy;
342 case NeonTypeFlags::Float16:
343 return Context.UnsignedShortTy;
344 case NeonTypeFlags::Float32:
345 return Context.FloatTy;
346 }
David Blaikie7530c032012-01-17 06:56:22 +0000347 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000348}
349
Nate Begeman26a31422010-06-08 02:47:44 +0000350bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000351 llvm::APSInt Result;
352
Nate Begeman0d15c532010-06-13 04:47:52 +0000353 unsigned mask = 0;
Nate Begeman61eecf52010-06-14 05:21:25 +0000354 unsigned TV = 0;
Bob Wilson46482552011-11-16 21:32:23 +0000355 int PtrArgNum = -1;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000356 bool HasConstPtr = false;
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000357 switch (BuiltinID) {
Nate Begemana23326b2010-06-17 04:17:01 +0000358#define GET_NEON_OVERLOAD_CHECK
359#include "clang/Basic/arm_neon.inc"
360#undef GET_NEON_OVERLOAD_CHECK
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000361 }
362
Nate Begeman0d15c532010-06-13 04:47:52 +0000363 // For NEON intrinsics which are overloaded on vector element type, validate
364 // the immediate which specifies which variant to emit.
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000365 unsigned ImmArg = TheCall->getNumArgs()-1;
Nate Begeman0d15c532010-06-13 04:47:52 +0000366 if (mask) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000367 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
Nate Begeman0d15c532010-06-13 04:47:52 +0000368 return true;
369
Bob Wilsonda95f732011-11-08 01:16:11 +0000370 TV = Result.getLimitedValue(64);
371 if ((TV > 63) || (mask & (1 << TV)) == 0)
Nate Begeman0d15c532010-06-13 04:47:52 +0000372 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000373 << TheCall->getArg(ImmArg)->getSourceRange();
374 }
375
Bob Wilson46482552011-11-16 21:32:23 +0000376 if (PtrArgNum >= 0) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000377 // Check that pointer arguments have the specified type.
Bob Wilson46482552011-11-16 21:32:23 +0000378 Expr *Arg = TheCall->getArg(PtrArgNum);
379 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
380 Arg = ICE->getSubExpr();
381 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
382 QualType RHSTy = RHS.get()->getType();
383 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context);
384 if (HasConstPtr)
385 EltTy = EltTy.withConst();
386 QualType LHSTy = Context.getPointerType(EltTy);
387 AssignConvertType ConvTy;
388 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
389 if (RHS.isInvalid())
390 return true;
391 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
392 RHS.get(), AA_Assigning))
393 return true;
Nate Begeman0d15c532010-06-13 04:47:52 +0000394 }
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000395
Nate Begeman0d15c532010-06-13 04:47:52 +0000396 // For NEON intrinsics which take an immediate value as part of the
397 // instruction, range check them here.
Nate Begeman61eecf52010-06-14 05:21:25 +0000398 unsigned i = 0, l = 0, u = 0;
Nate Begeman0d15c532010-06-13 04:47:52 +0000399 switch (BuiltinID) {
400 default: return false;
Nate Begemanbb37f502010-07-29 22:48:34 +0000401 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
402 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begeman99c40bb2010-08-03 21:32:34 +0000403 case ARM::BI__builtin_arm_vcvtr_f:
404 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Nate Begemana23326b2010-06-17 04:17:01 +0000405#define GET_NEON_IMMEDIATE_CHECK
406#include "clang/Basic/arm_neon.inc"
407#undef GET_NEON_IMMEDIATE_CHECK
Nate Begeman0d15c532010-06-13 04:47:52 +0000408 };
409
Nate Begeman61eecf52010-06-14 05:21:25 +0000410 // Check that the immediate argument is actually a constant.
Nate Begeman0d15c532010-06-13 04:47:52 +0000411 if (SemaBuiltinConstantArg(TheCall, i, Result))
412 return true;
413
Nate Begeman61eecf52010-06-14 05:21:25 +0000414 // Range check against the upper/lower values for this isntruction.
Nate Begeman0d15c532010-06-13 04:47:52 +0000415 unsigned Val = Result.getZExtValue();
Nate Begeman61eecf52010-06-14 05:21:25 +0000416 if (Val < l || Val > (u + l))
Nate Begeman0d15c532010-06-13 04:47:52 +0000417 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramer476d8b82010-08-11 14:47:12 +0000418 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begeman0d15c532010-06-13 04:47:52 +0000419
Nate Begeman99c40bb2010-08-03 21:32:34 +0000420 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman26a31422010-06-08 02:47:44 +0000421 return false;
Anders Carlssond406bf02009-08-16 01:56:34 +0000422}
Daniel Dunbarde454282008-10-02 18:44:07 +0000423
Anders Carlssond406bf02009-08-16 01:56:34 +0000424/// CheckFunctionCall - Check a direct function call for various correctness
425/// and safety properties not strictly enforced by the C type system.
426bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
427 // Get the IdentifierInfo* for the called function.
428 IdentifierInfo *FnInfo = FDecl->getIdentifier();
429
430 // None of the checks below are needed for functions that don't have
431 // simple names (e.g., C++ conversion functions).
432 if (!FnInfo)
433 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000434
Daniel Dunbarde454282008-10-02 18:44:07 +0000435 // FIXME: This mechanism should be abstracted to be less fragile and
436 // more efficient. For example, just map function ids to custom
437 // handlers.
438
Ted Kremenekc82faca2010-09-09 04:33:05 +0000439 // Printf and scanf checking.
440 for (specific_attr_iterator<FormatAttr>
441 i = FDecl->specific_attr_begin<FormatAttr>(),
442 e = FDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000443 CheckFormatArguments(*i, TheCall);
Chris Lattner59907c42007-08-10 20:18:51 +0000444 }
Mike Stump1eb44332009-09-09 15:08:12 +0000445
Ted Kremenekc82faca2010-09-09 04:33:05 +0000446 for (specific_attr_iterator<NonNullAttr>
447 i = FDecl->specific_attr_begin<NonNullAttr>(),
448 e = FDecl->specific_attr_end<NonNullAttr>(); i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +0000449 CheckNonNullArguments(*i, TheCall->getArgs(),
450 TheCall->getCallee()->getLocStart());
Ted Kremenekc82faca2010-09-09 04:33:05 +0000451 }
Sebastian Redl0eb23302009-01-19 00:08:26 +0000452
Anna Zaks0a151a12012-01-17 00:37:07 +0000453 unsigned CMId = FDecl->getMemoryFunctionKind();
454 if (CMId == 0)
Anna Zaksd9b859a2012-01-13 21:52:01 +0000455 return false;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000456
Anna Zaksd9b859a2012-01-13 21:52:01 +0000457 // Handle memory setting and copying functions.
Anna Zaks0a151a12012-01-17 00:37:07 +0000458 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000459 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaksc36bedc2012-02-01 19:08:57 +0000460 else if (CMId == Builtin::BIstrncat)
461 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaksd9b859a2012-01-13 21:52:01 +0000462 else
Anna Zaks0a151a12012-01-17 00:37:07 +0000463 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth7ccc95b2011-04-27 07:05:31 +0000464
Anders Carlssond406bf02009-08-16 01:56:34 +0000465 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000466}
467
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000468bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
469 Expr **Args, unsigned NumArgs) {
470 for (specific_attr_iterator<FormatAttr>
471 i = Method->specific_attr_begin<FormatAttr>(),
472 e = Method->specific_attr_end<FormatAttr>(); i != e ; ++i) {
473
474 CheckFormatArguments(*i, Args, NumArgs, false, lbrac,
475 Method->getSourceRange());
476 }
477
478 // diagnose nonnull arguments.
479 for (specific_attr_iterator<NonNullAttr>
480 i = Method->specific_attr_begin<NonNullAttr>(),
481 e = Method->specific_attr_end<NonNullAttr>(); i != e; ++i) {
482 CheckNonNullArguments(*i, Args, lbrac);
483 }
484
485 return false;
486}
487
Anders Carlssond406bf02009-08-16 01:56:34 +0000488bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000489 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
490 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000491 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000492
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000493 QualType Ty = V->getType();
494 if (!Ty->isBlockPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000495 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000496
Jean-Daniel Dupas43d12512012-01-25 00:55:11 +0000497 // format string checking.
498 for (specific_attr_iterator<FormatAttr>
499 i = NDecl->specific_attr_begin<FormatAttr>(),
500 e = NDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) {
501 CheckFormatArguments(*i, TheCall);
502 }
Anders Carlssond406bf02009-08-16 01:56:34 +0000503
504 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000505}
506
Eli Friedman276b0612011-10-11 02:20:01 +0000507ExprResult
508Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, AtomicExpr::AtomicOp Op) {
509 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
510 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedman276b0612011-10-11 02:20:01 +0000511
512 // All these operations take one of the following four forms:
513 // T __atomic_load(_Atomic(T)*, int) (loads)
514 // T* __atomic_add(_Atomic(T*)*, ptrdiff_t, int) (pointer add/sub)
515 // int __atomic_compare_exchange_strong(_Atomic(T)*, T*, T, int, int)
516 // (cmpxchg)
517 // T __atomic_exchange(_Atomic(T)*, T, int) (everything else)
518 // where T is an appropriate type, and the int paremeterss are for orderings.
519 unsigned NumVals = 1;
520 unsigned NumOrders = 1;
521 if (Op == AtomicExpr::Load) {
522 NumVals = 0;
523 } else if (Op == AtomicExpr::CmpXchgWeak || Op == AtomicExpr::CmpXchgStrong) {
524 NumVals = 2;
525 NumOrders = 2;
526 }
David Chisnall7a7ee302012-01-16 17:27:18 +0000527 if (Op == AtomicExpr::Init)
528 NumOrders = 0;
Eli Friedman276b0612011-10-11 02:20:01 +0000529
530 if (TheCall->getNumArgs() < NumVals+NumOrders+1) {
531 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
532 << 0 << NumVals+NumOrders+1 << TheCall->getNumArgs()
533 << TheCall->getCallee()->getSourceRange();
534 return ExprError();
535 } else if (TheCall->getNumArgs() > NumVals+NumOrders+1) {
536 Diag(TheCall->getArg(NumVals+NumOrders+1)->getLocStart(),
537 diag::err_typecheck_call_too_many_args)
538 << 0 << NumVals+NumOrders+1 << TheCall->getNumArgs()
539 << TheCall->getCallee()->getSourceRange();
540 return ExprError();
541 }
542
543 // Inspect the first argument of the atomic operation. This should always be
544 // a pointer to an _Atomic type.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000545 Expr *Ptr = TheCall->getArg(0);
Eli Friedman276b0612011-10-11 02:20:01 +0000546 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
547 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
548 if (!pointerType) {
549 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
550 << Ptr->getType() << Ptr->getSourceRange();
551 return ExprError();
552 }
553
554 QualType AtomTy = pointerType->getPointeeType();
555 if (!AtomTy->isAtomicType()) {
556 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
557 << Ptr->getType() << Ptr->getSourceRange();
558 return ExprError();
559 }
560 QualType ValType = AtomTy->getAs<AtomicType>()->getValueType();
561
562 if ((Op == AtomicExpr::Add || Op == AtomicExpr::Sub) &&
563 !ValType->isIntegerType() && !ValType->isPointerType()) {
564 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
565 << Ptr->getType() << Ptr->getSourceRange();
566 return ExprError();
567 }
568
569 if (!ValType->isIntegerType() &&
570 (Op == AtomicExpr::And || Op == AtomicExpr::Or || Op == AtomicExpr::Xor)){
571 Diag(DRE->getLocStart(), diag::err_atomic_op_logical_needs_atomic_int)
572 << Ptr->getType() << Ptr->getSourceRange();
573 return ExprError();
574 }
575
576 switch (ValType.getObjCLifetime()) {
577 case Qualifiers::OCL_None:
578 case Qualifiers::OCL_ExplicitNone:
579 // okay
580 break;
581
582 case Qualifiers::OCL_Weak:
583 case Qualifiers::OCL_Strong:
584 case Qualifiers::OCL_Autoreleasing:
585 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
586 << ValType << Ptr->getSourceRange();
587 return ExprError();
588 }
589
590 QualType ResultType = ValType;
David Chisnall7a7ee302012-01-16 17:27:18 +0000591 if (Op == AtomicExpr::Store || Op == AtomicExpr::Init)
Eli Friedman276b0612011-10-11 02:20:01 +0000592 ResultType = Context.VoidTy;
593 else if (Op == AtomicExpr::CmpXchgWeak || Op == AtomicExpr::CmpXchgStrong)
594 ResultType = Context.BoolTy;
595
596 // The first argument --- the pointer --- has a fixed type; we
597 // deduce the types of the rest of the arguments accordingly. Walk
598 // the remaining arguments, converting them to the deduced value type.
599 for (unsigned i = 1; i != NumVals+NumOrders+1; ++i) {
600 ExprResult Arg = TheCall->getArg(i);
601 QualType Ty;
602 if (i < NumVals+1) {
603 // The second argument to a cmpxchg is a pointer to the data which will
604 // be exchanged. The second argument to a pointer add/subtract is the
605 // amount to add/subtract, which must be a ptrdiff_t. The third
606 // argument to a cmpxchg and the second argument in all other cases
607 // is the type of the value.
608 if (i == 1 && (Op == AtomicExpr::CmpXchgWeak ||
609 Op == AtomicExpr::CmpXchgStrong))
610 Ty = Context.getPointerType(ValType.getUnqualifiedType());
611 else if (!ValType->isIntegerType() &&
612 (Op == AtomicExpr::Add || Op == AtomicExpr::Sub))
613 Ty = Context.getPointerDiffType();
614 else
615 Ty = ValType;
616 } else {
617 // The order(s) are always converted to int.
618 Ty = Context.IntTy;
619 }
620 InitializedEntity Entity =
621 InitializedEntity::InitializeParameter(Context, Ty, false);
622 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
623 if (Arg.isInvalid())
624 return true;
625 TheCall->setArg(i, Arg.get());
626 }
627
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000628 SmallVector<Expr*, 5> SubExprs;
629 SubExprs.push_back(Ptr);
Eli Friedman276b0612011-10-11 02:20:01 +0000630 if (Op == AtomicExpr::Load) {
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000631 SubExprs.push_back(TheCall->getArg(1)); // Order
David Chisnall7a7ee302012-01-16 17:27:18 +0000632 } else if (Op == AtomicExpr::Init) {
633 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman276b0612011-10-11 02:20:01 +0000634 } else if (Op != AtomicExpr::CmpXchgWeak && Op != AtomicExpr::CmpXchgStrong) {
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000635 SubExprs.push_back(TheCall->getArg(2)); // Order
636 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman276b0612011-10-11 02:20:01 +0000637 } else {
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000638 SubExprs.push_back(TheCall->getArg(3)); // Order
639 SubExprs.push_back(TheCall->getArg(1)); // Val1
640 SubExprs.push_back(TheCall->getArg(2)); // Val2
641 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
Eli Friedman276b0612011-10-11 02:20:01 +0000642 }
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000643
644 return Owned(new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
645 SubExprs.data(), SubExprs.size(),
646 ResultType, Op,
647 TheCall->getRParenLoc()));
Eli Friedman276b0612011-10-11 02:20:01 +0000648}
649
650
John McCall5f8d6042011-08-27 01:09:30 +0000651/// checkBuiltinArgument - Given a call to a builtin function, perform
652/// normal type-checking on the given argument, updating the call in
653/// place. This is useful when a builtin function requires custom
654/// type-checking for some of its arguments but not necessarily all of
655/// them.
656///
657/// Returns true on error.
658static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
659 FunctionDecl *Fn = E->getDirectCallee();
660 assert(Fn && "builtin call without direct callee!");
661
662 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
663 InitializedEntity Entity =
664 InitializedEntity::InitializeParameter(S.Context, Param);
665
666 ExprResult Arg = E->getArg(0);
667 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
668 if (Arg.isInvalid())
669 return true;
670
671 E->setArg(ArgIndex, Arg.take());
672 return false;
673}
674
Chris Lattner5caa3702009-05-08 06:58:22 +0000675/// SemaBuiltinAtomicOverloaded - We have a call to a function like
676/// __sync_fetch_and_add, which is an overloaded function based on the pointer
677/// type of its first argument. The main ActOnCallExpr routines have already
678/// promoted the types of arguments because all of these calls are prototyped as
679/// void(...).
680///
681/// This function goes through and does final semantic checking for these
682/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +0000683ExprResult
684Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000685 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +0000686 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
687 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
688
689 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +0000690 if (TheCall->getNumArgs() < 1) {
691 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
692 << 0 << 1 << TheCall->getNumArgs()
693 << TheCall->getCallee()->getSourceRange();
694 return ExprError();
695 }
Mike Stump1eb44332009-09-09 15:08:12 +0000696
Chris Lattner5caa3702009-05-08 06:58:22 +0000697 // Inspect the first argument of the atomic builtin. This should always be
698 // a pointer type, whose element is an integral scalar or pointer type.
699 // Because it is a pointer type, we don't have to worry about any implicit
700 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +0000701 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +0000702 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman8c382062012-01-23 02:35:22 +0000703 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
704 if (FirstArgResult.isInvalid())
705 return ExprError();
706 FirstArg = FirstArgResult.take();
707 TheCall->setArg(0, FirstArg);
708
John McCallf85e1932011-06-15 23:02:42 +0000709 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
710 if (!pointerType) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000711 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
712 << FirstArg->getType() << FirstArg->getSourceRange();
713 return ExprError();
714 }
Mike Stump1eb44332009-09-09 15:08:12 +0000715
John McCallf85e1932011-06-15 23:02:42 +0000716 QualType ValType = pointerType->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +0000717 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +0000718 !ValType->isBlockPointerType()) {
719 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
720 << FirstArg->getType() << FirstArg->getSourceRange();
721 return ExprError();
722 }
Chris Lattner5caa3702009-05-08 06:58:22 +0000723
John McCallf85e1932011-06-15 23:02:42 +0000724 switch (ValType.getObjCLifetime()) {
725 case Qualifiers::OCL_None:
726 case Qualifiers::OCL_ExplicitNone:
727 // okay
728 break;
729
730 case Qualifiers::OCL_Weak:
731 case Qualifiers::OCL_Strong:
732 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +0000733 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCallf85e1932011-06-15 23:02:42 +0000734 << ValType << FirstArg->getSourceRange();
735 return ExprError();
736 }
737
John McCallb45ae252011-10-05 07:41:44 +0000738 // Strip any qualifiers off ValType.
739 ValType = ValType.getUnqualifiedType();
740
Chandler Carruth8d13d222010-07-18 20:54:12 +0000741 // The majority of builtins return a value, but a few have special return
742 // types, so allow them to override appropriately below.
743 QualType ResultType = ValType;
744
Chris Lattner5caa3702009-05-08 06:58:22 +0000745 // We need to figure out which concrete builtin this maps onto. For example,
746 // __sync_fetch_and_add with a 2 byte object turns into
747 // __sync_fetch_and_add_2.
748#define BUILTIN_ROW(x) \
749 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
750 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +0000751
Chris Lattner5caa3702009-05-08 06:58:22 +0000752 static const unsigned BuiltinIndices[][5] = {
753 BUILTIN_ROW(__sync_fetch_and_add),
754 BUILTIN_ROW(__sync_fetch_and_sub),
755 BUILTIN_ROW(__sync_fetch_and_or),
756 BUILTIN_ROW(__sync_fetch_and_and),
757 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +0000758
Chris Lattner5caa3702009-05-08 06:58:22 +0000759 BUILTIN_ROW(__sync_add_and_fetch),
760 BUILTIN_ROW(__sync_sub_and_fetch),
761 BUILTIN_ROW(__sync_and_and_fetch),
762 BUILTIN_ROW(__sync_or_and_fetch),
763 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +0000764
Chris Lattner5caa3702009-05-08 06:58:22 +0000765 BUILTIN_ROW(__sync_val_compare_and_swap),
766 BUILTIN_ROW(__sync_bool_compare_and_swap),
767 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner23aa9c82011-04-09 03:57:26 +0000768 BUILTIN_ROW(__sync_lock_release),
769 BUILTIN_ROW(__sync_swap)
Chris Lattner5caa3702009-05-08 06:58:22 +0000770 };
Mike Stump1eb44332009-09-09 15:08:12 +0000771#undef BUILTIN_ROW
772
Chris Lattner5caa3702009-05-08 06:58:22 +0000773 // Determine the index of the size.
774 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +0000775 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +0000776 case 1: SizeIndex = 0; break;
777 case 2: SizeIndex = 1; break;
778 case 4: SizeIndex = 2; break;
779 case 8: SizeIndex = 3; break;
780 case 16: SizeIndex = 4; break;
781 default:
Chandler Carruthd2014572010-07-09 18:59:35 +0000782 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
783 << FirstArg->getType() << FirstArg->getSourceRange();
784 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +0000785 }
Mike Stump1eb44332009-09-09 15:08:12 +0000786
Chris Lattner5caa3702009-05-08 06:58:22 +0000787 // Each of these builtins has one pointer argument, followed by some number of
788 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
789 // that we ignore. Find out which row of BuiltinIndices to read from as well
790 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +0000791 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +0000792 unsigned BuiltinIndex, NumFixed = 1;
793 switch (BuiltinID) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000794 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregora9766412011-11-28 16:30:08 +0000795 case Builtin::BI__sync_fetch_and_add:
796 case Builtin::BI__sync_fetch_and_add_1:
797 case Builtin::BI__sync_fetch_and_add_2:
798 case Builtin::BI__sync_fetch_and_add_4:
799 case Builtin::BI__sync_fetch_and_add_8:
800 case Builtin::BI__sync_fetch_and_add_16:
801 BuiltinIndex = 0;
802 break;
803
804 case Builtin::BI__sync_fetch_and_sub:
805 case Builtin::BI__sync_fetch_and_sub_1:
806 case Builtin::BI__sync_fetch_and_sub_2:
807 case Builtin::BI__sync_fetch_and_sub_4:
808 case Builtin::BI__sync_fetch_and_sub_8:
809 case Builtin::BI__sync_fetch_and_sub_16:
810 BuiltinIndex = 1;
811 break;
812
813 case Builtin::BI__sync_fetch_and_or:
814 case Builtin::BI__sync_fetch_and_or_1:
815 case Builtin::BI__sync_fetch_and_or_2:
816 case Builtin::BI__sync_fetch_and_or_4:
817 case Builtin::BI__sync_fetch_and_or_8:
818 case Builtin::BI__sync_fetch_and_or_16:
819 BuiltinIndex = 2;
820 break;
821
822 case Builtin::BI__sync_fetch_and_and:
823 case Builtin::BI__sync_fetch_and_and_1:
824 case Builtin::BI__sync_fetch_and_and_2:
825 case Builtin::BI__sync_fetch_and_and_4:
826 case Builtin::BI__sync_fetch_and_and_8:
827 case Builtin::BI__sync_fetch_and_and_16:
828 BuiltinIndex = 3;
829 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000830
Douglas Gregora9766412011-11-28 16:30:08 +0000831 case Builtin::BI__sync_fetch_and_xor:
832 case Builtin::BI__sync_fetch_and_xor_1:
833 case Builtin::BI__sync_fetch_and_xor_2:
834 case Builtin::BI__sync_fetch_and_xor_4:
835 case Builtin::BI__sync_fetch_and_xor_8:
836 case Builtin::BI__sync_fetch_and_xor_16:
837 BuiltinIndex = 4;
838 break;
839
840 case Builtin::BI__sync_add_and_fetch:
841 case Builtin::BI__sync_add_and_fetch_1:
842 case Builtin::BI__sync_add_and_fetch_2:
843 case Builtin::BI__sync_add_and_fetch_4:
844 case Builtin::BI__sync_add_and_fetch_8:
845 case Builtin::BI__sync_add_and_fetch_16:
846 BuiltinIndex = 5;
847 break;
848
849 case Builtin::BI__sync_sub_and_fetch:
850 case Builtin::BI__sync_sub_and_fetch_1:
851 case Builtin::BI__sync_sub_and_fetch_2:
852 case Builtin::BI__sync_sub_and_fetch_4:
853 case Builtin::BI__sync_sub_and_fetch_8:
854 case Builtin::BI__sync_sub_and_fetch_16:
855 BuiltinIndex = 6;
856 break;
857
858 case Builtin::BI__sync_and_and_fetch:
859 case Builtin::BI__sync_and_and_fetch_1:
860 case Builtin::BI__sync_and_and_fetch_2:
861 case Builtin::BI__sync_and_and_fetch_4:
862 case Builtin::BI__sync_and_and_fetch_8:
863 case Builtin::BI__sync_and_and_fetch_16:
864 BuiltinIndex = 7;
865 break;
866
867 case Builtin::BI__sync_or_and_fetch:
868 case Builtin::BI__sync_or_and_fetch_1:
869 case Builtin::BI__sync_or_and_fetch_2:
870 case Builtin::BI__sync_or_and_fetch_4:
871 case Builtin::BI__sync_or_and_fetch_8:
872 case Builtin::BI__sync_or_and_fetch_16:
873 BuiltinIndex = 8;
874 break;
875
876 case Builtin::BI__sync_xor_and_fetch:
877 case Builtin::BI__sync_xor_and_fetch_1:
878 case Builtin::BI__sync_xor_and_fetch_2:
879 case Builtin::BI__sync_xor_and_fetch_4:
880 case Builtin::BI__sync_xor_and_fetch_8:
881 case Builtin::BI__sync_xor_and_fetch_16:
882 BuiltinIndex = 9;
883 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000884
Chris Lattner5caa3702009-05-08 06:58:22 +0000885 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000886 case Builtin::BI__sync_val_compare_and_swap_1:
887 case Builtin::BI__sync_val_compare_and_swap_2:
888 case Builtin::BI__sync_val_compare_and_swap_4:
889 case Builtin::BI__sync_val_compare_and_swap_8:
890 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000891 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +0000892 NumFixed = 2;
893 break;
Douglas Gregora9766412011-11-28 16:30:08 +0000894
Chris Lattner5caa3702009-05-08 06:58:22 +0000895 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000896 case Builtin::BI__sync_bool_compare_and_swap_1:
897 case Builtin::BI__sync_bool_compare_and_swap_2:
898 case Builtin::BI__sync_bool_compare_and_swap_4:
899 case Builtin::BI__sync_bool_compare_and_swap_8:
900 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000901 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +0000902 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +0000903 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +0000904 break;
Douglas Gregora9766412011-11-28 16:30:08 +0000905
906 case Builtin::BI__sync_lock_test_and_set:
907 case Builtin::BI__sync_lock_test_and_set_1:
908 case Builtin::BI__sync_lock_test_and_set_2:
909 case Builtin::BI__sync_lock_test_and_set_4:
910 case Builtin::BI__sync_lock_test_and_set_8:
911 case Builtin::BI__sync_lock_test_and_set_16:
912 BuiltinIndex = 12;
913 break;
914
Chris Lattner5caa3702009-05-08 06:58:22 +0000915 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +0000916 case Builtin::BI__sync_lock_release_1:
917 case Builtin::BI__sync_lock_release_2:
918 case Builtin::BI__sync_lock_release_4:
919 case Builtin::BI__sync_lock_release_8:
920 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000921 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +0000922 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +0000923 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +0000924 break;
Douglas Gregora9766412011-11-28 16:30:08 +0000925
926 case Builtin::BI__sync_swap:
927 case Builtin::BI__sync_swap_1:
928 case Builtin::BI__sync_swap_2:
929 case Builtin::BI__sync_swap_4:
930 case Builtin::BI__sync_swap_8:
931 case Builtin::BI__sync_swap_16:
932 BuiltinIndex = 14;
933 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000934 }
Mike Stump1eb44332009-09-09 15:08:12 +0000935
Chris Lattner5caa3702009-05-08 06:58:22 +0000936 // Now that we know how many fixed arguments we expect, first check that we
937 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +0000938 if (TheCall->getNumArgs() < 1+NumFixed) {
939 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
940 << 0 << 1+NumFixed << TheCall->getNumArgs()
941 << TheCall->getCallee()->getSourceRange();
942 return ExprError();
943 }
Mike Stump1eb44332009-09-09 15:08:12 +0000944
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000945 // Get the decl for the concrete builtin from this, we can tell what the
946 // concrete integer type we should convert to is.
947 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
948 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
949 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
Mike Stump1eb44332009-09-09 15:08:12 +0000950 FunctionDecl *NewBuiltinDecl =
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000951 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
952 TUScope, false, DRE->getLocStart()));
Chandler Carruthd2014572010-07-09 18:59:35 +0000953
John McCallf871d0c2010-08-07 06:22:56 +0000954 // The first argument --- the pointer --- has a fixed type; we
955 // deduce the types of the rest of the arguments accordingly. Walk
956 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +0000957 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley429bb272011-04-08 18:41:53 +0000958 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +0000959
Chris Lattner5caa3702009-05-08 06:58:22 +0000960 // GCC does an implicit conversion to the pointer or integer ValType. This
961 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb45ae252011-10-05 07:41:44 +0000962 // Initialize the argument.
963 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
964 ValType, /*consume*/ false);
965 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley429bb272011-04-08 18:41:53 +0000966 if (Arg.isInvalid())
Chandler Carruthd2014572010-07-09 18:59:35 +0000967 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000968
Chris Lattner5caa3702009-05-08 06:58:22 +0000969 // Okay, we have something that *can* be converted to the right type. Check
970 // to see if there is a potentially weird extension going on here. This can
971 // happen when you do an atomic operation on something like an char* and
972 // pass in 42. The 42 gets converted to char. This is even more strange
973 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +0000974 // FIXME: Do this check.
John McCallb45ae252011-10-05 07:41:44 +0000975 TheCall->setArg(i+1, Arg.take());
Chris Lattner5caa3702009-05-08 06:58:22 +0000976 }
Mike Stump1eb44332009-09-09 15:08:12 +0000977
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +0000978 ASTContext& Context = this->getASTContext();
979
980 // Create a new DeclRefExpr to refer to the new decl.
981 DeclRefExpr* NewDRE = DeclRefExpr::Create(
982 Context,
983 DRE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000984 SourceLocation(),
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +0000985 NewBuiltinDecl,
986 DRE->getLocation(),
987 NewBuiltinDecl->getType(),
988 DRE->getValueKind());
Mike Stump1eb44332009-09-09 15:08:12 +0000989
Chris Lattner5caa3702009-05-08 06:58:22 +0000990 // Set the callee in the CallExpr.
991 // FIXME: This leaks the original parens and implicit casts.
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +0000992 ExprResult PromotedCall = UsualUnaryConversions(NewDRE);
John Wiegley429bb272011-04-08 18:41:53 +0000993 if (PromotedCall.isInvalid())
994 return ExprError();
995 TheCall->setCallee(PromotedCall.take());
Mike Stump1eb44332009-09-09 15:08:12 +0000996
Chandler Carruthdb4325b2010-07-18 07:23:17 +0000997 // Change the result type of the call to match the original value type. This
998 // is arbitrary, but the codegen for these builtins ins design to handle it
999 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +00001000 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +00001001
1002 return move(TheCallResult);
Chris Lattner5caa3702009-05-08 06:58:22 +00001003}
1004
Chris Lattner69039812009-02-18 06:01:06 +00001005/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +00001006/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +00001007/// Note: It might also make sense to do the UTF-16 conversion here (would
1008/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +00001009bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +00001010 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +00001011 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1012
Douglas Gregor5cee1192011-07-27 05:40:30 +00001013 if (!Literal || !Literal->isAscii()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001014 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1015 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001016 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +00001017 }
Mike Stump1eb44332009-09-09 15:08:12 +00001018
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001019 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001020 StringRef String = Literal->getString();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001021 unsigned NumBytes = String.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001022 SmallVector<UTF16, 128> ToBuf(NumBytes);
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001023 const UTF8 *FromPtr = (UTF8 *)String.data();
1024 UTF16 *ToPtr = &ToBuf[0];
1025
1026 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1027 &ToPtr, ToPtr + NumBytes,
1028 strictConversion);
1029 // Check for conversion failure.
1030 if (Result != conversionOK)
1031 Diag(Arg->getLocStart(),
1032 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1033 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001034 return false;
Chris Lattner59907c42007-08-10 20:18:51 +00001035}
1036
Chris Lattnerc27c6652007-12-20 00:05:45 +00001037/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1038/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +00001039bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1040 Expr *Fn = TheCall->getCallee();
1041 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +00001042 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001043 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001044 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1045 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +00001046 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001047 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +00001048 return true;
1049 }
Eli Friedman56f20ae2008-12-15 22:05:35 +00001050
1051 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +00001052 return Diag(TheCall->getLocEnd(),
1053 diag::err_typecheck_call_too_few_args_at_least)
1054 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +00001055 }
1056
John McCall5f8d6042011-08-27 01:09:30 +00001057 // Type-check the first argument normally.
1058 if (checkBuiltinArgument(*this, TheCall, 0))
1059 return true;
1060
Chris Lattnerc27c6652007-12-20 00:05:45 +00001061 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001062 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +00001063 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001064 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +00001065 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +00001066 else if (FunctionDecl *FD = getCurFunctionDecl())
1067 isVariadic = FD->isVariadic();
1068 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001069 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +00001070
Chris Lattnerc27c6652007-12-20 00:05:45 +00001071 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001072 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1073 return true;
1074 }
Mike Stump1eb44332009-09-09 15:08:12 +00001075
Chris Lattner30ce3442007-12-19 23:59:04 +00001076 // Verify that the second argument to the builtin is the last argument of the
1077 // current function or method.
1078 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +00001079 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001080
Anders Carlsson88cf2262008-02-11 04:20:54 +00001081 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1082 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001083 // FIXME: This isn't correct for methods (results in bogus warning).
1084 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +00001085 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001086 if (CurBlock)
1087 LastArg = *(CurBlock->TheDecl->param_end()-1);
1088 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +00001089 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001090 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001091 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001092 SecondArgIsLastNamedArgument = PV == LastArg;
1093 }
1094 }
Mike Stump1eb44332009-09-09 15:08:12 +00001095
Chris Lattner30ce3442007-12-19 23:59:04 +00001096 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001097 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +00001098 diag::warn_second_parameter_of_va_start_not_last_named_argument);
1099 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +00001100}
Chris Lattner30ce3442007-12-19 23:59:04 +00001101
Chris Lattner1b9a0792007-12-20 00:26:33 +00001102/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1103/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +00001104bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1105 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +00001106 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001107 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +00001108 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +00001109 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001110 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001111 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001112 << SourceRange(TheCall->getArg(2)->getLocStart(),
1113 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001114
John Wiegley429bb272011-04-08 18:41:53 +00001115 ExprResult OrigArg0 = TheCall->getArg(0);
1116 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +00001117
Chris Lattner1b9a0792007-12-20 00:26:33 +00001118 // Do standard promotions between the two arguments, returning their common
1119 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +00001120 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley429bb272011-04-08 18:41:53 +00001121 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1122 return true;
Daniel Dunbar403bc2b2009-02-19 19:28:43 +00001123
1124 // Make sure any conversions are pushed back into the call; this is
1125 // type safe since unordered compare builtins are declared as "_Bool
1126 // foo(...)".
John Wiegley429bb272011-04-08 18:41:53 +00001127 TheCall->setArg(0, OrigArg0.get());
1128 TheCall->setArg(1, OrigArg1.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001129
John Wiegley429bb272011-04-08 18:41:53 +00001130 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorcde01732009-05-19 22:10:17 +00001131 return false;
1132
Chris Lattner1b9a0792007-12-20 00:26:33 +00001133 // If the common type isn't a real floating type, then the arguments were
1134 // invalid for this operation.
1135 if (!Res->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +00001136 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001137 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley429bb272011-04-08 18:41:53 +00001138 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1139 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001140
Chris Lattner1b9a0792007-12-20 00:26:33 +00001141 return false;
1142}
1143
Benjamin Kramere771a7a2010-02-15 22:42:31 +00001144/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1145/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001146/// to check everything. We expect the last argument to be a floating point
1147/// value.
1148bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1149 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +00001150 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001151 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001152 if (TheCall->getNumArgs() > NumArgs)
1153 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001154 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001155 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001156 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001157 (*(TheCall->arg_end()-1))->getLocEnd());
1158
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001159 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001160
Eli Friedman9ac6f622009-08-31 20:06:00 +00001161 if (OrigArg->isTypeDependent())
1162 return false;
1163
Chris Lattner81368fb2010-05-06 05:50:07 +00001164 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +00001165 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +00001166 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001167 diag::err_typecheck_call_invalid_unary_fp)
1168 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001169
Chris Lattner81368fb2010-05-06 05:50:07 +00001170 // If this is an implicit conversion from float -> double, remove it.
1171 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1172 Expr *CastArg = Cast->getSubExpr();
1173 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1174 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1175 "promotion from float to double is the only expected cast here");
1176 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +00001177 TheCall->setArg(NumArgs-1, CastArg);
1178 OrigArg = CastArg;
1179 }
1180 }
1181
Eli Friedman9ac6f622009-08-31 20:06:00 +00001182 return false;
1183}
1184
Eli Friedmand38617c2008-05-14 19:38:39 +00001185/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1186// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +00001187ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001188 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001189 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +00001190 diag::err_typecheck_call_too_few_args_at_least)
Nate Begeman37b6a572010-06-08 00:16:34 +00001191 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherd77b9a22010-04-16 04:48:22 +00001192 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001193
Nate Begeman37b6a572010-06-08 00:16:34 +00001194 // Determine which of the following types of shufflevector we're checking:
1195 // 1) unary, vector mask: (lhs, mask)
1196 // 2) binary, vector mask: (lhs, rhs, mask)
1197 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1198 QualType resType = TheCall->getArg(0)->getType();
1199 unsigned numElements = 0;
1200
Douglas Gregorcde01732009-05-19 22:10:17 +00001201 if (!TheCall->getArg(0)->isTypeDependent() &&
1202 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001203 QualType LHSType = TheCall->getArg(0)->getType();
1204 QualType RHSType = TheCall->getArg(1)->getType();
1205
1206 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001207 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001208 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001209 TheCall->getArg(1)->getLocEnd());
1210 return ExprError();
1211 }
Nate Begeman37b6a572010-06-08 00:16:34 +00001212
1213 numElements = LHSType->getAs<VectorType>()->getNumElements();
1214 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +00001215
Nate Begeman37b6a572010-06-08 00:16:34 +00001216 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1217 // with mask. If so, verify that RHS is an integer vector type with the
1218 // same number of elts as lhs.
1219 if (TheCall->getNumArgs() == 2) {
Douglas Gregorf6094622010-07-23 15:58:24 +00001220 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +00001221 RHSType->getAs<VectorType>()->getNumElements() != numElements)
1222 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
1223 << SourceRange(TheCall->getArg(1)->getLocStart(),
1224 TheCall->getArg(1)->getLocEnd());
1225 numResElements = numElements;
1226 }
1227 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001228 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001229 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001230 TheCall->getArg(1)->getLocEnd());
1231 return ExprError();
Nate Begeman37b6a572010-06-08 00:16:34 +00001232 } else if (numElements != numResElements) {
1233 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +00001234 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001235 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +00001236 }
Eli Friedmand38617c2008-05-14 19:38:39 +00001237 }
1238
1239 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001240 if (TheCall->getArg(i)->isTypeDependent() ||
1241 TheCall->getArg(i)->isValueDependent())
1242 continue;
1243
Nate Begeman37b6a572010-06-08 00:16:34 +00001244 llvm::APSInt Result(32);
1245 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1246 return ExprError(Diag(TheCall->getLocStart(),
1247 diag::err_shufflevector_nonconstant_argument)
1248 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001249
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001250 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001251 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001252 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001253 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001254 }
1255
Chris Lattner5f9e2722011-07-23 10:55:15 +00001256 SmallVector<Expr*, 32> exprs;
Eli Friedmand38617c2008-05-14 19:38:39 +00001257
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001258 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +00001259 exprs.push_back(TheCall->getArg(i));
1260 TheCall->setArg(i, 0);
1261 }
1262
Nate Begemana88dc302009-08-12 02:10:25 +00001263 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
Nate Begeman37b6a572010-06-08 00:16:34 +00001264 exprs.size(), resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001265 TheCall->getCallee()->getLocStart(),
1266 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +00001267}
Chris Lattner30ce3442007-12-19 23:59:04 +00001268
Daniel Dunbar4493f792008-07-21 22:59:13 +00001269/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1270// This is declared to take (const void*, ...) and can take two
1271// optional constant int args.
1272bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001273 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001274
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001275 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +00001276 return Diag(TheCall->getLocEnd(),
1277 diag::err_typecheck_call_too_many_args_at_most)
1278 << 0 /*function call*/ << 3 << NumArgs
1279 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001280
1281 // Argument 0 is checked for us and the remaining arguments must be
1282 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001283 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +00001284 Expr *Arg = TheCall->getArg(i);
Eric Christopher691ebc32010-04-17 02:26:23 +00001285
Eli Friedman9aef7262009-12-04 00:30:06 +00001286 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +00001287 if (SemaBuiltinConstantArg(TheCall, i, Result))
1288 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001289
Daniel Dunbar4493f792008-07-21 22:59:13 +00001290 // FIXME: gcc issues a warning and rewrites these to 0. These
1291 // seems especially odd for the third argument since the default
1292 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001293 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +00001294 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001295 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001296 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001297 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +00001298 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001299 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001300 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001301 }
1302 }
1303
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001304 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +00001305}
1306
Eric Christopher691ebc32010-04-17 02:26:23 +00001307/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1308/// TheCall is a constant expression.
1309bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1310 llvm::APSInt &Result) {
1311 Expr *Arg = TheCall->getArg(ArgNum);
1312 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1313 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1314
1315 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1316
1317 if (!Arg->isIntegerConstantExpr(Result, Context))
1318 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +00001319 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +00001320
Chris Lattner21fb98e2009-09-23 06:06:36 +00001321 return false;
1322}
1323
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001324/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1325/// int type). This simply type checks that type is one of the defined
1326/// constants (0-3).
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001327// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001328bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +00001329 llvm::APSInt Result;
1330
1331 // Check constant-ness first.
1332 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1333 return true;
1334
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001335 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001336 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001337 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1338 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001339 }
1340
1341 return false;
1342}
1343
Eli Friedman586d6a82009-05-03 06:04:26 +00001344/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +00001345/// This checks that val is a constant 1.
1346bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1347 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +00001348 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +00001349
Eric Christopher691ebc32010-04-17 02:26:23 +00001350 // TODO: This is less than ideal. Overload this to take a value.
1351 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1352 return true;
1353
1354 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +00001355 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1356 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1357
1358 return false;
1359}
1360
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001361// Handle i > 1 ? "x" : "y", recursively.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001362bool Sema::SemaCheckStringLiteral(const Expr *E, Expr **Args,
1363 unsigned NumArgs, bool HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00001364 unsigned format_idx, unsigned firstDataArg,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001365 FormatStringType Type, bool inFunctionCall) {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001366 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +00001367 if (E->isTypeDependent() || E->isValueDependent())
1368 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001369
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001370 E = E->IgnoreParenCasts();
Peter Collingbournef111d932011-04-15 00:35:48 +00001371
David Blaikiea73cdcb2012-02-10 21:07:25 +00001372 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
1373 // Technically -Wformat-nonliteral does not warn about this case.
1374 // The behavior of printf and friends in this case is implementation
1375 // dependent. Ideally if the format string cannot be null then
1376 // it should have a 'nonnull' attribute in the function prototype.
1377 return true;
1378
Ted Kremenekd30ef872009-01-12 23:09:09 +00001379 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +00001380 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +00001381 case Stmt::ConditionalOperatorClass: {
John McCall56ca35d2011-02-17 10:25:35 +00001382 const AbstractConditionalOperator *C = cast<AbstractConditionalOperator>(E);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001383 return SemaCheckStringLiteral(C->getTrueExpr(), Args, NumArgs, HasVAListArg,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001384 format_idx, firstDataArg, Type,
Richard Trieu55733de2011-10-28 00:41:25 +00001385 inFunctionCall)
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001386 && SemaCheckStringLiteral(C->getFalseExpr(), Args, NumArgs, HasVAListArg,
1387 format_idx, firstDataArg, Type,
1388 inFunctionCall);
Ted Kremenekd30ef872009-01-12 23:09:09 +00001389 }
1390
1391 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001392 E = cast<ImplicitCastExpr>(E)->getSubExpr();
1393 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001394 }
1395
John McCall56ca35d2011-02-17 10:25:35 +00001396 case Stmt::OpaqueValueExprClass:
1397 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
1398 E = src;
1399 goto tryAgain;
1400 }
1401 return false;
1402
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001403 case Stmt::PredefinedExprClass:
1404 // While __func__, etc., are technically not string literals, they
1405 // cannot contain format specifiers and thus are not a security
1406 // liability.
1407 return true;
1408
Ted Kremenek082d9362009-03-20 21:35:28 +00001409 case Stmt::DeclRefExprClass: {
1410 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001411
Ted Kremenek082d9362009-03-20 21:35:28 +00001412 // As an exception, do not flag errors for variables binding to
1413 // const string literals.
1414 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1415 bool isConstant = false;
1416 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001417
Ted Kremenek082d9362009-03-20 21:35:28 +00001418 if (const ArrayType *AT = Context.getAsArrayType(T)) {
1419 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001420 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001421 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +00001422 PT->getPointeeType().isConstant(Context);
Jean-Daniel Dupase98e5b52012-01-25 10:35:33 +00001423 } else if (T->isObjCObjectPointerType()) {
1424 // In ObjC, there is usually no "const ObjectPointer" type,
1425 // so don't check if the pointee type is constant.
1426 isConstant = T.isConstant(Context);
Ted Kremenek082d9362009-03-20 21:35:28 +00001427 }
Mike Stump1eb44332009-09-09 15:08:12 +00001428
Ted Kremenek082d9362009-03-20 21:35:28 +00001429 if (isConstant) {
Sebastian Redl31310a22010-02-01 20:16:42 +00001430 if (const Expr *Init = VD->getAnyInitializer())
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001431 return SemaCheckStringLiteral(Init, Args, NumArgs,
Ted Kremenek826a3452010-07-16 02:11:22 +00001432 HasVAListArg, format_idx, firstDataArg,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001433 Type, /*inFunctionCall*/false);
Ted Kremenek082d9362009-03-20 21:35:28 +00001434 }
Mike Stump1eb44332009-09-09 15:08:12 +00001435
Anders Carlssond966a552009-06-28 19:55:58 +00001436 // For vprintf* functions (i.e., HasVAListArg==true), we add a
1437 // special check to see if the format string is a function parameter
1438 // of the function calling the printf function. If the function
1439 // has an attribute indicating it is a printf-like function, then we
1440 // should suppress warnings concerning non-literals being used in a call
1441 // to a vprintf function. For example:
1442 //
1443 // void
1444 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
1445 // va_list ap;
1446 // va_start(ap, fmt);
1447 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
1448 // ...
1449 //
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00001450 if (HasVAListArg) {
1451 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
1452 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
1453 int PVIndex = PV->getFunctionScopeIndex() + 1;
1454 for (specific_attr_iterator<FormatAttr>
1455 i = ND->specific_attr_begin<FormatAttr>(),
1456 e = ND->specific_attr_end<FormatAttr>(); i != e ; ++i) {
1457 FormatAttr *PVFormat = *i;
1458 // adjust for implicit parameter
1459 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
1460 if (MD->isInstance())
1461 ++PVIndex;
1462 // We also check if the formats are compatible.
1463 // We can't pass a 'scanf' string to a 'printf' function.
1464 if (PVIndex == PVFormat->getFormatIdx() &&
1465 Type == GetFormatStringType(PVFormat))
1466 return true;
1467 }
1468 }
1469 }
1470 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001471 }
Mike Stump1eb44332009-09-09 15:08:12 +00001472
Ted Kremenek082d9362009-03-20 21:35:28 +00001473 return false;
1474 }
Ted Kremenekd30ef872009-01-12 23:09:09 +00001475
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001476 case Stmt::CallExprClass:
1477 case Stmt::CXXMemberCallExprClass: {
Anders Carlsson8f031b32009-06-27 04:05:33 +00001478 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001479 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
1480 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
1481 unsigned ArgIndex = FA->getFormatIdx();
1482 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
1483 if (MD->isInstance())
1484 --ArgIndex;
1485 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001486
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001487 return SemaCheckStringLiteral(Arg, Args, NumArgs, HasVAListArg,
1488 format_idx, firstDataArg, Type,
1489 inFunctionCall);
Anders Carlsson8f031b32009-06-27 04:05:33 +00001490 }
1491 }
Mike Stump1eb44332009-09-09 15:08:12 +00001492
Anders Carlsson8f031b32009-06-27 04:05:33 +00001493 return false;
1494 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001495 case Stmt::ObjCStringLiteralClass:
1496 case Stmt::StringLiteralClass: {
1497 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001498
Ted Kremenek082d9362009-03-20 21:35:28 +00001499 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00001500 StrE = ObjCFExpr->getString();
1501 else
Ted Kremenek082d9362009-03-20 21:35:28 +00001502 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001503
Ted Kremenekd30ef872009-01-12 23:09:09 +00001504 if (StrE) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001505 CheckFormatString(StrE, E, Args, NumArgs, HasVAListArg, format_idx,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001506 firstDataArg, Type, inFunctionCall);
Ted Kremenekd30ef872009-01-12 23:09:09 +00001507 return true;
1508 }
Mike Stump1eb44332009-09-09 15:08:12 +00001509
Ted Kremenekd30ef872009-01-12 23:09:09 +00001510 return false;
1511 }
Mike Stump1eb44332009-09-09 15:08:12 +00001512
Ted Kremenek082d9362009-03-20 21:35:28 +00001513 default:
1514 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001515 }
1516}
1517
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001518void
Mike Stump1eb44332009-09-09 15:08:12 +00001519Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewycky909a70d2011-03-25 01:44:32 +00001520 const Expr * const *ExprArgs,
1521 SourceLocation CallSiteLoc) {
Sean Huntcf807c42010-08-18 23:23:40 +00001522 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1523 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001524 i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +00001525 const Expr *ArgExpr = ExprArgs[*i];
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001526 if (ArgExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00001527 Expr::NPC_ValueDependentIsNotNull))
Nick Lewycky909a70d2011-03-25 01:44:32 +00001528 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001529 }
1530}
Ted Kremenekd30ef872009-01-12 23:09:09 +00001531
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001532Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
1533 return llvm::StringSwitch<FormatStringType>(Format->getType())
1534 .Case("scanf", FST_Scanf)
1535 .Cases("printf", "printf0", FST_Printf)
1536 .Cases("NSString", "CFString", FST_NSString)
1537 .Case("strftime", FST_Strftime)
1538 .Case("strfmon", FST_Strfmon)
1539 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
1540 .Default(FST_Unknown);
1541}
1542
Ted Kremenek826a3452010-07-16 02:11:22 +00001543/// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar
1544/// functions) for correct use of format strings.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001545void Sema::CheckFormatArguments(const FormatAttr *Format, CallExpr *TheCall) {
1546 bool IsCXXMember = false;
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001547 // The way the format attribute works in GCC, the implicit this argument
1548 // of member functions is counted. However, it doesn't appear in our own
1549 // lists, so decrement format_idx in that case.
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001550 IsCXXMember = isa<CXXMemberCallExpr>(TheCall);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001551 CheckFormatArguments(Format, TheCall->getArgs(), TheCall->getNumArgs(),
1552 IsCXXMember, TheCall->getRParenLoc(),
1553 TheCall->getCallee()->getSourceRange());
1554}
1555
1556void Sema::CheckFormatArguments(const FormatAttr *Format, Expr **Args,
1557 unsigned NumArgs, bool IsCXXMember,
1558 SourceLocation Loc, SourceRange Range) {
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001559 bool HasVAListArg = Format->getFirstArg() == 0;
1560 unsigned format_idx = Format->getFormatIdx() - 1;
1561 unsigned firstDataArg = HasVAListArg ? 0 : Format->getFirstArg() - 1;
1562 if (IsCXXMember) {
1563 if (format_idx == 0)
1564 return;
1565 --format_idx;
1566 if(firstDataArg != 0)
1567 --firstDataArg;
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001568 }
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001569 CheckFormatArguments(Args, NumArgs, HasVAListArg, format_idx,
1570 firstDataArg, GetFormatStringType(Format), Loc, Range);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001571}
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001572
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001573void Sema::CheckFormatArguments(Expr **Args, unsigned NumArgs,
1574 bool HasVAListArg, unsigned format_idx,
1575 unsigned firstDataArg, FormatStringType Type,
1576 SourceLocation Loc, SourceRange Range) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001577 // CHECK: printf/scanf-like function is called with no format string.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001578 if (format_idx >= NumArgs) {
1579 Diag(Loc, diag::warn_missing_format_string) << Range;
Ted Kremenek71895b92007-08-14 17:39:48 +00001580 return;
1581 }
Mike Stump1eb44332009-09-09 15:08:12 +00001582
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001583 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001584
Chris Lattner59907c42007-08-10 20:18:51 +00001585 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001586 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001587 // Dynamically generated format strings are difficult to
1588 // automatically vet at compile time. Requiring that format strings
1589 // are string literals: (1) permits the checking of format strings by
1590 // the compiler and thereby (2) can practically remove the source of
1591 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001592
Mike Stump1eb44332009-09-09 15:08:12 +00001593 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001594 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001595 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001596 // the same format string checking logic for both ObjC and C strings.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001597 if (SemaCheckStringLiteral(OrigFormatExpr, Args, NumArgs, HasVAListArg,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001598 format_idx, firstDataArg, Type))
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001599 return; // Literal format string found, check done!
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001600
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00001601 // Strftime is particular as it always uses a single 'time' argument,
1602 // so it is safe to pass a non-literal string.
1603 if (Type == FST_Strftime)
1604 return;
1605
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00001606 // Do not emit diag when the string param is a macro expansion and the
1607 // format is either NSString or CFString. This is a hack to prevent
1608 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
1609 // which are usually used in place of NS and CF string literals.
1610 if (Type == FST_NSString && Args[format_idx]->getLocStart().isMacroID())
1611 return;
1612
Chris Lattner655f1412009-04-29 04:59:47 +00001613 // If there are no arguments specified, warn with -Wformat-security, otherwise
1614 // warn only with -Wformat-nonliteral.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001615 if (NumArgs == format_idx+1)
1616 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001617 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00001618 << OrigFormatExpr->getSourceRange();
1619 else
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001620 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001621 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00001622 << OrigFormatExpr->getSourceRange();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001623}
Ted Kremenek71895b92007-08-14 17:39:48 +00001624
Ted Kremeneke0e53132010-01-28 23:39:18 +00001625namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00001626class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1627protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00001628 Sema &S;
1629 const StringLiteral *FExpr;
1630 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00001631 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001632 const unsigned NumDataArgs;
1633 const bool IsObjCLiteral;
1634 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00001635 const bool HasVAListArg;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001636 const Expr * const *Args;
1637 const unsigned NumArgs;
Ted Kremenek0d277352010-01-29 01:06:55 +00001638 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001639 llvm::BitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00001640 bool usesPositionalArgs;
1641 bool atFirstArg;
Richard Trieu55733de2011-10-28 00:41:25 +00001642 bool inFunctionCall;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001643public:
Ted Kremenek826a3452010-07-16 02:11:22 +00001644 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00001645 const Expr *origFormatExpr, unsigned firstDataArg,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001646 unsigned numDataArgs, bool isObjCLiteral,
Ted Kremenek0d277352010-01-29 01:06:55 +00001647 const char *beg, bool hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001648 Expr **args, unsigned numArgs,
1649 unsigned formatIdx, bool inFunctionCall)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001650 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Ted Kremenek6ee76532010-03-25 03:59:12 +00001651 FirstDataArg(firstDataArg),
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001652 NumDataArgs(numDataArgs),
Ted Kremenek0d277352010-01-29 01:06:55 +00001653 IsObjCLiteral(isObjCLiteral), Beg(beg),
1654 HasVAListArg(hasVAListArg),
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001655 Args(args), NumArgs(numArgs), FormatIdx(formatIdx),
Richard Trieu55733de2011-10-28 00:41:25 +00001656 usesPositionalArgs(false), atFirstArg(true),
1657 inFunctionCall(inFunctionCall) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001658 CoveredArgs.resize(numDataArgs);
1659 CoveredArgs.reset();
1660 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001661
Ted Kremenek07d161f2010-01-29 01:50:07 +00001662 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001663
Ted Kremenek826a3452010-07-16 02:11:22 +00001664 void HandleIncompleteSpecifier(const char *startSpecifier,
1665 unsigned specifierLen);
1666
Ted Kremenekefaff192010-02-27 01:41:03 +00001667 virtual void HandleInvalidPosition(const char *startSpecifier,
1668 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00001669 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00001670
1671 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1672
Ted Kremeneke0e53132010-01-28 23:39:18 +00001673 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001674
Richard Trieu55733de2011-10-28 00:41:25 +00001675 template <typename Range>
1676 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
1677 const Expr *ArgumentExpr,
1678 PartialDiagnostic PDiag,
1679 SourceLocation StringLoc,
1680 bool IsStringLocation, Range StringRange,
1681 FixItHint Fixit = FixItHint());
1682
Ted Kremenek826a3452010-07-16 02:11:22 +00001683protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001684 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
1685 const char *startSpec,
1686 unsigned specifierLen,
1687 const char *csStart, unsigned csLen);
Richard Trieu55733de2011-10-28 00:41:25 +00001688
1689 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
1690 const char *startSpec,
1691 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001692
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001693 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00001694 CharSourceRange getSpecifierRange(const char *startSpecifier,
1695 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001696 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001697
Ted Kremenek0d277352010-01-29 01:06:55 +00001698 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00001699
1700 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
1701 const analyze_format_string::ConversionSpecifier &CS,
1702 const char *startSpecifier, unsigned specifierLen,
1703 unsigned argIndex);
Richard Trieu55733de2011-10-28 00:41:25 +00001704
1705 template <typename Range>
1706 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
1707 bool IsStringLocation, Range StringRange,
1708 FixItHint Fixit = FixItHint());
1709
1710 void CheckPositionalAndNonpositionalArgs(
1711 const analyze_format_string::FormatSpecifier *FS);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001712};
1713}
1714
Ted Kremenek826a3452010-07-16 02:11:22 +00001715SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00001716 return OrigFormatExpr->getSourceRange();
1717}
1718
Ted Kremenek826a3452010-07-16 02:11:22 +00001719CharSourceRange CheckFormatHandler::
1720getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00001721 SourceLocation Start = getLocationOfByte(startSpecifier);
1722 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
1723
1724 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001725 End = End.getLocWithOffset(1);
Tom Care45f9b7e2010-06-21 21:21:01 +00001726
1727 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001728}
1729
Ted Kremenek826a3452010-07-16 02:11:22 +00001730SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001731 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001732}
1733
Ted Kremenek826a3452010-07-16 02:11:22 +00001734void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
1735 unsigned specifierLen){
Richard Trieu55733de2011-10-28 00:41:25 +00001736 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
1737 getLocationOfByte(startSpecifier),
1738 /*IsStringLocation*/true,
1739 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek808015a2010-01-29 03:16:21 +00001740}
1741
Ted Kremenekefaff192010-02-27 01:41:03 +00001742void
Ted Kremenek826a3452010-07-16 02:11:22 +00001743CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
1744 analyze_format_string::PositionContext p) {
Richard Trieu55733de2011-10-28 00:41:25 +00001745 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
1746 << (unsigned) p,
1747 getLocationOfByte(startPos), /*IsStringLocation*/true,
1748 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00001749}
1750
Ted Kremenek826a3452010-07-16 02:11:22 +00001751void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00001752 unsigned posLen) {
Richard Trieu55733de2011-10-28 00:41:25 +00001753 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
1754 getLocationOfByte(startPos),
1755 /*IsStringLocation*/true,
1756 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00001757}
1758
Ted Kremenek826a3452010-07-16 02:11:22 +00001759void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Ted Kremenek0c069442011-03-15 21:18:48 +00001760 if (!IsObjCLiteral) {
1761 // The presence of a null character is likely an error.
Richard Trieu55733de2011-10-28 00:41:25 +00001762 EmitFormatDiagnostic(
1763 S.PDiag(diag::warn_printf_format_string_contains_null_char),
1764 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
1765 getFormatStringRange());
Ted Kremenek0c069442011-03-15 21:18:48 +00001766 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001767}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001768
Ted Kremenek826a3452010-07-16 02:11:22 +00001769const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001770 return Args[FirstDataArg + i];
Ted Kremenek826a3452010-07-16 02:11:22 +00001771}
1772
1773void CheckFormatHandler::DoneProcessing() {
1774 // Does the number of data arguments exceed the number of
1775 // format conversions in the format string?
1776 if (!HasVAListArg) {
1777 // Find any arguments that weren't covered.
1778 CoveredArgs.flip();
1779 signed notCoveredArg = CoveredArgs.find_first();
1780 if (notCoveredArg >= 0) {
1781 assert((unsigned)notCoveredArg < NumDataArgs);
Richard Trieu55733de2011-10-28 00:41:25 +00001782 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
1783 getDataArg((unsigned) notCoveredArg)->getLocStart(),
1784 /*IsStringLocation*/false, getFormatStringRange());
Ted Kremenek826a3452010-07-16 02:11:22 +00001785 }
1786 }
1787}
1788
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001789bool
1790CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
1791 SourceLocation Loc,
1792 const char *startSpec,
1793 unsigned specifierLen,
1794 const char *csStart,
1795 unsigned csLen) {
1796
1797 bool keepGoing = true;
1798 if (argIndex < NumDataArgs) {
1799 // Consider the argument coverered, even though the specifier doesn't
1800 // make sense.
1801 CoveredArgs.set(argIndex);
1802 }
1803 else {
1804 // If argIndex exceeds the number of data arguments we
1805 // don't issue a warning because that is just a cascade of warnings (and
1806 // they may have intended '%%' anyway). We don't want to continue processing
1807 // the format string after this point, however, as we will like just get
1808 // gibberish when trying to match arguments.
1809 keepGoing = false;
1810 }
1811
Richard Trieu55733de2011-10-28 00:41:25 +00001812 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
1813 << StringRef(csStart, csLen),
1814 Loc, /*IsStringLocation*/true,
1815 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001816
1817 return keepGoing;
1818}
1819
Richard Trieu55733de2011-10-28 00:41:25 +00001820void
1821CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
1822 const char *startSpec,
1823 unsigned specifierLen) {
1824 EmitFormatDiagnostic(
1825 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
1826 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
1827}
1828
Ted Kremenek666a1972010-07-26 19:45:42 +00001829bool
1830CheckFormatHandler::CheckNumArgs(
1831 const analyze_format_string::FormatSpecifier &FS,
1832 const analyze_format_string::ConversionSpecifier &CS,
1833 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
1834
1835 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00001836 PartialDiagnostic PDiag = FS.usesPositionalArg()
1837 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
1838 << (argIndex+1) << NumDataArgs)
1839 : S.PDiag(diag::warn_printf_insufficient_data_args);
1840 EmitFormatDiagnostic(
1841 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
1842 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek666a1972010-07-26 19:45:42 +00001843 return false;
1844 }
1845 return true;
1846}
1847
Richard Trieu55733de2011-10-28 00:41:25 +00001848template<typename Range>
1849void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
1850 SourceLocation Loc,
1851 bool IsStringLocation,
1852 Range StringRange,
1853 FixItHint FixIt) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001854 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu55733de2011-10-28 00:41:25 +00001855 Loc, IsStringLocation, StringRange, FixIt);
1856}
1857
1858/// \brief If the format string is not within the funcion call, emit a note
1859/// so that the function call and string are in diagnostic messages.
1860///
1861/// \param inFunctionCall if true, the format string is within the function
1862/// call and only one diagnostic message will be produced. Otherwise, an
1863/// extra note will be emitted pointing to location of the format string.
1864///
1865/// \param ArgumentExpr the expression that is passed as the format string
1866/// argument in the function call. Used for getting locations when two
1867/// diagnostics are emitted.
1868///
1869/// \param PDiag the callee should already have provided any strings for the
1870/// diagnostic message. This function only adds locations and fixits
1871/// to diagnostics.
1872///
1873/// \param Loc primary location for diagnostic. If two diagnostics are
1874/// required, one will be at Loc and a new SourceLocation will be created for
1875/// the other one.
1876///
1877/// \param IsStringLocation if true, Loc points to the format string should be
1878/// used for the note. Otherwise, Loc points to the argument list and will
1879/// be used with PDiag.
1880///
1881/// \param StringRange some or all of the string to highlight. This is
1882/// templated so it can accept either a CharSourceRange or a SourceRange.
1883///
1884/// \param Fixit optional fix it hint for the format string.
1885template<typename Range>
1886void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
1887 const Expr *ArgumentExpr,
1888 PartialDiagnostic PDiag,
1889 SourceLocation Loc,
1890 bool IsStringLocation,
1891 Range StringRange,
1892 FixItHint FixIt) {
1893 if (InFunctionCall)
1894 S.Diag(Loc, PDiag) << StringRange << FixIt;
1895 else {
1896 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
1897 << ArgumentExpr->getSourceRange();
1898 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
1899 diag::note_format_string_defined)
1900 << StringRange << FixIt;
1901 }
1902}
1903
Ted Kremenek826a3452010-07-16 02:11:22 +00001904//===--- CHECK: Printf format string checking ------------------------------===//
1905
1906namespace {
1907class CheckPrintfHandler : public CheckFormatHandler {
1908public:
1909 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
1910 const Expr *origFormatExpr, unsigned firstDataArg,
1911 unsigned numDataArgs, bool isObjCLiteral,
1912 const char *beg, bool hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001913 Expr **Args, unsigned NumArgs,
1914 unsigned formatIdx, bool inFunctionCall)
Ted Kremenek826a3452010-07-16 02:11:22 +00001915 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1916 numDataArgs, isObjCLiteral, beg, hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001917 Args, NumArgs, formatIdx, inFunctionCall) {}
Ted Kremenek826a3452010-07-16 02:11:22 +00001918
1919
1920 bool HandleInvalidPrintfConversionSpecifier(
1921 const analyze_printf::PrintfSpecifier &FS,
1922 const char *startSpecifier,
1923 unsigned specifierLen);
1924
1925 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
1926 const char *startSpecifier,
1927 unsigned specifierLen);
1928
1929 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
1930 const char *startSpecifier, unsigned specifierLen);
1931 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
1932 const analyze_printf::OptionalAmount &Amt,
1933 unsigned type,
1934 const char *startSpecifier, unsigned specifierLen);
1935 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
1936 const analyze_printf::OptionalFlag &flag,
1937 const char *startSpecifier, unsigned specifierLen);
1938 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
1939 const analyze_printf::OptionalFlag &ignoredFlag,
1940 const analyze_printf::OptionalFlag &flag,
1941 const char *startSpecifier, unsigned specifierLen);
1942};
1943}
1944
1945bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
1946 const analyze_printf::PrintfSpecifier &FS,
1947 const char *startSpecifier,
1948 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001949 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001950 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00001951
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001952 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1953 getLocationOfByte(CS.getStart()),
1954 startSpecifier, specifierLen,
1955 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001956}
1957
Ted Kremenek826a3452010-07-16 02:11:22 +00001958bool CheckPrintfHandler::HandleAmount(
1959 const analyze_format_string::OptionalAmount &Amt,
1960 unsigned k, const char *startSpecifier,
1961 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001962
1963 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001964 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001965 unsigned argIndex = Amt.getArgIndex();
1966 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00001967 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
1968 << k,
1969 getLocationOfByte(Amt.getStart()),
1970 /*IsStringLocation*/true,
1971 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00001972 // Don't do any more checking. We will just emit
1973 // spurious errors.
1974 return false;
1975 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001976
Ted Kremenek0d277352010-01-29 01:06:55 +00001977 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00001978 // Although not in conformance with C99, we also allow the argument to be
1979 // an 'unsigned int' as that is a reasonably safe case. GCC also
1980 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001981 CoveredArgs.set(argIndex);
1982 const Expr *Arg = getDataArg(argIndex);
Ted Kremenek0d277352010-01-29 01:06:55 +00001983 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001984
1985 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
1986 assert(ATR.isValid());
1987
1988 if (!ATR.matchesType(S.Context, T)) {
Richard Trieu55733de2011-10-28 00:41:25 +00001989 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborga792aff2011-12-07 10:33:11 +00001990 << k << ATR.getRepresentativeTypeName(S.Context)
Richard Trieu55733de2011-10-28 00:41:25 +00001991 << T << Arg->getSourceRange(),
1992 getLocationOfByte(Amt.getStart()),
1993 /*IsStringLocation*/true,
1994 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00001995 // Don't do any more checking. We will just emit
1996 // spurious errors.
1997 return false;
1998 }
1999 }
2000 }
2001 return true;
2002}
Ted Kremenek0d277352010-01-29 01:06:55 +00002003
Tom Caree4ee9662010-06-17 19:00:27 +00002004void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00002005 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002006 const analyze_printf::OptionalAmount &Amt,
2007 unsigned type,
2008 const char *startSpecifier,
2009 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002010 const analyze_printf::PrintfConversionSpecifier &CS =
2011 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00002012
Richard Trieu55733de2011-10-28 00:41:25 +00002013 FixItHint fixit =
2014 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2015 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2016 Amt.getConstantLength()))
2017 : FixItHint();
2018
2019 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2020 << type << CS.toString(),
2021 getLocationOfByte(Amt.getStart()),
2022 /*IsStringLocation*/true,
2023 getSpecifierRange(startSpecifier, specifierLen),
2024 fixit);
Tom Caree4ee9662010-06-17 19:00:27 +00002025}
2026
Ted Kremenek826a3452010-07-16 02:11:22 +00002027void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002028 const analyze_printf::OptionalFlag &flag,
2029 const char *startSpecifier,
2030 unsigned specifierLen) {
2031 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002032 const analyze_printf::PrintfConversionSpecifier &CS =
2033 FS.getConversionSpecifier();
Richard Trieu55733de2011-10-28 00:41:25 +00002034 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2035 << flag.toString() << CS.toString(),
2036 getLocationOfByte(flag.getPosition()),
2037 /*IsStringLocation*/true,
2038 getSpecifierRange(startSpecifier, specifierLen),
2039 FixItHint::CreateRemoval(
2040 getSpecifierRange(flag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002041}
2042
2043void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00002044 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002045 const analyze_printf::OptionalFlag &ignoredFlag,
2046 const analyze_printf::OptionalFlag &flag,
2047 const char *startSpecifier,
2048 unsigned specifierLen) {
2049 // Warn about ignored flag with a fixit removal.
Richard Trieu55733de2011-10-28 00:41:25 +00002050 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2051 << ignoredFlag.toString() << flag.toString(),
2052 getLocationOfByte(ignoredFlag.getPosition()),
2053 /*IsStringLocation*/true,
2054 getSpecifierRange(startSpecifier, specifierLen),
2055 FixItHint::CreateRemoval(
2056 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002057}
2058
Ted Kremeneke0e53132010-01-28 23:39:18 +00002059bool
Ted Kremenek826a3452010-07-16 02:11:22 +00002060CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00002061 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00002062 const char *startSpecifier,
2063 unsigned specifierLen) {
2064
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002065 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00002066 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002067 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00002068
Ted Kremenekbaa40062010-07-19 22:01:06 +00002069 if (FS.consumesDataArgument()) {
2070 if (atFirstArg) {
2071 atFirstArg = false;
2072 usesPositionalArgs = FS.usesPositionalArg();
2073 }
2074 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002075 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2076 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002077 return false;
2078 }
Ted Kremenek0d277352010-01-29 01:06:55 +00002079 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002080
Ted Kremenekefaff192010-02-27 01:41:03 +00002081 // First check if the field width, precision, and conversion specifier
2082 // have matching data arguments.
2083 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2084 startSpecifier, specifierLen)) {
2085 return false;
2086 }
2087
2088 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2089 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002090 return false;
2091 }
2092
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002093 if (!CS.consumesDataArgument()) {
2094 // FIXME: Technically specifying a precision or field width here
2095 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002096 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002097 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002098
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002099 // Consume the argument.
2100 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00002101 if (argIndex < NumDataArgs) {
2102 // The check to see if the argIndex is valid will come later.
2103 // We set the bit here because we may exit early from this
2104 // function if we encounter some other error.
2105 CoveredArgs.set(argIndex);
2106 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002107
2108 // Check for using an Objective-C specific conversion specifier
2109 // in a non-ObjC literal.
2110 if (!IsObjCLiteral && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002111 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
2112 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002113 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002114
Tom Caree4ee9662010-06-17 19:00:27 +00002115 // Check for invalid use of field width
2116 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002117 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00002118 startSpecifier, specifierLen);
2119 }
2120
2121 // Check for invalid use of precision
2122 if (!FS.hasValidPrecision()) {
2123 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
2124 startSpecifier, specifierLen);
2125 }
2126
2127 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00002128 if (!FS.hasValidThousandsGroupingPrefix())
2129 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002130 if (!FS.hasValidLeadingZeros())
2131 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
2132 if (!FS.hasValidPlusPrefix())
2133 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00002134 if (!FS.hasValidSpacePrefix())
2135 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002136 if (!FS.hasValidAlternativeForm())
2137 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
2138 if (!FS.hasValidLeftJustified())
2139 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
2140
2141 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00002142 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
2143 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
2144 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002145 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
2146 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
2147 startSpecifier, specifierLen);
2148
2149 // Check the length modifier is valid with the given conversion specifier.
2150 const LengthModifier &LM = FS.getLengthModifier();
2151 if (!FS.hasValidLengthModifier())
Richard Trieu55733de2011-10-28 00:41:25 +00002152 EmitFormatDiagnostic(S.PDiag(diag::warn_format_nonsensical_length)
2153 << LM.toString() << CS.toString(),
2154 getLocationOfByte(LM.getStart()),
2155 /*IsStringLocation*/true,
2156 getSpecifierRange(startSpecifier, specifierLen),
2157 FixItHint::CreateRemoval(
2158 getSpecifierRange(LM.getStart(),
2159 LM.getLength())));
Tom Caree4ee9662010-06-17 19:00:27 +00002160
2161 // Are we using '%n'?
Ted Kremenek35d353b2010-07-20 20:04:10 +00002162 if (CS.getKind() == ConversionSpecifier::nArg) {
Tom Caree4ee9662010-06-17 19:00:27 +00002163 // Issue a warning about this being a possible security issue.
Richard Trieu55733de2011-10-28 00:41:25 +00002164 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_write_back),
2165 getLocationOfByte(CS.getStart()),
2166 /*IsStringLocation*/true,
2167 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremeneke82d8042010-01-29 01:35:25 +00002168 // Continue checking the other format specifiers.
2169 return true;
2170 }
Ted Kremenek5c41ee82010-02-11 09:27:41 +00002171
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002172 // The remaining checks depend on the data arguments.
2173 if (HasVAListArg)
2174 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002175
Ted Kremenek666a1972010-07-26 19:45:42 +00002176 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002177 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002178
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002179 // Now type check the data expression that matches the
2180 // format specifier.
2181 const Expr *Ex = getDataArg(argIndex);
Nico Weber339b9072012-01-31 01:43:25 +00002182 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context,
2183 IsObjCLiteral);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002184 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
2185 // Check if we didn't match because of an implicit cast from a 'char'
2186 // or 'short' to an 'int'. This is done because printf is a varargs
2187 // function.
2188 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00002189 if (ICE->getType() == S.Context.IntTy) {
2190 // All further checking is done on the subexpression.
2191 Ex = ICE->getSubExpr();
2192 if (ATR.matchesType(S.Context, Ex->getType()))
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002193 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00002194 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002195
2196 // We may be able to offer a FixItHint if it is a supported type.
2197 PrintfSpecifier fixedFS = FS;
Hans Wennborgbe6126a2012-02-15 09:59:46 +00002198 bool success = fixedFS.fixType(Ex->getType(), S.getLangOptions(),
2199 S.Context, IsObjCLiteral);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002200
2201 if (success) {
2202 // Get the fix string from the fixed format specifier
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002203 SmallString<128> buf;
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002204 llvm::raw_svector_ostream os(buf);
2205 fixedFS.toString(os);
2206
Richard Trieu55733de2011-10-28 00:41:25 +00002207 EmitFormatDiagnostic(
2208 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborga792aff2011-12-07 10:33:11 +00002209 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
Richard Trieu55733de2011-10-28 00:41:25 +00002210 << Ex->getSourceRange(),
2211 getLocationOfByte(CS.getStart()),
2212 /*IsStringLocation*/true,
2213 getSpecifierRange(startSpecifier, specifierLen),
2214 FixItHint::CreateReplacement(
2215 getSpecifierRange(startSpecifier, specifierLen),
2216 os.str()));
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002217 }
2218 else {
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00002219 EmitFormatDiagnostic(
2220 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2221 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
2222 << getSpecifierRange(startSpecifier, specifierLen)
2223 << Ex->getSourceRange(),
2224 getLocationOfByte(CS.getStart()),
2225 true,
2226 getSpecifierRange(startSpecifier, specifierLen));
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002227 }
2228 }
2229
Ted Kremeneke0e53132010-01-28 23:39:18 +00002230 return true;
2231}
2232
Ted Kremenek826a3452010-07-16 02:11:22 +00002233//===--- CHECK: Scanf format string checking ------------------------------===//
2234
2235namespace {
2236class CheckScanfHandler : public CheckFormatHandler {
2237public:
2238 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
2239 const Expr *origFormatExpr, unsigned firstDataArg,
2240 unsigned numDataArgs, bool isObjCLiteral,
2241 const char *beg, bool hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002242 Expr **Args, unsigned NumArgs,
2243 unsigned formatIdx, bool inFunctionCall)
Ted Kremenek826a3452010-07-16 02:11:22 +00002244 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2245 numDataArgs, isObjCLiteral, beg, hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002246 Args, NumArgs, formatIdx, inFunctionCall) {}
Ted Kremenek826a3452010-07-16 02:11:22 +00002247
2248 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
2249 const char *startSpecifier,
2250 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002251
2252 bool HandleInvalidScanfConversionSpecifier(
2253 const analyze_scanf::ScanfSpecifier &FS,
2254 const char *startSpecifier,
2255 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00002256
2257 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00002258};
Ted Kremenek07d161f2010-01-29 01:50:07 +00002259}
Ted Kremeneke0e53132010-01-28 23:39:18 +00002260
Ted Kremenekb7c21012010-07-16 18:28:03 +00002261void CheckScanfHandler::HandleIncompleteScanList(const char *start,
2262 const char *end) {
Richard Trieu55733de2011-10-28 00:41:25 +00002263 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
2264 getLocationOfByte(end), /*IsStringLocation*/true,
2265 getSpecifierRange(start, end - start));
Ted Kremenekb7c21012010-07-16 18:28:03 +00002266}
2267
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002268bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
2269 const analyze_scanf::ScanfSpecifier &FS,
2270 const char *startSpecifier,
2271 unsigned specifierLen) {
2272
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002273 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002274 FS.getConversionSpecifier();
2275
2276 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2277 getLocationOfByte(CS.getStart()),
2278 startSpecifier, specifierLen,
2279 CS.getStart(), CS.getLength());
2280}
2281
Ted Kremenek826a3452010-07-16 02:11:22 +00002282bool CheckScanfHandler::HandleScanfSpecifier(
2283 const analyze_scanf::ScanfSpecifier &FS,
2284 const char *startSpecifier,
2285 unsigned specifierLen) {
2286
2287 using namespace analyze_scanf;
2288 using namespace analyze_format_string;
2289
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002290 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002291
Ted Kremenekbaa40062010-07-19 22:01:06 +00002292 // Handle case where '%' and '*' don't consume an argument. These shouldn't
2293 // be used to decide if we are using positional arguments consistently.
2294 if (FS.consumesDataArgument()) {
2295 if (atFirstArg) {
2296 atFirstArg = false;
2297 usesPositionalArgs = FS.usesPositionalArg();
2298 }
2299 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002300 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2301 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002302 return false;
2303 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002304 }
2305
2306 // Check if the field with is non-zero.
2307 const OptionalAmount &Amt = FS.getFieldWidth();
2308 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
2309 if (Amt.getConstantAmount() == 0) {
2310 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
2311 Amt.getConstantLength());
Richard Trieu55733de2011-10-28 00:41:25 +00002312 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
2313 getLocationOfByte(Amt.getStart()),
2314 /*IsStringLocation*/true, R,
2315 FixItHint::CreateRemoval(R));
Ted Kremenek826a3452010-07-16 02:11:22 +00002316 }
2317 }
2318
2319 if (!FS.consumesDataArgument()) {
2320 // FIXME: Technically specifying a precision or field width here
2321 // makes no sense. Worth issuing a warning at some point.
2322 return true;
2323 }
2324
2325 // Consume the argument.
2326 unsigned argIndex = FS.getArgIndex();
2327 if (argIndex < NumDataArgs) {
2328 // The check to see if the argIndex is valid will come later.
2329 // We set the bit here because we may exit early from this
2330 // function if we encounter some other error.
2331 CoveredArgs.set(argIndex);
2332 }
2333
Ted Kremenek1e51c202010-07-20 20:04:47 +00002334 // Check the length modifier is valid with the given conversion specifier.
2335 const LengthModifier &LM = FS.getLengthModifier();
2336 if (!FS.hasValidLengthModifier()) {
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00002337 const CharSourceRange &R = getSpecifierRange(LM.getStart(), LM.getLength());
2338 EmitFormatDiagnostic(S.PDiag(diag::warn_format_nonsensical_length)
2339 << LM.toString() << CS.toString()
2340 << getSpecifierRange(startSpecifier, specifierLen),
2341 getLocationOfByte(LM.getStart()),
2342 /*IsStringLocation*/true, R,
2343 FixItHint::CreateRemoval(R));
Ted Kremenek1e51c202010-07-20 20:04:47 +00002344 }
2345
Ted Kremenek826a3452010-07-16 02:11:22 +00002346 // The remaining checks depend on the data arguments.
2347 if (HasVAListArg)
2348 return true;
2349
Ted Kremenek666a1972010-07-26 19:45:42 +00002350 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00002351 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00002352
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002353 // Check that the argument type matches the format specifier.
2354 const Expr *Ex = getDataArg(argIndex);
2355 const analyze_scanf::ScanfArgTypeResult &ATR = FS.getArgType(S.Context);
2356 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
2357 ScanfSpecifier fixedFS = FS;
Hans Wennborgbe6126a2012-02-15 09:59:46 +00002358 bool success = fixedFS.fixType(Ex->getType(), S.getLangOptions(),
2359 S.Context);
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002360
2361 if (success) {
2362 // Get the fix string from the fixed format specifier.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002363 SmallString<128> buf;
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002364 llvm::raw_svector_ostream os(buf);
2365 fixedFS.toString(os);
2366
2367 EmitFormatDiagnostic(
2368 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2369 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
2370 << Ex->getSourceRange(),
2371 getLocationOfByte(CS.getStart()),
2372 /*IsStringLocation*/true,
2373 getSpecifierRange(startSpecifier, specifierLen),
2374 FixItHint::CreateReplacement(
2375 getSpecifierRange(startSpecifier, specifierLen),
2376 os.str()));
2377 } else {
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00002378 EmitFormatDiagnostic(
2379 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002380 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00002381 << Ex->getSourceRange(),
2382 getLocationOfByte(CS.getStart()),
2383 /*IsStringLocation*/true,
2384 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002385 }
2386 }
2387
Ted Kremenek826a3452010-07-16 02:11:22 +00002388 return true;
2389}
2390
2391void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002392 const Expr *OrigFormatExpr,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002393 Expr **Args, unsigned NumArgs,
2394 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002395 unsigned firstDataArg, FormatStringType Type,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002396 bool inFunctionCall) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002397
Ted Kremeneke0e53132010-01-28 23:39:18 +00002398 // CHECK: is the format string a wide literal?
Douglas Gregor5cee1192011-07-27 05:40:30 +00002399 if (!FExpr->isAscii()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002400 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002401 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00002402 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
2403 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00002404 return;
2405 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002406
Ted Kremeneke0e53132010-01-28 23:39:18 +00002407 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner5f9e2722011-07-23 10:55:15 +00002408 StringRef StrRef = FExpr->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00002409 const char *Str = StrRef.data();
2410 unsigned StrLen = StrRef.size();
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002411 const unsigned numDataArgs = NumArgs - firstDataArg;
Ted Kremenek826a3452010-07-16 02:11:22 +00002412
Ted Kremeneke0e53132010-01-28 23:39:18 +00002413 // CHECK: empty format string?
Ted Kremenek4cd57912011-09-29 05:52:16 +00002414 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu55733de2011-10-28 00:41:25 +00002415 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002416 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00002417 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
2418 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00002419 return;
2420 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002421
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002422 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002423 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Ted Kremenek4cd57912011-09-29 05:52:16 +00002424 numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr),
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002425 Str, HasVAListArg, Args, NumArgs, format_idx,
Richard Trieu55733de2011-10-28 00:41:25 +00002426 inFunctionCall);
Ted Kremenek826a3452010-07-16 02:11:22 +00002427
Hans Wennborgd02deeb2011-12-15 10:25:47 +00002428 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
2429 getLangOptions()))
Ted Kremenek826a3452010-07-16 02:11:22 +00002430 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002431 } else if (Type == FST_Scanf) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002432 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Ted Kremenek4cd57912011-09-29 05:52:16 +00002433 numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr),
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002434 Str, HasVAListArg, Args, NumArgs, format_idx,
Richard Trieu55733de2011-10-28 00:41:25 +00002435 inFunctionCall);
Ted Kremenek826a3452010-07-16 02:11:22 +00002436
Hans Wennborgd02deeb2011-12-15 10:25:47 +00002437 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
2438 getLangOptions()))
Ted Kremenek826a3452010-07-16 02:11:22 +00002439 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002440 } // TODO: handle other formats
Ted Kremenekce7024e2010-01-28 01:18:22 +00002441}
2442
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002443//===--- CHECK: Standard memory functions ---------------------------------===//
2444
Douglas Gregor2a053a32011-05-03 20:05:22 +00002445/// \brief Determine whether the given type is a dynamic class type (e.g.,
2446/// whether it has a vtable).
2447static bool isDynamicClassType(QualType T) {
2448 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
2449 if (CXXRecordDecl *Definition = Record->getDefinition())
2450 if (Definition->isDynamicClass())
2451 return true;
2452
2453 return false;
2454}
2455
Chandler Carrutha72a12f2011-06-21 23:04:20 +00002456/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth000d4282011-06-16 09:09:40 +00002457/// otherwise returns NULL.
2458static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Webere4a1c642011-06-14 16:14:58 +00002459 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth000d4282011-06-16 09:09:40 +00002460 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2461 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
2462 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00002463
Chandler Carruth000d4282011-06-16 09:09:40 +00002464 return 0;
2465}
2466
Chandler Carrutha72a12f2011-06-21 23:04:20 +00002467/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth000d4282011-06-16 09:09:40 +00002468static QualType getSizeOfArgType(const Expr* E) {
2469 if (const UnaryExprOrTypeTraitExpr *SizeOf =
2470 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2471 if (SizeOf->getKind() == clang::UETT_SizeOf)
2472 return SizeOf->getTypeOfArgument();
2473
2474 return QualType();
Nico Webere4a1c642011-06-14 16:14:58 +00002475}
2476
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002477/// \brief Check for dangerous or invalid arguments to memset().
2478///
Chandler Carruth929f0132011-06-03 06:23:57 +00002479/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002480/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
2481/// function calls.
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002482///
2483/// \param Call The call expression to diagnose.
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002484void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks0a151a12012-01-17 00:37:07 +00002485 unsigned BId,
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002486 IdentifierInfo *FnName) {
Anna Zaks0a151a12012-01-17 00:37:07 +00002487 assert(BId != 0);
2488
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00002489 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor707a23e2011-06-16 17:56:04 +00002490 // we have enough arguments, and if not, abort further checking.
Anna Zaks0a151a12012-01-17 00:37:07 +00002491 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Webercda57822011-10-13 22:30:23 +00002492 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00002493 return;
2494
Anna Zaks0a151a12012-01-17 00:37:07 +00002495 unsigned LastArg = (BId == Builtin::BImemset ||
2496 BId == Builtin::BIstrndup ? 1 : 2);
2497 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Webercda57822011-10-13 22:30:23 +00002498 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth000d4282011-06-16 09:09:40 +00002499
2500 // We have special checking when the length is a sizeof expression.
2501 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
2502 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
2503 llvm::FoldingSetNodeID SizeOfArgID;
2504
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002505 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
2506 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00002507 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002508
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002509 QualType DestTy = Dest->getType();
2510 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
2511 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00002512
Chandler Carruth000d4282011-06-16 09:09:40 +00002513 // Never warn about void type pointers. This can be used to suppress
2514 // false positives.
2515 if (PointeeTy->isVoidType())
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002516 continue;
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002517
Chandler Carruth000d4282011-06-16 09:09:40 +00002518 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
2519 // actually comparing the expressions for equality. Because computing the
2520 // expression IDs can be expensive, we only do this if the diagnostic is
2521 // enabled.
2522 if (SizeOfArg &&
2523 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
2524 SizeOfArg->getExprLoc())) {
2525 // We only compute IDs for expressions if the warning is enabled, and
2526 // cache the sizeof arg's ID.
2527 if (SizeOfArgID == llvm::FoldingSetNodeID())
2528 SizeOfArg->Profile(SizeOfArgID, Context, true);
2529 llvm::FoldingSetNodeID DestID;
2530 Dest->Profile(DestID, Context, true);
2531 if (DestID == SizeOfArgID) {
Nico Webercda57822011-10-13 22:30:23 +00002532 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
2533 // over sizeof(src) as well.
Chandler Carruth000d4282011-06-16 09:09:40 +00002534 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
2535 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
2536 if (UnaryOp->getOpcode() == UO_AddrOf)
2537 ActionIdx = 1; // If its an address-of operator, just remove it.
2538 if (Context.getTypeSize(PointeeTy) == Context.getCharWidth())
2539 ActionIdx = 2; // If the pointee's size is sizeof(char),
2540 // suggest an explicit length.
Anna Zaksd9b859a2012-01-13 21:52:01 +00002541 unsigned DestSrcSelect =
Anna Zaks0a151a12012-01-17 00:37:07 +00002542 (BId == Builtin::BIstrndup ? 1 : ArgIdx);
Chandler Carruth000d4282011-06-16 09:09:40 +00002543 DiagRuntimeBehavior(SizeOfArg->getExprLoc(), Dest,
2544 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Nico Webercda57822011-10-13 22:30:23 +00002545 << FnName << DestSrcSelect << ActionIdx
Chandler Carruth000d4282011-06-16 09:09:40 +00002546 << Dest->getSourceRange()
2547 << SizeOfArg->getSourceRange());
2548 break;
2549 }
2550 }
2551
2552 // Also check for cases where the sizeof argument is the exact same
2553 // type as the memory argument, and where it points to a user-defined
2554 // record type.
2555 if (SizeOfArgTy != QualType()) {
2556 if (PointeeTy->isRecordType() &&
2557 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
2558 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
2559 PDiag(diag::warn_sizeof_pointer_type_memaccess)
2560 << FnName << SizeOfArgTy << ArgIdx
2561 << PointeeTy << Dest->getSourceRange()
2562 << LenExpr->getSourceRange());
2563 break;
2564 }
Nico Webere4a1c642011-06-14 16:14:58 +00002565 }
2566
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002567 // Always complain about dynamic classes.
Anna Zaks0a151a12012-01-17 00:37:07 +00002568 if (isDynamicClassType(PointeeTy)) {
2569
2570 unsigned OperationType = 0;
2571 // "overwritten" if we're warning about the destination for any call
2572 // but memcmp; otherwise a verb appropriate to the call.
2573 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
2574 if (BId == Builtin::BImemcpy)
2575 OperationType = 1;
2576 else if(BId == Builtin::BImemmove)
2577 OperationType = 2;
2578 else if (BId == Builtin::BImemcmp)
2579 OperationType = 3;
2580 }
2581
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00002582 DiagRuntimeBehavior(
2583 Dest->getExprLoc(), Dest,
2584 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks0a151a12012-01-17 00:37:07 +00002585 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Anna Zaksd9b859a2012-01-13 21:52:01 +00002586 << FnName << PointeeTy
Anna Zaks0a151a12012-01-17 00:37:07 +00002587 << OperationType
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00002588 << Call->getCallee()->getSourceRange());
Anna Zaks0a151a12012-01-17 00:37:07 +00002589 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
2590 BId != Builtin::BImemset)
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00002591 DiagRuntimeBehavior(
2592 Dest->getExprLoc(), Dest,
2593 PDiag(diag::warn_arc_object_memaccess)
2594 << ArgIdx << FnName << PointeeTy
2595 << Call->getCallee()->getSourceRange());
John McCallf85e1932011-06-15 23:02:42 +00002596 else
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002597 continue;
John McCallf85e1932011-06-15 23:02:42 +00002598
2599 DiagRuntimeBehavior(
2600 Dest->getExprLoc(), Dest,
Chandler Carruth929f0132011-06-03 06:23:57 +00002601 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002602 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
2603 break;
2604 }
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002605 }
2606}
2607
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002608// A little helper routine: ignore addition and subtraction of integer literals.
2609// This intentionally does not ignore all integer constant expressions because
2610// we don't want to remove sizeof().
2611static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
2612 Ex = Ex->IgnoreParenCasts();
2613
2614 for (;;) {
2615 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
2616 if (!BO || !BO->isAdditiveOp())
2617 break;
2618
2619 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
2620 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
2621
2622 if (isa<IntegerLiteral>(RHS))
2623 Ex = LHS;
2624 else if (isa<IntegerLiteral>(LHS))
2625 Ex = RHS;
2626 else
2627 break;
2628 }
2629
2630 return Ex;
2631}
2632
2633// Warn if the user has made the 'size' argument to strlcpy or strlcat
2634// be the size of the source, instead of the destination.
2635void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
2636 IdentifierInfo *FnName) {
2637
2638 // Don't crash if the user has the wrong number of arguments
2639 if (Call->getNumArgs() != 3)
2640 return;
2641
2642 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
2643 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
2644 const Expr *CompareWithSrc = NULL;
2645
2646 // Look for 'strlcpy(dst, x, sizeof(x))'
2647 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
2648 CompareWithSrc = Ex;
2649 else {
2650 // Look for 'strlcpy(dst, x, strlen(x))'
2651 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Richard Smith180f4792011-11-10 06:34:14 +00002652 if (SizeCall->isBuiltinCall() == Builtin::BIstrlen
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002653 && SizeCall->getNumArgs() == 1)
2654 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
2655 }
2656 }
2657
2658 if (!CompareWithSrc)
2659 return;
2660
2661 // Determine if the argument to sizeof/strlen is equal to the source
2662 // argument. In principle there's all kinds of things you could do
2663 // here, for instance creating an == expression and evaluating it with
2664 // EvaluateAsBooleanCondition, but this uses a more direct technique:
2665 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
2666 if (!SrcArgDRE)
2667 return;
2668
2669 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
2670 if (!CompareWithSrcDRE ||
2671 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
2672 return;
2673
2674 const Expr *OriginalSizeArg = Call->getArg(2);
2675 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
2676 << OriginalSizeArg->getSourceRange() << FnName;
2677
2678 // Output a FIXIT hint if the destination is an array (rather than a
2679 // pointer to an array). This could be enhanced to handle some
2680 // pointers if we know the actual size, like if DstArg is 'array+2'
2681 // we could say 'sizeof(array)-2'.
2682 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Ted Kremenek8f746222011-08-18 22:48:41 +00002683 QualType DstArgTy = DstArg->getType();
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002684
Ted Kremenek8f746222011-08-18 22:48:41 +00002685 // Only handle constant-sized or VLAs, but not flexible members.
2686 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(DstArgTy)) {
2687 // Only issue the FIXIT for arrays of size > 1.
2688 if (CAT->getSize().getSExtValue() <= 1)
2689 return;
2690 } else if (!DstArgTy->isVariableArrayType()) {
2691 return;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002692 }
Ted Kremenek8f746222011-08-18 22:48:41 +00002693
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002694 SmallString<128> sizeString;
Ted Kremenek8f746222011-08-18 22:48:41 +00002695 llvm::raw_svector_ostream OS(sizeString);
2696 OS << "sizeof(";
Douglas Gregor8987b232011-09-27 23:30:47 +00002697 DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
Ted Kremenek8f746222011-08-18 22:48:41 +00002698 OS << ")";
2699
2700 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
2701 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
2702 OS.str());
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002703}
2704
Anna Zaksc36bedc2012-02-01 19:08:57 +00002705/// Check if two expressions refer to the same declaration.
2706static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
2707 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
2708 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
2709 return D1->getDecl() == D2->getDecl();
2710 return false;
2711}
2712
2713static const Expr *getStrlenExprArg(const Expr *E) {
2714 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
2715 const FunctionDecl *FD = CE->getDirectCallee();
2716 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
2717 return 0;
2718 return CE->getArg(0)->IgnoreParenCasts();
2719 }
2720 return 0;
2721}
2722
2723// Warn on anti-patterns as the 'size' argument to strncat.
2724// The correct size argument should look like following:
2725// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
2726void Sema::CheckStrncatArguments(const CallExpr *CE,
2727 IdentifierInfo *FnName) {
2728 // Don't crash if the user has the wrong number of arguments.
2729 if (CE->getNumArgs() < 3)
2730 return;
2731 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
2732 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
2733 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
2734
2735 // Identify common expressions, which are wrongly used as the size argument
2736 // to strncat and may lead to buffer overflows.
2737 unsigned PatternType = 0;
2738 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
2739 // - sizeof(dst)
2740 if (referToTheSameDecl(SizeOfArg, DstArg))
2741 PatternType = 1;
2742 // - sizeof(src)
2743 else if (referToTheSameDecl(SizeOfArg, SrcArg))
2744 PatternType = 2;
2745 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
2746 if (BE->getOpcode() == BO_Sub) {
2747 const Expr *L = BE->getLHS()->IgnoreParenCasts();
2748 const Expr *R = BE->getRHS()->IgnoreParenCasts();
2749 // - sizeof(dst) - strlen(dst)
2750 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
2751 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
2752 PatternType = 1;
2753 // - sizeof(src) - (anything)
2754 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
2755 PatternType = 2;
2756 }
2757 }
2758
2759 if (PatternType == 0)
2760 return;
2761
Anna Zaksafdb0412012-02-03 01:27:37 +00002762 // Generate the diagnostic.
2763 SourceLocation SL = LenArg->getLocStart();
2764 SourceRange SR = LenArg->getSourceRange();
2765 SourceManager &SM = PP.getSourceManager();
2766
2767 // If the function is defined as a builtin macro, do not show macro expansion.
2768 if (SM.isMacroArgExpansion(SL)) {
2769 SL = SM.getSpellingLoc(SL);
2770 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
2771 SM.getSpellingLoc(SR.getEnd()));
2772 }
2773
Anna Zaksc36bedc2012-02-01 19:08:57 +00002774 if (PatternType == 1)
Anna Zaksafdb0412012-02-03 01:27:37 +00002775 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00002776 else
Anna Zaksafdb0412012-02-03 01:27:37 +00002777 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00002778
2779 // Output a FIXIT hint if the destination is an array (rather than a
2780 // pointer to an array). This could be enhanced to handle some
2781 // pointers if we know the actual size, like if DstArg is 'array+2'
2782 // we could say 'sizeof(array)-2'.
2783 QualType DstArgTy = DstArg->getType();
2784
2785 // Only handle constant-sized or VLAs, but not flexible members.
2786 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(DstArgTy)) {
2787 // Only issue the FIXIT for arrays of size > 1.
2788 if (CAT->getSize().getSExtValue() <= 1)
2789 return;
2790 } else if (!DstArgTy->isVariableArrayType()) {
2791 return;
2792 }
2793
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002794 SmallString<128> sizeString;
Anna Zaksc36bedc2012-02-01 19:08:57 +00002795 llvm::raw_svector_ostream OS(sizeString);
2796 OS << "sizeof(";
2797 DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
2798 OS << ") - ";
2799 OS << "strlen(";
2800 DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
2801 OS << ") - 1";
2802
Anna Zaksafdb0412012-02-03 01:27:37 +00002803 Diag(SL, diag::note_strncat_wrong_size)
2804 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaksc36bedc2012-02-01 19:08:57 +00002805}
2806
Ted Kremenek06de2762007-08-17 16:46:58 +00002807//===--- CHECK: Return Address of Stack Variable --------------------------===//
2808
Chris Lattner5f9e2722011-07-23 10:55:15 +00002809static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars);
2810static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002811
2812/// CheckReturnStackAddr - Check if a return statement returns the address
2813/// of a stack variable.
2814void
2815Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
2816 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00002817
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002818 Expr *stackE = 0;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002819 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002820
2821 // Perform checking for returned stack addresses, local blocks,
2822 // label addresses or references to temporaries.
John McCallf85e1932011-06-15 23:02:42 +00002823 if (lhsType->isPointerType() ||
2824 (!getLangOptions().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002825 stackE = EvalAddr(RetValExp, refVars);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002826 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002827 stackE = EvalVal(RetValExp, refVars);
2828 }
2829
2830 if (stackE == 0)
2831 return; // Nothing suspicious was found.
2832
2833 SourceLocation diagLoc;
2834 SourceRange diagRange;
2835 if (refVars.empty()) {
2836 diagLoc = stackE->getLocStart();
2837 diagRange = stackE->getSourceRange();
2838 } else {
2839 // We followed through a reference variable. 'stackE' contains the
2840 // problematic expression but we will warn at the return statement pointing
2841 // at the reference variable. We will later display the "trail" of
2842 // reference variables using notes.
2843 diagLoc = refVars[0]->getLocStart();
2844 diagRange = refVars[0]->getSourceRange();
2845 }
2846
2847 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
2848 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
2849 : diag::warn_ret_stack_addr)
2850 << DR->getDecl()->getDeclName() << diagRange;
2851 } else if (isa<BlockExpr>(stackE)) { // local block.
2852 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
2853 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
2854 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
2855 } else { // local temporary.
2856 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
2857 : diag::warn_ret_local_temp_addr)
2858 << diagRange;
2859 }
2860
2861 // Display the "trail" of reference variables that we followed until we
2862 // found the problematic expression using notes.
2863 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
2864 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
2865 // If this var binds to another reference var, show the range of the next
2866 // var, otherwise the var binds to the problematic expression, in which case
2867 // show the range of the expression.
2868 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
2869 : stackE->getSourceRange();
2870 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
2871 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00002872 }
2873}
2874
2875/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
2876/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002877/// to a location on the stack, a local block, an address of a label, or a
2878/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00002879/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002880/// encounter a subexpression that (1) clearly does not lead to one of the
2881/// above problematic expressions (2) is something we cannot determine leads to
2882/// a problematic expression based on such local checking.
2883///
2884/// Both EvalAddr and EvalVal follow through reference variables to evaluate
2885/// the expression that they point to. Such variables are added to the
2886/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00002887///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00002888/// EvalAddr processes expressions that are pointers that are used as
2889/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002890/// At the base case of the recursion is a check for the above problematic
2891/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00002892///
2893/// This implementation handles:
2894///
2895/// * pointer-to-pointer casts
2896/// * implicit conversions from array references to pointers
2897/// * taking the address of fields
2898/// * arbitrary interplay between "&" and "*" operators
2899/// * pointer arithmetic from an address of a stack variable
2900/// * taking the address of an array element where the array is on the stack
Chris Lattner5f9e2722011-07-23 10:55:15 +00002901static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002902 if (E->isTypeDependent())
2903 return NULL;
2904
Ted Kremenek06de2762007-08-17 16:46:58 +00002905 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00002906 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00002907 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002908 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002909 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00002910
Peter Collingbournef111d932011-04-15 00:35:48 +00002911 E = E->IgnoreParens();
2912
Ted Kremenek06de2762007-08-17 16:46:58 +00002913 // Our "symbolic interpreter" is just a dispatch off the currently
2914 // viewed AST node. We then recursively traverse the AST by calling
2915 // EvalAddr and EvalVal appropriately.
2916 switch (E->getStmtClass()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002917 case Stmt::DeclRefExprClass: {
2918 DeclRefExpr *DR = cast<DeclRefExpr>(E);
2919
2920 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
2921 // If this is a reference variable, follow through to the expression that
2922 // it points to.
2923 if (V->hasLocalStorage() &&
2924 V->getType()->isReferenceType() && V->hasInit()) {
2925 // Add the reference variable to the "trail".
2926 refVars.push_back(DR);
2927 return EvalAddr(V->getInit(), refVars);
2928 }
2929
2930 return NULL;
2931 }
Ted Kremenek06de2762007-08-17 16:46:58 +00002932
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002933 case Stmt::UnaryOperatorClass: {
2934 // The only unary operator that make sense to handle here
2935 // is AddrOf. All others don't make sense as pointers.
2936 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002937
John McCall2de56d12010-08-25 11:45:40 +00002938 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002939 return EvalVal(U->getSubExpr(), refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002940 else
Ted Kremenek06de2762007-08-17 16:46:58 +00002941 return NULL;
2942 }
Mike Stump1eb44332009-09-09 15:08:12 +00002943
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002944 case Stmt::BinaryOperatorClass: {
2945 // Handle pointer arithmetic. All other binary operators are not valid
2946 // in this context.
2947 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00002948 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00002949
John McCall2de56d12010-08-25 11:45:40 +00002950 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002951 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00002952
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002953 Expr *Base = B->getLHS();
2954
2955 // Determine which argument is the real pointer base. It could be
2956 // the RHS argument instead of the LHS.
2957 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00002958
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002959 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002960 return EvalAddr(Base, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002961 }
Steve Naroff61f40a22008-09-10 19:17:48 +00002962
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002963 // For conditional operators we need to see if either the LHS or RHS are
2964 // valid DeclRefExpr*s. If one of them is valid, we return it.
2965 case Stmt::ConditionalOperatorClass: {
2966 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002967
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002968 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00002969 if (Expr *lhsExpr = C->getLHS()) {
2970 // In C++, we can have a throw-expression, which has 'void' type.
2971 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002972 if (Expr* LHS = EvalAddr(lhsExpr, refVars))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00002973 return LHS;
2974 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002975
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00002976 // In C++, we can have a throw-expression, which has 'void' type.
2977 if (C->getRHS()->getType()->isVoidType())
2978 return NULL;
2979
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002980 return EvalAddr(C->getRHS(), refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002981 }
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002982
2983 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00002984 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002985 return E; // local block.
2986 return NULL;
2987
2988 case Stmt::AddrLabelExprClass:
2989 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00002990
John McCall80ee6e82011-11-10 05:35:25 +00002991 case Stmt::ExprWithCleanupsClass:
2992 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars);
2993
Ted Kremenek54b52742008-08-07 00:49:01 +00002994 // For casts, we need to handle conversions from arrays to
2995 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00002996 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002997 case Stmt::CStyleCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00002998 case Stmt::CXXFunctionalCastExprClass:
2999 case Stmt::ObjCBridgedCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00003000 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenek54b52742008-08-07 00:49:01 +00003001 QualType T = SubExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003002
Steve Naroffdd972f22008-09-05 22:11:13 +00003003 if (SubExpr->getType()->isPointerType() ||
3004 SubExpr->getType()->isBlockPointerType() ||
3005 SubExpr->getType()->isObjCQualifiedIdType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003006 return EvalAddr(SubExpr, refVars);
Ted Kremenek54b52742008-08-07 00:49:01 +00003007 else if (T->isArrayType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003008 return EvalVal(SubExpr, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003009 else
Ted Kremenek54b52742008-08-07 00:49:01 +00003010 return 0;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003011 }
Mike Stump1eb44332009-09-09 15:08:12 +00003012
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003013 // C++ casts. For dynamic casts, static casts, and const casts, we
3014 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor49badde2008-10-27 19:41:14 +00003015 // through the cast. In the case the dynamic cast doesn't fail (and
3016 // return NULL), we take the conservative route and report cases
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003017 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor49badde2008-10-27 19:41:14 +00003018 // FIXME: The comment about is wrong; we're not always converting
3019 // from pointer to pointer. I'm guessing that this code should also
Mike Stump1eb44332009-09-09 15:08:12 +00003020 // handle references to objects.
3021 case Stmt::CXXStaticCastExprClass:
3022 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00003023 case Stmt::CXXConstCastExprClass:
3024 case Stmt::CXXReinterpretCastExprClass: {
3025 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffdd972f22008-09-05 22:11:13 +00003026 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003027 return EvalAddr(S, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003028 else
3029 return NULL;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003030 }
Mike Stump1eb44332009-09-09 15:08:12 +00003031
Douglas Gregor03e80032011-06-21 17:03:29 +00003032 case Stmt::MaterializeTemporaryExprClass:
3033 if (Expr *Result = EvalAddr(
3034 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
3035 refVars))
3036 return Result;
3037
3038 return E;
3039
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003040 // Everything else: we simply don't reason about them.
3041 default:
3042 return NULL;
3043 }
Ted Kremenek06de2762007-08-17 16:46:58 +00003044}
Mike Stump1eb44332009-09-09 15:08:12 +00003045
Ted Kremenek06de2762007-08-17 16:46:58 +00003046
3047/// EvalVal - This function is complements EvalAddr in the mutual recursion.
3048/// See the comments for EvalAddr for more details.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003049static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003050do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00003051 // We should only be called for evaluating non-pointer expressions, or
3052 // expressions with a pointer type that are not used as references but instead
3053 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00003054
Ted Kremenek06de2762007-08-17 16:46:58 +00003055 // Our "symbolic interpreter" is just a dispatch off the currently
3056 // viewed AST node. We then recursively traverse the AST by calling
3057 // EvalAddr and EvalVal appropriately.
Peter Collingbournef111d932011-04-15 00:35:48 +00003058
3059 E = E->IgnoreParens();
Ted Kremenek06de2762007-08-17 16:46:58 +00003060 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003061 case Stmt::ImplicitCastExprClass: {
3062 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00003063 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003064 E = IE->getSubExpr();
3065 continue;
3066 }
3067 return NULL;
3068 }
3069
John McCall80ee6e82011-11-10 05:35:25 +00003070 case Stmt::ExprWithCleanupsClass:
3071 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars);
3072
Douglas Gregora2813ce2009-10-23 18:54:35 +00003073 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003074 // When we hit a DeclRefExpr we are looking at code that refers to a
3075 // variable's name. If it's not a reference variable we check if it has
3076 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00003077 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003078
Ted Kremenek06de2762007-08-17 16:46:58 +00003079 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003080 if (V->hasLocalStorage()) {
3081 if (!V->getType()->isReferenceType())
3082 return DR;
3083
3084 // Reference variable, follow through to the expression that
3085 // it points to.
3086 if (V->hasInit()) {
3087 // Add the reference variable to the "trail".
3088 refVars.push_back(DR);
3089 return EvalVal(V->getInit(), refVars);
3090 }
3091 }
Mike Stump1eb44332009-09-09 15:08:12 +00003092
Ted Kremenek06de2762007-08-17 16:46:58 +00003093 return NULL;
3094 }
Mike Stump1eb44332009-09-09 15:08:12 +00003095
Ted Kremenek06de2762007-08-17 16:46:58 +00003096 case Stmt::UnaryOperatorClass: {
3097 // The only unary operator that make sense to handle here
3098 // is Deref. All others don't resolve to a "name." This includes
3099 // handling all sorts of rvalues passed to a unary operator.
3100 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003101
John McCall2de56d12010-08-25 11:45:40 +00003102 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003103 return EvalAddr(U->getSubExpr(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00003104
3105 return NULL;
3106 }
Mike Stump1eb44332009-09-09 15:08:12 +00003107
Ted Kremenek06de2762007-08-17 16:46:58 +00003108 case Stmt::ArraySubscriptExprClass: {
3109 // Array subscripts are potential references to data on the stack. We
3110 // retrieve the DeclRefExpr* for the array variable if it indeed
3111 // has local storage.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003112 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00003113 }
Mike Stump1eb44332009-09-09 15:08:12 +00003114
Ted Kremenek06de2762007-08-17 16:46:58 +00003115 case Stmt::ConditionalOperatorClass: {
3116 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003117 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00003118 ConditionalOperator *C = cast<ConditionalOperator>(E);
3119
Anders Carlsson39073232007-11-30 19:04:31 +00003120 // Handle the GNU extension for missing LHS.
3121 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003122 if (Expr *LHS = EvalVal(lhsExpr, refVars))
Anders Carlsson39073232007-11-30 19:04:31 +00003123 return LHS;
3124
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003125 return EvalVal(C->getRHS(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00003126 }
Mike Stump1eb44332009-09-09 15:08:12 +00003127
Ted Kremenek06de2762007-08-17 16:46:58 +00003128 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00003129 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00003130 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003131
Ted Kremenek06de2762007-08-17 16:46:58 +00003132 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00003133 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00003134 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00003135
3136 // Check whether the member type is itself a reference, in which case
3137 // we're not going to refer to the member, but to what the member refers to.
3138 if (M->getMemberDecl()->getType()->isReferenceType())
3139 return NULL;
3140
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003141 return EvalVal(M->getBase(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00003142 }
Mike Stump1eb44332009-09-09 15:08:12 +00003143
Douglas Gregor03e80032011-06-21 17:03:29 +00003144 case Stmt::MaterializeTemporaryExprClass:
3145 if (Expr *Result = EvalVal(
3146 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
3147 refVars))
3148 return Result;
3149
3150 return E;
3151
Ted Kremenek06de2762007-08-17 16:46:58 +00003152 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003153 // Check that we don't return or take the address of a reference to a
3154 // temporary. This is only useful in C++.
3155 if (!E->isTypeDependent() && E->isRValue())
3156 return E;
3157
3158 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00003159 return NULL;
3160 }
Ted Kremenek68957a92010-08-04 20:01:07 +00003161} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00003162}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003163
3164//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
3165
3166/// Check for comparisons of floating point operands using != and ==.
3167/// Issue a warning if these are no self-comparisons, as they are not likely
3168/// to do what the programmer intended.
Richard Trieudd225092011-09-15 21:56:47 +00003169void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003170 bool EmitWarning = true;
Mike Stump1eb44332009-09-09 15:08:12 +00003171
Richard Trieudd225092011-09-15 21:56:47 +00003172 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
3173 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003174
3175 // Special case: check for x == x (which is OK).
3176 // Do not emit warnings for such cases.
3177 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
3178 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
3179 if (DRL->getDecl() == DRR->getDecl())
3180 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003181
3182
Ted Kremenek1b500bb2007-11-29 00:59:04 +00003183 // Special case: check for comparisons against literals that can be exactly
3184 // represented by APFloat. In such cases, do not emit a warning. This
3185 // is a heuristic: often comparison against such literals are used to
3186 // detect if a value in a variable has not changed. This clearly can
3187 // lead to false negatives.
3188 if (EmitWarning) {
3189 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
3190 if (FLL->isExact())
3191 EmitWarning = false;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003192 } else
Ted Kremenek1b500bb2007-11-29 00:59:04 +00003193 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
3194 if (FLR->isExact())
3195 EmitWarning = false;
3196 }
3197 }
Mike Stump1eb44332009-09-09 15:08:12 +00003198
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003199 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003200 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003201 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Richard Smith180f4792011-11-10 06:34:14 +00003202 if (CL->isBuiltinCall())
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003203 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003204
Sebastian Redl0eb23302009-01-19 00:08:26 +00003205 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003206 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Richard Smith180f4792011-11-10 06:34:14 +00003207 if (CR->isBuiltinCall())
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003208 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003209
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003210 // Emit the diagnostic.
3211 if (EmitWarning)
Richard Trieudd225092011-09-15 21:56:47 +00003212 Diag(Loc, diag::warn_floatingpoint_eq)
3213 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003214}
John McCallba26e582010-01-04 23:21:16 +00003215
John McCallf2370c92010-01-06 05:24:50 +00003216//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
3217//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00003218
John McCallf2370c92010-01-06 05:24:50 +00003219namespace {
John McCallba26e582010-01-04 23:21:16 +00003220
John McCallf2370c92010-01-06 05:24:50 +00003221/// Structure recording the 'active' range of an integer-valued
3222/// expression.
3223struct IntRange {
3224 /// The number of bits active in the int.
3225 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00003226
John McCallf2370c92010-01-06 05:24:50 +00003227 /// True if the int is known not to have negative values.
3228 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00003229
John McCallf2370c92010-01-06 05:24:50 +00003230 IntRange(unsigned Width, bool NonNegative)
3231 : Width(Width), NonNegative(NonNegative)
3232 {}
John McCallba26e582010-01-04 23:21:16 +00003233
John McCall1844a6e2010-11-10 23:38:19 +00003234 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00003235 static IntRange forBoolType() {
3236 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00003237 }
3238
John McCall1844a6e2010-11-10 23:38:19 +00003239 /// Returns the range of an opaque value of the given integral type.
3240 static IntRange forValueOfType(ASTContext &C, QualType T) {
3241 return forValueOfCanonicalType(C,
3242 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00003243 }
3244
John McCall1844a6e2010-11-10 23:38:19 +00003245 /// Returns the range of an opaque value of a canonical integral type.
3246 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00003247 assert(T->isCanonicalUnqualified());
3248
3249 if (const VectorType *VT = dyn_cast<VectorType>(T))
3250 T = VT->getElementType().getTypePtr();
3251 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
3252 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00003253
John McCall091f23f2010-11-09 22:22:12 +00003254 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00003255 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
3256 EnumDecl *Enum = ET->getDecl();
John McCall5e1cdac2011-10-07 06:10:15 +00003257 if (!Enum->isCompleteDefinition())
John McCall091f23f2010-11-09 22:22:12 +00003258 return IntRange(C.getIntWidth(QualType(T, 0)), false);
3259
John McCall323ed742010-05-06 08:58:33 +00003260 unsigned NumPositive = Enum->getNumPositiveBits();
3261 unsigned NumNegative = Enum->getNumNegativeBits();
3262
3263 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
3264 }
John McCallf2370c92010-01-06 05:24:50 +00003265
3266 const BuiltinType *BT = cast<BuiltinType>(T);
3267 assert(BT->isInteger());
3268
3269 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
3270 }
3271
John McCall1844a6e2010-11-10 23:38:19 +00003272 /// Returns the "target" range of a canonical integral type, i.e.
3273 /// the range of values expressible in the type.
3274 ///
3275 /// This matches forValueOfCanonicalType except that enums have the
3276 /// full range of their type, not the range of their enumerators.
3277 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
3278 assert(T->isCanonicalUnqualified());
3279
3280 if (const VectorType *VT = dyn_cast<VectorType>(T))
3281 T = VT->getElementType().getTypePtr();
3282 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
3283 T = CT->getElementType().getTypePtr();
3284 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor69ff26b2011-09-08 23:29:05 +00003285 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall1844a6e2010-11-10 23:38:19 +00003286
3287 const BuiltinType *BT = cast<BuiltinType>(T);
3288 assert(BT->isInteger());
3289
3290 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
3291 }
3292
3293 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00003294 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00003295 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00003296 L.NonNegative && R.NonNegative);
3297 }
3298
John McCall1844a6e2010-11-10 23:38:19 +00003299 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00003300 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00003301 return IntRange(std::min(L.Width, R.Width),
3302 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00003303 }
3304};
3305
Ted Kremenek0692a192012-01-31 05:37:37 +00003306static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
3307 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00003308 if (value.isSigned() && value.isNegative())
3309 return IntRange(value.getMinSignedBits(), false);
3310
3311 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00003312 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00003313
3314 // isNonNegative() just checks the sign bit without considering
3315 // signedness.
3316 return IntRange(value.getActiveBits(), true);
3317}
3318
Ted Kremenek0692a192012-01-31 05:37:37 +00003319static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
3320 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00003321 if (result.isInt())
3322 return GetValueRange(C, result.getInt(), MaxWidth);
3323
3324 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00003325 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
3326 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
3327 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
3328 R = IntRange::join(R, El);
3329 }
John McCallf2370c92010-01-06 05:24:50 +00003330 return R;
3331 }
3332
3333 if (result.isComplexInt()) {
3334 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
3335 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
3336 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00003337 }
3338
3339 // This can happen with lossless casts to intptr_t of "based" lvalues.
3340 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00003341 // FIXME: The only reason we need to pass the type in here is to get
3342 // the sign right on this one case. It would be nice if APValue
3343 // preserved this.
Eli Friedman65639282012-01-04 23:13:47 +00003344 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00003345 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall51313c32010-01-04 23:31:57 +00003346}
John McCallf2370c92010-01-06 05:24:50 +00003347
3348/// Pseudo-evaluate the given integer expression, estimating the
3349/// range of values it might take.
3350///
3351/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek0692a192012-01-31 05:37:37 +00003352static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00003353 E = E->IgnoreParens();
3354
3355 // Try a full evaluation first.
3356 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00003357 if (E->EvaluateAsRValue(result, C))
John McCall0acc3112010-01-06 22:57:21 +00003358 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00003359
3360 // I think we only want to look through implicit casts here; if the
3361 // user has an explicit widening cast, we should treat the value as
3362 // being of the new, wider type.
3363 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedmanb17ee5b2011-12-15 02:41:52 +00003364 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCallf2370c92010-01-06 05:24:50 +00003365 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
3366
John McCall1844a6e2010-11-10 23:38:19 +00003367 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
John McCallf2370c92010-01-06 05:24:50 +00003368
John McCall2de56d12010-08-25 11:45:40 +00003369 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00003370
John McCallf2370c92010-01-06 05:24:50 +00003371 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00003372 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00003373 return OutputTypeRange;
3374
3375 IntRange SubRange
3376 = GetExprRange(C, CE->getSubExpr(),
3377 std::min(MaxWidth, OutputTypeRange.Width));
3378
3379 // Bail out if the subexpr's range is as wide as the cast type.
3380 if (SubRange.Width >= OutputTypeRange.Width)
3381 return OutputTypeRange;
3382
3383 // Otherwise, we take the smaller width, and we're non-negative if
3384 // either the output type or the subexpr is.
3385 return IntRange(SubRange.Width,
3386 SubRange.NonNegative || OutputTypeRange.NonNegative);
3387 }
3388
3389 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3390 // If we can fold the condition, just take that operand.
3391 bool CondResult;
3392 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
3393 return GetExprRange(C, CondResult ? CO->getTrueExpr()
3394 : CO->getFalseExpr(),
3395 MaxWidth);
3396
3397 // Otherwise, conservatively merge.
3398 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
3399 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
3400 return IntRange::join(L, R);
3401 }
3402
3403 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3404 switch (BO->getOpcode()) {
3405
3406 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00003407 case BO_LAnd:
3408 case BO_LOr:
3409 case BO_LT:
3410 case BO_GT:
3411 case BO_LE:
3412 case BO_GE:
3413 case BO_EQ:
3414 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00003415 return IntRange::forBoolType();
3416
John McCall862ff872011-07-13 06:35:24 +00003417 // The type of the assignments is the type of the LHS, so the RHS
3418 // is not necessarily the same type.
John McCall2de56d12010-08-25 11:45:40 +00003419 case BO_MulAssign:
3420 case BO_DivAssign:
3421 case BO_RemAssign:
3422 case BO_AddAssign:
3423 case BO_SubAssign:
John McCall862ff872011-07-13 06:35:24 +00003424 case BO_XorAssign:
3425 case BO_OrAssign:
3426 // TODO: bitfields?
John McCall1844a6e2010-11-10 23:38:19 +00003427 return IntRange::forValueOfType(C, E->getType());
John McCallc0cd21d2010-02-23 19:22:29 +00003428
John McCall862ff872011-07-13 06:35:24 +00003429 // Simple assignments just pass through the RHS, which will have
3430 // been coerced to the LHS type.
3431 case BO_Assign:
3432 // TODO: bitfields?
3433 return GetExprRange(C, BO->getRHS(), MaxWidth);
3434
John McCallf2370c92010-01-06 05:24:50 +00003435 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00003436 case BO_PtrMemD:
3437 case BO_PtrMemI:
John McCall1844a6e2010-11-10 23:38:19 +00003438 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003439
John McCall60fad452010-01-06 22:07:33 +00003440 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00003441 case BO_And:
3442 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00003443 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
3444 GetExprRange(C, BO->getRHS(), MaxWidth));
3445
John McCallf2370c92010-01-06 05:24:50 +00003446 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00003447 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00003448 // ...except that we want to treat '1 << (blah)' as logically
3449 // positive. It's an important idiom.
3450 if (IntegerLiteral *I
3451 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
3452 if (I->getValue() == 1) {
John McCall1844a6e2010-11-10 23:38:19 +00003453 IntRange R = IntRange::forValueOfType(C, E->getType());
John McCall3aae6092010-04-07 01:14:35 +00003454 return IntRange(R.Width, /*NonNegative*/ true);
3455 }
3456 }
3457 // fallthrough
3458
John McCall2de56d12010-08-25 11:45:40 +00003459 case BO_ShlAssign:
John McCall1844a6e2010-11-10 23:38:19 +00003460 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003461
John McCall60fad452010-01-06 22:07:33 +00003462 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00003463 case BO_Shr:
3464 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00003465 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3466
3467 // If the shift amount is a positive constant, drop the width by
3468 // that much.
3469 llvm::APSInt shift;
3470 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
3471 shift.isNonNegative()) {
3472 unsigned zext = shift.getZExtValue();
3473 if (zext >= L.Width)
3474 L.Width = (L.NonNegative ? 0 : 1);
3475 else
3476 L.Width -= zext;
3477 }
3478
3479 return L;
3480 }
3481
3482 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00003483 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00003484 return GetExprRange(C, BO->getRHS(), MaxWidth);
3485
John McCall60fad452010-01-06 22:07:33 +00003486 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00003487 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00003488 if (BO->getLHS()->getType()->isPointerType())
John McCall1844a6e2010-11-10 23:38:19 +00003489 return IntRange::forValueOfType(C, E->getType());
John McCall00fe7612011-07-14 22:39:48 +00003490 break;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003491
John McCall00fe7612011-07-14 22:39:48 +00003492 // The width of a division result is mostly determined by the size
3493 // of the LHS.
3494 case BO_Div: {
3495 // Don't 'pre-truncate' the operands.
3496 unsigned opWidth = C.getIntWidth(E->getType());
3497 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3498
3499 // If the divisor is constant, use that.
3500 llvm::APSInt divisor;
3501 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
3502 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
3503 if (log2 >= L.Width)
3504 L.Width = (L.NonNegative ? 0 : 1);
3505 else
3506 L.Width = std::min(L.Width - log2, MaxWidth);
3507 return L;
3508 }
3509
3510 // Otherwise, just use the LHS's width.
3511 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3512 return IntRange(L.Width, L.NonNegative && R.NonNegative);
3513 }
3514
3515 // The result of a remainder can't be larger than the result of
3516 // either side.
3517 case BO_Rem: {
3518 // Don't 'pre-truncate' the operands.
3519 unsigned opWidth = C.getIntWidth(E->getType());
3520 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3521 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3522
3523 IntRange meet = IntRange::meet(L, R);
3524 meet.Width = std::min(meet.Width, MaxWidth);
3525 return meet;
3526 }
3527
3528 // The default behavior is okay for these.
3529 case BO_Mul:
3530 case BO_Add:
3531 case BO_Xor:
3532 case BO_Or:
John McCallf2370c92010-01-06 05:24:50 +00003533 break;
3534 }
3535
John McCall00fe7612011-07-14 22:39:48 +00003536 // The default case is to treat the operation as if it were closed
3537 // on the narrowest type that encompasses both operands.
John McCallf2370c92010-01-06 05:24:50 +00003538 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3539 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
3540 return IntRange::join(L, R);
3541 }
3542
3543 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
3544 switch (UO->getOpcode()) {
3545 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00003546 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00003547 return IntRange::forBoolType();
3548
3549 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00003550 case UO_Deref:
3551 case UO_AddrOf: // should be impossible
John McCall1844a6e2010-11-10 23:38:19 +00003552 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003553
3554 default:
3555 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
3556 }
3557 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003558
3559 if (dyn_cast<OffsetOfExpr>(E)) {
John McCall1844a6e2010-11-10 23:38:19 +00003560 IntRange::forValueOfType(C, E->getType());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003561 }
John McCallf2370c92010-01-06 05:24:50 +00003562
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003563 if (FieldDecl *BitField = E->getBitField())
3564 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00003565 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCallf2370c92010-01-06 05:24:50 +00003566
John McCall1844a6e2010-11-10 23:38:19 +00003567 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003568}
John McCall51313c32010-01-04 23:31:57 +00003569
Ted Kremenek0692a192012-01-31 05:37:37 +00003570static IntRange GetExprRange(ASTContext &C, Expr *E) {
John McCall323ed742010-05-06 08:58:33 +00003571 return GetExprRange(C, E, C.getIntWidth(E->getType()));
3572}
3573
John McCall51313c32010-01-04 23:31:57 +00003574/// Checks whether the given value, which currently has the given
3575/// source semantics, has the same value when coerced through the
3576/// target semantics.
Ted Kremenek0692a192012-01-31 05:37:37 +00003577static bool IsSameFloatAfterCast(const llvm::APFloat &value,
3578 const llvm::fltSemantics &Src,
3579 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00003580 llvm::APFloat truncated = value;
3581
3582 bool ignored;
3583 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
3584 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
3585
3586 return truncated.bitwiseIsEqual(value);
3587}
3588
3589/// Checks whether the given value, which currently has the given
3590/// source semantics, has the same value when coerced through the
3591/// target semantics.
3592///
3593/// The value might be a vector of floats (or a complex number).
Ted Kremenek0692a192012-01-31 05:37:37 +00003594static bool IsSameFloatAfterCast(const APValue &value,
3595 const llvm::fltSemantics &Src,
3596 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00003597 if (value.isFloat())
3598 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
3599
3600 if (value.isVector()) {
3601 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
3602 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
3603 return false;
3604 return true;
3605 }
3606
3607 assert(value.isComplexFloat());
3608 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
3609 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
3610}
3611
Ted Kremenek0692a192012-01-31 05:37:37 +00003612static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00003613
Ted Kremeneke3b159c2010-09-23 21:43:44 +00003614static bool IsZero(Sema &S, Expr *E) {
3615 // Suppress cases where we are comparing against an enum constant.
3616 if (const DeclRefExpr *DR =
3617 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
3618 if (isa<EnumConstantDecl>(DR->getDecl()))
3619 return false;
3620
3621 // Suppress cases where the '0' value is expanded from a macro.
3622 if (E->getLocStart().isMacroID())
3623 return false;
3624
John McCall323ed742010-05-06 08:58:33 +00003625 llvm::APSInt Value;
3626 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
3627}
3628
John McCall372e1032010-10-06 00:25:24 +00003629static bool HasEnumType(Expr *E) {
3630 // Strip off implicit integral promotions.
3631 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00003632 if (ICE->getCastKind() != CK_IntegralCast &&
3633 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00003634 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00003635 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00003636 }
3637
3638 return E->getType()->isEnumeralType();
3639}
3640
Ted Kremenek0692a192012-01-31 05:37:37 +00003641static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00003642 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00003643 if (E->isValueDependent())
3644 return;
3645
John McCall2de56d12010-08-25 11:45:40 +00003646 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00003647 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003648 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00003649 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00003650 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00003651 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003652 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00003653 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00003654 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00003655 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003656 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00003657 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00003658 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00003659 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003660 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00003661 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
3662 }
3663}
3664
3665/// Analyze the operands of the given comparison. Implements the
3666/// fallback case from AnalyzeComparison.
Ted Kremenek0692a192012-01-31 05:37:37 +00003667static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00003668 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
3669 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00003670}
John McCall51313c32010-01-04 23:31:57 +00003671
John McCallba26e582010-01-04 23:21:16 +00003672/// \brief Implements -Wsign-compare.
3673///
Richard Trieudd225092011-09-15 21:56:47 +00003674/// \param E the binary operator to check for warnings
Ted Kremenek0692a192012-01-31 05:37:37 +00003675static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCall323ed742010-05-06 08:58:33 +00003676 // The type the comparison is being performed in.
3677 QualType T = E->getLHS()->getType();
3678 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
3679 && "comparison with mismatched types");
John McCallba26e582010-01-04 23:21:16 +00003680
John McCall323ed742010-05-06 08:58:33 +00003681 // We don't do anything special if this isn't an unsigned integral
3682 // comparison: we're only interested in integral comparisons, and
3683 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00003684 //
3685 // We also don't care about value-dependent expressions or expressions
3686 // whose result is a constant.
3687 if (!T->hasUnsignedIntegerRepresentation()
3688 || E->isValueDependent() || E->isIntegerConstantExpr(S.Context))
John McCall323ed742010-05-06 08:58:33 +00003689 return AnalyzeImpConvsInComparison(S, E);
John McCallf2370c92010-01-06 05:24:50 +00003690
Richard Trieudd225092011-09-15 21:56:47 +00003691 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
3692 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
John McCallba26e582010-01-04 23:21:16 +00003693
John McCall323ed742010-05-06 08:58:33 +00003694 // Check to see if one of the (unmodified) operands is of different
3695 // signedness.
3696 Expr *signedOperand, *unsignedOperand;
Richard Trieudd225092011-09-15 21:56:47 +00003697 if (LHS->getType()->hasSignedIntegerRepresentation()) {
3698 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00003699 "unsigned comparison between two signed integer expressions?");
Richard Trieudd225092011-09-15 21:56:47 +00003700 signedOperand = LHS;
3701 unsignedOperand = RHS;
3702 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
3703 signedOperand = RHS;
3704 unsignedOperand = LHS;
John McCallba26e582010-01-04 23:21:16 +00003705 } else {
John McCall323ed742010-05-06 08:58:33 +00003706 CheckTrivialUnsignedComparison(S, E);
3707 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00003708 }
3709
John McCall323ed742010-05-06 08:58:33 +00003710 // Otherwise, calculate the effective range of the signed operand.
3711 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00003712
John McCall323ed742010-05-06 08:58:33 +00003713 // Go ahead and analyze implicit conversions in the operands. Note
3714 // that we skip the implicit conversions on both sides.
Richard Trieudd225092011-09-15 21:56:47 +00003715 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
3716 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00003717
John McCall323ed742010-05-06 08:58:33 +00003718 // If the signed range is non-negative, -Wsign-compare won't fire,
3719 // but we should still check for comparisons which are always true
3720 // or false.
3721 if (signedRange.NonNegative)
3722 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00003723
3724 // For (in)equality comparisons, if the unsigned operand is a
3725 // constant which cannot collide with a overflowed signed operand,
3726 // then reinterpreting the signed operand as unsigned will not
3727 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00003728 if (E->isEqualityOp()) {
3729 unsigned comparisonWidth = S.Context.getIntWidth(T);
3730 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00003731
John McCall323ed742010-05-06 08:58:33 +00003732 // We should never be unable to prove that the unsigned operand is
3733 // non-negative.
3734 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
3735
3736 if (unsignedRange.Width < comparisonWidth)
3737 return;
3738 }
3739
3740 S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison)
Richard Trieudd225092011-09-15 21:56:47 +00003741 << LHS->getType() << RHS->getType()
3742 << LHS->getSourceRange() << RHS->getSourceRange();
John McCallba26e582010-01-04 23:21:16 +00003743}
3744
John McCall15d7d122010-11-11 03:21:53 +00003745/// Analyzes an attempt to assign the given value to a bitfield.
3746///
3747/// Returns true if there was something fishy about the attempt.
Ted Kremenek0692a192012-01-31 05:37:37 +00003748static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
3749 SourceLocation InitLoc) {
John McCall15d7d122010-11-11 03:21:53 +00003750 assert(Bitfield->isBitField());
3751 if (Bitfield->isInvalidDecl())
3752 return false;
3753
John McCall91b60142010-11-11 05:33:51 +00003754 // White-list bool bitfields.
3755 if (Bitfield->getType()->isBooleanType())
3756 return false;
3757
Douglas Gregor46ff3032011-02-04 13:09:01 +00003758 // Ignore value- or type-dependent expressions.
3759 if (Bitfield->getBitWidth()->isValueDependent() ||
3760 Bitfield->getBitWidth()->isTypeDependent() ||
3761 Init->isValueDependent() ||
3762 Init->isTypeDependent())
3763 return false;
3764
John McCall15d7d122010-11-11 03:21:53 +00003765 Expr *OriginalInit = Init->IgnoreParenImpCasts();
3766
Richard Smith80d4b552011-12-28 19:48:30 +00003767 llvm::APSInt Value;
3768 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall15d7d122010-11-11 03:21:53 +00003769 return false;
3770
John McCall15d7d122010-11-11 03:21:53 +00003771 unsigned OriginalWidth = Value.getBitWidth();
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003772 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall15d7d122010-11-11 03:21:53 +00003773
3774 if (OriginalWidth <= FieldWidth)
3775 return false;
3776
Eli Friedman3a643af2012-01-26 23:11:39 +00003777 // Compute the value which the bitfield will contain.
Jay Foad9f71a8f2010-12-07 08:25:34 +00003778 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedman3a643af2012-01-26 23:11:39 +00003779 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall15d7d122010-11-11 03:21:53 +00003780
Eli Friedman3a643af2012-01-26 23:11:39 +00003781 // Check whether the stored value is equal to the original value.
3782 TruncatedValue = TruncatedValue.extend(OriginalWidth);
John McCall15d7d122010-11-11 03:21:53 +00003783 if (Value == TruncatedValue)
3784 return false;
3785
Eli Friedman3a643af2012-01-26 23:11:39 +00003786 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedman34ff0622012-02-02 00:40:20 +00003787 // therefore don't strictly fit into a signed bitfield of width 1.
3788 if (FieldWidth == 1 && Value == 1)
Eli Friedman3a643af2012-01-26 23:11:39 +00003789 return false;
3790
John McCall15d7d122010-11-11 03:21:53 +00003791 std::string PrettyValue = Value.toString(10);
3792 std::string PrettyTrunc = TruncatedValue.toString(10);
3793
3794 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
3795 << PrettyValue << PrettyTrunc << OriginalInit->getType()
3796 << Init->getSourceRange();
3797
3798 return true;
3799}
3800
John McCallbeb22aa2010-11-09 23:24:47 +00003801/// Analyze the given simple or compound assignment for warning-worthy
3802/// operations.
Ted Kremenek0692a192012-01-31 05:37:37 +00003803static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCallbeb22aa2010-11-09 23:24:47 +00003804 // Just recurse on the LHS.
3805 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
3806
3807 // We want to recurse on the RHS as normal unless we're assigning to
3808 // a bitfield.
3809 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
John McCall15d7d122010-11-11 03:21:53 +00003810 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
3811 E->getOperatorLoc())) {
3812 // Recurse, ignoring any implicit conversions on the RHS.
3813 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
3814 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00003815 }
3816 }
3817
3818 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
3819}
3820
John McCall51313c32010-01-04 23:31:57 +00003821/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00003822static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00003823 SourceLocation CContext, unsigned diag,
3824 bool pruneControlFlow = false) {
3825 if (pruneControlFlow) {
3826 S.DiagRuntimeBehavior(E->getExprLoc(), E,
3827 S.PDiag(diag)
3828 << SourceType << T << E->getSourceRange()
3829 << SourceRange(CContext));
3830 return;
3831 }
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00003832 S.Diag(E->getExprLoc(), diag)
3833 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
3834}
3835
Chandler Carruthe1b02e02011-04-05 06:47:57 +00003836/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00003837static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00003838 SourceLocation CContext, unsigned diag,
3839 bool pruneControlFlow = false) {
3840 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruthe1b02e02011-04-05 06:47:57 +00003841}
3842
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003843/// Diagnose an implicit cast from a literal expression. Does not warn when the
3844/// cast wouldn't lose information.
Chandler Carruthf65076e2011-04-10 08:36:24 +00003845void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
3846 SourceLocation CContext) {
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003847 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruthf65076e2011-04-10 08:36:24 +00003848 bool isExact = false;
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003849 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00003850 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
3851 T->hasUnsignedIntegerRepresentation());
3852 if (Value.convertToInteger(IntegerValue,
Chandler Carruthf65076e2011-04-10 08:36:24 +00003853 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003854 == llvm::APFloat::opOK && isExact)
Chandler Carruthf65076e2011-04-10 08:36:24 +00003855 return;
3856
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003857 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
3858 << FL->getType() << T << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruthf65076e2011-04-10 08:36:24 +00003859}
3860
John McCall091f23f2010-11-09 22:22:12 +00003861std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
3862 if (!Range.Width) return "0";
3863
3864 llvm::APSInt ValueInRange = Value;
3865 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00003866 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00003867 return ValueInRange.toString(10);
3868}
3869
John McCall323ed742010-05-06 08:58:33 +00003870void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00003871 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00003872 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00003873
John McCall323ed742010-05-06 08:58:33 +00003874 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
3875 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
3876 if (Source == Target) return;
3877 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00003878
Chandler Carruth108f7562011-07-26 05:40:03 +00003879 // If the conversion context location is invalid don't complain. We also
3880 // don't want to emit a warning if the issue occurs from the expansion of
3881 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
3882 // delay this check as long as possible. Once we detect we are in that
3883 // scenario, we just return.
Ted Kremenekef9ff882011-03-10 20:03:42 +00003884 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00003885 return;
3886
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00003887 // Diagnose implicit casts to bool.
3888 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
3889 if (isa<StringLiteral>(E))
3890 // Warn on string literal to bool. Checks for string literals in logical
3891 // expressions, for instances, assert(0 && "error here"), is prevented
3892 // by a check in AnalyzeImplicitConversions().
3893 return DiagnoseImpCast(S, E, T, CC,
3894 diag::warn_impcast_string_literal_to_bool);
Lang Hamese14ca9f2011-12-05 20:49:50 +00003895 if (Source->isFunctionType()) {
3896 // Warn on function to bool. Checks free functions and static member
3897 // functions. Weakly imported functions are excluded from the check,
3898 // since it's common to test their value to check whether the linker
3899 // found a definition for them.
3900 ValueDecl *D = 0;
3901 if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
3902 D = R->getDecl();
3903 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
3904 D = M->getMemberDecl();
3905 }
3906
3907 if (D && !D->isWeak()) {
Richard Trieu26b45d82011-12-06 04:48:01 +00003908 if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
3909 S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
3910 << F << E->getSourceRange() << SourceRange(CC);
David Blaikie2def7732011-12-09 21:42:37 +00003911 S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
3912 << FixItHint::CreateInsertion(E->getExprLoc(), "&");
3913 QualType ReturnType;
3914 UnresolvedSet<4> NonTemplateOverloads;
3915 S.isExprCallable(*E, ReturnType, NonTemplateOverloads);
3916 if (!ReturnType.isNull()
3917 && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
3918 S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
3919 << FixItHint::CreateInsertion(
3920 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu26b45d82011-12-06 04:48:01 +00003921 return;
3922 }
Lang Hamese14ca9f2011-12-05 20:49:50 +00003923 }
3924 }
David Blaikiee37cdc42011-09-29 04:06:47 +00003925 return; // Other casts to bool are not checked.
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00003926 }
John McCall51313c32010-01-04 23:31:57 +00003927
3928 // Strip vector types.
3929 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003930 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00003931 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00003932 return;
John McCallb4eb64d2010-10-08 02:01:28 +00003933 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00003934 }
Chris Lattnerb792b302011-06-14 04:51:15 +00003935
3936 // If the vector cast is cast between two vectors of the same size, it is
3937 // a bitcast, not a conversion.
3938 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
3939 return;
John McCall51313c32010-01-04 23:31:57 +00003940
3941 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
3942 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
3943 }
3944
3945 // Strip complex types.
3946 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003947 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00003948 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00003949 return;
3950
John McCallb4eb64d2010-10-08 02:01:28 +00003951 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00003952 }
John McCall51313c32010-01-04 23:31:57 +00003953
3954 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
3955 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
3956 }
3957
3958 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
3959 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
3960
3961 // If the source is floating point...
3962 if (SourceBT && SourceBT->isFloatingPoint()) {
3963 // ...and the target is floating point...
3964 if (TargetBT && TargetBT->isFloatingPoint()) {
3965 // ...then warn if we're dropping FP rank.
3966
3967 // Builtin FP kinds are ordered by increasing FP rank.
3968 if (SourceBT->getKind() > TargetBT->getKind()) {
3969 // Don't warn about float constants that are precisely
3970 // representable in the target type.
3971 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00003972 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00003973 // Value might be a float, a float vector, or a float complex.
3974 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00003975 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
3976 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00003977 return;
3978 }
3979
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00003980 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00003981 return;
3982
John McCallb4eb64d2010-10-08 02:01:28 +00003983 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00003984 }
3985 return;
3986 }
3987
Ted Kremenekef9ff882011-03-10 20:03:42 +00003988 // If the target is integral, always warn.
Chandler Carrutha5b93322011-02-17 11:05:49 +00003989 if ((TargetBT && TargetBT->isInteger())) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00003990 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00003991 return;
3992
Chandler Carrutha5b93322011-02-17 11:05:49 +00003993 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay634c8af2011-09-08 22:30:47 +00003994 // We also want to warn on, e.g., "int i = -1.234"
3995 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
3996 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
3997 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
3998
Chandler Carruthf65076e2011-04-10 08:36:24 +00003999 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
4000 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00004001 } else {
4002 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
4003 }
4004 }
John McCall51313c32010-01-04 23:31:57 +00004005
4006 return;
4007 }
4008
John McCallf2370c92010-01-06 05:24:50 +00004009 if (!Source->isIntegerType() || !Target->isIntegerType())
John McCall51313c32010-01-04 23:31:57 +00004010 return;
4011
Richard Trieu1838ca52011-05-29 19:59:02 +00004012 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
4013 == Expr::NPCK_GNUNull) && Target->isIntegerType()) {
4014 S.Diag(E->getExprLoc(), diag::warn_impcast_null_pointer_to_integer)
4015 << E->getSourceRange() << clang::SourceRange(CC);
4016 return;
4017 }
4018
John McCall323ed742010-05-06 08:58:33 +00004019 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00004020 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00004021
4022 if (SourceRange.Width > TargetRange.Width) {
John McCall091f23f2010-11-09 22:22:12 +00004023 // If the source is a constant, use a default-on diagnostic.
4024 // TODO: this should happen for bitfield stores, too.
4025 llvm::APSInt Value(32);
4026 if (E->isIntegerConstantExpr(Value, S.Context)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004027 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004028 return;
4029
John McCall091f23f2010-11-09 22:22:12 +00004030 std::string PrettySourceValue = Value.toString(10);
4031 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
4032
Ted Kremenek5e745da2011-10-22 02:37:33 +00004033 S.DiagRuntimeBehavior(E->getExprLoc(), E,
4034 S.PDiag(diag::warn_impcast_integer_precision_constant)
4035 << PrettySourceValue << PrettyTargetValue
4036 << E->getType() << T << E->getSourceRange()
4037 << clang::SourceRange(CC));
John McCall091f23f2010-11-09 22:22:12 +00004038 return;
4039 }
4040
Chris Lattnerb792b302011-06-14 04:51:15 +00004041 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004042 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004043 return;
4044
John McCallf2370c92010-01-06 05:24:50 +00004045 if (SourceRange.Width == 64 && TargetRange.Width == 32)
Anna Zaksc36bedc2012-02-01 19:08:57 +00004046 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
4047 /* pruneControlFlow */ true);
John McCallb4eb64d2010-10-08 02:01:28 +00004048 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00004049 }
4050
4051 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
4052 (!TargetRange.NonNegative && SourceRange.NonNegative &&
4053 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004054
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004055 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004056 return;
4057
John McCall323ed742010-05-06 08:58:33 +00004058 unsigned DiagID = diag::warn_impcast_integer_sign;
4059
4060 // Traditionally, gcc has warned about this under -Wsign-compare.
4061 // We also want to warn about it in -Wconversion.
4062 // So if -Wconversion is off, use a completely identical diagnostic
4063 // in the sign-compare group.
4064 // The conditional-checking code will
4065 if (ICContext) {
4066 DiagID = diag::warn_impcast_integer_sign_conditional;
4067 *ICContext = true;
4068 }
4069
John McCallb4eb64d2010-10-08 02:01:28 +00004070 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00004071 }
4072
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004073 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004074 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
4075 // type, to give us better diagnostics.
4076 QualType SourceType = E->getType();
4077 if (!S.getLangOptions().CPlusPlus) {
4078 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
4079 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
4080 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
4081 SourceType = S.Context.getTypeDeclType(Enum);
4082 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
4083 }
4084 }
4085
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004086 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
4087 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
4088 if ((SourceEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00004089 SourceEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004090 (TargetEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00004091 TargetEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00004092 SourceEnum != TargetEnum) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004093 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004094 return;
4095
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004096 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004097 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004098 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004099
John McCall51313c32010-01-04 23:31:57 +00004100 return;
4101}
4102
John McCall323ed742010-05-06 08:58:33 +00004103void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T);
4104
4105void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00004106 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00004107 E = E->IgnoreParenImpCasts();
4108
4109 if (isa<ConditionalOperator>(E))
4110 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T);
4111
John McCallb4eb64d2010-10-08 02:01:28 +00004112 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00004113 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00004114 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00004115 return;
4116}
4117
4118void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00004119 SourceLocation CC = E->getQuestionLoc();
4120
4121 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00004122
4123 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00004124 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
4125 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00004126
4127 // If -Wconversion would have warned about either of the candidates
4128 // for a signedness conversion to the context type...
4129 if (!Suspicious) return;
4130
4131 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00004132 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
4133 CC))
John McCall323ed742010-05-06 08:58:33 +00004134 return;
4135
John McCall323ed742010-05-06 08:58:33 +00004136 // ...then check whether it would have warned about either of the
4137 // candidates for a signedness conversion to the condition type.
Richard Trieu52541612011-07-21 02:46:28 +00004138 if (E->getType() == T) return;
4139
4140 Suspicious = false;
4141 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
4142 E->getType(), CC, &Suspicious);
4143 if (!Suspicious)
4144 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00004145 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00004146}
4147
4148/// AnalyzeImplicitConversions - Find and report any interesting
4149/// implicit conversions in the given expression. There are a couple
4150/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00004151void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00004152 QualType T = OrigE->getType();
4153 Expr *E = OrigE->IgnoreParenImpCasts();
4154
Douglas Gregorf8b6e152011-10-10 17:38:18 +00004155 if (E->isTypeDependent() || E->isValueDependent())
4156 return;
4157
John McCall323ed742010-05-06 08:58:33 +00004158 // For conditional operators, we analyze the arguments as if they
4159 // were being fed directly into the output.
4160 if (isa<ConditionalOperator>(E)) {
4161 ConditionalOperator *CO = cast<ConditionalOperator>(E);
4162 CheckConditionalOperator(S, CO, T);
4163 return;
4164 }
4165
4166 // Go ahead and check any implicit conversions we might have skipped.
4167 // The non-canonical typecheck is just an optimization;
4168 // CheckImplicitConversion will filter out dead implicit conversions.
4169 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00004170 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00004171
4172 // Now continue drilling into this expression.
4173
4174 // Skip past explicit casts.
4175 if (isa<ExplicitCastExpr>(E)) {
4176 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00004177 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00004178 }
4179
John McCallbeb22aa2010-11-09 23:24:47 +00004180 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4181 // Do a somewhat different check with comparison operators.
4182 if (BO->isComparisonOp())
4183 return AnalyzeComparison(S, BO);
4184
Eli Friedman0fa06382012-01-26 23:34:06 +00004185 // And with simple assignments.
4186 if (BO->getOpcode() == BO_Assign)
John McCallbeb22aa2010-11-09 23:24:47 +00004187 return AnalyzeAssignment(S, BO);
4188 }
John McCall323ed742010-05-06 08:58:33 +00004189
4190 // These break the otherwise-useful invariant below. Fortunately,
4191 // we don't really need to recurse into them, because any internal
4192 // expressions should have been analyzed already when they were
4193 // built into statements.
4194 if (isa<StmtExpr>(E)) return;
4195
4196 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004197 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00004198
4199 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00004200 CC = E->getExprLoc();
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004201 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
4202 bool IsLogicalOperator = BO && BO->isLogicalOp();
4203 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor54042f12012-02-09 10:18:50 +00004204 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor503384f2012-02-09 00:47:04 +00004205 if (!ChildExpr)
4206 continue;
4207
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004208 if (IsLogicalOperator &&
4209 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
4210 // Ignore checking string literals that are in logical operators.
4211 continue;
4212 AnalyzeImplicitConversions(S, ChildExpr, CC);
4213 }
John McCall323ed742010-05-06 08:58:33 +00004214}
4215
4216} // end anonymous namespace
4217
4218/// Diagnoses "dangerous" implicit conversions within the given
4219/// expression (which is a full expression). Implements -Wconversion
4220/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00004221///
4222/// \param CC the "context" location of the implicit conversion, i.e.
4223/// the most location of the syntactic entity requiring the implicit
4224/// conversion
4225void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00004226 // Don't diagnose in unevaluated contexts.
4227 if (ExprEvalContexts.back().Context == Sema::Unevaluated)
4228 return;
4229
4230 // Don't diagnose for value- or type-dependent expressions.
4231 if (E->isTypeDependent() || E->isValueDependent())
4232 return;
4233
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004234 // Check for array bounds violations in cases where the check isn't triggered
4235 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
4236 // ArraySubscriptExpr is on the RHS of a variable initialization.
4237 CheckArrayAccess(E);
4238
John McCallb4eb64d2010-10-08 02:01:28 +00004239 // This is not the right CC for (e.g.) a variable initialization.
4240 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00004241}
4242
John McCall15d7d122010-11-11 03:21:53 +00004243void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
4244 FieldDecl *BitField,
4245 Expr *Init) {
4246 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
4247}
4248
Mike Stumpf8c49212010-01-21 03:59:47 +00004249/// CheckParmsForFunctionDef - Check that the parameters of the given
4250/// function are appropriate for the definition of a function. This
4251/// takes care of any checks that cannot be performed on the
4252/// declaration itself, e.g., that the types of each of the function
4253/// parameters are complete.
Douglas Gregor82aa7132010-11-01 18:37:59 +00004254bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
4255 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00004256 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00004257 for (; P != PEnd; ++P) {
4258 ParmVarDecl *Param = *P;
4259
Mike Stumpf8c49212010-01-21 03:59:47 +00004260 // C99 6.7.5.3p4: the parameters in a parameter type list in a
4261 // function declarator that is part of a function definition of
4262 // that function shall not have incomplete type.
4263 //
4264 // This is also C++ [dcl.fct]p6.
4265 if (!Param->isInvalidDecl() &&
4266 RequireCompleteType(Param->getLocation(), Param->getType(),
4267 diag::err_typecheck_decl_incomplete_type)) {
4268 Param->setInvalidDecl();
4269 HasInvalidParm = true;
4270 }
4271
4272 // C99 6.9.1p5: If the declarator includes a parameter type list, the
4273 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00004274 if (CheckParameterNames &&
4275 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00004276 !Param->isImplicit() &&
4277 !getLangOptions().CPlusPlus)
4278 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00004279
4280 // C99 6.7.5.3p12:
4281 // If the function declarator is not part of a definition of that
4282 // function, parameters may have incomplete type and may use the [*]
4283 // notation in their sequences of declarator specifiers to specify
4284 // variable length array types.
4285 QualType PType = Param->getOriginalType();
4286 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
4287 if (AT->getSizeModifier() == ArrayType::Star) {
4288 // FIXME: This diagnosic should point the the '[*]' if source-location
4289 // information is added for it.
4290 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
4291 }
4292 }
Mike Stumpf8c49212010-01-21 03:59:47 +00004293 }
4294
4295 return HasInvalidParm;
4296}
John McCallb7f4ffe2010-08-12 21:44:57 +00004297
4298/// CheckCastAlign - Implements -Wcast-align, which warns when a
4299/// pointer cast increases the alignment requirements.
4300void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
4301 // This is actually a lot of work to potentially be doing on every
4302 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00004303 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
4304 TRange.getBegin())
David Blaikied6471f72011-09-25 23:23:43 +00004305 == DiagnosticsEngine::Ignored)
John McCallb7f4ffe2010-08-12 21:44:57 +00004306 return;
4307
4308 // Ignore dependent types.
4309 if (T->isDependentType() || Op->getType()->isDependentType())
4310 return;
4311
4312 // Require that the destination be a pointer type.
4313 const PointerType *DestPtr = T->getAs<PointerType>();
4314 if (!DestPtr) return;
4315
4316 // If the destination has alignment 1, we're done.
4317 QualType DestPointee = DestPtr->getPointeeType();
4318 if (DestPointee->isIncompleteType()) return;
4319 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
4320 if (DestAlign.isOne()) return;
4321
4322 // Require that the source be a pointer type.
4323 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
4324 if (!SrcPtr) return;
4325 QualType SrcPointee = SrcPtr->getPointeeType();
4326
4327 // Whitelist casts from cv void*. We already implicitly
4328 // whitelisted casts to cv void*, since they have alignment 1.
4329 // Also whitelist casts involving incomplete types, which implicitly
4330 // includes 'void'.
4331 if (SrcPointee->isIncompleteType()) return;
4332
4333 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
4334 if (SrcAlign >= DestAlign) return;
4335
4336 Diag(TRange.getBegin(), diag::warn_cast_align)
4337 << Op->getType() << T
4338 << static_cast<unsigned>(SrcAlign.getQuantity())
4339 << static_cast<unsigned>(DestAlign.getQuantity())
4340 << TRange << Op->getSourceRange();
4341}
4342
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004343static const Type* getElementType(const Expr *BaseExpr) {
4344 const Type* EltType = BaseExpr->getType().getTypePtr();
4345 if (EltType->isAnyPointerType())
4346 return EltType->getPointeeType().getTypePtr();
4347 else if (EltType->isArrayType())
4348 return EltType->getBaseElementTypeUnsafe();
4349 return EltType;
4350}
4351
Chandler Carruthc2684342011-08-05 09:10:50 +00004352/// \brief Check whether this array fits the idiom of a size-one tail padded
4353/// array member of a struct.
4354///
4355/// We avoid emitting out-of-bounds access warnings for such arrays as they are
4356/// commonly used to emulate flexible arrays in C89 code.
4357static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
4358 const NamedDecl *ND) {
4359 if (Size != 1 || !ND) return false;
4360
4361 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
4362 if (!FD) return false;
4363
4364 // Don't consider sizes resulting from macro expansions or template argument
4365 // substitution to form C89 tail-padded arrays.
4366 ConstantArrayTypeLoc TL =
4367 cast<ConstantArrayTypeLoc>(FD->getTypeSourceInfo()->getTypeLoc());
4368 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(TL.getSizeExpr());
4369 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
4370 return false;
4371
4372 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gay381711c2011-11-29 22:43:53 +00004373 if (!RD) return false;
4374 if (RD->isUnion()) return false;
4375 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
4376 if (!CRD->isStandardLayout()) return false;
4377 }
Chandler Carruthc2684342011-08-05 09:10:50 +00004378
Benjamin Kramer22d4fed2011-08-06 03:04:42 +00004379 // See if this is the last field decl in the record.
4380 const Decl *D = FD;
4381 while ((D = D->getNextDeclInContext()))
4382 if (isa<FieldDecl>(D))
4383 return false;
4384 return true;
Chandler Carruthc2684342011-08-05 09:10:50 +00004385}
4386
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004387void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004388 const ArraySubscriptExpr *ASE,
Richard Smith25b009a2011-12-16 19:31:14 +00004389 bool AllowOnePastEnd, bool IndexNegated) {
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004390 IndexExpr = IndexExpr->IgnoreParenCasts();
4391 if (IndexExpr->isValueDependent())
4392 return;
4393
Matt Beaumont-Gay8ef8f432011-12-12 22:35:02 +00004394 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004395 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth34064582011-02-17 20:55:08 +00004396 const ConstantArrayType *ArrayTy =
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004397 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00004398 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00004399 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00004400
Chandler Carruth34064582011-02-17 20:55:08 +00004401 llvm::APSInt index;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004402 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00004403 return;
Richard Smith25b009a2011-12-16 19:31:14 +00004404 if (IndexNegated)
4405 index = -index;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00004406
Chandler Carruthba447122011-08-05 08:07:29 +00004407 const NamedDecl *ND = NULL;
Chandler Carruthba447122011-08-05 08:07:29 +00004408 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
4409 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruthc2684342011-08-05 09:10:50 +00004410 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruthba447122011-08-05 08:07:29 +00004411 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruthba447122011-08-05 08:07:29 +00004412
Ted Kremenek9e060ca2011-02-23 23:06:04 +00004413 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00004414 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00004415 if (!size.isStrictlyPositive())
4416 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004417
4418 const Type* BaseType = getElementType(BaseExpr);
Nico Weberde5998f2011-09-17 22:59:41 +00004419 if (BaseType != EffectiveType) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004420 // Make sure we're comparing apples to apples when comparing index to size
4421 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
4422 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhraind10f4bc2011-08-10 19:47:25 +00004423 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhrain18f16972011-08-10 18:49:28 +00004424 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004425 if (ptrarith_typesize != array_typesize) {
4426 // There's a cast to a different size type involved
4427 uint64_t ratio = array_typesize / ptrarith_typesize;
4428 // TODO: Be smarter about handling cases where array_typesize is not a
4429 // multiple of ptrarith_typesize
4430 if (ptrarith_typesize * ratio == array_typesize)
4431 size *= llvm::APInt(size.getBitWidth(), ratio);
4432 }
4433 }
4434
Chandler Carruth34064582011-02-17 20:55:08 +00004435 if (size.getBitWidth() > index.getBitWidth())
4436 index = index.sext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00004437 else if (size.getBitWidth() < index.getBitWidth())
4438 size = size.sext(index.getBitWidth());
4439
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004440 // For array subscripting the index must be less than size, but for pointer
4441 // arithmetic also allow the index (offset) to be equal to size since
4442 // computing the next address after the end of the array is legal and
4443 // commonly done e.g. in C++ iterators and range-based for loops.
4444 if (AllowOnePastEnd ? index.sle(size) : index.slt(size))
Chandler Carruthba447122011-08-05 08:07:29 +00004445 return;
4446
4447 // Also don't warn for arrays of size 1 which are members of some
4448 // structure. These are often used to approximate flexible arrays in C89
4449 // code.
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004450 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00004451 return;
Chandler Carruth34064582011-02-17 20:55:08 +00004452
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004453 // Suppress the warning if the subscript expression (as identified by the
4454 // ']' location) and the index expression are both from macro expansions
4455 // within a system header.
4456 if (ASE) {
4457 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
4458 ASE->getRBracketLoc());
4459 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
4460 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
4461 IndexExpr->getLocStart());
4462 if (SourceMgr.isFromSameFile(RBracketLoc, IndexLoc))
4463 return;
4464 }
4465 }
4466
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004467 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004468 if (ASE)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004469 DiagID = diag::warn_array_index_exceeds_bounds;
4470
4471 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
4472 PDiag(DiagID) << index.toString(10, true)
4473 << size.toString(10, true)
4474 << (unsigned)size.getLimitedValue(~0U)
4475 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00004476 } else {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004477 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004478 if (!ASE) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004479 DiagID = diag::warn_ptr_arith_precedes_bounds;
4480 if (index.isNegative()) index = -index;
4481 }
4482
4483 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
4484 PDiag(DiagID) << index.toString(10, true)
4485 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00004486 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00004487
Matt Beaumont-Gaycfbc5b52011-11-29 19:27:11 +00004488 if (!ND) {
4489 // Try harder to find a NamedDecl to point at in the note.
4490 while (const ArraySubscriptExpr *ASE =
4491 dyn_cast<ArraySubscriptExpr>(BaseExpr))
4492 BaseExpr = ASE->getBase()->IgnoreParenCasts();
4493 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
4494 ND = dyn_cast<NamedDecl>(DRE->getDecl());
4495 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
4496 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
4497 }
4498
Chandler Carruth35001ca2011-02-17 21:10:52 +00004499 if (ND)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004500 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
4501 PDiag(diag::note_array_index_out_of_bounds)
4502 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00004503}
4504
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004505void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004506 int AllowOnePastEnd = 0;
4507 while (expr) {
4508 expr = expr->IgnoreParenImpCasts();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004509 switch (expr->getStmtClass()) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004510 case Stmt::ArraySubscriptExprClass: {
4511 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004512 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004513 AllowOnePastEnd > 0);
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004514 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004515 }
4516 case Stmt::UnaryOperatorClass: {
4517 // Only unwrap the * and & unary operators
4518 const UnaryOperator *UO = cast<UnaryOperator>(expr);
4519 expr = UO->getSubExpr();
4520 switch (UO->getOpcode()) {
4521 case UO_AddrOf:
4522 AllowOnePastEnd++;
4523 break;
4524 case UO_Deref:
4525 AllowOnePastEnd--;
4526 break;
4527 default:
4528 return;
4529 }
4530 break;
4531 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004532 case Stmt::ConditionalOperatorClass: {
4533 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
4534 if (const Expr *lhs = cond->getLHS())
4535 CheckArrayAccess(lhs);
4536 if (const Expr *rhs = cond->getRHS())
4537 CheckArrayAccess(rhs);
4538 return;
4539 }
4540 default:
4541 return;
4542 }
Peter Collingbournef111d932011-04-15 00:35:48 +00004543 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004544}
John McCallf85e1932011-06-15 23:02:42 +00004545
4546//===--- CHECK: Objective-C retain cycles ----------------------------------//
4547
4548namespace {
4549 struct RetainCycleOwner {
4550 RetainCycleOwner() : Variable(0), Indirect(false) {}
4551 VarDecl *Variable;
4552 SourceRange Range;
4553 SourceLocation Loc;
4554 bool Indirect;
4555
4556 void setLocsFrom(Expr *e) {
4557 Loc = e->getExprLoc();
4558 Range = e->getSourceRange();
4559 }
4560 };
4561}
4562
4563/// Consider whether capturing the given variable can possibly lead to
4564/// a retain cycle.
4565static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
4566 // In ARC, it's captured strongly iff the variable has __strong
4567 // lifetime. In MRR, it's captured strongly if the variable is
4568 // __block and has an appropriate type.
4569 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
4570 return false;
4571
4572 owner.Variable = var;
4573 owner.setLocsFrom(ref);
4574 return true;
4575}
4576
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00004577static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCallf85e1932011-06-15 23:02:42 +00004578 while (true) {
4579 e = e->IgnoreParens();
4580 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
4581 switch (cast->getCastKind()) {
4582 case CK_BitCast:
4583 case CK_LValueBitCast:
4584 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00004585 case CK_ARCReclaimReturnedObject:
John McCallf85e1932011-06-15 23:02:42 +00004586 e = cast->getSubExpr();
4587 continue;
4588
John McCallf85e1932011-06-15 23:02:42 +00004589 default:
4590 return false;
4591 }
4592 }
4593
4594 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
4595 ObjCIvarDecl *ivar = ref->getDecl();
4596 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
4597 return false;
4598
4599 // Try to find a retain cycle in the base.
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00004600 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCallf85e1932011-06-15 23:02:42 +00004601 return false;
4602
4603 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
4604 owner.Indirect = true;
4605 return true;
4606 }
4607
4608 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
4609 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
4610 if (!var) return false;
4611 return considerVariable(var, ref, owner);
4612 }
4613
4614 if (BlockDeclRefExpr *ref = dyn_cast<BlockDeclRefExpr>(e)) {
4615 owner.Variable = ref->getDecl();
4616 owner.setLocsFrom(ref);
4617 return true;
4618 }
4619
4620 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
4621 if (member->isArrow()) return false;
4622
4623 // Don't count this as an indirect ownership.
4624 e = member->getBase();
4625 continue;
4626 }
4627
John McCall4b9c2d22011-11-06 09:01:30 +00004628 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
4629 // Only pay attention to pseudo-objects on property references.
4630 ObjCPropertyRefExpr *pre
4631 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
4632 ->IgnoreParens());
4633 if (!pre) return false;
4634 if (pre->isImplicitProperty()) return false;
4635 ObjCPropertyDecl *property = pre->getExplicitProperty();
4636 if (!property->isRetaining() &&
4637 !(property->getPropertyIvarDecl() &&
4638 property->getPropertyIvarDecl()->getType()
4639 .getObjCLifetime() == Qualifiers::OCL_Strong))
4640 return false;
4641
4642 owner.Indirect = true;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00004643 if (pre->isSuperReceiver()) {
4644 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
4645 if (!owner.Variable)
4646 return false;
4647 owner.Loc = pre->getLocation();
4648 owner.Range = pre->getSourceRange();
4649 return true;
4650 }
John McCall4b9c2d22011-11-06 09:01:30 +00004651 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
4652 ->getSourceExpr());
4653 continue;
4654 }
4655
John McCallf85e1932011-06-15 23:02:42 +00004656 // Array ivars?
4657
4658 return false;
4659 }
4660}
4661
4662namespace {
4663 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
4664 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
4665 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
4666 Variable(variable), Capturer(0) {}
4667
4668 VarDecl *Variable;
4669 Expr *Capturer;
4670
4671 void VisitDeclRefExpr(DeclRefExpr *ref) {
4672 if (ref->getDecl() == Variable && !Capturer)
4673 Capturer = ref;
4674 }
4675
4676 void VisitBlockDeclRefExpr(BlockDeclRefExpr *ref) {
4677 if (ref->getDecl() == Variable && !Capturer)
4678 Capturer = ref;
4679 }
4680
4681 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
4682 if (Capturer) return;
4683 Visit(ref->getBase());
4684 if (Capturer && ref->isFreeIvar())
4685 Capturer = ref;
4686 }
4687
4688 void VisitBlockExpr(BlockExpr *block) {
4689 // Look inside nested blocks
4690 if (block->getBlockDecl()->capturesVariable(Variable))
4691 Visit(block->getBlockDecl()->getBody());
4692 }
4693 };
4694}
4695
4696/// Check whether the given argument is a block which captures a
4697/// variable.
4698static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
4699 assert(owner.Variable && owner.Loc.isValid());
4700
4701 e = e->IgnoreParenCasts();
4702 BlockExpr *block = dyn_cast<BlockExpr>(e);
4703 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
4704 return 0;
4705
4706 FindCaptureVisitor visitor(S.Context, owner.Variable);
4707 visitor.Visit(block->getBlockDecl()->getBody());
4708 return visitor.Capturer;
4709}
4710
4711static void diagnoseRetainCycle(Sema &S, Expr *capturer,
4712 RetainCycleOwner &owner) {
4713 assert(capturer);
4714 assert(owner.Variable && owner.Loc.isValid());
4715
4716 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
4717 << owner.Variable << capturer->getSourceRange();
4718 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
4719 << owner.Indirect << owner.Range;
4720}
4721
4722/// Check for a keyword selector that starts with the word 'add' or
4723/// 'set'.
4724static bool isSetterLikeSelector(Selector sel) {
4725 if (sel.isUnarySelector()) return false;
4726
Chris Lattner5f9e2722011-07-23 10:55:15 +00004727 StringRef str = sel.getNameForSlot(0);
John McCallf85e1932011-06-15 23:02:42 +00004728 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00004729 if (str.startswith("set"))
John McCallf85e1932011-06-15 23:02:42 +00004730 str = str.substr(3);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00004731 else if (str.startswith("add")) {
4732 // Specially whitelist 'addOperationWithBlock:'.
4733 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
4734 return false;
4735 str = str.substr(3);
4736 }
John McCallf85e1932011-06-15 23:02:42 +00004737 else
4738 return false;
4739
4740 if (str.empty()) return true;
4741 return !islower(str.front());
4742}
4743
4744/// Check a message send to see if it's likely to cause a retain cycle.
4745void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
4746 // Only check instance methods whose selector looks like a setter.
4747 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
4748 return;
4749
4750 // Try to find a variable that the receiver is strongly owned by.
4751 RetainCycleOwner owner;
4752 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00004753 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCallf85e1932011-06-15 23:02:42 +00004754 return;
4755 } else {
4756 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
4757 owner.Variable = getCurMethodDecl()->getSelfDecl();
4758 owner.Loc = msg->getSuperLoc();
4759 owner.Range = msg->getSuperLoc();
4760 }
4761
4762 // Check whether the receiver is captured by any of the arguments.
4763 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
4764 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
4765 return diagnoseRetainCycle(*this, capturer, owner);
4766}
4767
4768/// Check a property assign to see if it's likely to cause a retain cycle.
4769void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
4770 RetainCycleOwner owner;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00004771 if (!findRetainCycleOwner(*this, receiver, owner))
John McCallf85e1932011-06-15 23:02:42 +00004772 return;
4773
4774 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
4775 diagnoseRetainCycle(*this, capturer, owner);
4776}
4777
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004778bool Sema::checkUnsafeAssigns(SourceLocation Loc,
John McCallf85e1932011-06-15 23:02:42 +00004779 QualType LHS, Expr *RHS) {
4780 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
4781 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004782 return false;
4783 // strip off any implicit cast added to get to the one arc-specific
4784 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00004785 if (cast->getCastKind() == CK_ARCConsumeObject) {
John McCallf85e1932011-06-15 23:02:42 +00004786 Diag(Loc, diag::warn_arc_retained_assign)
4787 << (LT == Qualifiers::OCL_ExplicitNone)
4788 << RHS->getSourceRange();
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004789 return true;
4790 }
4791 RHS = cast->getSubExpr();
4792 }
4793 return false;
John McCallf85e1932011-06-15 23:02:42 +00004794}
4795
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004796void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
4797 Expr *LHS, Expr *RHS) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00004798 QualType LHSType;
4799 // PropertyRef on LHS type need be directly obtained from
4800 // its declaration as it has a PsuedoType.
4801 ObjCPropertyRefExpr *PRE
4802 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
4803 if (PRE && !PRE->isImplicitProperty()) {
4804 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
4805 if (PD)
4806 LHSType = PD->getType();
4807 }
4808
4809 if (LHSType.isNull())
4810 LHSType = LHS->getType();
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004811 if (checkUnsafeAssigns(Loc, LHSType, RHS))
4812 return;
4813 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
4814 // FIXME. Check for other life times.
4815 if (LT != Qualifiers::OCL_None)
4816 return;
4817
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00004818 if (PRE) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004819 if (PRE->isImplicitProperty())
4820 return;
4821 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
4822 if (!PD)
4823 return;
4824
4825 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00004826 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
4827 // when 'assign' attribute was not explicitly specified
4828 // by user, ignore it and rely on property type itself
4829 // for lifetime info.
4830 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
4831 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
4832 LHSType->isObjCRetainableType())
4833 return;
4834
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004835 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00004836 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004837 Diag(Loc, diag::warn_arc_retained_property_assign)
4838 << RHS->getSourceRange();
4839 return;
4840 }
4841 RHS = cast->getSubExpr();
4842 }
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00004843 }
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004844 }
4845}
Dmitri Gribenko625bb562012-02-14 22:14:32 +00004846
4847//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
4848
4849namespace {
4850bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
4851 SourceLocation StmtLoc,
4852 const NullStmt *Body) {
4853 // Do not warn if the body is a macro that expands to nothing, e.g:
4854 //
4855 // #define CALL(x)
4856 // if (condition)
4857 // CALL(0);
4858 //
4859 if (Body->hasLeadingEmptyMacro())
4860 return false;
4861
4862 // Get line numbers of statement and body.
4863 bool StmtLineInvalid;
4864 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
4865 &StmtLineInvalid);
4866 if (StmtLineInvalid)
4867 return false;
4868
4869 bool BodyLineInvalid;
4870 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
4871 &BodyLineInvalid);
4872 if (BodyLineInvalid)
4873 return false;
4874
4875 // Warn if null statement and body are on the same line.
4876 if (StmtLine != BodyLine)
4877 return false;
4878
4879 return true;
4880}
4881} // Unnamed namespace
4882
4883void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
4884 const Stmt *Body,
4885 unsigned DiagID) {
4886 // Since this is a syntactic check, don't emit diagnostic for template
4887 // instantiations, this just adds noise.
4888 if (CurrentInstantiationScope)
4889 return;
4890
4891 // The body should be a null statement.
4892 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
4893 if (!NBody)
4894 return;
4895
4896 // Do the usual checks.
4897 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
4898 return;
4899
4900 Diag(NBody->getSemiLoc(), DiagID);
4901 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
4902}
4903
4904void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
4905 const Stmt *PossibleBody) {
4906 assert(!CurrentInstantiationScope); // Ensured by caller
4907
4908 SourceLocation StmtLoc;
4909 const Stmt *Body;
4910 unsigned DiagID;
4911 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
4912 StmtLoc = FS->getRParenLoc();
4913 Body = FS->getBody();
4914 DiagID = diag::warn_empty_for_body;
4915 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
4916 StmtLoc = WS->getCond()->getSourceRange().getEnd();
4917 Body = WS->getBody();
4918 DiagID = diag::warn_empty_while_body;
4919 } else
4920 return; // Neither `for' nor `while'.
4921
4922 // The body should be a null statement.
4923 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
4924 if (!NBody)
4925 return;
4926
4927 // Skip expensive checks if diagnostic is disabled.
4928 if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
4929 DiagnosticsEngine::Ignored)
4930 return;
4931
4932 // Do the usual checks.
4933 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
4934 return;
4935
4936 // `for(...);' and `while(...);' are popular idioms, so in order to keep
4937 // noise level low, emit diagnostics only if for/while is followed by a
4938 // CompoundStmt, e.g.:
4939 // for (int i = 0; i < n; i++);
4940 // {
4941 // a(i);
4942 // }
4943 // or if for/while is followed by a statement with more indentation
4944 // than for/while itself:
4945 // for (int i = 0; i < n; i++);
4946 // a(i);
4947 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
4948 if (!ProbableTypo) {
4949 bool BodyColInvalid;
4950 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
4951 PossibleBody->getLocStart(),
4952 &BodyColInvalid);
4953 if (BodyColInvalid)
4954 return;
4955
4956 bool StmtColInvalid;
4957 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
4958 S->getLocStart(),
4959 &StmtColInvalid);
4960 if (StmtColInvalid)
4961 return;
4962
4963 if (BodyCol > StmtCol)
4964 ProbableTypo = true;
4965 }
4966
4967 if (ProbableTypo) {
4968 Diag(NBody->getSemiLoc(), DiagID);
4969 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
4970 }
4971}
4972