blob: 10cf173216583105939cadbf5137c5dc8e776862 [file] [log] [blame]
Chris Lattner59907c42007-08-10 20:18:51 +00001//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner59907c42007-08-10 20:18:51 +00007//
8//===----------------------------------------------------------------------===//
9//
Mike Stump1eb44332009-09-09 15:08:12 +000010// This file implements extra semantic analysis beyond what is enforced
Chris Lattner59907c42007-08-10 20:18:51 +000011// by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
John McCall5f8d6042011-08-27 01:09:30 +000015#include "clang/Sema/Initialization.h"
Douglas Gregore737f502010-08-12 20:07:10 +000016#include "clang/Sema/Sema.h"
John McCall2d887082010-08-25 22:03:47 +000017#include "clang/Sema/SemaInternal.h"
Eli Friedman276b0612011-10-11 02:20:01 +000018#include "clang/Sema/Initialization.h"
John McCall781472f2010-08-25 08:40:02 +000019#include "clang/Sema/ScopeInfo.h"
Ted Kremenek826a3452010-07-16 02:11:22 +000020#include "clang/Analysis/Analyses/FormatString.h"
Chris Lattner59907c42007-08-10 20:18:51 +000021#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000022#include "clang/AST/CharUnits.h"
John McCall384aff82010-08-25 07:42:41 +000023#include "clang/AST/DeclCXX.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000024#include "clang/AST/DeclObjC.h"
Ted Kremenek23245122007-08-20 16:18:38 +000025#include "clang/AST/ExprCXX.h"
Ted Kremenek7ff22b22008-06-16 18:00:42 +000026#include "clang/AST/ExprObjC.h"
John McCallf85e1932011-06-15 23:02:42 +000027#include "clang/AST/EvaluatedExprVisitor.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000028#include "clang/AST/DeclObjC.h"
29#include "clang/AST/StmtCXX.h"
30#include "clang/AST/StmtObjC.h"
Chris Lattner59907c42007-08-10 20:18:51 +000031#include "clang/Lex/Preprocessor.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000032#include "llvm/ADT/BitVector.h"
33#include "llvm/ADT/STLExtras.h"
Tom Care3bfc5f42010-06-09 04:11:11 +000034#include "llvm/Support/raw_ostream.h"
Eric Christopher691ebc32010-04-17 02:26:23 +000035#include "clang/Basic/TargetBuiltins.h"
Nate Begeman26a31422010-06-08 02:47:44 +000036#include "clang/Basic/TargetInfo.h"
Fariborz Jahanian7da71022010-09-07 19:38:13 +000037#include "clang/Basic/ConvertUTF.h"
Zhongxing Xua1f3dba2009-05-20 01:55:10 +000038#include <limits>
Chris Lattner59907c42007-08-10 20:18:51 +000039using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000040using namespace sema;
Chris Lattner59907c42007-08-10 20:18:51 +000041
Chris Lattner60800082009-02-18 17:49:48 +000042SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
43 unsigned ByteNo) const {
Chris Lattner08f92e32010-11-17 07:37:15 +000044 return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
45 PP.getLangOptions(), PP.getTargetInfo());
Chris Lattner60800082009-02-18 17:49:48 +000046}
47
John McCall8e10f3b2011-02-26 05:39:39 +000048/// Checks that a call expression's argument count is the desired number.
49/// This is useful when doing custom type-checking. Returns true on error.
50static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
51 unsigned argCount = call->getNumArgs();
52 if (argCount == desiredArgCount) return false;
53
54 if (argCount < desiredArgCount)
55 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
56 << 0 /*function call*/ << desiredArgCount << argCount
57 << call->getSourceRange();
58
59 // Highlight all the excess arguments.
60 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
61 call->getArg(argCount - 1)->getLocEnd());
62
63 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
64 << 0 /*function call*/ << desiredArgCount << argCount
65 << call->getArg(1)->getSourceRange();
66}
67
Julien Lerouge77f68bb2011-09-09 22:41:49 +000068/// CheckBuiltinAnnotationString - Checks that string argument to the builtin
69/// annotation is a non wide string literal.
70static bool CheckBuiltinAnnotationString(Sema &S, Expr *Arg) {
71 Arg = Arg->IgnoreParenCasts();
72 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
73 if (!Literal || !Literal->isAscii()) {
74 S.Diag(Arg->getLocStart(), diag::err_builtin_annotation_not_string_constant)
75 << Arg->getSourceRange();
76 return true;
77 }
78 return false;
79}
80
John McCall60d7b3a2010-08-24 06:29:42 +000081ExprResult
Anders Carlssond406bf02009-08-16 01:56:34 +000082Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
John McCall60d7b3a2010-08-24 06:29:42 +000083 ExprResult TheCallResult(Owned(TheCall));
Douglas Gregor2def4832008-11-17 20:34:05 +000084
Chris Lattner946928f2010-10-01 23:23:24 +000085 // Find out if any arguments are required to be integer constant expressions.
86 unsigned ICEArguments = 0;
87 ASTContext::GetBuiltinTypeError Error;
88 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
89 if (Error != ASTContext::GE_None)
90 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
91
92 // If any arguments are required to be ICE's, check and diagnose.
93 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
94 // Skip arguments not required to be ICE's.
95 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
96
97 llvm::APSInt Result;
98 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
99 return true;
100 ICEArguments &= ~(1 << ArgNo);
101 }
102
Anders Carlssond406bf02009-08-16 01:56:34 +0000103 switch (BuiltinID) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000104 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +0000105 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +0000106 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner69039812009-02-18 06:01:06 +0000107 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000108 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000109 break;
Ted Kremenek49ff7a12008-07-09 17:58:53 +0000110 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +0000111 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000112 if (SemaBuiltinVAStart(TheCall))
113 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000114 break;
Chris Lattner1b9a0792007-12-20 00:26:33 +0000115 case Builtin::BI__builtin_isgreater:
116 case Builtin::BI__builtin_isgreaterequal:
117 case Builtin::BI__builtin_isless:
118 case Builtin::BI__builtin_islessequal:
119 case Builtin::BI__builtin_islessgreater:
120 case Builtin::BI__builtin_isunordered:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000121 if (SemaBuiltinUnorderedCompare(TheCall))
122 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000123 break;
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000124 case Builtin::BI__builtin_fpclassify:
125 if (SemaBuiltinFPClassification(TheCall, 6))
126 return ExprError();
127 break;
Eli Friedman9ac6f622009-08-31 20:06:00 +0000128 case Builtin::BI__builtin_isfinite:
129 case Builtin::BI__builtin_isinf:
130 case Builtin::BI__builtin_isinf_sign:
131 case Builtin::BI__builtin_isnan:
132 case Builtin::BI__builtin_isnormal:
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000133 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman9ac6f622009-08-31 20:06:00 +0000134 return ExprError();
135 break;
Eli Friedmand38617c2008-05-14 19:38:39 +0000136 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000137 return SemaBuiltinShuffleVector(TheCall);
138 // TheCall will be freed by the smart pointer here, but that's fine, since
139 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000140 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000141 if (SemaBuiltinPrefetch(TheCall))
142 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000143 break;
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000144 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000145 if (SemaBuiltinObjectSize(TheCall))
146 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000147 break;
Eli Friedmand875fed2009-05-03 04:46:36 +0000148 case Builtin::BI__builtin_longjmp:
149 if (SemaBuiltinLongjmp(TheCall))
150 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000151 break;
John McCall8e10f3b2011-02-26 05:39:39 +0000152
153 case Builtin::BI__builtin_classify_type:
154 if (checkArgCount(*this, TheCall, 1)) return true;
155 TheCall->setType(Context.IntTy);
156 break;
Chris Lattner75c29a02010-10-12 17:47:42 +0000157 case Builtin::BI__builtin_constant_p:
John McCall8e10f3b2011-02-26 05:39:39 +0000158 if (checkArgCount(*this, TheCall, 1)) return true;
159 TheCall->setType(Context.IntTy);
Chris Lattner75c29a02010-10-12 17:47:42 +0000160 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000161 case Builtin::BI__sync_fetch_and_add:
Douglas Gregora9766412011-11-28 16:30:08 +0000162 case Builtin::BI__sync_fetch_and_add_1:
163 case Builtin::BI__sync_fetch_and_add_2:
164 case Builtin::BI__sync_fetch_and_add_4:
165 case Builtin::BI__sync_fetch_and_add_8:
166 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000167 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregora9766412011-11-28 16:30:08 +0000168 case Builtin::BI__sync_fetch_and_sub_1:
169 case Builtin::BI__sync_fetch_and_sub_2:
170 case Builtin::BI__sync_fetch_and_sub_4:
171 case Builtin::BI__sync_fetch_and_sub_8:
172 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000173 case Builtin::BI__sync_fetch_and_or:
Douglas Gregora9766412011-11-28 16:30:08 +0000174 case Builtin::BI__sync_fetch_and_or_1:
175 case Builtin::BI__sync_fetch_and_or_2:
176 case Builtin::BI__sync_fetch_and_or_4:
177 case Builtin::BI__sync_fetch_and_or_8:
178 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000179 case Builtin::BI__sync_fetch_and_and:
Douglas Gregora9766412011-11-28 16:30:08 +0000180 case Builtin::BI__sync_fetch_and_and_1:
181 case Builtin::BI__sync_fetch_and_and_2:
182 case Builtin::BI__sync_fetch_and_and_4:
183 case Builtin::BI__sync_fetch_and_and_8:
184 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000185 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregora9766412011-11-28 16:30:08 +0000186 case Builtin::BI__sync_fetch_and_xor_1:
187 case Builtin::BI__sync_fetch_and_xor_2:
188 case Builtin::BI__sync_fetch_and_xor_4:
189 case Builtin::BI__sync_fetch_and_xor_8:
190 case Builtin::BI__sync_fetch_and_xor_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000191 case Builtin::BI__sync_add_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000192 case Builtin::BI__sync_add_and_fetch_1:
193 case Builtin::BI__sync_add_and_fetch_2:
194 case Builtin::BI__sync_add_and_fetch_4:
195 case Builtin::BI__sync_add_and_fetch_8:
196 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000197 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000198 case Builtin::BI__sync_sub_and_fetch_1:
199 case Builtin::BI__sync_sub_and_fetch_2:
200 case Builtin::BI__sync_sub_and_fetch_4:
201 case Builtin::BI__sync_sub_and_fetch_8:
202 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000203 case Builtin::BI__sync_and_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000204 case Builtin::BI__sync_and_and_fetch_1:
205 case Builtin::BI__sync_and_and_fetch_2:
206 case Builtin::BI__sync_and_and_fetch_4:
207 case Builtin::BI__sync_and_and_fetch_8:
208 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000209 case Builtin::BI__sync_or_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000210 case Builtin::BI__sync_or_and_fetch_1:
211 case Builtin::BI__sync_or_and_fetch_2:
212 case Builtin::BI__sync_or_and_fetch_4:
213 case Builtin::BI__sync_or_and_fetch_8:
214 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000215 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000216 case Builtin::BI__sync_xor_and_fetch_1:
217 case Builtin::BI__sync_xor_and_fetch_2:
218 case Builtin::BI__sync_xor_and_fetch_4:
219 case Builtin::BI__sync_xor_and_fetch_8:
220 case Builtin::BI__sync_xor_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000221 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000222 case Builtin::BI__sync_val_compare_and_swap_1:
223 case Builtin::BI__sync_val_compare_and_swap_2:
224 case Builtin::BI__sync_val_compare_and_swap_4:
225 case Builtin::BI__sync_val_compare_and_swap_8:
226 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000227 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000228 case Builtin::BI__sync_bool_compare_and_swap_1:
229 case Builtin::BI__sync_bool_compare_and_swap_2:
230 case Builtin::BI__sync_bool_compare_and_swap_4:
231 case Builtin::BI__sync_bool_compare_and_swap_8:
232 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000233 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregora9766412011-11-28 16:30:08 +0000234 case Builtin::BI__sync_lock_test_and_set_1:
235 case Builtin::BI__sync_lock_test_and_set_2:
236 case Builtin::BI__sync_lock_test_and_set_4:
237 case Builtin::BI__sync_lock_test_and_set_8:
238 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000239 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +0000240 case Builtin::BI__sync_lock_release_1:
241 case Builtin::BI__sync_lock_release_2:
242 case Builtin::BI__sync_lock_release_4:
243 case Builtin::BI__sync_lock_release_8:
244 case Builtin::BI__sync_lock_release_16:
Chris Lattner23aa9c82011-04-09 03:57:26 +0000245 case Builtin::BI__sync_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000246 case Builtin::BI__sync_swap_1:
247 case Builtin::BI__sync_swap_2:
248 case Builtin::BI__sync_swap_4:
249 case Builtin::BI__sync_swap_8:
250 case Builtin::BI__sync_swap_16:
Chandler Carruthd2014572010-07-09 18:59:35 +0000251 return SemaBuiltinAtomicOverloaded(move(TheCallResult));
Eli Friedman276b0612011-10-11 02:20:01 +0000252 case Builtin::BI__atomic_load:
253 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Load);
254 case Builtin::BI__atomic_store:
255 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Store);
David Chisnall7a7ee302012-01-16 17:27:18 +0000256 case Builtin::BI__atomic_init:
257 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Init);
Eli Friedman276b0612011-10-11 02:20:01 +0000258 case Builtin::BI__atomic_exchange:
259 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Xchg);
260 case Builtin::BI__atomic_compare_exchange_strong:
261 return SemaAtomicOpsOverloaded(move(TheCallResult),
262 AtomicExpr::CmpXchgStrong);
263 case Builtin::BI__atomic_compare_exchange_weak:
264 return SemaAtomicOpsOverloaded(move(TheCallResult),
265 AtomicExpr::CmpXchgWeak);
266 case Builtin::BI__atomic_fetch_add:
267 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Add);
268 case Builtin::BI__atomic_fetch_sub:
269 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Sub);
270 case Builtin::BI__atomic_fetch_and:
271 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::And);
272 case Builtin::BI__atomic_fetch_or:
273 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Or);
274 case Builtin::BI__atomic_fetch_xor:
275 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Xor);
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000276 case Builtin::BI__builtin_annotation:
277 if (CheckBuiltinAnnotationString(*this, TheCall->getArg(1)))
278 return ExprError();
279 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000280 }
281
282 // Since the target specific builtins for each arch overlap, only check those
283 // of the arch we are compiling for.
284 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000285 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman26a31422010-06-08 02:47:44 +0000286 case llvm::Triple::arm:
287 case llvm::Triple::thumb:
288 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
289 return ExprError();
290 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000291 default:
292 break;
293 }
294 }
295
296 return move(TheCallResult);
297}
298
Nate Begeman61eecf52010-06-14 05:21:25 +0000299// Get the valid immediate range for the specified NEON type code.
300static unsigned RFT(unsigned t, bool shift = false) {
Bob Wilsonda95f732011-11-08 01:16:11 +0000301 NeonTypeFlags Type(t);
302 int IsQuad = Type.isQuad();
303 switch (Type.getEltType()) {
304 case NeonTypeFlags::Int8:
305 case NeonTypeFlags::Poly8:
306 return shift ? 7 : (8 << IsQuad) - 1;
307 case NeonTypeFlags::Int16:
308 case NeonTypeFlags::Poly16:
309 return shift ? 15 : (4 << IsQuad) - 1;
310 case NeonTypeFlags::Int32:
311 return shift ? 31 : (2 << IsQuad) - 1;
312 case NeonTypeFlags::Int64:
313 return shift ? 63 : (1 << IsQuad) - 1;
314 case NeonTypeFlags::Float16:
315 assert(!shift && "cannot shift float types!");
316 return (4 << IsQuad) - 1;
317 case NeonTypeFlags::Float32:
318 assert(!shift && "cannot shift float types!");
319 return (2 << IsQuad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000320 }
David Blaikie7530c032012-01-17 06:56:22 +0000321 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman61eecf52010-06-14 05:21:25 +0000322}
323
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000324/// getNeonEltType - Return the QualType corresponding to the elements of
325/// the vector type specified by the NeonTypeFlags. This is used to check
326/// the pointer arguments for Neon load/store intrinsics.
327static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context) {
328 switch (Flags.getEltType()) {
329 case NeonTypeFlags::Int8:
330 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
331 case NeonTypeFlags::Int16:
332 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
333 case NeonTypeFlags::Int32:
334 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
335 case NeonTypeFlags::Int64:
336 return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy;
337 case NeonTypeFlags::Poly8:
338 return Context.SignedCharTy;
339 case NeonTypeFlags::Poly16:
340 return Context.ShortTy;
341 case NeonTypeFlags::Float16:
342 return Context.UnsignedShortTy;
343 case NeonTypeFlags::Float32:
344 return Context.FloatTy;
345 }
David Blaikie7530c032012-01-17 06:56:22 +0000346 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000347}
348
Nate Begeman26a31422010-06-08 02:47:44 +0000349bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000350 llvm::APSInt Result;
351
Nate Begeman0d15c532010-06-13 04:47:52 +0000352 unsigned mask = 0;
Nate Begeman61eecf52010-06-14 05:21:25 +0000353 unsigned TV = 0;
Bob Wilson46482552011-11-16 21:32:23 +0000354 int PtrArgNum = -1;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000355 bool HasConstPtr = false;
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000356 switch (BuiltinID) {
Nate Begemana23326b2010-06-17 04:17:01 +0000357#define GET_NEON_OVERLOAD_CHECK
358#include "clang/Basic/arm_neon.inc"
359#undef GET_NEON_OVERLOAD_CHECK
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000360 }
361
Nate Begeman0d15c532010-06-13 04:47:52 +0000362 // For NEON intrinsics which are overloaded on vector element type, validate
363 // the immediate which specifies which variant to emit.
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000364 unsigned ImmArg = TheCall->getNumArgs()-1;
Nate Begeman0d15c532010-06-13 04:47:52 +0000365 if (mask) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000366 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
Nate Begeman0d15c532010-06-13 04:47:52 +0000367 return true;
368
Bob Wilsonda95f732011-11-08 01:16:11 +0000369 TV = Result.getLimitedValue(64);
370 if ((TV > 63) || (mask & (1 << TV)) == 0)
Nate Begeman0d15c532010-06-13 04:47:52 +0000371 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000372 << TheCall->getArg(ImmArg)->getSourceRange();
373 }
374
Bob Wilson46482552011-11-16 21:32:23 +0000375 if (PtrArgNum >= 0) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000376 // Check that pointer arguments have the specified type.
Bob Wilson46482552011-11-16 21:32:23 +0000377 Expr *Arg = TheCall->getArg(PtrArgNum);
378 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
379 Arg = ICE->getSubExpr();
380 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
381 QualType RHSTy = RHS.get()->getType();
382 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context);
383 if (HasConstPtr)
384 EltTy = EltTy.withConst();
385 QualType LHSTy = Context.getPointerType(EltTy);
386 AssignConvertType ConvTy;
387 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
388 if (RHS.isInvalid())
389 return true;
390 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
391 RHS.get(), AA_Assigning))
392 return true;
Nate Begeman0d15c532010-06-13 04:47:52 +0000393 }
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000394
Nate Begeman0d15c532010-06-13 04:47:52 +0000395 // For NEON intrinsics which take an immediate value as part of the
396 // instruction, range check them here.
Nate Begeman61eecf52010-06-14 05:21:25 +0000397 unsigned i = 0, l = 0, u = 0;
Nate Begeman0d15c532010-06-13 04:47:52 +0000398 switch (BuiltinID) {
399 default: return false;
Nate Begemanbb37f502010-07-29 22:48:34 +0000400 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
401 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begeman99c40bb2010-08-03 21:32:34 +0000402 case ARM::BI__builtin_arm_vcvtr_f:
403 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Nate Begemana23326b2010-06-17 04:17:01 +0000404#define GET_NEON_IMMEDIATE_CHECK
405#include "clang/Basic/arm_neon.inc"
406#undef GET_NEON_IMMEDIATE_CHECK
Nate Begeman0d15c532010-06-13 04:47:52 +0000407 };
408
Nate Begeman61eecf52010-06-14 05:21:25 +0000409 // Check that the immediate argument is actually a constant.
Nate Begeman0d15c532010-06-13 04:47:52 +0000410 if (SemaBuiltinConstantArg(TheCall, i, Result))
411 return true;
412
Nate Begeman61eecf52010-06-14 05:21:25 +0000413 // Range check against the upper/lower values for this isntruction.
Nate Begeman0d15c532010-06-13 04:47:52 +0000414 unsigned Val = Result.getZExtValue();
Nate Begeman61eecf52010-06-14 05:21:25 +0000415 if (Val < l || Val > (u + l))
Nate Begeman0d15c532010-06-13 04:47:52 +0000416 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramer476d8b82010-08-11 14:47:12 +0000417 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begeman0d15c532010-06-13 04:47:52 +0000418
Nate Begeman99c40bb2010-08-03 21:32:34 +0000419 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman26a31422010-06-08 02:47:44 +0000420 return false;
Anders Carlssond406bf02009-08-16 01:56:34 +0000421}
Daniel Dunbarde454282008-10-02 18:44:07 +0000422
Anders Carlssond406bf02009-08-16 01:56:34 +0000423/// CheckFunctionCall - Check a direct function call for various correctness
424/// and safety properties not strictly enforced by the C type system.
425bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
426 // Get the IdentifierInfo* for the called function.
427 IdentifierInfo *FnInfo = FDecl->getIdentifier();
428
429 // None of the checks below are needed for functions that don't have
430 // simple names (e.g., C++ conversion functions).
431 if (!FnInfo)
432 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000433
Daniel Dunbarde454282008-10-02 18:44:07 +0000434 // FIXME: This mechanism should be abstracted to be less fragile and
435 // more efficient. For example, just map function ids to custom
436 // handlers.
437
Ted Kremenekc82faca2010-09-09 04:33:05 +0000438 // Printf and scanf checking.
439 for (specific_attr_iterator<FormatAttr>
440 i = FDecl->specific_attr_begin<FormatAttr>(),
441 e = FDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000442 CheckFormatArguments(*i, TheCall);
Chris Lattner59907c42007-08-10 20:18:51 +0000443 }
Mike Stump1eb44332009-09-09 15:08:12 +0000444
Ted Kremenekc82faca2010-09-09 04:33:05 +0000445 for (specific_attr_iterator<NonNullAttr>
446 i = FDecl->specific_attr_begin<NonNullAttr>(),
447 e = FDecl->specific_attr_end<NonNullAttr>(); i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +0000448 CheckNonNullArguments(*i, TheCall->getArgs(),
449 TheCall->getCallee()->getLocStart());
Ted Kremenekc82faca2010-09-09 04:33:05 +0000450 }
Sebastian Redl0eb23302009-01-19 00:08:26 +0000451
Anna Zaks0a151a12012-01-17 00:37:07 +0000452 unsigned CMId = FDecl->getMemoryFunctionKind();
453 if (CMId == 0)
Anna Zaksd9b859a2012-01-13 21:52:01 +0000454 return false;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000455
Anna Zaksd9b859a2012-01-13 21:52:01 +0000456 // Handle memory setting and copying functions.
Anna Zaks0a151a12012-01-17 00:37:07 +0000457 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000458 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaksc36bedc2012-02-01 19:08:57 +0000459 else if (CMId == Builtin::BIstrncat)
460 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaksd9b859a2012-01-13 21:52:01 +0000461 else
Anna Zaks0a151a12012-01-17 00:37:07 +0000462 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth7ccc95b2011-04-27 07:05:31 +0000463
Anders Carlssond406bf02009-08-16 01:56:34 +0000464 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000465}
466
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000467bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
468 Expr **Args, unsigned NumArgs) {
469 for (specific_attr_iterator<FormatAttr>
470 i = Method->specific_attr_begin<FormatAttr>(),
471 e = Method->specific_attr_end<FormatAttr>(); i != e ; ++i) {
472
473 CheckFormatArguments(*i, Args, NumArgs, false, lbrac,
474 Method->getSourceRange());
475 }
476
477 // diagnose nonnull arguments.
478 for (specific_attr_iterator<NonNullAttr>
479 i = Method->specific_attr_begin<NonNullAttr>(),
480 e = Method->specific_attr_end<NonNullAttr>(); i != e; ++i) {
481 CheckNonNullArguments(*i, Args, lbrac);
482 }
483
484 return false;
485}
486
Anders Carlssond406bf02009-08-16 01:56:34 +0000487bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000488 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
489 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000490 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000491
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000492 QualType Ty = V->getType();
493 if (!Ty->isBlockPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000494 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000495
Jean-Daniel Dupas43d12512012-01-25 00:55:11 +0000496 // format string checking.
497 for (specific_attr_iterator<FormatAttr>
498 i = NDecl->specific_attr_begin<FormatAttr>(),
499 e = NDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) {
500 CheckFormatArguments(*i, TheCall);
501 }
Anders Carlssond406bf02009-08-16 01:56:34 +0000502
503 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000504}
505
Eli Friedman276b0612011-10-11 02:20:01 +0000506ExprResult
507Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, AtomicExpr::AtomicOp Op) {
508 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
509 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedman276b0612011-10-11 02:20:01 +0000510
511 // All these operations take one of the following four forms:
512 // T __atomic_load(_Atomic(T)*, int) (loads)
513 // T* __atomic_add(_Atomic(T*)*, ptrdiff_t, int) (pointer add/sub)
514 // int __atomic_compare_exchange_strong(_Atomic(T)*, T*, T, int, int)
515 // (cmpxchg)
516 // T __atomic_exchange(_Atomic(T)*, T, int) (everything else)
517 // where T is an appropriate type, and the int paremeterss are for orderings.
518 unsigned NumVals = 1;
519 unsigned NumOrders = 1;
520 if (Op == AtomicExpr::Load) {
521 NumVals = 0;
522 } else if (Op == AtomicExpr::CmpXchgWeak || Op == AtomicExpr::CmpXchgStrong) {
523 NumVals = 2;
524 NumOrders = 2;
525 }
David Chisnall7a7ee302012-01-16 17:27:18 +0000526 if (Op == AtomicExpr::Init)
527 NumOrders = 0;
Eli Friedman276b0612011-10-11 02:20:01 +0000528
529 if (TheCall->getNumArgs() < NumVals+NumOrders+1) {
530 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
531 << 0 << NumVals+NumOrders+1 << TheCall->getNumArgs()
532 << TheCall->getCallee()->getSourceRange();
533 return ExprError();
534 } else if (TheCall->getNumArgs() > NumVals+NumOrders+1) {
535 Diag(TheCall->getArg(NumVals+NumOrders+1)->getLocStart(),
536 diag::err_typecheck_call_too_many_args)
537 << 0 << NumVals+NumOrders+1 << TheCall->getNumArgs()
538 << TheCall->getCallee()->getSourceRange();
539 return ExprError();
540 }
541
542 // Inspect the first argument of the atomic operation. This should always be
543 // a pointer to an _Atomic type.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000544 Expr *Ptr = TheCall->getArg(0);
Eli Friedman276b0612011-10-11 02:20:01 +0000545 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
546 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
547 if (!pointerType) {
548 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
549 << Ptr->getType() << Ptr->getSourceRange();
550 return ExprError();
551 }
552
553 QualType AtomTy = pointerType->getPointeeType();
554 if (!AtomTy->isAtomicType()) {
555 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
556 << Ptr->getType() << Ptr->getSourceRange();
557 return ExprError();
558 }
559 QualType ValType = AtomTy->getAs<AtomicType>()->getValueType();
560
561 if ((Op == AtomicExpr::Add || Op == AtomicExpr::Sub) &&
562 !ValType->isIntegerType() && !ValType->isPointerType()) {
563 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
564 << Ptr->getType() << Ptr->getSourceRange();
565 return ExprError();
566 }
567
568 if (!ValType->isIntegerType() &&
569 (Op == AtomicExpr::And || Op == AtomicExpr::Or || Op == AtomicExpr::Xor)){
570 Diag(DRE->getLocStart(), diag::err_atomic_op_logical_needs_atomic_int)
571 << Ptr->getType() << Ptr->getSourceRange();
572 return ExprError();
573 }
574
575 switch (ValType.getObjCLifetime()) {
576 case Qualifiers::OCL_None:
577 case Qualifiers::OCL_ExplicitNone:
578 // okay
579 break;
580
581 case Qualifiers::OCL_Weak:
582 case Qualifiers::OCL_Strong:
583 case Qualifiers::OCL_Autoreleasing:
584 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
585 << ValType << Ptr->getSourceRange();
586 return ExprError();
587 }
588
589 QualType ResultType = ValType;
David Chisnall7a7ee302012-01-16 17:27:18 +0000590 if (Op == AtomicExpr::Store || Op == AtomicExpr::Init)
Eli Friedman276b0612011-10-11 02:20:01 +0000591 ResultType = Context.VoidTy;
592 else if (Op == AtomicExpr::CmpXchgWeak || Op == AtomicExpr::CmpXchgStrong)
593 ResultType = Context.BoolTy;
594
595 // The first argument --- the pointer --- has a fixed type; we
596 // deduce the types of the rest of the arguments accordingly. Walk
597 // the remaining arguments, converting them to the deduced value type.
598 for (unsigned i = 1; i != NumVals+NumOrders+1; ++i) {
599 ExprResult Arg = TheCall->getArg(i);
600 QualType Ty;
601 if (i < NumVals+1) {
602 // The second argument to a cmpxchg is a pointer to the data which will
603 // be exchanged. The second argument to a pointer add/subtract is the
604 // amount to add/subtract, which must be a ptrdiff_t. The third
605 // argument to a cmpxchg and the second argument in all other cases
606 // is the type of the value.
607 if (i == 1 && (Op == AtomicExpr::CmpXchgWeak ||
608 Op == AtomicExpr::CmpXchgStrong))
609 Ty = Context.getPointerType(ValType.getUnqualifiedType());
610 else if (!ValType->isIntegerType() &&
611 (Op == AtomicExpr::Add || Op == AtomicExpr::Sub))
612 Ty = Context.getPointerDiffType();
613 else
614 Ty = ValType;
615 } else {
616 // The order(s) are always converted to int.
617 Ty = Context.IntTy;
618 }
619 InitializedEntity Entity =
620 InitializedEntity::InitializeParameter(Context, Ty, false);
621 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
622 if (Arg.isInvalid())
623 return true;
624 TheCall->setArg(i, Arg.get());
625 }
626
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000627 SmallVector<Expr*, 5> SubExprs;
628 SubExprs.push_back(Ptr);
Eli Friedman276b0612011-10-11 02:20:01 +0000629 if (Op == AtomicExpr::Load) {
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000630 SubExprs.push_back(TheCall->getArg(1)); // Order
David Chisnall7a7ee302012-01-16 17:27:18 +0000631 } else if (Op == AtomicExpr::Init) {
632 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman276b0612011-10-11 02:20:01 +0000633 } else if (Op != AtomicExpr::CmpXchgWeak && Op != AtomicExpr::CmpXchgStrong) {
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000634 SubExprs.push_back(TheCall->getArg(2)); // Order
635 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman276b0612011-10-11 02:20:01 +0000636 } else {
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000637 SubExprs.push_back(TheCall->getArg(3)); // Order
638 SubExprs.push_back(TheCall->getArg(1)); // Val1
639 SubExprs.push_back(TheCall->getArg(2)); // Val2
640 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
Eli Friedman276b0612011-10-11 02:20:01 +0000641 }
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000642
643 return Owned(new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
644 SubExprs.data(), SubExprs.size(),
645 ResultType, Op,
646 TheCall->getRParenLoc()));
Eli Friedman276b0612011-10-11 02:20:01 +0000647}
648
649
John McCall5f8d6042011-08-27 01:09:30 +0000650/// checkBuiltinArgument - Given a call to a builtin function, perform
651/// normal type-checking on the given argument, updating the call in
652/// place. This is useful when a builtin function requires custom
653/// type-checking for some of its arguments but not necessarily all of
654/// them.
655///
656/// Returns true on error.
657static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
658 FunctionDecl *Fn = E->getDirectCallee();
659 assert(Fn && "builtin call without direct callee!");
660
661 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
662 InitializedEntity Entity =
663 InitializedEntity::InitializeParameter(S.Context, Param);
664
665 ExprResult Arg = E->getArg(0);
666 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
667 if (Arg.isInvalid())
668 return true;
669
670 E->setArg(ArgIndex, Arg.take());
671 return false;
672}
673
Chris Lattner5caa3702009-05-08 06:58:22 +0000674/// SemaBuiltinAtomicOverloaded - We have a call to a function like
675/// __sync_fetch_and_add, which is an overloaded function based on the pointer
676/// type of its first argument. The main ActOnCallExpr routines have already
677/// promoted the types of arguments because all of these calls are prototyped as
678/// void(...).
679///
680/// This function goes through and does final semantic checking for these
681/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +0000682ExprResult
683Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000684 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +0000685 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
686 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
687
688 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +0000689 if (TheCall->getNumArgs() < 1) {
690 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
691 << 0 << 1 << TheCall->getNumArgs()
692 << TheCall->getCallee()->getSourceRange();
693 return ExprError();
694 }
Mike Stump1eb44332009-09-09 15:08:12 +0000695
Chris Lattner5caa3702009-05-08 06:58:22 +0000696 // Inspect the first argument of the atomic builtin. This should always be
697 // a pointer type, whose element is an integral scalar or pointer type.
698 // Because it is a pointer type, we don't have to worry about any implicit
699 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +0000700 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +0000701 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman8c382062012-01-23 02:35:22 +0000702 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
703 if (FirstArgResult.isInvalid())
704 return ExprError();
705 FirstArg = FirstArgResult.take();
706 TheCall->setArg(0, FirstArg);
707
John McCallf85e1932011-06-15 23:02:42 +0000708 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
709 if (!pointerType) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000710 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
711 << FirstArg->getType() << FirstArg->getSourceRange();
712 return ExprError();
713 }
Mike Stump1eb44332009-09-09 15:08:12 +0000714
John McCallf85e1932011-06-15 23:02:42 +0000715 QualType ValType = pointerType->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +0000716 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +0000717 !ValType->isBlockPointerType()) {
718 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
719 << FirstArg->getType() << FirstArg->getSourceRange();
720 return ExprError();
721 }
Chris Lattner5caa3702009-05-08 06:58:22 +0000722
John McCallf85e1932011-06-15 23:02:42 +0000723 switch (ValType.getObjCLifetime()) {
724 case Qualifiers::OCL_None:
725 case Qualifiers::OCL_ExplicitNone:
726 // okay
727 break;
728
729 case Qualifiers::OCL_Weak:
730 case Qualifiers::OCL_Strong:
731 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +0000732 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCallf85e1932011-06-15 23:02:42 +0000733 << ValType << FirstArg->getSourceRange();
734 return ExprError();
735 }
736
John McCallb45ae252011-10-05 07:41:44 +0000737 // Strip any qualifiers off ValType.
738 ValType = ValType.getUnqualifiedType();
739
Chandler Carruth8d13d222010-07-18 20:54:12 +0000740 // The majority of builtins return a value, but a few have special return
741 // types, so allow them to override appropriately below.
742 QualType ResultType = ValType;
743
Chris Lattner5caa3702009-05-08 06:58:22 +0000744 // We need to figure out which concrete builtin this maps onto. For example,
745 // __sync_fetch_and_add with a 2 byte object turns into
746 // __sync_fetch_and_add_2.
747#define BUILTIN_ROW(x) \
748 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
749 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +0000750
Chris Lattner5caa3702009-05-08 06:58:22 +0000751 static const unsigned BuiltinIndices[][5] = {
752 BUILTIN_ROW(__sync_fetch_and_add),
753 BUILTIN_ROW(__sync_fetch_and_sub),
754 BUILTIN_ROW(__sync_fetch_and_or),
755 BUILTIN_ROW(__sync_fetch_and_and),
756 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +0000757
Chris Lattner5caa3702009-05-08 06:58:22 +0000758 BUILTIN_ROW(__sync_add_and_fetch),
759 BUILTIN_ROW(__sync_sub_and_fetch),
760 BUILTIN_ROW(__sync_and_and_fetch),
761 BUILTIN_ROW(__sync_or_and_fetch),
762 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +0000763
Chris Lattner5caa3702009-05-08 06:58:22 +0000764 BUILTIN_ROW(__sync_val_compare_and_swap),
765 BUILTIN_ROW(__sync_bool_compare_and_swap),
766 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner23aa9c82011-04-09 03:57:26 +0000767 BUILTIN_ROW(__sync_lock_release),
768 BUILTIN_ROW(__sync_swap)
Chris Lattner5caa3702009-05-08 06:58:22 +0000769 };
Mike Stump1eb44332009-09-09 15:08:12 +0000770#undef BUILTIN_ROW
771
Chris Lattner5caa3702009-05-08 06:58:22 +0000772 // Determine the index of the size.
773 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +0000774 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +0000775 case 1: SizeIndex = 0; break;
776 case 2: SizeIndex = 1; break;
777 case 4: SizeIndex = 2; break;
778 case 8: SizeIndex = 3; break;
779 case 16: SizeIndex = 4; break;
780 default:
Chandler Carruthd2014572010-07-09 18:59:35 +0000781 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
782 << FirstArg->getType() << FirstArg->getSourceRange();
783 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +0000784 }
Mike Stump1eb44332009-09-09 15:08:12 +0000785
Chris Lattner5caa3702009-05-08 06:58:22 +0000786 // Each of these builtins has one pointer argument, followed by some number of
787 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
788 // that we ignore. Find out which row of BuiltinIndices to read from as well
789 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +0000790 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +0000791 unsigned BuiltinIndex, NumFixed = 1;
792 switch (BuiltinID) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000793 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregora9766412011-11-28 16:30:08 +0000794 case Builtin::BI__sync_fetch_and_add:
795 case Builtin::BI__sync_fetch_and_add_1:
796 case Builtin::BI__sync_fetch_and_add_2:
797 case Builtin::BI__sync_fetch_and_add_4:
798 case Builtin::BI__sync_fetch_and_add_8:
799 case Builtin::BI__sync_fetch_and_add_16:
800 BuiltinIndex = 0;
801 break;
802
803 case Builtin::BI__sync_fetch_and_sub:
804 case Builtin::BI__sync_fetch_and_sub_1:
805 case Builtin::BI__sync_fetch_and_sub_2:
806 case Builtin::BI__sync_fetch_and_sub_4:
807 case Builtin::BI__sync_fetch_and_sub_8:
808 case Builtin::BI__sync_fetch_and_sub_16:
809 BuiltinIndex = 1;
810 break;
811
812 case Builtin::BI__sync_fetch_and_or:
813 case Builtin::BI__sync_fetch_and_or_1:
814 case Builtin::BI__sync_fetch_and_or_2:
815 case Builtin::BI__sync_fetch_and_or_4:
816 case Builtin::BI__sync_fetch_and_or_8:
817 case Builtin::BI__sync_fetch_and_or_16:
818 BuiltinIndex = 2;
819 break;
820
821 case Builtin::BI__sync_fetch_and_and:
822 case Builtin::BI__sync_fetch_and_and_1:
823 case Builtin::BI__sync_fetch_and_and_2:
824 case Builtin::BI__sync_fetch_and_and_4:
825 case Builtin::BI__sync_fetch_and_and_8:
826 case Builtin::BI__sync_fetch_and_and_16:
827 BuiltinIndex = 3;
828 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000829
Douglas Gregora9766412011-11-28 16:30:08 +0000830 case Builtin::BI__sync_fetch_and_xor:
831 case Builtin::BI__sync_fetch_and_xor_1:
832 case Builtin::BI__sync_fetch_and_xor_2:
833 case Builtin::BI__sync_fetch_and_xor_4:
834 case Builtin::BI__sync_fetch_and_xor_8:
835 case Builtin::BI__sync_fetch_and_xor_16:
836 BuiltinIndex = 4;
837 break;
838
839 case Builtin::BI__sync_add_and_fetch:
840 case Builtin::BI__sync_add_and_fetch_1:
841 case Builtin::BI__sync_add_and_fetch_2:
842 case Builtin::BI__sync_add_and_fetch_4:
843 case Builtin::BI__sync_add_and_fetch_8:
844 case Builtin::BI__sync_add_and_fetch_16:
845 BuiltinIndex = 5;
846 break;
847
848 case Builtin::BI__sync_sub_and_fetch:
849 case Builtin::BI__sync_sub_and_fetch_1:
850 case Builtin::BI__sync_sub_and_fetch_2:
851 case Builtin::BI__sync_sub_and_fetch_4:
852 case Builtin::BI__sync_sub_and_fetch_8:
853 case Builtin::BI__sync_sub_and_fetch_16:
854 BuiltinIndex = 6;
855 break;
856
857 case Builtin::BI__sync_and_and_fetch:
858 case Builtin::BI__sync_and_and_fetch_1:
859 case Builtin::BI__sync_and_and_fetch_2:
860 case Builtin::BI__sync_and_and_fetch_4:
861 case Builtin::BI__sync_and_and_fetch_8:
862 case Builtin::BI__sync_and_and_fetch_16:
863 BuiltinIndex = 7;
864 break;
865
866 case Builtin::BI__sync_or_and_fetch:
867 case Builtin::BI__sync_or_and_fetch_1:
868 case Builtin::BI__sync_or_and_fetch_2:
869 case Builtin::BI__sync_or_and_fetch_4:
870 case Builtin::BI__sync_or_and_fetch_8:
871 case Builtin::BI__sync_or_and_fetch_16:
872 BuiltinIndex = 8;
873 break;
874
875 case Builtin::BI__sync_xor_and_fetch:
876 case Builtin::BI__sync_xor_and_fetch_1:
877 case Builtin::BI__sync_xor_and_fetch_2:
878 case Builtin::BI__sync_xor_and_fetch_4:
879 case Builtin::BI__sync_xor_and_fetch_8:
880 case Builtin::BI__sync_xor_and_fetch_16:
881 BuiltinIndex = 9;
882 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000883
Chris Lattner5caa3702009-05-08 06:58:22 +0000884 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000885 case Builtin::BI__sync_val_compare_and_swap_1:
886 case Builtin::BI__sync_val_compare_and_swap_2:
887 case Builtin::BI__sync_val_compare_and_swap_4:
888 case Builtin::BI__sync_val_compare_and_swap_8:
889 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000890 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +0000891 NumFixed = 2;
892 break;
Douglas Gregora9766412011-11-28 16:30:08 +0000893
Chris Lattner5caa3702009-05-08 06:58:22 +0000894 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000895 case Builtin::BI__sync_bool_compare_and_swap_1:
896 case Builtin::BI__sync_bool_compare_and_swap_2:
897 case Builtin::BI__sync_bool_compare_and_swap_4:
898 case Builtin::BI__sync_bool_compare_and_swap_8:
899 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000900 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +0000901 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +0000902 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +0000903 break;
Douglas Gregora9766412011-11-28 16:30:08 +0000904
905 case Builtin::BI__sync_lock_test_and_set:
906 case Builtin::BI__sync_lock_test_and_set_1:
907 case Builtin::BI__sync_lock_test_and_set_2:
908 case Builtin::BI__sync_lock_test_and_set_4:
909 case Builtin::BI__sync_lock_test_and_set_8:
910 case Builtin::BI__sync_lock_test_and_set_16:
911 BuiltinIndex = 12;
912 break;
913
Chris Lattner5caa3702009-05-08 06:58:22 +0000914 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +0000915 case Builtin::BI__sync_lock_release_1:
916 case Builtin::BI__sync_lock_release_2:
917 case Builtin::BI__sync_lock_release_4:
918 case Builtin::BI__sync_lock_release_8:
919 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000920 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +0000921 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +0000922 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +0000923 break;
Douglas Gregora9766412011-11-28 16:30:08 +0000924
925 case Builtin::BI__sync_swap:
926 case Builtin::BI__sync_swap_1:
927 case Builtin::BI__sync_swap_2:
928 case Builtin::BI__sync_swap_4:
929 case Builtin::BI__sync_swap_8:
930 case Builtin::BI__sync_swap_16:
931 BuiltinIndex = 14;
932 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000933 }
Mike Stump1eb44332009-09-09 15:08:12 +0000934
Chris Lattner5caa3702009-05-08 06:58:22 +0000935 // Now that we know how many fixed arguments we expect, first check that we
936 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +0000937 if (TheCall->getNumArgs() < 1+NumFixed) {
938 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
939 << 0 << 1+NumFixed << TheCall->getNumArgs()
940 << TheCall->getCallee()->getSourceRange();
941 return ExprError();
942 }
Mike Stump1eb44332009-09-09 15:08:12 +0000943
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000944 // Get the decl for the concrete builtin from this, we can tell what the
945 // concrete integer type we should convert to is.
946 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
947 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
948 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
Mike Stump1eb44332009-09-09 15:08:12 +0000949 FunctionDecl *NewBuiltinDecl =
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000950 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
951 TUScope, false, DRE->getLocStart()));
Chandler Carruthd2014572010-07-09 18:59:35 +0000952
John McCallf871d0c2010-08-07 06:22:56 +0000953 // The first argument --- the pointer --- has a fixed type; we
954 // deduce the types of the rest of the arguments accordingly. Walk
955 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +0000956 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley429bb272011-04-08 18:41:53 +0000957 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +0000958
Chris Lattner5caa3702009-05-08 06:58:22 +0000959 // GCC does an implicit conversion to the pointer or integer ValType. This
960 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb45ae252011-10-05 07:41:44 +0000961 // Initialize the argument.
962 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
963 ValType, /*consume*/ false);
964 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley429bb272011-04-08 18:41:53 +0000965 if (Arg.isInvalid())
Chandler Carruthd2014572010-07-09 18:59:35 +0000966 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000967
Chris Lattner5caa3702009-05-08 06:58:22 +0000968 // Okay, we have something that *can* be converted to the right type. Check
969 // to see if there is a potentially weird extension going on here. This can
970 // happen when you do an atomic operation on something like an char* and
971 // pass in 42. The 42 gets converted to char. This is even more strange
972 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +0000973 // FIXME: Do this check.
John McCallb45ae252011-10-05 07:41:44 +0000974 TheCall->setArg(i+1, Arg.take());
Chris Lattner5caa3702009-05-08 06:58:22 +0000975 }
Mike Stump1eb44332009-09-09 15:08:12 +0000976
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +0000977 ASTContext& Context = this->getASTContext();
978
979 // Create a new DeclRefExpr to refer to the new decl.
980 DeclRefExpr* NewDRE = DeclRefExpr::Create(
981 Context,
982 DRE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000983 SourceLocation(),
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +0000984 NewBuiltinDecl,
985 DRE->getLocation(),
986 NewBuiltinDecl->getType(),
987 DRE->getValueKind());
Mike Stump1eb44332009-09-09 15:08:12 +0000988
Chris Lattner5caa3702009-05-08 06:58:22 +0000989 // Set the callee in the CallExpr.
990 // FIXME: This leaks the original parens and implicit casts.
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +0000991 ExprResult PromotedCall = UsualUnaryConversions(NewDRE);
John Wiegley429bb272011-04-08 18:41:53 +0000992 if (PromotedCall.isInvalid())
993 return ExprError();
994 TheCall->setCallee(PromotedCall.take());
Mike Stump1eb44332009-09-09 15:08:12 +0000995
Chandler Carruthdb4325b2010-07-18 07:23:17 +0000996 // Change the result type of the call to match the original value type. This
997 // is arbitrary, but the codegen for these builtins ins design to handle it
998 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +0000999 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +00001000
1001 return move(TheCallResult);
Chris Lattner5caa3702009-05-08 06:58:22 +00001002}
1003
Chris Lattner69039812009-02-18 06:01:06 +00001004/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +00001005/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +00001006/// Note: It might also make sense to do the UTF-16 conversion here (would
1007/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +00001008bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +00001009 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +00001010 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1011
Douglas Gregor5cee1192011-07-27 05:40:30 +00001012 if (!Literal || !Literal->isAscii()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001013 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1014 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001015 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +00001016 }
Mike Stump1eb44332009-09-09 15:08:12 +00001017
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001018 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001019 StringRef String = Literal->getString();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001020 unsigned NumBytes = String.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001021 SmallVector<UTF16, 128> ToBuf(NumBytes);
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001022 const UTF8 *FromPtr = (UTF8 *)String.data();
1023 UTF16 *ToPtr = &ToBuf[0];
1024
1025 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1026 &ToPtr, ToPtr + NumBytes,
1027 strictConversion);
1028 // Check for conversion failure.
1029 if (Result != conversionOK)
1030 Diag(Arg->getLocStart(),
1031 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1032 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001033 return false;
Chris Lattner59907c42007-08-10 20:18:51 +00001034}
1035
Chris Lattnerc27c6652007-12-20 00:05:45 +00001036/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1037/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +00001038bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1039 Expr *Fn = TheCall->getCallee();
1040 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +00001041 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001042 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001043 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1044 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +00001045 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001046 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +00001047 return true;
1048 }
Eli Friedman56f20ae2008-12-15 22:05:35 +00001049
1050 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +00001051 return Diag(TheCall->getLocEnd(),
1052 diag::err_typecheck_call_too_few_args_at_least)
1053 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +00001054 }
1055
John McCall5f8d6042011-08-27 01:09:30 +00001056 // Type-check the first argument normally.
1057 if (checkBuiltinArgument(*this, TheCall, 0))
1058 return true;
1059
Chris Lattnerc27c6652007-12-20 00:05:45 +00001060 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001061 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +00001062 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001063 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +00001064 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +00001065 else if (FunctionDecl *FD = getCurFunctionDecl())
1066 isVariadic = FD->isVariadic();
1067 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001068 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +00001069
Chris Lattnerc27c6652007-12-20 00:05:45 +00001070 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001071 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1072 return true;
1073 }
Mike Stump1eb44332009-09-09 15:08:12 +00001074
Chris Lattner30ce3442007-12-19 23:59:04 +00001075 // Verify that the second argument to the builtin is the last argument of the
1076 // current function or method.
1077 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +00001078 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001079
Anders Carlsson88cf2262008-02-11 04:20:54 +00001080 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1081 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001082 // FIXME: This isn't correct for methods (results in bogus warning).
1083 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +00001084 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001085 if (CurBlock)
1086 LastArg = *(CurBlock->TheDecl->param_end()-1);
1087 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +00001088 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001089 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001090 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001091 SecondArgIsLastNamedArgument = PV == LastArg;
1092 }
1093 }
Mike Stump1eb44332009-09-09 15:08:12 +00001094
Chris Lattner30ce3442007-12-19 23:59:04 +00001095 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001096 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +00001097 diag::warn_second_parameter_of_va_start_not_last_named_argument);
1098 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +00001099}
Chris Lattner30ce3442007-12-19 23:59:04 +00001100
Chris Lattner1b9a0792007-12-20 00:26:33 +00001101/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1102/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +00001103bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1104 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +00001105 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001106 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +00001107 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +00001108 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001109 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001110 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001111 << SourceRange(TheCall->getArg(2)->getLocStart(),
1112 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001113
John Wiegley429bb272011-04-08 18:41:53 +00001114 ExprResult OrigArg0 = TheCall->getArg(0);
1115 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +00001116
Chris Lattner1b9a0792007-12-20 00:26:33 +00001117 // Do standard promotions between the two arguments, returning their common
1118 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +00001119 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley429bb272011-04-08 18:41:53 +00001120 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1121 return true;
Daniel Dunbar403bc2b2009-02-19 19:28:43 +00001122
1123 // Make sure any conversions are pushed back into the call; this is
1124 // type safe since unordered compare builtins are declared as "_Bool
1125 // foo(...)".
John Wiegley429bb272011-04-08 18:41:53 +00001126 TheCall->setArg(0, OrigArg0.get());
1127 TheCall->setArg(1, OrigArg1.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001128
John Wiegley429bb272011-04-08 18:41:53 +00001129 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorcde01732009-05-19 22:10:17 +00001130 return false;
1131
Chris Lattner1b9a0792007-12-20 00:26:33 +00001132 // If the common type isn't a real floating type, then the arguments were
1133 // invalid for this operation.
1134 if (!Res->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +00001135 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001136 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley429bb272011-04-08 18:41:53 +00001137 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1138 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001139
Chris Lattner1b9a0792007-12-20 00:26:33 +00001140 return false;
1141}
1142
Benjamin Kramere771a7a2010-02-15 22:42:31 +00001143/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1144/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001145/// to check everything. We expect the last argument to be a floating point
1146/// value.
1147bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1148 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +00001149 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001150 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001151 if (TheCall->getNumArgs() > NumArgs)
1152 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001153 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001154 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001155 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001156 (*(TheCall->arg_end()-1))->getLocEnd());
1157
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001158 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001159
Eli Friedman9ac6f622009-08-31 20:06:00 +00001160 if (OrigArg->isTypeDependent())
1161 return false;
1162
Chris Lattner81368fb2010-05-06 05:50:07 +00001163 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +00001164 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +00001165 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001166 diag::err_typecheck_call_invalid_unary_fp)
1167 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001168
Chris Lattner81368fb2010-05-06 05:50:07 +00001169 // If this is an implicit conversion from float -> double, remove it.
1170 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1171 Expr *CastArg = Cast->getSubExpr();
1172 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1173 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1174 "promotion from float to double is the only expected cast here");
1175 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +00001176 TheCall->setArg(NumArgs-1, CastArg);
1177 OrigArg = CastArg;
1178 }
1179 }
1180
Eli Friedman9ac6f622009-08-31 20:06:00 +00001181 return false;
1182}
1183
Eli Friedmand38617c2008-05-14 19:38:39 +00001184/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1185// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +00001186ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001187 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001188 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +00001189 diag::err_typecheck_call_too_few_args_at_least)
Nate Begeman37b6a572010-06-08 00:16:34 +00001190 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherd77b9a22010-04-16 04:48:22 +00001191 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001192
Nate Begeman37b6a572010-06-08 00:16:34 +00001193 // Determine which of the following types of shufflevector we're checking:
1194 // 1) unary, vector mask: (lhs, mask)
1195 // 2) binary, vector mask: (lhs, rhs, mask)
1196 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1197 QualType resType = TheCall->getArg(0)->getType();
1198 unsigned numElements = 0;
1199
Douglas Gregorcde01732009-05-19 22:10:17 +00001200 if (!TheCall->getArg(0)->isTypeDependent() &&
1201 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001202 QualType LHSType = TheCall->getArg(0)->getType();
1203 QualType RHSType = TheCall->getArg(1)->getType();
1204
1205 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001206 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001207 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001208 TheCall->getArg(1)->getLocEnd());
1209 return ExprError();
1210 }
Nate Begeman37b6a572010-06-08 00:16:34 +00001211
1212 numElements = LHSType->getAs<VectorType>()->getNumElements();
1213 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +00001214
Nate Begeman37b6a572010-06-08 00:16:34 +00001215 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1216 // with mask. If so, verify that RHS is an integer vector type with the
1217 // same number of elts as lhs.
1218 if (TheCall->getNumArgs() == 2) {
Douglas Gregorf6094622010-07-23 15:58:24 +00001219 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +00001220 RHSType->getAs<VectorType>()->getNumElements() != numElements)
1221 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
1222 << SourceRange(TheCall->getArg(1)->getLocStart(),
1223 TheCall->getArg(1)->getLocEnd());
1224 numResElements = numElements;
1225 }
1226 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001227 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001228 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001229 TheCall->getArg(1)->getLocEnd());
1230 return ExprError();
Nate Begeman37b6a572010-06-08 00:16:34 +00001231 } else if (numElements != numResElements) {
1232 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +00001233 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001234 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +00001235 }
Eli Friedmand38617c2008-05-14 19:38:39 +00001236 }
1237
1238 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001239 if (TheCall->getArg(i)->isTypeDependent() ||
1240 TheCall->getArg(i)->isValueDependent())
1241 continue;
1242
Nate Begeman37b6a572010-06-08 00:16:34 +00001243 llvm::APSInt Result(32);
1244 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1245 return ExprError(Diag(TheCall->getLocStart(),
1246 diag::err_shufflevector_nonconstant_argument)
1247 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001248
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001249 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001250 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001251 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001252 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001253 }
1254
Chris Lattner5f9e2722011-07-23 10:55:15 +00001255 SmallVector<Expr*, 32> exprs;
Eli Friedmand38617c2008-05-14 19:38:39 +00001256
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001257 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +00001258 exprs.push_back(TheCall->getArg(i));
1259 TheCall->setArg(i, 0);
1260 }
1261
Nate Begemana88dc302009-08-12 02:10:25 +00001262 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
Nate Begeman37b6a572010-06-08 00:16:34 +00001263 exprs.size(), resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001264 TheCall->getCallee()->getLocStart(),
1265 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +00001266}
Chris Lattner30ce3442007-12-19 23:59:04 +00001267
Daniel Dunbar4493f792008-07-21 22:59:13 +00001268/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1269// This is declared to take (const void*, ...) and can take two
1270// optional constant int args.
1271bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001272 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001273
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001274 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +00001275 return Diag(TheCall->getLocEnd(),
1276 diag::err_typecheck_call_too_many_args_at_most)
1277 << 0 /*function call*/ << 3 << NumArgs
1278 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001279
1280 // Argument 0 is checked for us and the remaining arguments must be
1281 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001282 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +00001283 Expr *Arg = TheCall->getArg(i);
Eric Christopher691ebc32010-04-17 02:26:23 +00001284
Eli Friedman9aef7262009-12-04 00:30:06 +00001285 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +00001286 if (SemaBuiltinConstantArg(TheCall, i, Result))
1287 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001288
Daniel Dunbar4493f792008-07-21 22:59:13 +00001289 // FIXME: gcc issues a warning and rewrites these to 0. These
1290 // seems especially odd for the third argument since the default
1291 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001292 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +00001293 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001294 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001295 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001296 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +00001297 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001298 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001299 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001300 }
1301 }
1302
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001303 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +00001304}
1305
Eric Christopher691ebc32010-04-17 02:26:23 +00001306/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1307/// TheCall is a constant expression.
1308bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1309 llvm::APSInt &Result) {
1310 Expr *Arg = TheCall->getArg(ArgNum);
1311 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1312 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1313
1314 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1315
1316 if (!Arg->isIntegerConstantExpr(Result, Context))
1317 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +00001318 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +00001319
Chris Lattner21fb98e2009-09-23 06:06:36 +00001320 return false;
1321}
1322
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001323/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1324/// int type). This simply type checks that type is one of the defined
1325/// constants (0-3).
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001326// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001327bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +00001328 llvm::APSInt Result;
1329
1330 // Check constant-ness first.
1331 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1332 return true;
1333
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001334 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001335 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001336 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1337 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001338 }
1339
1340 return false;
1341}
1342
Eli Friedman586d6a82009-05-03 06:04:26 +00001343/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +00001344/// This checks that val is a constant 1.
1345bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1346 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +00001347 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +00001348
Eric Christopher691ebc32010-04-17 02:26:23 +00001349 // TODO: This is less than ideal. Overload this to take a value.
1350 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1351 return true;
1352
1353 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +00001354 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1355 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1356
1357 return false;
1358}
1359
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001360// Handle i > 1 ? "x" : "y", recursively.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001361bool Sema::SemaCheckStringLiteral(const Expr *E, Expr **Args,
1362 unsigned NumArgs, bool HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00001363 unsigned format_idx, unsigned firstDataArg,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001364 FormatStringType Type, bool inFunctionCall) {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001365 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +00001366 if (E->isTypeDependent() || E->isValueDependent())
1367 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001368
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001369 E = E->IgnoreParenCasts();
Peter Collingbournef111d932011-04-15 00:35:48 +00001370
Ted Kremenekd30ef872009-01-12 23:09:09 +00001371 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +00001372 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +00001373 case Stmt::ConditionalOperatorClass: {
John McCall56ca35d2011-02-17 10:25:35 +00001374 const AbstractConditionalOperator *C = cast<AbstractConditionalOperator>(E);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001375 return SemaCheckStringLiteral(C->getTrueExpr(), Args, NumArgs, HasVAListArg,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001376 format_idx, firstDataArg, Type,
Richard Trieu55733de2011-10-28 00:41:25 +00001377 inFunctionCall)
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001378 && SemaCheckStringLiteral(C->getFalseExpr(), Args, NumArgs, HasVAListArg,
1379 format_idx, firstDataArg, Type,
1380 inFunctionCall);
Ted Kremenekd30ef872009-01-12 23:09:09 +00001381 }
1382
Ted Kremenek95355bb2010-09-09 03:51:42 +00001383 case Stmt::IntegerLiteralClass:
1384 // Technically -Wformat-nonliteral does not warn about this case.
1385 // The behavior of printf and friends in this case is implementation
1386 // dependent. Ideally if the format string cannot be null then
1387 // it should have a 'nonnull' attribute in the function prototype.
1388 return true;
1389
Ted Kremenekd30ef872009-01-12 23:09:09 +00001390 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001391 E = cast<ImplicitCastExpr>(E)->getSubExpr();
1392 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001393 }
1394
John McCall56ca35d2011-02-17 10:25:35 +00001395 case Stmt::OpaqueValueExprClass:
1396 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
1397 E = src;
1398 goto tryAgain;
1399 }
1400 return false;
1401
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001402 case Stmt::PredefinedExprClass:
1403 // While __func__, etc., are technically not string literals, they
1404 // cannot contain format specifiers and thus are not a security
1405 // liability.
1406 return true;
1407
Ted Kremenek082d9362009-03-20 21:35:28 +00001408 case Stmt::DeclRefExprClass: {
1409 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001410
Ted Kremenek082d9362009-03-20 21:35:28 +00001411 // As an exception, do not flag errors for variables binding to
1412 // const string literals.
1413 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1414 bool isConstant = false;
1415 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001416
Ted Kremenek082d9362009-03-20 21:35:28 +00001417 if (const ArrayType *AT = Context.getAsArrayType(T)) {
1418 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001419 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001420 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +00001421 PT->getPointeeType().isConstant(Context);
Jean-Daniel Dupase98e5b52012-01-25 10:35:33 +00001422 } else if (T->isObjCObjectPointerType()) {
1423 // In ObjC, there is usually no "const ObjectPointer" type,
1424 // so don't check if the pointee type is constant.
1425 isConstant = T.isConstant(Context);
Ted Kremenek082d9362009-03-20 21:35:28 +00001426 }
Mike Stump1eb44332009-09-09 15:08:12 +00001427
Ted Kremenek082d9362009-03-20 21:35:28 +00001428 if (isConstant) {
Sebastian Redl31310a22010-02-01 20:16:42 +00001429 if (const Expr *Init = VD->getAnyInitializer())
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001430 return SemaCheckStringLiteral(Init, Args, NumArgs,
Ted Kremenek826a3452010-07-16 02:11:22 +00001431 HasVAListArg, format_idx, firstDataArg,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001432 Type, /*inFunctionCall*/false);
Ted Kremenek082d9362009-03-20 21:35:28 +00001433 }
Mike Stump1eb44332009-09-09 15:08:12 +00001434
Anders Carlssond966a552009-06-28 19:55:58 +00001435 // For vprintf* functions (i.e., HasVAListArg==true), we add a
1436 // special check to see if the format string is a function parameter
1437 // of the function calling the printf function. If the function
1438 // has an attribute indicating it is a printf-like function, then we
1439 // should suppress warnings concerning non-literals being used in a call
1440 // to a vprintf function. For example:
1441 //
1442 // void
1443 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
1444 // va_list ap;
1445 // va_start(ap, fmt);
1446 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
1447 // ...
1448 //
1449 //
1450 // FIXME: We don't have full attribute support yet, so just check to see
1451 // if the argument is a DeclRefExpr that references a parameter. We'll
1452 // add proper support for checking the attribute later.
1453 if (HasVAListArg)
1454 if (isa<ParmVarDecl>(VD))
1455 return true;
Ted Kremenek082d9362009-03-20 21:35:28 +00001456 }
Mike Stump1eb44332009-09-09 15:08:12 +00001457
Ted Kremenek082d9362009-03-20 21:35:28 +00001458 return false;
1459 }
Ted Kremenekd30ef872009-01-12 23:09:09 +00001460
Anders Carlsson8f031b32009-06-27 04:05:33 +00001461 case Stmt::CallExprClass: {
1462 const CallExpr *CE = cast<CallExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001463 if (const ImplicitCastExpr *ICE
Anders Carlsson8f031b32009-06-27 04:05:33 +00001464 = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
1465 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
1466 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001467 if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
Anders Carlsson8f031b32009-06-27 04:05:33 +00001468 unsigned ArgIndex = FA->getFormatIdx();
1469 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001470
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001471 return SemaCheckStringLiteral(Arg, Args, NumArgs, HasVAListArg,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001472 format_idx, firstDataArg, Type,
Richard Trieu55733de2011-10-28 00:41:25 +00001473 inFunctionCall);
Anders Carlsson8f031b32009-06-27 04:05:33 +00001474 }
1475 }
1476 }
1477 }
Mike Stump1eb44332009-09-09 15:08:12 +00001478
Anders Carlsson8f031b32009-06-27 04:05:33 +00001479 return false;
1480 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001481 case Stmt::ObjCStringLiteralClass:
1482 case Stmt::StringLiteralClass: {
1483 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001484
Ted Kremenek082d9362009-03-20 21:35:28 +00001485 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00001486 StrE = ObjCFExpr->getString();
1487 else
Ted Kremenek082d9362009-03-20 21:35:28 +00001488 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001489
Ted Kremenekd30ef872009-01-12 23:09:09 +00001490 if (StrE) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001491 CheckFormatString(StrE, E, Args, NumArgs, HasVAListArg, format_idx,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001492 firstDataArg, Type, inFunctionCall);
Ted Kremenekd30ef872009-01-12 23:09:09 +00001493 return true;
1494 }
Mike Stump1eb44332009-09-09 15:08:12 +00001495
Ted Kremenekd30ef872009-01-12 23:09:09 +00001496 return false;
1497 }
Mike Stump1eb44332009-09-09 15:08:12 +00001498
Ted Kremenek082d9362009-03-20 21:35:28 +00001499 default:
1500 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001501 }
1502}
1503
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001504void
Mike Stump1eb44332009-09-09 15:08:12 +00001505Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewycky909a70d2011-03-25 01:44:32 +00001506 const Expr * const *ExprArgs,
1507 SourceLocation CallSiteLoc) {
Sean Huntcf807c42010-08-18 23:23:40 +00001508 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1509 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001510 i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +00001511 const Expr *ArgExpr = ExprArgs[*i];
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001512 if (ArgExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00001513 Expr::NPC_ValueDependentIsNotNull))
Nick Lewycky909a70d2011-03-25 01:44:32 +00001514 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001515 }
1516}
Ted Kremenekd30ef872009-01-12 23:09:09 +00001517
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001518Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
1519 return llvm::StringSwitch<FormatStringType>(Format->getType())
1520 .Case("scanf", FST_Scanf)
1521 .Cases("printf", "printf0", FST_Printf)
1522 .Cases("NSString", "CFString", FST_NSString)
1523 .Case("strftime", FST_Strftime)
1524 .Case("strfmon", FST_Strfmon)
1525 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
1526 .Default(FST_Unknown);
1527}
1528
Ted Kremenek826a3452010-07-16 02:11:22 +00001529/// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar
1530/// functions) for correct use of format strings.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001531void Sema::CheckFormatArguments(const FormatAttr *Format, CallExpr *TheCall) {
1532 bool IsCXXMember = false;
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001533 // The way the format attribute works in GCC, the implicit this argument
1534 // of member functions is counted. However, it doesn't appear in our own
1535 // lists, so decrement format_idx in that case.
1536 if (isa<CXXMemberCallExpr>(TheCall)) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001537 const CXXMethodDecl *method_decl =
1538 dyn_cast<CXXMethodDecl>(TheCall->getCalleeDecl());
1539 IsCXXMember = method_decl && method_decl->isInstance();
1540 }
1541 CheckFormatArguments(Format, TheCall->getArgs(), TheCall->getNumArgs(),
1542 IsCXXMember, TheCall->getRParenLoc(),
1543 TheCall->getCallee()->getSourceRange());
1544}
1545
1546void Sema::CheckFormatArguments(const FormatAttr *Format, Expr **Args,
1547 unsigned NumArgs, bool IsCXXMember,
1548 SourceLocation Loc, SourceRange Range) {
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001549 bool HasVAListArg = Format->getFirstArg() == 0;
1550 unsigned format_idx = Format->getFormatIdx() - 1;
1551 unsigned firstDataArg = HasVAListArg ? 0 : Format->getFirstArg() - 1;
1552 if (IsCXXMember) {
1553 if (format_idx == 0)
1554 return;
1555 --format_idx;
1556 if(firstDataArg != 0)
1557 --firstDataArg;
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001558 }
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001559 CheckFormatArguments(Args, NumArgs, HasVAListArg, format_idx,
1560 firstDataArg, GetFormatStringType(Format), Loc, Range);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001561}
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001562
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001563void Sema::CheckFormatArguments(Expr **Args, unsigned NumArgs,
1564 bool HasVAListArg, unsigned format_idx,
1565 unsigned firstDataArg, FormatStringType Type,
1566 SourceLocation Loc, SourceRange Range) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001567 // CHECK: printf/scanf-like function is called with no format string.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001568 if (format_idx >= NumArgs) {
1569 Diag(Loc, diag::warn_missing_format_string) << Range;
Ted Kremenek71895b92007-08-14 17:39:48 +00001570 return;
1571 }
Mike Stump1eb44332009-09-09 15:08:12 +00001572
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001573 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001574
Chris Lattner59907c42007-08-10 20:18:51 +00001575 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001576 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001577 // Dynamically generated format strings are difficult to
1578 // automatically vet at compile time. Requiring that format strings
1579 // are string literals: (1) permits the checking of format strings by
1580 // the compiler and thereby (2) can practically remove the source of
1581 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001582
Mike Stump1eb44332009-09-09 15:08:12 +00001583 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001584 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001585 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001586 // the same format string checking logic for both ObjC and C strings.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001587 if (SemaCheckStringLiteral(OrigFormatExpr, Args, NumArgs, HasVAListArg,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001588 format_idx, firstDataArg, Type))
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001589 return; // Literal format string found, check done!
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001590
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00001591 // Do not emit diag when the string param is a macro expansion and the
1592 // format is either NSString or CFString. This is a hack to prevent
1593 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
1594 // which are usually used in place of NS and CF string literals.
1595 if (Type == FST_NSString && Args[format_idx]->getLocStart().isMacroID())
1596 return;
1597
Chris Lattner655f1412009-04-29 04:59:47 +00001598 // If there are no arguments specified, warn with -Wformat-security, otherwise
1599 // warn only with -Wformat-nonliteral.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001600 if (NumArgs == format_idx+1)
1601 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001602 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00001603 << OrigFormatExpr->getSourceRange();
1604 else
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001605 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001606 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00001607 << OrigFormatExpr->getSourceRange();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001608}
Ted Kremenek71895b92007-08-14 17:39:48 +00001609
Ted Kremeneke0e53132010-01-28 23:39:18 +00001610namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00001611class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1612protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00001613 Sema &S;
1614 const StringLiteral *FExpr;
1615 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00001616 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001617 const unsigned NumDataArgs;
1618 const bool IsObjCLiteral;
1619 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00001620 const bool HasVAListArg;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001621 const Expr * const *Args;
1622 const unsigned NumArgs;
Ted Kremenek0d277352010-01-29 01:06:55 +00001623 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001624 llvm::BitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00001625 bool usesPositionalArgs;
1626 bool atFirstArg;
Richard Trieu55733de2011-10-28 00:41:25 +00001627 bool inFunctionCall;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001628public:
Ted Kremenek826a3452010-07-16 02:11:22 +00001629 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00001630 const Expr *origFormatExpr, unsigned firstDataArg,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001631 unsigned numDataArgs, bool isObjCLiteral,
Ted Kremenek0d277352010-01-29 01:06:55 +00001632 const char *beg, bool hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001633 Expr **args, unsigned numArgs,
1634 unsigned formatIdx, bool inFunctionCall)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001635 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Ted Kremenek6ee76532010-03-25 03:59:12 +00001636 FirstDataArg(firstDataArg),
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001637 NumDataArgs(numDataArgs),
Ted Kremenek0d277352010-01-29 01:06:55 +00001638 IsObjCLiteral(isObjCLiteral), Beg(beg),
1639 HasVAListArg(hasVAListArg),
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001640 Args(args), NumArgs(numArgs), FormatIdx(formatIdx),
Richard Trieu55733de2011-10-28 00:41:25 +00001641 usesPositionalArgs(false), atFirstArg(true),
1642 inFunctionCall(inFunctionCall) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001643 CoveredArgs.resize(numDataArgs);
1644 CoveredArgs.reset();
1645 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001646
Ted Kremenek07d161f2010-01-29 01:50:07 +00001647 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001648
Ted Kremenek826a3452010-07-16 02:11:22 +00001649 void HandleIncompleteSpecifier(const char *startSpecifier,
1650 unsigned specifierLen);
1651
Ted Kremenekefaff192010-02-27 01:41:03 +00001652 virtual void HandleInvalidPosition(const char *startSpecifier,
1653 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00001654 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00001655
1656 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1657
Ted Kremeneke0e53132010-01-28 23:39:18 +00001658 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001659
Richard Trieu55733de2011-10-28 00:41:25 +00001660 template <typename Range>
1661 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
1662 const Expr *ArgumentExpr,
1663 PartialDiagnostic PDiag,
1664 SourceLocation StringLoc,
1665 bool IsStringLocation, Range StringRange,
1666 FixItHint Fixit = FixItHint());
1667
Ted Kremenek826a3452010-07-16 02:11:22 +00001668protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001669 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
1670 const char *startSpec,
1671 unsigned specifierLen,
1672 const char *csStart, unsigned csLen);
Richard Trieu55733de2011-10-28 00:41:25 +00001673
1674 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
1675 const char *startSpec,
1676 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001677
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001678 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00001679 CharSourceRange getSpecifierRange(const char *startSpecifier,
1680 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001681 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001682
Ted Kremenek0d277352010-01-29 01:06:55 +00001683 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00001684
1685 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
1686 const analyze_format_string::ConversionSpecifier &CS,
1687 const char *startSpecifier, unsigned specifierLen,
1688 unsigned argIndex);
Richard Trieu55733de2011-10-28 00:41:25 +00001689
1690 template <typename Range>
1691 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
1692 bool IsStringLocation, Range StringRange,
1693 FixItHint Fixit = FixItHint());
1694
1695 void CheckPositionalAndNonpositionalArgs(
1696 const analyze_format_string::FormatSpecifier *FS);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001697};
1698}
1699
Ted Kremenek826a3452010-07-16 02:11:22 +00001700SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00001701 return OrigFormatExpr->getSourceRange();
1702}
1703
Ted Kremenek826a3452010-07-16 02:11:22 +00001704CharSourceRange CheckFormatHandler::
1705getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00001706 SourceLocation Start = getLocationOfByte(startSpecifier);
1707 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
1708
1709 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001710 End = End.getLocWithOffset(1);
Tom Care45f9b7e2010-06-21 21:21:01 +00001711
1712 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001713}
1714
Ted Kremenek826a3452010-07-16 02:11:22 +00001715SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001716 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001717}
1718
Ted Kremenek826a3452010-07-16 02:11:22 +00001719void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
1720 unsigned specifierLen){
Richard Trieu55733de2011-10-28 00:41:25 +00001721 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
1722 getLocationOfByte(startSpecifier),
1723 /*IsStringLocation*/true,
1724 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek808015a2010-01-29 03:16:21 +00001725}
1726
Ted Kremenekefaff192010-02-27 01:41:03 +00001727void
Ted Kremenek826a3452010-07-16 02:11:22 +00001728CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
1729 analyze_format_string::PositionContext p) {
Richard Trieu55733de2011-10-28 00:41:25 +00001730 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
1731 << (unsigned) p,
1732 getLocationOfByte(startPos), /*IsStringLocation*/true,
1733 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00001734}
1735
Ted Kremenek826a3452010-07-16 02:11:22 +00001736void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00001737 unsigned posLen) {
Richard Trieu55733de2011-10-28 00:41:25 +00001738 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
1739 getLocationOfByte(startPos),
1740 /*IsStringLocation*/true,
1741 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00001742}
1743
Ted Kremenek826a3452010-07-16 02:11:22 +00001744void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Ted Kremenek0c069442011-03-15 21:18:48 +00001745 if (!IsObjCLiteral) {
1746 // The presence of a null character is likely an error.
Richard Trieu55733de2011-10-28 00:41:25 +00001747 EmitFormatDiagnostic(
1748 S.PDiag(diag::warn_printf_format_string_contains_null_char),
1749 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
1750 getFormatStringRange());
Ted Kremenek0c069442011-03-15 21:18:48 +00001751 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001752}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001753
Ted Kremenek826a3452010-07-16 02:11:22 +00001754const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001755 return Args[FirstDataArg + i];
Ted Kremenek826a3452010-07-16 02:11:22 +00001756}
1757
1758void CheckFormatHandler::DoneProcessing() {
1759 // Does the number of data arguments exceed the number of
1760 // format conversions in the format string?
1761 if (!HasVAListArg) {
1762 // Find any arguments that weren't covered.
1763 CoveredArgs.flip();
1764 signed notCoveredArg = CoveredArgs.find_first();
1765 if (notCoveredArg >= 0) {
1766 assert((unsigned)notCoveredArg < NumDataArgs);
Richard Trieu55733de2011-10-28 00:41:25 +00001767 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
1768 getDataArg((unsigned) notCoveredArg)->getLocStart(),
1769 /*IsStringLocation*/false, getFormatStringRange());
Ted Kremenek826a3452010-07-16 02:11:22 +00001770 }
1771 }
1772}
1773
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001774bool
1775CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
1776 SourceLocation Loc,
1777 const char *startSpec,
1778 unsigned specifierLen,
1779 const char *csStart,
1780 unsigned csLen) {
1781
1782 bool keepGoing = true;
1783 if (argIndex < NumDataArgs) {
1784 // Consider the argument coverered, even though the specifier doesn't
1785 // make sense.
1786 CoveredArgs.set(argIndex);
1787 }
1788 else {
1789 // If argIndex exceeds the number of data arguments we
1790 // don't issue a warning because that is just a cascade of warnings (and
1791 // they may have intended '%%' anyway). We don't want to continue processing
1792 // the format string after this point, however, as we will like just get
1793 // gibberish when trying to match arguments.
1794 keepGoing = false;
1795 }
1796
Richard Trieu55733de2011-10-28 00:41:25 +00001797 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
1798 << StringRef(csStart, csLen),
1799 Loc, /*IsStringLocation*/true,
1800 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001801
1802 return keepGoing;
1803}
1804
Richard Trieu55733de2011-10-28 00:41:25 +00001805void
1806CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
1807 const char *startSpec,
1808 unsigned specifierLen) {
1809 EmitFormatDiagnostic(
1810 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
1811 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
1812}
1813
Ted Kremenek666a1972010-07-26 19:45:42 +00001814bool
1815CheckFormatHandler::CheckNumArgs(
1816 const analyze_format_string::FormatSpecifier &FS,
1817 const analyze_format_string::ConversionSpecifier &CS,
1818 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
1819
1820 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00001821 PartialDiagnostic PDiag = FS.usesPositionalArg()
1822 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
1823 << (argIndex+1) << NumDataArgs)
1824 : S.PDiag(diag::warn_printf_insufficient_data_args);
1825 EmitFormatDiagnostic(
1826 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
1827 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek666a1972010-07-26 19:45:42 +00001828 return false;
1829 }
1830 return true;
1831}
1832
Richard Trieu55733de2011-10-28 00:41:25 +00001833template<typename Range>
1834void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
1835 SourceLocation Loc,
1836 bool IsStringLocation,
1837 Range StringRange,
1838 FixItHint FixIt) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001839 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu55733de2011-10-28 00:41:25 +00001840 Loc, IsStringLocation, StringRange, FixIt);
1841}
1842
1843/// \brief If the format string is not within the funcion call, emit a note
1844/// so that the function call and string are in diagnostic messages.
1845///
1846/// \param inFunctionCall if true, the format string is within the function
1847/// call and only one diagnostic message will be produced. Otherwise, an
1848/// extra note will be emitted pointing to location of the format string.
1849///
1850/// \param ArgumentExpr the expression that is passed as the format string
1851/// argument in the function call. Used for getting locations when two
1852/// diagnostics are emitted.
1853///
1854/// \param PDiag the callee should already have provided any strings for the
1855/// diagnostic message. This function only adds locations and fixits
1856/// to diagnostics.
1857///
1858/// \param Loc primary location for diagnostic. If two diagnostics are
1859/// required, one will be at Loc and a new SourceLocation will be created for
1860/// the other one.
1861///
1862/// \param IsStringLocation if true, Loc points to the format string should be
1863/// used for the note. Otherwise, Loc points to the argument list and will
1864/// be used with PDiag.
1865///
1866/// \param StringRange some or all of the string to highlight. This is
1867/// templated so it can accept either a CharSourceRange or a SourceRange.
1868///
1869/// \param Fixit optional fix it hint for the format string.
1870template<typename Range>
1871void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
1872 const Expr *ArgumentExpr,
1873 PartialDiagnostic PDiag,
1874 SourceLocation Loc,
1875 bool IsStringLocation,
1876 Range StringRange,
1877 FixItHint FixIt) {
1878 if (InFunctionCall)
1879 S.Diag(Loc, PDiag) << StringRange << FixIt;
1880 else {
1881 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
1882 << ArgumentExpr->getSourceRange();
1883 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
1884 diag::note_format_string_defined)
1885 << StringRange << FixIt;
1886 }
1887}
1888
Ted Kremenek826a3452010-07-16 02:11:22 +00001889//===--- CHECK: Printf format string checking ------------------------------===//
1890
1891namespace {
1892class CheckPrintfHandler : public CheckFormatHandler {
1893public:
1894 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
1895 const Expr *origFormatExpr, unsigned firstDataArg,
1896 unsigned numDataArgs, bool isObjCLiteral,
1897 const char *beg, bool hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001898 Expr **Args, unsigned NumArgs,
1899 unsigned formatIdx, bool inFunctionCall)
Ted Kremenek826a3452010-07-16 02:11:22 +00001900 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1901 numDataArgs, isObjCLiteral, beg, hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001902 Args, NumArgs, formatIdx, inFunctionCall) {}
Ted Kremenek826a3452010-07-16 02:11:22 +00001903
1904
1905 bool HandleInvalidPrintfConversionSpecifier(
1906 const analyze_printf::PrintfSpecifier &FS,
1907 const char *startSpecifier,
1908 unsigned specifierLen);
1909
1910 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
1911 const char *startSpecifier,
1912 unsigned specifierLen);
1913
1914 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
1915 const char *startSpecifier, unsigned specifierLen);
1916 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
1917 const analyze_printf::OptionalAmount &Amt,
1918 unsigned type,
1919 const char *startSpecifier, unsigned specifierLen);
1920 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
1921 const analyze_printf::OptionalFlag &flag,
1922 const char *startSpecifier, unsigned specifierLen);
1923 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
1924 const analyze_printf::OptionalFlag &ignoredFlag,
1925 const analyze_printf::OptionalFlag &flag,
1926 const char *startSpecifier, unsigned specifierLen);
1927};
1928}
1929
1930bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
1931 const analyze_printf::PrintfSpecifier &FS,
1932 const char *startSpecifier,
1933 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001934 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001935 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00001936
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001937 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1938 getLocationOfByte(CS.getStart()),
1939 startSpecifier, specifierLen,
1940 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001941}
1942
Ted Kremenek826a3452010-07-16 02:11:22 +00001943bool CheckPrintfHandler::HandleAmount(
1944 const analyze_format_string::OptionalAmount &Amt,
1945 unsigned k, const char *startSpecifier,
1946 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001947
1948 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001949 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001950 unsigned argIndex = Amt.getArgIndex();
1951 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00001952 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
1953 << k,
1954 getLocationOfByte(Amt.getStart()),
1955 /*IsStringLocation*/true,
1956 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00001957 // Don't do any more checking. We will just emit
1958 // spurious errors.
1959 return false;
1960 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001961
Ted Kremenek0d277352010-01-29 01:06:55 +00001962 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00001963 // Although not in conformance with C99, we also allow the argument to be
1964 // an 'unsigned int' as that is a reasonably safe case. GCC also
1965 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001966 CoveredArgs.set(argIndex);
1967 const Expr *Arg = getDataArg(argIndex);
Ted Kremenek0d277352010-01-29 01:06:55 +00001968 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001969
1970 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
1971 assert(ATR.isValid());
1972
1973 if (!ATR.matchesType(S.Context, T)) {
Richard Trieu55733de2011-10-28 00:41:25 +00001974 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborga792aff2011-12-07 10:33:11 +00001975 << k << ATR.getRepresentativeTypeName(S.Context)
Richard Trieu55733de2011-10-28 00:41:25 +00001976 << T << Arg->getSourceRange(),
1977 getLocationOfByte(Amt.getStart()),
1978 /*IsStringLocation*/true,
1979 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00001980 // Don't do any more checking. We will just emit
1981 // spurious errors.
1982 return false;
1983 }
1984 }
1985 }
1986 return true;
1987}
Ted Kremenek0d277352010-01-29 01:06:55 +00001988
Tom Caree4ee9662010-06-17 19:00:27 +00001989void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00001990 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001991 const analyze_printf::OptionalAmount &Amt,
1992 unsigned type,
1993 const char *startSpecifier,
1994 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001995 const analyze_printf::PrintfConversionSpecifier &CS =
1996 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00001997
Richard Trieu55733de2011-10-28 00:41:25 +00001998 FixItHint fixit =
1999 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2000 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2001 Amt.getConstantLength()))
2002 : FixItHint();
2003
2004 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2005 << type << CS.toString(),
2006 getLocationOfByte(Amt.getStart()),
2007 /*IsStringLocation*/true,
2008 getSpecifierRange(startSpecifier, specifierLen),
2009 fixit);
Tom Caree4ee9662010-06-17 19:00:27 +00002010}
2011
Ted Kremenek826a3452010-07-16 02:11:22 +00002012void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002013 const analyze_printf::OptionalFlag &flag,
2014 const char *startSpecifier,
2015 unsigned specifierLen) {
2016 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002017 const analyze_printf::PrintfConversionSpecifier &CS =
2018 FS.getConversionSpecifier();
Richard Trieu55733de2011-10-28 00:41:25 +00002019 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2020 << flag.toString() << CS.toString(),
2021 getLocationOfByte(flag.getPosition()),
2022 /*IsStringLocation*/true,
2023 getSpecifierRange(startSpecifier, specifierLen),
2024 FixItHint::CreateRemoval(
2025 getSpecifierRange(flag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002026}
2027
2028void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00002029 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002030 const analyze_printf::OptionalFlag &ignoredFlag,
2031 const analyze_printf::OptionalFlag &flag,
2032 const char *startSpecifier,
2033 unsigned specifierLen) {
2034 // Warn about ignored flag with a fixit removal.
Richard Trieu55733de2011-10-28 00:41:25 +00002035 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2036 << ignoredFlag.toString() << flag.toString(),
2037 getLocationOfByte(ignoredFlag.getPosition()),
2038 /*IsStringLocation*/true,
2039 getSpecifierRange(startSpecifier, specifierLen),
2040 FixItHint::CreateRemoval(
2041 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002042}
2043
Ted Kremeneke0e53132010-01-28 23:39:18 +00002044bool
Ted Kremenek826a3452010-07-16 02:11:22 +00002045CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00002046 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00002047 const char *startSpecifier,
2048 unsigned specifierLen) {
2049
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002050 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00002051 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002052 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00002053
Ted Kremenekbaa40062010-07-19 22:01:06 +00002054 if (FS.consumesDataArgument()) {
2055 if (atFirstArg) {
2056 atFirstArg = false;
2057 usesPositionalArgs = FS.usesPositionalArg();
2058 }
2059 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002060 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2061 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002062 return false;
2063 }
Ted Kremenek0d277352010-01-29 01:06:55 +00002064 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002065
Ted Kremenekefaff192010-02-27 01:41:03 +00002066 // First check if the field width, precision, and conversion specifier
2067 // have matching data arguments.
2068 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2069 startSpecifier, specifierLen)) {
2070 return false;
2071 }
2072
2073 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2074 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002075 return false;
2076 }
2077
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002078 if (!CS.consumesDataArgument()) {
2079 // FIXME: Technically specifying a precision or field width here
2080 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002081 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002082 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002083
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002084 // Consume the argument.
2085 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00002086 if (argIndex < NumDataArgs) {
2087 // The check to see if the argIndex is valid will come later.
2088 // We set the bit here because we may exit early from this
2089 // function if we encounter some other error.
2090 CoveredArgs.set(argIndex);
2091 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002092
2093 // Check for using an Objective-C specific conversion specifier
2094 // in a non-ObjC literal.
2095 if (!IsObjCLiteral && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002096 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
2097 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002098 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002099
Tom Caree4ee9662010-06-17 19:00:27 +00002100 // Check for invalid use of field width
2101 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002102 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00002103 startSpecifier, specifierLen);
2104 }
2105
2106 // Check for invalid use of precision
2107 if (!FS.hasValidPrecision()) {
2108 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
2109 startSpecifier, specifierLen);
2110 }
2111
2112 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00002113 if (!FS.hasValidThousandsGroupingPrefix())
2114 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002115 if (!FS.hasValidLeadingZeros())
2116 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
2117 if (!FS.hasValidPlusPrefix())
2118 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00002119 if (!FS.hasValidSpacePrefix())
2120 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002121 if (!FS.hasValidAlternativeForm())
2122 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
2123 if (!FS.hasValidLeftJustified())
2124 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
2125
2126 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00002127 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
2128 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
2129 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002130 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
2131 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
2132 startSpecifier, specifierLen);
2133
2134 // Check the length modifier is valid with the given conversion specifier.
2135 const LengthModifier &LM = FS.getLengthModifier();
2136 if (!FS.hasValidLengthModifier())
Richard Trieu55733de2011-10-28 00:41:25 +00002137 EmitFormatDiagnostic(S.PDiag(diag::warn_format_nonsensical_length)
2138 << LM.toString() << CS.toString(),
2139 getLocationOfByte(LM.getStart()),
2140 /*IsStringLocation*/true,
2141 getSpecifierRange(startSpecifier, specifierLen),
2142 FixItHint::CreateRemoval(
2143 getSpecifierRange(LM.getStart(),
2144 LM.getLength())));
Tom Caree4ee9662010-06-17 19:00:27 +00002145
2146 // Are we using '%n'?
Ted Kremenek35d353b2010-07-20 20:04:10 +00002147 if (CS.getKind() == ConversionSpecifier::nArg) {
Tom Caree4ee9662010-06-17 19:00:27 +00002148 // Issue a warning about this being a possible security issue.
Richard Trieu55733de2011-10-28 00:41:25 +00002149 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_write_back),
2150 getLocationOfByte(CS.getStart()),
2151 /*IsStringLocation*/true,
2152 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremeneke82d8042010-01-29 01:35:25 +00002153 // Continue checking the other format specifiers.
2154 return true;
2155 }
Ted Kremenek5c41ee82010-02-11 09:27:41 +00002156
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002157 // The remaining checks depend on the data arguments.
2158 if (HasVAListArg)
2159 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002160
Ted Kremenek666a1972010-07-26 19:45:42 +00002161 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002162 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002163
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002164 // Now type check the data expression that matches the
2165 // format specifier.
2166 const Expr *Ex = getDataArg(argIndex);
Nico Weber339b9072012-01-31 01:43:25 +00002167 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context,
2168 IsObjCLiteral);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002169 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
2170 // Check if we didn't match because of an implicit cast from a 'char'
2171 // or 'short' to an 'int'. This is done because printf is a varargs
2172 // function.
2173 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00002174 if (ICE->getType() == S.Context.IntTy) {
2175 // All further checking is done on the subexpression.
2176 Ex = ICE->getSubExpr();
2177 if (ATR.matchesType(S.Context, Ex->getType()))
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002178 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00002179 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002180
2181 // We may be able to offer a FixItHint if it is a supported type.
2182 PrintfSpecifier fixedFS = FS;
Hans Wennborga7da2152011-10-18 08:10:06 +00002183 bool success = fixedFS.fixType(Ex->getType(), S.getLangOptions());
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002184
2185 if (success) {
2186 // Get the fix string from the fixed format specifier
2187 llvm::SmallString<128> buf;
2188 llvm::raw_svector_ostream os(buf);
2189 fixedFS.toString(os);
2190
Richard Trieu55733de2011-10-28 00:41:25 +00002191 EmitFormatDiagnostic(
2192 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborga792aff2011-12-07 10:33:11 +00002193 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
Richard Trieu55733de2011-10-28 00:41:25 +00002194 << Ex->getSourceRange(),
2195 getLocationOfByte(CS.getStart()),
2196 /*IsStringLocation*/true,
2197 getSpecifierRange(startSpecifier, specifierLen),
2198 FixItHint::CreateReplacement(
2199 getSpecifierRange(startSpecifier, specifierLen),
2200 os.str()));
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002201 }
2202 else {
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00002203 EmitFormatDiagnostic(
2204 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2205 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
2206 << getSpecifierRange(startSpecifier, specifierLen)
2207 << Ex->getSourceRange(),
2208 getLocationOfByte(CS.getStart()),
2209 true,
2210 getSpecifierRange(startSpecifier, specifierLen));
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002211 }
2212 }
2213
Ted Kremeneke0e53132010-01-28 23:39:18 +00002214 return true;
2215}
2216
Ted Kremenek826a3452010-07-16 02:11:22 +00002217//===--- CHECK: Scanf format string checking ------------------------------===//
2218
2219namespace {
2220class CheckScanfHandler : public CheckFormatHandler {
2221public:
2222 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
2223 const Expr *origFormatExpr, unsigned firstDataArg,
2224 unsigned numDataArgs, bool isObjCLiteral,
2225 const char *beg, bool hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002226 Expr **Args, unsigned NumArgs,
2227 unsigned formatIdx, bool inFunctionCall)
Ted Kremenek826a3452010-07-16 02:11:22 +00002228 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2229 numDataArgs, isObjCLiteral, beg, hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002230 Args, NumArgs, formatIdx, inFunctionCall) {}
Ted Kremenek826a3452010-07-16 02:11:22 +00002231
2232 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
2233 const char *startSpecifier,
2234 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002235
2236 bool HandleInvalidScanfConversionSpecifier(
2237 const analyze_scanf::ScanfSpecifier &FS,
2238 const char *startSpecifier,
2239 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00002240
2241 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00002242};
Ted Kremenek07d161f2010-01-29 01:50:07 +00002243}
Ted Kremeneke0e53132010-01-28 23:39:18 +00002244
Ted Kremenekb7c21012010-07-16 18:28:03 +00002245void CheckScanfHandler::HandleIncompleteScanList(const char *start,
2246 const char *end) {
Richard Trieu55733de2011-10-28 00:41:25 +00002247 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
2248 getLocationOfByte(end), /*IsStringLocation*/true,
2249 getSpecifierRange(start, end - start));
Ted Kremenekb7c21012010-07-16 18:28:03 +00002250}
2251
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002252bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
2253 const analyze_scanf::ScanfSpecifier &FS,
2254 const char *startSpecifier,
2255 unsigned specifierLen) {
2256
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002257 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002258 FS.getConversionSpecifier();
2259
2260 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2261 getLocationOfByte(CS.getStart()),
2262 startSpecifier, specifierLen,
2263 CS.getStart(), CS.getLength());
2264}
2265
Ted Kremenek826a3452010-07-16 02:11:22 +00002266bool CheckScanfHandler::HandleScanfSpecifier(
2267 const analyze_scanf::ScanfSpecifier &FS,
2268 const char *startSpecifier,
2269 unsigned specifierLen) {
2270
2271 using namespace analyze_scanf;
2272 using namespace analyze_format_string;
2273
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002274 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002275
Ted Kremenekbaa40062010-07-19 22:01:06 +00002276 // Handle case where '%' and '*' don't consume an argument. These shouldn't
2277 // be used to decide if we are using positional arguments consistently.
2278 if (FS.consumesDataArgument()) {
2279 if (atFirstArg) {
2280 atFirstArg = false;
2281 usesPositionalArgs = FS.usesPositionalArg();
2282 }
2283 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002284 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2285 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002286 return false;
2287 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002288 }
2289
2290 // Check if the field with is non-zero.
2291 const OptionalAmount &Amt = FS.getFieldWidth();
2292 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
2293 if (Amt.getConstantAmount() == 0) {
2294 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
2295 Amt.getConstantLength());
Richard Trieu55733de2011-10-28 00:41:25 +00002296 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
2297 getLocationOfByte(Amt.getStart()),
2298 /*IsStringLocation*/true, R,
2299 FixItHint::CreateRemoval(R));
Ted Kremenek826a3452010-07-16 02:11:22 +00002300 }
2301 }
2302
2303 if (!FS.consumesDataArgument()) {
2304 // FIXME: Technically specifying a precision or field width here
2305 // makes no sense. Worth issuing a warning at some point.
2306 return true;
2307 }
2308
2309 // Consume the argument.
2310 unsigned argIndex = FS.getArgIndex();
2311 if (argIndex < NumDataArgs) {
2312 // The check to see if the argIndex is valid will come later.
2313 // We set the bit here because we may exit early from this
2314 // function if we encounter some other error.
2315 CoveredArgs.set(argIndex);
2316 }
2317
Ted Kremenek1e51c202010-07-20 20:04:47 +00002318 // Check the length modifier is valid with the given conversion specifier.
2319 const LengthModifier &LM = FS.getLengthModifier();
2320 if (!FS.hasValidLengthModifier()) {
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00002321 const CharSourceRange &R = getSpecifierRange(LM.getStart(), LM.getLength());
2322 EmitFormatDiagnostic(S.PDiag(diag::warn_format_nonsensical_length)
2323 << LM.toString() << CS.toString()
2324 << getSpecifierRange(startSpecifier, specifierLen),
2325 getLocationOfByte(LM.getStart()),
2326 /*IsStringLocation*/true, R,
2327 FixItHint::CreateRemoval(R));
Ted Kremenek1e51c202010-07-20 20:04:47 +00002328 }
2329
Ted Kremenek826a3452010-07-16 02:11:22 +00002330 // The remaining checks depend on the data arguments.
2331 if (HasVAListArg)
2332 return true;
2333
Ted Kremenek666a1972010-07-26 19:45:42 +00002334 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00002335 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00002336
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002337 // Check that the argument type matches the format specifier.
2338 const Expr *Ex = getDataArg(argIndex);
2339 const analyze_scanf::ScanfArgTypeResult &ATR = FS.getArgType(S.Context);
2340 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
2341 ScanfSpecifier fixedFS = FS;
2342 bool success = fixedFS.fixType(Ex->getType(), S.getLangOptions());
2343
2344 if (success) {
2345 // Get the fix string from the fixed format specifier.
2346 llvm::SmallString<128> buf;
2347 llvm::raw_svector_ostream os(buf);
2348 fixedFS.toString(os);
2349
2350 EmitFormatDiagnostic(
2351 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2352 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
2353 << Ex->getSourceRange(),
2354 getLocationOfByte(CS.getStart()),
2355 /*IsStringLocation*/true,
2356 getSpecifierRange(startSpecifier, specifierLen),
2357 FixItHint::CreateReplacement(
2358 getSpecifierRange(startSpecifier, specifierLen),
2359 os.str()));
2360 } else {
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00002361 EmitFormatDiagnostic(
2362 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002363 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00002364 << Ex->getSourceRange(),
2365 getLocationOfByte(CS.getStart()),
2366 /*IsStringLocation*/true,
2367 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002368 }
2369 }
2370
Ted Kremenek826a3452010-07-16 02:11:22 +00002371 return true;
2372}
2373
2374void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002375 const Expr *OrigFormatExpr,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002376 Expr **Args, unsigned NumArgs,
2377 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002378 unsigned firstDataArg, FormatStringType Type,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002379 bool inFunctionCall) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002380
Ted Kremeneke0e53132010-01-28 23:39:18 +00002381 // CHECK: is the format string a wide literal?
Douglas Gregor5cee1192011-07-27 05:40:30 +00002382 if (!FExpr->isAscii()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002383 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002384 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00002385 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
2386 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00002387 return;
2388 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002389
Ted Kremeneke0e53132010-01-28 23:39:18 +00002390 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner5f9e2722011-07-23 10:55:15 +00002391 StringRef StrRef = FExpr->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00002392 const char *Str = StrRef.data();
2393 unsigned StrLen = StrRef.size();
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002394 const unsigned numDataArgs = NumArgs - firstDataArg;
Ted Kremenek826a3452010-07-16 02:11:22 +00002395
Ted Kremeneke0e53132010-01-28 23:39:18 +00002396 // CHECK: empty format string?
Ted Kremenek4cd57912011-09-29 05:52:16 +00002397 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu55733de2011-10-28 00:41:25 +00002398 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002399 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00002400 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
2401 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00002402 return;
2403 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002404
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002405 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002406 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Ted Kremenek4cd57912011-09-29 05:52:16 +00002407 numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr),
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002408 Str, HasVAListArg, Args, NumArgs, format_idx,
Richard Trieu55733de2011-10-28 00:41:25 +00002409 inFunctionCall);
Ted Kremenek826a3452010-07-16 02:11:22 +00002410
Hans Wennborgd02deeb2011-12-15 10:25:47 +00002411 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
2412 getLangOptions()))
Ted Kremenek826a3452010-07-16 02:11:22 +00002413 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002414 } else if (Type == FST_Scanf) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002415 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Ted Kremenek4cd57912011-09-29 05:52:16 +00002416 numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr),
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002417 Str, HasVAListArg, Args, NumArgs, format_idx,
Richard Trieu55733de2011-10-28 00:41:25 +00002418 inFunctionCall);
Ted Kremenek826a3452010-07-16 02:11:22 +00002419
Hans Wennborgd02deeb2011-12-15 10:25:47 +00002420 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
2421 getLangOptions()))
Ted Kremenek826a3452010-07-16 02:11:22 +00002422 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002423 } // TODO: handle other formats
Ted Kremenekce7024e2010-01-28 01:18:22 +00002424}
2425
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002426//===--- CHECK: Standard memory functions ---------------------------------===//
2427
Douglas Gregor2a053a32011-05-03 20:05:22 +00002428/// \brief Determine whether the given type is a dynamic class type (e.g.,
2429/// whether it has a vtable).
2430static bool isDynamicClassType(QualType T) {
2431 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
2432 if (CXXRecordDecl *Definition = Record->getDefinition())
2433 if (Definition->isDynamicClass())
2434 return true;
2435
2436 return false;
2437}
2438
Chandler Carrutha72a12f2011-06-21 23:04:20 +00002439/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth000d4282011-06-16 09:09:40 +00002440/// otherwise returns NULL.
2441static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Webere4a1c642011-06-14 16:14:58 +00002442 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth000d4282011-06-16 09:09:40 +00002443 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2444 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
2445 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00002446
Chandler Carruth000d4282011-06-16 09:09:40 +00002447 return 0;
2448}
2449
Chandler Carrutha72a12f2011-06-21 23:04:20 +00002450/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth000d4282011-06-16 09:09:40 +00002451static QualType getSizeOfArgType(const Expr* E) {
2452 if (const UnaryExprOrTypeTraitExpr *SizeOf =
2453 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2454 if (SizeOf->getKind() == clang::UETT_SizeOf)
2455 return SizeOf->getTypeOfArgument();
2456
2457 return QualType();
Nico Webere4a1c642011-06-14 16:14:58 +00002458}
2459
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002460/// \brief Check for dangerous or invalid arguments to memset().
2461///
Chandler Carruth929f0132011-06-03 06:23:57 +00002462/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002463/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
2464/// function calls.
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002465///
2466/// \param Call The call expression to diagnose.
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002467void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks0a151a12012-01-17 00:37:07 +00002468 unsigned BId,
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002469 IdentifierInfo *FnName) {
Anna Zaks0a151a12012-01-17 00:37:07 +00002470 assert(BId != 0);
2471
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00002472 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor707a23e2011-06-16 17:56:04 +00002473 // we have enough arguments, and if not, abort further checking.
Anna Zaks0a151a12012-01-17 00:37:07 +00002474 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Webercda57822011-10-13 22:30:23 +00002475 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00002476 return;
2477
Anna Zaks0a151a12012-01-17 00:37:07 +00002478 unsigned LastArg = (BId == Builtin::BImemset ||
2479 BId == Builtin::BIstrndup ? 1 : 2);
2480 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Webercda57822011-10-13 22:30:23 +00002481 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth000d4282011-06-16 09:09:40 +00002482
2483 // We have special checking when the length is a sizeof expression.
2484 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
2485 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
2486 llvm::FoldingSetNodeID SizeOfArgID;
2487
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002488 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
2489 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00002490 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002491
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002492 QualType DestTy = Dest->getType();
2493 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
2494 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00002495
Chandler Carruth000d4282011-06-16 09:09:40 +00002496 // Never warn about void type pointers. This can be used to suppress
2497 // false positives.
2498 if (PointeeTy->isVoidType())
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002499 continue;
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002500
Chandler Carruth000d4282011-06-16 09:09:40 +00002501 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
2502 // actually comparing the expressions for equality. Because computing the
2503 // expression IDs can be expensive, we only do this if the diagnostic is
2504 // enabled.
2505 if (SizeOfArg &&
2506 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
2507 SizeOfArg->getExprLoc())) {
2508 // We only compute IDs for expressions if the warning is enabled, and
2509 // cache the sizeof arg's ID.
2510 if (SizeOfArgID == llvm::FoldingSetNodeID())
2511 SizeOfArg->Profile(SizeOfArgID, Context, true);
2512 llvm::FoldingSetNodeID DestID;
2513 Dest->Profile(DestID, Context, true);
2514 if (DestID == SizeOfArgID) {
Nico Webercda57822011-10-13 22:30:23 +00002515 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
2516 // over sizeof(src) as well.
Chandler Carruth000d4282011-06-16 09:09:40 +00002517 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
2518 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
2519 if (UnaryOp->getOpcode() == UO_AddrOf)
2520 ActionIdx = 1; // If its an address-of operator, just remove it.
2521 if (Context.getTypeSize(PointeeTy) == Context.getCharWidth())
2522 ActionIdx = 2; // If the pointee's size is sizeof(char),
2523 // suggest an explicit length.
Anna Zaksd9b859a2012-01-13 21:52:01 +00002524 unsigned DestSrcSelect =
Anna Zaks0a151a12012-01-17 00:37:07 +00002525 (BId == Builtin::BIstrndup ? 1 : ArgIdx);
Chandler Carruth000d4282011-06-16 09:09:40 +00002526 DiagRuntimeBehavior(SizeOfArg->getExprLoc(), Dest,
2527 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Nico Webercda57822011-10-13 22:30:23 +00002528 << FnName << DestSrcSelect << ActionIdx
Chandler Carruth000d4282011-06-16 09:09:40 +00002529 << Dest->getSourceRange()
2530 << SizeOfArg->getSourceRange());
2531 break;
2532 }
2533 }
2534
2535 // Also check for cases where the sizeof argument is the exact same
2536 // type as the memory argument, and where it points to a user-defined
2537 // record type.
2538 if (SizeOfArgTy != QualType()) {
2539 if (PointeeTy->isRecordType() &&
2540 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
2541 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
2542 PDiag(diag::warn_sizeof_pointer_type_memaccess)
2543 << FnName << SizeOfArgTy << ArgIdx
2544 << PointeeTy << Dest->getSourceRange()
2545 << LenExpr->getSourceRange());
2546 break;
2547 }
Nico Webere4a1c642011-06-14 16:14:58 +00002548 }
2549
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002550 // Always complain about dynamic classes.
Anna Zaks0a151a12012-01-17 00:37:07 +00002551 if (isDynamicClassType(PointeeTy)) {
2552
2553 unsigned OperationType = 0;
2554 // "overwritten" if we're warning about the destination for any call
2555 // but memcmp; otherwise a verb appropriate to the call.
2556 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
2557 if (BId == Builtin::BImemcpy)
2558 OperationType = 1;
2559 else if(BId == Builtin::BImemmove)
2560 OperationType = 2;
2561 else if (BId == Builtin::BImemcmp)
2562 OperationType = 3;
2563 }
2564
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00002565 DiagRuntimeBehavior(
2566 Dest->getExprLoc(), Dest,
2567 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks0a151a12012-01-17 00:37:07 +00002568 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Anna Zaksd9b859a2012-01-13 21:52:01 +00002569 << FnName << PointeeTy
Anna Zaks0a151a12012-01-17 00:37:07 +00002570 << OperationType
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00002571 << Call->getCallee()->getSourceRange());
Anna Zaks0a151a12012-01-17 00:37:07 +00002572 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
2573 BId != Builtin::BImemset)
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00002574 DiagRuntimeBehavior(
2575 Dest->getExprLoc(), Dest,
2576 PDiag(diag::warn_arc_object_memaccess)
2577 << ArgIdx << FnName << PointeeTy
2578 << Call->getCallee()->getSourceRange());
John McCallf85e1932011-06-15 23:02:42 +00002579 else
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002580 continue;
John McCallf85e1932011-06-15 23:02:42 +00002581
2582 DiagRuntimeBehavior(
2583 Dest->getExprLoc(), Dest,
Chandler Carruth929f0132011-06-03 06:23:57 +00002584 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002585 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
2586 break;
2587 }
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002588 }
2589}
2590
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002591// A little helper routine: ignore addition and subtraction of integer literals.
2592// This intentionally does not ignore all integer constant expressions because
2593// we don't want to remove sizeof().
2594static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
2595 Ex = Ex->IgnoreParenCasts();
2596
2597 for (;;) {
2598 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
2599 if (!BO || !BO->isAdditiveOp())
2600 break;
2601
2602 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
2603 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
2604
2605 if (isa<IntegerLiteral>(RHS))
2606 Ex = LHS;
2607 else if (isa<IntegerLiteral>(LHS))
2608 Ex = RHS;
2609 else
2610 break;
2611 }
2612
2613 return Ex;
2614}
2615
2616// Warn if the user has made the 'size' argument to strlcpy or strlcat
2617// be the size of the source, instead of the destination.
2618void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
2619 IdentifierInfo *FnName) {
2620
2621 // Don't crash if the user has the wrong number of arguments
2622 if (Call->getNumArgs() != 3)
2623 return;
2624
2625 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
2626 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
2627 const Expr *CompareWithSrc = NULL;
2628
2629 // Look for 'strlcpy(dst, x, sizeof(x))'
2630 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
2631 CompareWithSrc = Ex;
2632 else {
2633 // Look for 'strlcpy(dst, x, strlen(x))'
2634 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Richard Smith180f4792011-11-10 06:34:14 +00002635 if (SizeCall->isBuiltinCall() == Builtin::BIstrlen
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002636 && SizeCall->getNumArgs() == 1)
2637 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
2638 }
2639 }
2640
2641 if (!CompareWithSrc)
2642 return;
2643
2644 // Determine if the argument to sizeof/strlen is equal to the source
2645 // argument. In principle there's all kinds of things you could do
2646 // here, for instance creating an == expression and evaluating it with
2647 // EvaluateAsBooleanCondition, but this uses a more direct technique:
2648 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
2649 if (!SrcArgDRE)
2650 return;
2651
2652 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
2653 if (!CompareWithSrcDRE ||
2654 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
2655 return;
2656
2657 const Expr *OriginalSizeArg = Call->getArg(2);
2658 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
2659 << OriginalSizeArg->getSourceRange() << FnName;
2660
2661 // Output a FIXIT hint if the destination is an array (rather than a
2662 // pointer to an array). This could be enhanced to handle some
2663 // pointers if we know the actual size, like if DstArg is 'array+2'
2664 // we could say 'sizeof(array)-2'.
2665 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Ted Kremenek8f746222011-08-18 22:48:41 +00002666 QualType DstArgTy = DstArg->getType();
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002667
Ted Kremenek8f746222011-08-18 22:48:41 +00002668 // Only handle constant-sized or VLAs, but not flexible members.
2669 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(DstArgTy)) {
2670 // Only issue the FIXIT for arrays of size > 1.
2671 if (CAT->getSize().getSExtValue() <= 1)
2672 return;
2673 } else if (!DstArgTy->isVariableArrayType()) {
2674 return;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002675 }
Ted Kremenek8f746222011-08-18 22:48:41 +00002676
2677 llvm::SmallString<128> sizeString;
2678 llvm::raw_svector_ostream OS(sizeString);
2679 OS << "sizeof(";
Douglas Gregor8987b232011-09-27 23:30:47 +00002680 DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
Ted Kremenek8f746222011-08-18 22:48:41 +00002681 OS << ")";
2682
2683 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
2684 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
2685 OS.str());
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002686}
2687
Anna Zaksc36bedc2012-02-01 19:08:57 +00002688/// Check if two expressions refer to the same declaration.
2689static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
2690 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
2691 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
2692 return D1->getDecl() == D2->getDecl();
2693 return false;
2694}
2695
2696static const Expr *getStrlenExprArg(const Expr *E) {
2697 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
2698 const FunctionDecl *FD = CE->getDirectCallee();
2699 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
2700 return 0;
2701 return CE->getArg(0)->IgnoreParenCasts();
2702 }
2703 return 0;
2704}
2705
2706// Warn on anti-patterns as the 'size' argument to strncat.
2707// The correct size argument should look like following:
2708// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
2709void Sema::CheckStrncatArguments(const CallExpr *CE,
2710 IdentifierInfo *FnName) {
2711 // Don't crash if the user has the wrong number of arguments.
2712 if (CE->getNumArgs() < 3)
2713 return;
2714 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
2715 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
2716 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
2717
2718 // Identify common expressions, which are wrongly used as the size argument
2719 // to strncat and may lead to buffer overflows.
2720 unsigned PatternType = 0;
2721 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
2722 // - sizeof(dst)
2723 if (referToTheSameDecl(SizeOfArg, DstArg))
2724 PatternType = 1;
2725 // - sizeof(src)
2726 else if (referToTheSameDecl(SizeOfArg, SrcArg))
2727 PatternType = 2;
2728 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
2729 if (BE->getOpcode() == BO_Sub) {
2730 const Expr *L = BE->getLHS()->IgnoreParenCasts();
2731 const Expr *R = BE->getRHS()->IgnoreParenCasts();
2732 // - sizeof(dst) - strlen(dst)
2733 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
2734 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
2735 PatternType = 1;
2736 // - sizeof(src) - (anything)
2737 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
2738 PatternType = 2;
2739 }
2740 }
2741
2742 if (PatternType == 0)
2743 return;
2744
Anna Zaksafdb0412012-02-03 01:27:37 +00002745 // Generate the diagnostic.
2746 SourceLocation SL = LenArg->getLocStart();
2747 SourceRange SR = LenArg->getSourceRange();
2748 SourceManager &SM = PP.getSourceManager();
2749
2750 // If the function is defined as a builtin macro, do not show macro expansion.
2751 if (SM.isMacroArgExpansion(SL)) {
2752 SL = SM.getSpellingLoc(SL);
2753 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
2754 SM.getSpellingLoc(SR.getEnd()));
2755 }
2756
Anna Zaksc36bedc2012-02-01 19:08:57 +00002757 if (PatternType == 1)
Anna Zaksafdb0412012-02-03 01:27:37 +00002758 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00002759 else
Anna Zaksafdb0412012-02-03 01:27:37 +00002760 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00002761
2762 // Output a FIXIT hint if the destination is an array (rather than a
2763 // pointer to an array). This could be enhanced to handle some
2764 // pointers if we know the actual size, like if DstArg is 'array+2'
2765 // we could say 'sizeof(array)-2'.
2766 QualType DstArgTy = DstArg->getType();
2767
2768 // Only handle constant-sized or VLAs, but not flexible members.
2769 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(DstArgTy)) {
2770 // Only issue the FIXIT for arrays of size > 1.
2771 if (CAT->getSize().getSExtValue() <= 1)
2772 return;
2773 } else if (!DstArgTy->isVariableArrayType()) {
2774 return;
2775 }
2776
2777 llvm::SmallString<128> sizeString;
2778 llvm::raw_svector_ostream OS(sizeString);
2779 OS << "sizeof(";
2780 DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
2781 OS << ") - ";
2782 OS << "strlen(";
2783 DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
2784 OS << ") - 1";
2785
Anna Zaksafdb0412012-02-03 01:27:37 +00002786 Diag(SL, diag::note_strncat_wrong_size)
2787 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaksc36bedc2012-02-01 19:08:57 +00002788}
2789
Ted Kremenek06de2762007-08-17 16:46:58 +00002790//===--- CHECK: Return Address of Stack Variable --------------------------===//
2791
Chris Lattner5f9e2722011-07-23 10:55:15 +00002792static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars);
2793static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002794
2795/// CheckReturnStackAddr - Check if a return statement returns the address
2796/// of a stack variable.
2797void
2798Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
2799 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00002800
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002801 Expr *stackE = 0;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002802 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002803
2804 // Perform checking for returned stack addresses, local blocks,
2805 // label addresses or references to temporaries.
John McCallf85e1932011-06-15 23:02:42 +00002806 if (lhsType->isPointerType() ||
2807 (!getLangOptions().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002808 stackE = EvalAddr(RetValExp, refVars);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002809 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002810 stackE = EvalVal(RetValExp, refVars);
2811 }
2812
2813 if (stackE == 0)
2814 return; // Nothing suspicious was found.
2815
2816 SourceLocation diagLoc;
2817 SourceRange diagRange;
2818 if (refVars.empty()) {
2819 diagLoc = stackE->getLocStart();
2820 diagRange = stackE->getSourceRange();
2821 } else {
2822 // We followed through a reference variable. 'stackE' contains the
2823 // problematic expression but we will warn at the return statement pointing
2824 // at the reference variable. We will later display the "trail" of
2825 // reference variables using notes.
2826 diagLoc = refVars[0]->getLocStart();
2827 diagRange = refVars[0]->getSourceRange();
2828 }
2829
2830 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
2831 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
2832 : diag::warn_ret_stack_addr)
2833 << DR->getDecl()->getDeclName() << diagRange;
2834 } else if (isa<BlockExpr>(stackE)) { // local block.
2835 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
2836 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
2837 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
2838 } else { // local temporary.
2839 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
2840 : diag::warn_ret_local_temp_addr)
2841 << diagRange;
2842 }
2843
2844 // Display the "trail" of reference variables that we followed until we
2845 // found the problematic expression using notes.
2846 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
2847 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
2848 // If this var binds to another reference var, show the range of the next
2849 // var, otherwise the var binds to the problematic expression, in which case
2850 // show the range of the expression.
2851 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
2852 : stackE->getSourceRange();
2853 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
2854 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00002855 }
2856}
2857
2858/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
2859/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002860/// to a location on the stack, a local block, an address of a label, or a
2861/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00002862/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002863/// encounter a subexpression that (1) clearly does not lead to one of the
2864/// above problematic expressions (2) is something we cannot determine leads to
2865/// a problematic expression based on such local checking.
2866///
2867/// Both EvalAddr and EvalVal follow through reference variables to evaluate
2868/// the expression that they point to. Such variables are added to the
2869/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00002870///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00002871/// EvalAddr processes expressions that are pointers that are used as
2872/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002873/// At the base case of the recursion is a check for the above problematic
2874/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00002875///
2876/// This implementation handles:
2877///
2878/// * pointer-to-pointer casts
2879/// * implicit conversions from array references to pointers
2880/// * taking the address of fields
2881/// * arbitrary interplay between "&" and "*" operators
2882/// * pointer arithmetic from an address of a stack variable
2883/// * taking the address of an array element where the array is on the stack
Chris Lattner5f9e2722011-07-23 10:55:15 +00002884static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002885 if (E->isTypeDependent())
2886 return NULL;
2887
Ted Kremenek06de2762007-08-17 16:46:58 +00002888 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00002889 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00002890 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002891 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002892 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00002893
Peter Collingbournef111d932011-04-15 00:35:48 +00002894 E = E->IgnoreParens();
2895
Ted Kremenek06de2762007-08-17 16:46:58 +00002896 // Our "symbolic interpreter" is just a dispatch off the currently
2897 // viewed AST node. We then recursively traverse the AST by calling
2898 // EvalAddr and EvalVal appropriately.
2899 switch (E->getStmtClass()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002900 case Stmt::DeclRefExprClass: {
2901 DeclRefExpr *DR = cast<DeclRefExpr>(E);
2902
2903 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
2904 // If this is a reference variable, follow through to the expression that
2905 // it points to.
2906 if (V->hasLocalStorage() &&
2907 V->getType()->isReferenceType() && V->hasInit()) {
2908 // Add the reference variable to the "trail".
2909 refVars.push_back(DR);
2910 return EvalAddr(V->getInit(), refVars);
2911 }
2912
2913 return NULL;
2914 }
Ted Kremenek06de2762007-08-17 16:46:58 +00002915
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002916 case Stmt::UnaryOperatorClass: {
2917 // The only unary operator that make sense to handle here
2918 // is AddrOf. All others don't make sense as pointers.
2919 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002920
John McCall2de56d12010-08-25 11:45:40 +00002921 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002922 return EvalVal(U->getSubExpr(), refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002923 else
Ted Kremenek06de2762007-08-17 16:46:58 +00002924 return NULL;
2925 }
Mike Stump1eb44332009-09-09 15:08:12 +00002926
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002927 case Stmt::BinaryOperatorClass: {
2928 // Handle pointer arithmetic. All other binary operators are not valid
2929 // in this context.
2930 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00002931 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00002932
John McCall2de56d12010-08-25 11:45:40 +00002933 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002934 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00002935
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002936 Expr *Base = B->getLHS();
2937
2938 // Determine which argument is the real pointer base. It could be
2939 // the RHS argument instead of the LHS.
2940 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00002941
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002942 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002943 return EvalAddr(Base, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002944 }
Steve Naroff61f40a22008-09-10 19:17:48 +00002945
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002946 // For conditional operators we need to see if either the LHS or RHS are
2947 // valid DeclRefExpr*s. If one of them is valid, we return it.
2948 case Stmt::ConditionalOperatorClass: {
2949 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002950
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002951 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00002952 if (Expr *lhsExpr = C->getLHS()) {
2953 // In C++, we can have a throw-expression, which has 'void' type.
2954 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002955 if (Expr* LHS = EvalAddr(lhsExpr, refVars))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00002956 return LHS;
2957 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002958
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00002959 // In C++, we can have a throw-expression, which has 'void' type.
2960 if (C->getRHS()->getType()->isVoidType())
2961 return NULL;
2962
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002963 return EvalAddr(C->getRHS(), refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002964 }
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002965
2966 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00002967 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002968 return E; // local block.
2969 return NULL;
2970
2971 case Stmt::AddrLabelExprClass:
2972 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00002973
John McCall80ee6e82011-11-10 05:35:25 +00002974 case Stmt::ExprWithCleanupsClass:
2975 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars);
2976
Ted Kremenek54b52742008-08-07 00:49:01 +00002977 // For casts, we need to handle conversions from arrays to
2978 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00002979 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002980 case Stmt::CStyleCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00002981 case Stmt::CXXFunctionalCastExprClass:
2982 case Stmt::ObjCBridgedCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002983 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenek54b52742008-08-07 00:49:01 +00002984 QualType T = SubExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002985
Steve Naroffdd972f22008-09-05 22:11:13 +00002986 if (SubExpr->getType()->isPointerType() ||
2987 SubExpr->getType()->isBlockPointerType() ||
2988 SubExpr->getType()->isObjCQualifiedIdType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002989 return EvalAddr(SubExpr, refVars);
Ted Kremenek54b52742008-08-07 00:49:01 +00002990 else if (T->isArrayType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002991 return EvalVal(SubExpr, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002992 else
Ted Kremenek54b52742008-08-07 00:49:01 +00002993 return 0;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002994 }
Mike Stump1eb44332009-09-09 15:08:12 +00002995
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002996 // C++ casts. For dynamic casts, static casts, and const casts, we
2997 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor49badde2008-10-27 19:41:14 +00002998 // through the cast. In the case the dynamic cast doesn't fail (and
2999 // return NULL), we take the conservative route and report cases
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003000 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor49badde2008-10-27 19:41:14 +00003001 // FIXME: The comment about is wrong; we're not always converting
3002 // from pointer to pointer. I'm guessing that this code should also
Mike Stump1eb44332009-09-09 15:08:12 +00003003 // handle references to objects.
3004 case Stmt::CXXStaticCastExprClass:
3005 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00003006 case Stmt::CXXConstCastExprClass:
3007 case Stmt::CXXReinterpretCastExprClass: {
3008 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffdd972f22008-09-05 22:11:13 +00003009 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003010 return EvalAddr(S, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003011 else
3012 return NULL;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003013 }
Mike Stump1eb44332009-09-09 15:08:12 +00003014
Douglas Gregor03e80032011-06-21 17:03:29 +00003015 case Stmt::MaterializeTemporaryExprClass:
3016 if (Expr *Result = EvalAddr(
3017 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
3018 refVars))
3019 return Result;
3020
3021 return E;
3022
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003023 // Everything else: we simply don't reason about them.
3024 default:
3025 return NULL;
3026 }
Ted Kremenek06de2762007-08-17 16:46:58 +00003027}
Mike Stump1eb44332009-09-09 15:08:12 +00003028
Ted Kremenek06de2762007-08-17 16:46:58 +00003029
3030/// EvalVal - This function is complements EvalAddr in the mutual recursion.
3031/// See the comments for EvalAddr for more details.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003032static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003033do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00003034 // We should only be called for evaluating non-pointer expressions, or
3035 // expressions with a pointer type that are not used as references but instead
3036 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00003037
Ted Kremenek06de2762007-08-17 16:46:58 +00003038 // Our "symbolic interpreter" is just a dispatch off the currently
3039 // viewed AST node. We then recursively traverse the AST by calling
3040 // EvalAddr and EvalVal appropriately.
Peter Collingbournef111d932011-04-15 00:35:48 +00003041
3042 E = E->IgnoreParens();
Ted Kremenek06de2762007-08-17 16:46:58 +00003043 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003044 case Stmt::ImplicitCastExprClass: {
3045 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00003046 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003047 E = IE->getSubExpr();
3048 continue;
3049 }
3050 return NULL;
3051 }
3052
John McCall80ee6e82011-11-10 05:35:25 +00003053 case Stmt::ExprWithCleanupsClass:
3054 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars);
3055
Douglas Gregora2813ce2009-10-23 18:54:35 +00003056 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003057 // When we hit a DeclRefExpr we are looking at code that refers to a
3058 // variable's name. If it's not a reference variable we check if it has
3059 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00003060 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003061
Ted Kremenek06de2762007-08-17 16:46:58 +00003062 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003063 if (V->hasLocalStorage()) {
3064 if (!V->getType()->isReferenceType())
3065 return DR;
3066
3067 // Reference variable, follow through to the expression that
3068 // it points to.
3069 if (V->hasInit()) {
3070 // Add the reference variable to the "trail".
3071 refVars.push_back(DR);
3072 return EvalVal(V->getInit(), refVars);
3073 }
3074 }
Mike Stump1eb44332009-09-09 15:08:12 +00003075
Ted Kremenek06de2762007-08-17 16:46:58 +00003076 return NULL;
3077 }
Mike Stump1eb44332009-09-09 15:08:12 +00003078
Ted Kremenek06de2762007-08-17 16:46:58 +00003079 case Stmt::UnaryOperatorClass: {
3080 // The only unary operator that make sense to handle here
3081 // is Deref. All others don't resolve to a "name." This includes
3082 // handling all sorts of rvalues passed to a unary operator.
3083 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003084
John McCall2de56d12010-08-25 11:45:40 +00003085 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003086 return EvalAddr(U->getSubExpr(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00003087
3088 return NULL;
3089 }
Mike Stump1eb44332009-09-09 15:08:12 +00003090
Ted Kremenek06de2762007-08-17 16:46:58 +00003091 case Stmt::ArraySubscriptExprClass: {
3092 // Array subscripts are potential references to data on the stack. We
3093 // retrieve the DeclRefExpr* for the array variable if it indeed
3094 // has local storage.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003095 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00003096 }
Mike Stump1eb44332009-09-09 15:08:12 +00003097
Ted Kremenek06de2762007-08-17 16:46:58 +00003098 case Stmt::ConditionalOperatorClass: {
3099 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003100 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00003101 ConditionalOperator *C = cast<ConditionalOperator>(E);
3102
Anders Carlsson39073232007-11-30 19:04:31 +00003103 // Handle the GNU extension for missing LHS.
3104 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003105 if (Expr *LHS = EvalVal(lhsExpr, refVars))
Anders Carlsson39073232007-11-30 19:04:31 +00003106 return LHS;
3107
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003108 return EvalVal(C->getRHS(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00003109 }
Mike Stump1eb44332009-09-09 15:08:12 +00003110
Ted Kremenek06de2762007-08-17 16:46:58 +00003111 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00003112 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00003113 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003114
Ted Kremenek06de2762007-08-17 16:46:58 +00003115 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00003116 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00003117 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00003118
3119 // Check whether the member type is itself a reference, in which case
3120 // we're not going to refer to the member, but to what the member refers to.
3121 if (M->getMemberDecl()->getType()->isReferenceType())
3122 return NULL;
3123
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003124 return EvalVal(M->getBase(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00003125 }
Mike Stump1eb44332009-09-09 15:08:12 +00003126
Douglas Gregor03e80032011-06-21 17:03:29 +00003127 case Stmt::MaterializeTemporaryExprClass:
3128 if (Expr *Result = EvalVal(
3129 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
3130 refVars))
3131 return Result;
3132
3133 return E;
3134
Ted Kremenek06de2762007-08-17 16:46:58 +00003135 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003136 // Check that we don't return or take the address of a reference to a
3137 // temporary. This is only useful in C++.
3138 if (!E->isTypeDependent() && E->isRValue())
3139 return E;
3140
3141 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00003142 return NULL;
3143 }
Ted Kremenek68957a92010-08-04 20:01:07 +00003144} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00003145}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003146
3147//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
3148
3149/// Check for comparisons of floating point operands using != and ==.
3150/// Issue a warning if these are no self-comparisons, as they are not likely
3151/// to do what the programmer intended.
Richard Trieudd225092011-09-15 21:56:47 +00003152void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003153 bool EmitWarning = true;
Mike Stump1eb44332009-09-09 15:08:12 +00003154
Richard Trieudd225092011-09-15 21:56:47 +00003155 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
3156 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003157
3158 // Special case: check for x == x (which is OK).
3159 // Do not emit warnings for such cases.
3160 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
3161 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
3162 if (DRL->getDecl() == DRR->getDecl())
3163 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003164
3165
Ted Kremenek1b500bb2007-11-29 00:59:04 +00003166 // Special case: check for comparisons against literals that can be exactly
3167 // represented by APFloat. In such cases, do not emit a warning. This
3168 // is a heuristic: often comparison against such literals are used to
3169 // detect if a value in a variable has not changed. This clearly can
3170 // lead to false negatives.
3171 if (EmitWarning) {
3172 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
3173 if (FLL->isExact())
3174 EmitWarning = false;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003175 } else
Ted Kremenek1b500bb2007-11-29 00:59:04 +00003176 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
3177 if (FLR->isExact())
3178 EmitWarning = false;
3179 }
3180 }
Mike Stump1eb44332009-09-09 15:08:12 +00003181
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003182 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003183 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003184 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Richard Smith180f4792011-11-10 06:34:14 +00003185 if (CL->isBuiltinCall())
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003186 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003187
Sebastian Redl0eb23302009-01-19 00:08:26 +00003188 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003189 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Richard Smith180f4792011-11-10 06:34:14 +00003190 if (CR->isBuiltinCall())
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003191 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003192
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003193 // Emit the diagnostic.
3194 if (EmitWarning)
Richard Trieudd225092011-09-15 21:56:47 +00003195 Diag(Loc, diag::warn_floatingpoint_eq)
3196 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003197}
John McCallba26e582010-01-04 23:21:16 +00003198
John McCallf2370c92010-01-06 05:24:50 +00003199//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
3200//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00003201
John McCallf2370c92010-01-06 05:24:50 +00003202namespace {
John McCallba26e582010-01-04 23:21:16 +00003203
John McCallf2370c92010-01-06 05:24:50 +00003204/// Structure recording the 'active' range of an integer-valued
3205/// expression.
3206struct IntRange {
3207 /// The number of bits active in the int.
3208 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00003209
John McCallf2370c92010-01-06 05:24:50 +00003210 /// True if the int is known not to have negative values.
3211 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00003212
John McCallf2370c92010-01-06 05:24:50 +00003213 IntRange(unsigned Width, bool NonNegative)
3214 : Width(Width), NonNegative(NonNegative)
3215 {}
John McCallba26e582010-01-04 23:21:16 +00003216
John McCall1844a6e2010-11-10 23:38:19 +00003217 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00003218 static IntRange forBoolType() {
3219 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00003220 }
3221
John McCall1844a6e2010-11-10 23:38:19 +00003222 /// Returns the range of an opaque value of the given integral type.
3223 static IntRange forValueOfType(ASTContext &C, QualType T) {
3224 return forValueOfCanonicalType(C,
3225 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00003226 }
3227
John McCall1844a6e2010-11-10 23:38:19 +00003228 /// Returns the range of an opaque value of a canonical integral type.
3229 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00003230 assert(T->isCanonicalUnqualified());
3231
3232 if (const VectorType *VT = dyn_cast<VectorType>(T))
3233 T = VT->getElementType().getTypePtr();
3234 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
3235 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00003236
John McCall091f23f2010-11-09 22:22:12 +00003237 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00003238 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
3239 EnumDecl *Enum = ET->getDecl();
John McCall5e1cdac2011-10-07 06:10:15 +00003240 if (!Enum->isCompleteDefinition())
John McCall091f23f2010-11-09 22:22:12 +00003241 return IntRange(C.getIntWidth(QualType(T, 0)), false);
3242
John McCall323ed742010-05-06 08:58:33 +00003243 unsigned NumPositive = Enum->getNumPositiveBits();
3244 unsigned NumNegative = Enum->getNumNegativeBits();
3245
3246 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
3247 }
John McCallf2370c92010-01-06 05:24:50 +00003248
3249 const BuiltinType *BT = cast<BuiltinType>(T);
3250 assert(BT->isInteger());
3251
3252 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
3253 }
3254
John McCall1844a6e2010-11-10 23:38:19 +00003255 /// Returns the "target" range of a canonical integral type, i.e.
3256 /// the range of values expressible in the type.
3257 ///
3258 /// This matches forValueOfCanonicalType except that enums have the
3259 /// full range of their type, not the range of their enumerators.
3260 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
3261 assert(T->isCanonicalUnqualified());
3262
3263 if (const VectorType *VT = dyn_cast<VectorType>(T))
3264 T = VT->getElementType().getTypePtr();
3265 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
3266 T = CT->getElementType().getTypePtr();
3267 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor69ff26b2011-09-08 23:29:05 +00003268 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall1844a6e2010-11-10 23:38:19 +00003269
3270 const BuiltinType *BT = cast<BuiltinType>(T);
3271 assert(BT->isInteger());
3272
3273 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
3274 }
3275
3276 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00003277 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00003278 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00003279 L.NonNegative && R.NonNegative);
3280 }
3281
John McCall1844a6e2010-11-10 23:38:19 +00003282 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00003283 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00003284 return IntRange(std::min(L.Width, R.Width),
3285 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00003286 }
3287};
3288
Ted Kremenek0692a192012-01-31 05:37:37 +00003289static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
3290 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00003291 if (value.isSigned() && value.isNegative())
3292 return IntRange(value.getMinSignedBits(), false);
3293
3294 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00003295 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00003296
3297 // isNonNegative() just checks the sign bit without considering
3298 // signedness.
3299 return IntRange(value.getActiveBits(), true);
3300}
3301
Ted Kremenek0692a192012-01-31 05:37:37 +00003302static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
3303 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00003304 if (result.isInt())
3305 return GetValueRange(C, result.getInt(), MaxWidth);
3306
3307 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00003308 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
3309 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
3310 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
3311 R = IntRange::join(R, El);
3312 }
John McCallf2370c92010-01-06 05:24:50 +00003313 return R;
3314 }
3315
3316 if (result.isComplexInt()) {
3317 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
3318 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
3319 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00003320 }
3321
3322 // This can happen with lossless casts to intptr_t of "based" lvalues.
3323 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00003324 // FIXME: The only reason we need to pass the type in here is to get
3325 // the sign right on this one case. It would be nice if APValue
3326 // preserved this.
Eli Friedman65639282012-01-04 23:13:47 +00003327 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00003328 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall51313c32010-01-04 23:31:57 +00003329}
John McCallf2370c92010-01-06 05:24:50 +00003330
3331/// Pseudo-evaluate the given integer expression, estimating the
3332/// range of values it might take.
3333///
3334/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek0692a192012-01-31 05:37:37 +00003335static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00003336 E = E->IgnoreParens();
3337
3338 // Try a full evaluation first.
3339 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00003340 if (E->EvaluateAsRValue(result, C))
John McCall0acc3112010-01-06 22:57:21 +00003341 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00003342
3343 // I think we only want to look through implicit casts here; if the
3344 // user has an explicit widening cast, we should treat the value as
3345 // being of the new, wider type.
3346 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedmanb17ee5b2011-12-15 02:41:52 +00003347 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCallf2370c92010-01-06 05:24:50 +00003348 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
3349
John McCall1844a6e2010-11-10 23:38:19 +00003350 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
John McCallf2370c92010-01-06 05:24:50 +00003351
John McCall2de56d12010-08-25 11:45:40 +00003352 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00003353
John McCallf2370c92010-01-06 05:24:50 +00003354 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00003355 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00003356 return OutputTypeRange;
3357
3358 IntRange SubRange
3359 = GetExprRange(C, CE->getSubExpr(),
3360 std::min(MaxWidth, OutputTypeRange.Width));
3361
3362 // Bail out if the subexpr's range is as wide as the cast type.
3363 if (SubRange.Width >= OutputTypeRange.Width)
3364 return OutputTypeRange;
3365
3366 // Otherwise, we take the smaller width, and we're non-negative if
3367 // either the output type or the subexpr is.
3368 return IntRange(SubRange.Width,
3369 SubRange.NonNegative || OutputTypeRange.NonNegative);
3370 }
3371
3372 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3373 // If we can fold the condition, just take that operand.
3374 bool CondResult;
3375 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
3376 return GetExprRange(C, CondResult ? CO->getTrueExpr()
3377 : CO->getFalseExpr(),
3378 MaxWidth);
3379
3380 // Otherwise, conservatively merge.
3381 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
3382 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
3383 return IntRange::join(L, R);
3384 }
3385
3386 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3387 switch (BO->getOpcode()) {
3388
3389 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00003390 case BO_LAnd:
3391 case BO_LOr:
3392 case BO_LT:
3393 case BO_GT:
3394 case BO_LE:
3395 case BO_GE:
3396 case BO_EQ:
3397 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00003398 return IntRange::forBoolType();
3399
John McCall862ff872011-07-13 06:35:24 +00003400 // The type of the assignments is the type of the LHS, so the RHS
3401 // is not necessarily the same type.
John McCall2de56d12010-08-25 11:45:40 +00003402 case BO_MulAssign:
3403 case BO_DivAssign:
3404 case BO_RemAssign:
3405 case BO_AddAssign:
3406 case BO_SubAssign:
John McCall862ff872011-07-13 06:35:24 +00003407 case BO_XorAssign:
3408 case BO_OrAssign:
3409 // TODO: bitfields?
John McCall1844a6e2010-11-10 23:38:19 +00003410 return IntRange::forValueOfType(C, E->getType());
John McCallc0cd21d2010-02-23 19:22:29 +00003411
John McCall862ff872011-07-13 06:35:24 +00003412 // Simple assignments just pass through the RHS, which will have
3413 // been coerced to the LHS type.
3414 case BO_Assign:
3415 // TODO: bitfields?
3416 return GetExprRange(C, BO->getRHS(), MaxWidth);
3417
John McCallf2370c92010-01-06 05:24:50 +00003418 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00003419 case BO_PtrMemD:
3420 case BO_PtrMemI:
John McCall1844a6e2010-11-10 23:38:19 +00003421 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003422
John McCall60fad452010-01-06 22:07:33 +00003423 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00003424 case BO_And:
3425 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00003426 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
3427 GetExprRange(C, BO->getRHS(), MaxWidth));
3428
John McCallf2370c92010-01-06 05:24:50 +00003429 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00003430 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00003431 // ...except that we want to treat '1 << (blah)' as logically
3432 // positive. It's an important idiom.
3433 if (IntegerLiteral *I
3434 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
3435 if (I->getValue() == 1) {
John McCall1844a6e2010-11-10 23:38:19 +00003436 IntRange R = IntRange::forValueOfType(C, E->getType());
John McCall3aae6092010-04-07 01:14:35 +00003437 return IntRange(R.Width, /*NonNegative*/ true);
3438 }
3439 }
3440 // fallthrough
3441
John McCall2de56d12010-08-25 11:45:40 +00003442 case BO_ShlAssign:
John McCall1844a6e2010-11-10 23:38:19 +00003443 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003444
John McCall60fad452010-01-06 22:07:33 +00003445 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00003446 case BO_Shr:
3447 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00003448 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3449
3450 // If the shift amount is a positive constant, drop the width by
3451 // that much.
3452 llvm::APSInt shift;
3453 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
3454 shift.isNonNegative()) {
3455 unsigned zext = shift.getZExtValue();
3456 if (zext >= L.Width)
3457 L.Width = (L.NonNegative ? 0 : 1);
3458 else
3459 L.Width -= zext;
3460 }
3461
3462 return L;
3463 }
3464
3465 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00003466 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00003467 return GetExprRange(C, BO->getRHS(), MaxWidth);
3468
John McCall60fad452010-01-06 22:07:33 +00003469 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00003470 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00003471 if (BO->getLHS()->getType()->isPointerType())
John McCall1844a6e2010-11-10 23:38:19 +00003472 return IntRange::forValueOfType(C, E->getType());
John McCall00fe7612011-07-14 22:39:48 +00003473 break;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003474
John McCall00fe7612011-07-14 22:39:48 +00003475 // The width of a division result is mostly determined by the size
3476 // of the LHS.
3477 case BO_Div: {
3478 // Don't 'pre-truncate' the operands.
3479 unsigned opWidth = C.getIntWidth(E->getType());
3480 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3481
3482 // If the divisor is constant, use that.
3483 llvm::APSInt divisor;
3484 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
3485 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
3486 if (log2 >= L.Width)
3487 L.Width = (L.NonNegative ? 0 : 1);
3488 else
3489 L.Width = std::min(L.Width - log2, MaxWidth);
3490 return L;
3491 }
3492
3493 // Otherwise, just use the LHS's width.
3494 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3495 return IntRange(L.Width, L.NonNegative && R.NonNegative);
3496 }
3497
3498 // The result of a remainder can't be larger than the result of
3499 // either side.
3500 case BO_Rem: {
3501 // Don't 'pre-truncate' the operands.
3502 unsigned opWidth = C.getIntWidth(E->getType());
3503 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3504 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3505
3506 IntRange meet = IntRange::meet(L, R);
3507 meet.Width = std::min(meet.Width, MaxWidth);
3508 return meet;
3509 }
3510
3511 // The default behavior is okay for these.
3512 case BO_Mul:
3513 case BO_Add:
3514 case BO_Xor:
3515 case BO_Or:
John McCallf2370c92010-01-06 05:24:50 +00003516 break;
3517 }
3518
John McCall00fe7612011-07-14 22:39:48 +00003519 // The default case is to treat the operation as if it were closed
3520 // on the narrowest type that encompasses both operands.
John McCallf2370c92010-01-06 05:24:50 +00003521 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3522 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
3523 return IntRange::join(L, R);
3524 }
3525
3526 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
3527 switch (UO->getOpcode()) {
3528 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00003529 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00003530 return IntRange::forBoolType();
3531
3532 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00003533 case UO_Deref:
3534 case UO_AddrOf: // should be impossible
John McCall1844a6e2010-11-10 23:38:19 +00003535 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003536
3537 default:
3538 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
3539 }
3540 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003541
3542 if (dyn_cast<OffsetOfExpr>(E)) {
John McCall1844a6e2010-11-10 23:38:19 +00003543 IntRange::forValueOfType(C, E->getType());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003544 }
John McCallf2370c92010-01-06 05:24:50 +00003545
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003546 if (FieldDecl *BitField = E->getBitField())
3547 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00003548 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCallf2370c92010-01-06 05:24:50 +00003549
John McCall1844a6e2010-11-10 23:38:19 +00003550 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003551}
John McCall51313c32010-01-04 23:31:57 +00003552
Ted Kremenek0692a192012-01-31 05:37:37 +00003553static IntRange GetExprRange(ASTContext &C, Expr *E) {
John McCall323ed742010-05-06 08:58:33 +00003554 return GetExprRange(C, E, C.getIntWidth(E->getType()));
3555}
3556
John McCall51313c32010-01-04 23:31:57 +00003557/// Checks whether the given value, which currently has the given
3558/// source semantics, has the same value when coerced through the
3559/// target semantics.
Ted Kremenek0692a192012-01-31 05:37:37 +00003560static bool IsSameFloatAfterCast(const llvm::APFloat &value,
3561 const llvm::fltSemantics &Src,
3562 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00003563 llvm::APFloat truncated = value;
3564
3565 bool ignored;
3566 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
3567 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
3568
3569 return truncated.bitwiseIsEqual(value);
3570}
3571
3572/// Checks whether the given value, which currently has the given
3573/// source semantics, has the same value when coerced through the
3574/// target semantics.
3575///
3576/// The value might be a vector of floats (or a complex number).
Ted Kremenek0692a192012-01-31 05:37:37 +00003577static bool IsSameFloatAfterCast(const APValue &value,
3578 const llvm::fltSemantics &Src,
3579 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00003580 if (value.isFloat())
3581 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
3582
3583 if (value.isVector()) {
3584 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
3585 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
3586 return false;
3587 return true;
3588 }
3589
3590 assert(value.isComplexFloat());
3591 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
3592 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
3593}
3594
Ted Kremenek0692a192012-01-31 05:37:37 +00003595static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00003596
Ted Kremeneke3b159c2010-09-23 21:43:44 +00003597static bool IsZero(Sema &S, Expr *E) {
3598 // Suppress cases where we are comparing against an enum constant.
3599 if (const DeclRefExpr *DR =
3600 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
3601 if (isa<EnumConstantDecl>(DR->getDecl()))
3602 return false;
3603
3604 // Suppress cases where the '0' value is expanded from a macro.
3605 if (E->getLocStart().isMacroID())
3606 return false;
3607
John McCall323ed742010-05-06 08:58:33 +00003608 llvm::APSInt Value;
3609 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
3610}
3611
John McCall372e1032010-10-06 00:25:24 +00003612static bool HasEnumType(Expr *E) {
3613 // Strip off implicit integral promotions.
3614 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00003615 if (ICE->getCastKind() != CK_IntegralCast &&
3616 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00003617 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00003618 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00003619 }
3620
3621 return E->getType()->isEnumeralType();
3622}
3623
Ted Kremenek0692a192012-01-31 05:37:37 +00003624static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00003625 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00003626 if (E->isValueDependent())
3627 return;
3628
John McCall2de56d12010-08-25 11:45:40 +00003629 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00003630 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003631 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00003632 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00003633 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00003634 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003635 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00003636 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00003637 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00003638 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003639 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00003640 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00003641 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00003642 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003643 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00003644 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
3645 }
3646}
3647
3648/// Analyze the operands of the given comparison. Implements the
3649/// fallback case from AnalyzeComparison.
Ted Kremenek0692a192012-01-31 05:37:37 +00003650static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00003651 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
3652 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00003653}
John McCall51313c32010-01-04 23:31:57 +00003654
John McCallba26e582010-01-04 23:21:16 +00003655/// \brief Implements -Wsign-compare.
3656///
Richard Trieudd225092011-09-15 21:56:47 +00003657/// \param E the binary operator to check for warnings
Ted Kremenek0692a192012-01-31 05:37:37 +00003658static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCall323ed742010-05-06 08:58:33 +00003659 // The type the comparison is being performed in.
3660 QualType T = E->getLHS()->getType();
3661 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
3662 && "comparison with mismatched types");
John McCallba26e582010-01-04 23:21:16 +00003663
John McCall323ed742010-05-06 08:58:33 +00003664 // We don't do anything special if this isn't an unsigned integral
3665 // comparison: we're only interested in integral comparisons, and
3666 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00003667 //
3668 // We also don't care about value-dependent expressions or expressions
3669 // whose result is a constant.
3670 if (!T->hasUnsignedIntegerRepresentation()
3671 || E->isValueDependent() || E->isIntegerConstantExpr(S.Context))
John McCall323ed742010-05-06 08:58:33 +00003672 return AnalyzeImpConvsInComparison(S, E);
John McCallf2370c92010-01-06 05:24:50 +00003673
Richard Trieudd225092011-09-15 21:56:47 +00003674 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
3675 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
John McCallba26e582010-01-04 23:21:16 +00003676
John McCall323ed742010-05-06 08:58:33 +00003677 // Check to see if one of the (unmodified) operands is of different
3678 // signedness.
3679 Expr *signedOperand, *unsignedOperand;
Richard Trieudd225092011-09-15 21:56:47 +00003680 if (LHS->getType()->hasSignedIntegerRepresentation()) {
3681 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00003682 "unsigned comparison between two signed integer expressions?");
Richard Trieudd225092011-09-15 21:56:47 +00003683 signedOperand = LHS;
3684 unsignedOperand = RHS;
3685 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
3686 signedOperand = RHS;
3687 unsignedOperand = LHS;
John McCallba26e582010-01-04 23:21:16 +00003688 } else {
John McCall323ed742010-05-06 08:58:33 +00003689 CheckTrivialUnsignedComparison(S, E);
3690 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00003691 }
3692
John McCall323ed742010-05-06 08:58:33 +00003693 // Otherwise, calculate the effective range of the signed operand.
3694 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00003695
John McCall323ed742010-05-06 08:58:33 +00003696 // Go ahead and analyze implicit conversions in the operands. Note
3697 // that we skip the implicit conversions on both sides.
Richard Trieudd225092011-09-15 21:56:47 +00003698 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
3699 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00003700
John McCall323ed742010-05-06 08:58:33 +00003701 // If the signed range is non-negative, -Wsign-compare won't fire,
3702 // but we should still check for comparisons which are always true
3703 // or false.
3704 if (signedRange.NonNegative)
3705 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00003706
3707 // For (in)equality comparisons, if the unsigned operand is a
3708 // constant which cannot collide with a overflowed signed operand,
3709 // then reinterpreting the signed operand as unsigned will not
3710 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00003711 if (E->isEqualityOp()) {
3712 unsigned comparisonWidth = S.Context.getIntWidth(T);
3713 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00003714
John McCall323ed742010-05-06 08:58:33 +00003715 // We should never be unable to prove that the unsigned operand is
3716 // non-negative.
3717 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
3718
3719 if (unsignedRange.Width < comparisonWidth)
3720 return;
3721 }
3722
3723 S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison)
Richard Trieudd225092011-09-15 21:56:47 +00003724 << LHS->getType() << RHS->getType()
3725 << LHS->getSourceRange() << RHS->getSourceRange();
John McCallba26e582010-01-04 23:21:16 +00003726}
3727
John McCall15d7d122010-11-11 03:21:53 +00003728/// Analyzes an attempt to assign the given value to a bitfield.
3729///
3730/// Returns true if there was something fishy about the attempt.
Ted Kremenek0692a192012-01-31 05:37:37 +00003731static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
3732 SourceLocation InitLoc) {
John McCall15d7d122010-11-11 03:21:53 +00003733 assert(Bitfield->isBitField());
3734 if (Bitfield->isInvalidDecl())
3735 return false;
3736
John McCall91b60142010-11-11 05:33:51 +00003737 // White-list bool bitfields.
3738 if (Bitfield->getType()->isBooleanType())
3739 return false;
3740
Douglas Gregor46ff3032011-02-04 13:09:01 +00003741 // Ignore value- or type-dependent expressions.
3742 if (Bitfield->getBitWidth()->isValueDependent() ||
3743 Bitfield->getBitWidth()->isTypeDependent() ||
3744 Init->isValueDependent() ||
3745 Init->isTypeDependent())
3746 return false;
3747
John McCall15d7d122010-11-11 03:21:53 +00003748 Expr *OriginalInit = Init->IgnoreParenImpCasts();
3749
Richard Smith80d4b552011-12-28 19:48:30 +00003750 llvm::APSInt Value;
3751 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall15d7d122010-11-11 03:21:53 +00003752 return false;
3753
John McCall15d7d122010-11-11 03:21:53 +00003754 unsigned OriginalWidth = Value.getBitWidth();
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003755 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall15d7d122010-11-11 03:21:53 +00003756
3757 if (OriginalWidth <= FieldWidth)
3758 return false;
3759
Eli Friedman3a643af2012-01-26 23:11:39 +00003760 // Compute the value which the bitfield will contain.
Jay Foad9f71a8f2010-12-07 08:25:34 +00003761 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedman3a643af2012-01-26 23:11:39 +00003762 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall15d7d122010-11-11 03:21:53 +00003763
Eli Friedman3a643af2012-01-26 23:11:39 +00003764 // Check whether the stored value is equal to the original value.
3765 TruncatedValue = TruncatedValue.extend(OriginalWidth);
John McCall15d7d122010-11-11 03:21:53 +00003766 if (Value == TruncatedValue)
3767 return false;
3768
Eli Friedman3a643af2012-01-26 23:11:39 +00003769 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedman34ff0622012-02-02 00:40:20 +00003770 // therefore don't strictly fit into a signed bitfield of width 1.
3771 if (FieldWidth == 1 && Value == 1)
Eli Friedman3a643af2012-01-26 23:11:39 +00003772 return false;
3773
John McCall15d7d122010-11-11 03:21:53 +00003774 std::string PrettyValue = Value.toString(10);
3775 std::string PrettyTrunc = TruncatedValue.toString(10);
3776
3777 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
3778 << PrettyValue << PrettyTrunc << OriginalInit->getType()
3779 << Init->getSourceRange();
3780
3781 return true;
3782}
3783
John McCallbeb22aa2010-11-09 23:24:47 +00003784/// Analyze the given simple or compound assignment for warning-worthy
3785/// operations.
Ted Kremenek0692a192012-01-31 05:37:37 +00003786static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCallbeb22aa2010-11-09 23:24:47 +00003787 // Just recurse on the LHS.
3788 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
3789
3790 // We want to recurse on the RHS as normal unless we're assigning to
3791 // a bitfield.
3792 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
John McCall15d7d122010-11-11 03:21:53 +00003793 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
3794 E->getOperatorLoc())) {
3795 // Recurse, ignoring any implicit conversions on the RHS.
3796 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
3797 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00003798 }
3799 }
3800
3801 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
3802}
3803
John McCall51313c32010-01-04 23:31:57 +00003804/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00003805static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00003806 SourceLocation CContext, unsigned diag,
3807 bool pruneControlFlow = false) {
3808 if (pruneControlFlow) {
3809 S.DiagRuntimeBehavior(E->getExprLoc(), E,
3810 S.PDiag(diag)
3811 << SourceType << T << E->getSourceRange()
3812 << SourceRange(CContext));
3813 return;
3814 }
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00003815 S.Diag(E->getExprLoc(), diag)
3816 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
3817}
3818
Chandler Carruthe1b02e02011-04-05 06:47:57 +00003819/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00003820static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00003821 SourceLocation CContext, unsigned diag,
3822 bool pruneControlFlow = false) {
3823 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruthe1b02e02011-04-05 06:47:57 +00003824}
3825
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003826/// Diagnose an implicit cast from a literal expression. Does not warn when the
3827/// cast wouldn't lose information.
Chandler Carruthf65076e2011-04-10 08:36:24 +00003828void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
3829 SourceLocation CContext) {
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003830 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruthf65076e2011-04-10 08:36:24 +00003831 bool isExact = false;
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003832 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00003833 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
3834 T->hasUnsignedIntegerRepresentation());
3835 if (Value.convertToInteger(IntegerValue,
Chandler Carruthf65076e2011-04-10 08:36:24 +00003836 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003837 == llvm::APFloat::opOK && isExact)
Chandler Carruthf65076e2011-04-10 08:36:24 +00003838 return;
3839
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003840 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
3841 << FL->getType() << T << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruthf65076e2011-04-10 08:36:24 +00003842}
3843
John McCall091f23f2010-11-09 22:22:12 +00003844std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
3845 if (!Range.Width) return "0";
3846
3847 llvm::APSInt ValueInRange = Value;
3848 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00003849 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00003850 return ValueInRange.toString(10);
3851}
3852
John McCall323ed742010-05-06 08:58:33 +00003853void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00003854 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00003855 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00003856
John McCall323ed742010-05-06 08:58:33 +00003857 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
3858 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
3859 if (Source == Target) return;
3860 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00003861
Chandler Carruth108f7562011-07-26 05:40:03 +00003862 // If the conversion context location is invalid don't complain. We also
3863 // don't want to emit a warning if the issue occurs from the expansion of
3864 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
3865 // delay this check as long as possible. Once we detect we are in that
3866 // scenario, we just return.
Ted Kremenekef9ff882011-03-10 20:03:42 +00003867 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00003868 return;
3869
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00003870 // Diagnose implicit casts to bool.
3871 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
3872 if (isa<StringLiteral>(E))
3873 // Warn on string literal to bool. Checks for string literals in logical
3874 // expressions, for instances, assert(0 && "error here"), is prevented
3875 // by a check in AnalyzeImplicitConversions().
3876 return DiagnoseImpCast(S, E, T, CC,
3877 diag::warn_impcast_string_literal_to_bool);
Lang Hamese14ca9f2011-12-05 20:49:50 +00003878 if (Source->isFunctionType()) {
3879 // Warn on function to bool. Checks free functions and static member
3880 // functions. Weakly imported functions are excluded from the check,
3881 // since it's common to test their value to check whether the linker
3882 // found a definition for them.
3883 ValueDecl *D = 0;
3884 if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
3885 D = R->getDecl();
3886 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
3887 D = M->getMemberDecl();
3888 }
3889
3890 if (D && !D->isWeak()) {
Richard Trieu26b45d82011-12-06 04:48:01 +00003891 if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
3892 S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
3893 << F << E->getSourceRange() << SourceRange(CC);
David Blaikie2def7732011-12-09 21:42:37 +00003894 S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
3895 << FixItHint::CreateInsertion(E->getExprLoc(), "&");
3896 QualType ReturnType;
3897 UnresolvedSet<4> NonTemplateOverloads;
3898 S.isExprCallable(*E, ReturnType, NonTemplateOverloads);
3899 if (!ReturnType.isNull()
3900 && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
3901 S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
3902 << FixItHint::CreateInsertion(
3903 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu26b45d82011-12-06 04:48:01 +00003904 return;
3905 }
Lang Hamese14ca9f2011-12-05 20:49:50 +00003906 }
3907 }
David Blaikiee37cdc42011-09-29 04:06:47 +00003908 return; // Other casts to bool are not checked.
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00003909 }
John McCall51313c32010-01-04 23:31:57 +00003910
3911 // Strip vector types.
3912 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003913 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00003914 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00003915 return;
John McCallb4eb64d2010-10-08 02:01:28 +00003916 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00003917 }
Chris Lattnerb792b302011-06-14 04:51:15 +00003918
3919 // If the vector cast is cast between two vectors of the same size, it is
3920 // a bitcast, not a conversion.
3921 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
3922 return;
John McCall51313c32010-01-04 23:31:57 +00003923
3924 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
3925 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
3926 }
3927
3928 // Strip complex types.
3929 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003930 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00003931 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00003932 return;
3933
John McCallb4eb64d2010-10-08 02:01:28 +00003934 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00003935 }
John McCall51313c32010-01-04 23:31:57 +00003936
3937 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
3938 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
3939 }
3940
3941 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
3942 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
3943
3944 // If the source is floating point...
3945 if (SourceBT && SourceBT->isFloatingPoint()) {
3946 // ...and the target is floating point...
3947 if (TargetBT && TargetBT->isFloatingPoint()) {
3948 // ...then warn if we're dropping FP rank.
3949
3950 // Builtin FP kinds are ordered by increasing FP rank.
3951 if (SourceBT->getKind() > TargetBT->getKind()) {
3952 // Don't warn about float constants that are precisely
3953 // representable in the target type.
3954 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00003955 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00003956 // Value might be a float, a float vector, or a float complex.
3957 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00003958 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
3959 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00003960 return;
3961 }
3962
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00003963 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00003964 return;
3965
John McCallb4eb64d2010-10-08 02:01:28 +00003966 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00003967 }
3968 return;
3969 }
3970
Ted Kremenekef9ff882011-03-10 20:03:42 +00003971 // If the target is integral, always warn.
Chandler Carrutha5b93322011-02-17 11:05:49 +00003972 if ((TargetBT && TargetBT->isInteger())) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00003973 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00003974 return;
3975
Chandler Carrutha5b93322011-02-17 11:05:49 +00003976 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay634c8af2011-09-08 22:30:47 +00003977 // We also want to warn on, e.g., "int i = -1.234"
3978 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
3979 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
3980 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
3981
Chandler Carruthf65076e2011-04-10 08:36:24 +00003982 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
3983 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00003984 } else {
3985 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
3986 }
3987 }
John McCall51313c32010-01-04 23:31:57 +00003988
3989 return;
3990 }
3991
John McCallf2370c92010-01-06 05:24:50 +00003992 if (!Source->isIntegerType() || !Target->isIntegerType())
John McCall51313c32010-01-04 23:31:57 +00003993 return;
3994
Richard Trieu1838ca52011-05-29 19:59:02 +00003995 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
3996 == Expr::NPCK_GNUNull) && Target->isIntegerType()) {
3997 S.Diag(E->getExprLoc(), diag::warn_impcast_null_pointer_to_integer)
3998 << E->getSourceRange() << clang::SourceRange(CC);
3999 return;
4000 }
4001
John McCall323ed742010-05-06 08:58:33 +00004002 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00004003 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00004004
4005 if (SourceRange.Width > TargetRange.Width) {
John McCall091f23f2010-11-09 22:22:12 +00004006 // If the source is a constant, use a default-on diagnostic.
4007 // TODO: this should happen for bitfield stores, too.
4008 llvm::APSInt Value(32);
4009 if (E->isIntegerConstantExpr(Value, S.Context)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004010 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004011 return;
4012
John McCall091f23f2010-11-09 22:22:12 +00004013 std::string PrettySourceValue = Value.toString(10);
4014 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
4015
Ted Kremenek5e745da2011-10-22 02:37:33 +00004016 S.DiagRuntimeBehavior(E->getExprLoc(), E,
4017 S.PDiag(diag::warn_impcast_integer_precision_constant)
4018 << PrettySourceValue << PrettyTargetValue
4019 << E->getType() << T << E->getSourceRange()
4020 << clang::SourceRange(CC));
John McCall091f23f2010-11-09 22:22:12 +00004021 return;
4022 }
4023
Chris Lattnerb792b302011-06-14 04:51:15 +00004024 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004025 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004026 return;
4027
John McCallf2370c92010-01-06 05:24:50 +00004028 if (SourceRange.Width == 64 && TargetRange.Width == 32)
Anna Zaksc36bedc2012-02-01 19:08:57 +00004029 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
4030 /* pruneControlFlow */ true);
John McCallb4eb64d2010-10-08 02:01:28 +00004031 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00004032 }
4033
4034 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
4035 (!TargetRange.NonNegative && SourceRange.NonNegative &&
4036 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004037
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004038 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004039 return;
4040
John McCall323ed742010-05-06 08:58:33 +00004041 unsigned DiagID = diag::warn_impcast_integer_sign;
4042
4043 // Traditionally, gcc has warned about this under -Wsign-compare.
4044 // We also want to warn about it in -Wconversion.
4045 // So if -Wconversion is off, use a completely identical diagnostic
4046 // in the sign-compare group.
4047 // The conditional-checking code will
4048 if (ICContext) {
4049 DiagID = diag::warn_impcast_integer_sign_conditional;
4050 *ICContext = true;
4051 }
4052
John McCallb4eb64d2010-10-08 02:01:28 +00004053 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00004054 }
4055
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004056 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004057 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
4058 // type, to give us better diagnostics.
4059 QualType SourceType = E->getType();
4060 if (!S.getLangOptions().CPlusPlus) {
4061 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
4062 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
4063 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
4064 SourceType = S.Context.getTypeDeclType(Enum);
4065 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
4066 }
4067 }
4068
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004069 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
4070 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
4071 if ((SourceEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00004072 SourceEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004073 (TargetEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00004074 TargetEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00004075 SourceEnum != TargetEnum) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004076 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004077 return;
4078
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004079 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004080 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004081 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004082
John McCall51313c32010-01-04 23:31:57 +00004083 return;
4084}
4085
John McCall323ed742010-05-06 08:58:33 +00004086void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T);
4087
4088void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00004089 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00004090 E = E->IgnoreParenImpCasts();
4091
4092 if (isa<ConditionalOperator>(E))
4093 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T);
4094
John McCallb4eb64d2010-10-08 02:01:28 +00004095 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00004096 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00004097 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00004098 return;
4099}
4100
4101void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00004102 SourceLocation CC = E->getQuestionLoc();
4103
4104 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00004105
4106 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00004107 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
4108 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00004109
4110 // If -Wconversion would have warned about either of the candidates
4111 // for a signedness conversion to the context type...
4112 if (!Suspicious) return;
4113
4114 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00004115 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
4116 CC))
John McCall323ed742010-05-06 08:58:33 +00004117 return;
4118
John McCall323ed742010-05-06 08:58:33 +00004119 // ...then check whether it would have warned about either of the
4120 // candidates for a signedness conversion to the condition type.
Richard Trieu52541612011-07-21 02:46:28 +00004121 if (E->getType() == T) return;
4122
4123 Suspicious = false;
4124 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
4125 E->getType(), CC, &Suspicious);
4126 if (!Suspicious)
4127 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00004128 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00004129}
4130
4131/// AnalyzeImplicitConversions - Find and report any interesting
4132/// implicit conversions in the given expression. There are a couple
4133/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00004134void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00004135 QualType T = OrigE->getType();
4136 Expr *E = OrigE->IgnoreParenImpCasts();
4137
Douglas Gregorf8b6e152011-10-10 17:38:18 +00004138 if (E->isTypeDependent() || E->isValueDependent())
4139 return;
4140
John McCall323ed742010-05-06 08:58:33 +00004141 // For conditional operators, we analyze the arguments as if they
4142 // were being fed directly into the output.
4143 if (isa<ConditionalOperator>(E)) {
4144 ConditionalOperator *CO = cast<ConditionalOperator>(E);
4145 CheckConditionalOperator(S, CO, T);
4146 return;
4147 }
4148
4149 // Go ahead and check any implicit conversions we might have skipped.
4150 // The non-canonical typecheck is just an optimization;
4151 // CheckImplicitConversion will filter out dead implicit conversions.
4152 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00004153 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00004154
4155 // Now continue drilling into this expression.
4156
4157 // Skip past explicit casts.
4158 if (isa<ExplicitCastExpr>(E)) {
4159 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00004160 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00004161 }
4162
John McCallbeb22aa2010-11-09 23:24:47 +00004163 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4164 // Do a somewhat different check with comparison operators.
4165 if (BO->isComparisonOp())
4166 return AnalyzeComparison(S, BO);
4167
Eli Friedman0fa06382012-01-26 23:34:06 +00004168 // And with simple assignments.
4169 if (BO->getOpcode() == BO_Assign)
John McCallbeb22aa2010-11-09 23:24:47 +00004170 return AnalyzeAssignment(S, BO);
4171 }
John McCall323ed742010-05-06 08:58:33 +00004172
4173 // These break the otherwise-useful invariant below. Fortunately,
4174 // we don't really need to recurse into them, because any internal
4175 // expressions should have been analyzed already when they were
4176 // built into statements.
4177 if (isa<StmtExpr>(E)) return;
4178
4179 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004180 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00004181
4182 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00004183 CC = E->getExprLoc();
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004184 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
4185 bool IsLogicalOperator = BO && BO->isLogicalOp();
4186 for (Stmt::child_range I = E->children(); I; ++I) {
4187 Expr *ChildExpr = cast<Expr>(*I);
4188 if (IsLogicalOperator &&
4189 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
4190 // Ignore checking string literals that are in logical operators.
4191 continue;
4192 AnalyzeImplicitConversions(S, ChildExpr, CC);
4193 }
John McCall323ed742010-05-06 08:58:33 +00004194}
4195
4196} // end anonymous namespace
4197
4198/// Diagnoses "dangerous" implicit conversions within the given
4199/// expression (which is a full expression). Implements -Wconversion
4200/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00004201///
4202/// \param CC the "context" location of the implicit conversion, i.e.
4203/// the most location of the syntactic entity requiring the implicit
4204/// conversion
4205void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00004206 // Don't diagnose in unevaluated contexts.
4207 if (ExprEvalContexts.back().Context == Sema::Unevaluated)
4208 return;
4209
4210 // Don't diagnose for value- or type-dependent expressions.
4211 if (E->isTypeDependent() || E->isValueDependent())
4212 return;
4213
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004214 // Check for array bounds violations in cases where the check isn't triggered
4215 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
4216 // ArraySubscriptExpr is on the RHS of a variable initialization.
4217 CheckArrayAccess(E);
4218
John McCallb4eb64d2010-10-08 02:01:28 +00004219 // This is not the right CC for (e.g.) a variable initialization.
4220 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00004221}
4222
John McCall15d7d122010-11-11 03:21:53 +00004223void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
4224 FieldDecl *BitField,
4225 Expr *Init) {
4226 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
4227}
4228
Mike Stumpf8c49212010-01-21 03:59:47 +00004229/// CheckParmsForFunctionDef - Check that the parameters of the given
4230/// function are appropriate for the definition of a function. This
4231/// takes care of any checks that cannot be performed on the
4232/// declaration itself, e.g., that the types of each of the function
4233/// parameters are complete.
Douglas Gregor82aa7132010-11-01 18:37:59 +00004234bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
4235 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00004236 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00004237 for (; P != PEnd; ++P) {
4238 ParmVarDecl *Param = *P;
4239
Mike Stumpf8c49212010-01-21 03:59:47 +00004240 // C99 6.7.5.3p4: the parameters in a parameter type list in a
4241 // function declarator that is part of a function definition of
4242 // that function shall not have incomplete type.
4243 //
4244 // This is also C++ [dcl.fct]p6.
4245 if (!Param->isInvalidDecl() &&
4246 RequireCompleteType(Param->getLocation(), Param->getType(),
4247 diag::err_typecheck_decl_incomplete_type)) {
4248 Param->setInvalidDecl();
4249 HasInvalidParm = true;
4250 }
4251
4252 // C99 6.9.1p5: If the declarator includes a parameter type list, the
4253 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00004254 if (CheckParameterNames &&
4255 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00004256 !Param->isImplicit() &&
4257 !getLangOptions().CPlusPlus)
4258 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00004259
4260 // C99 6.7.5.3p12:
4261 // If the function declarator is not part of a definition of that
4262 // function, parameters may have incomplete type and may use the [*]
4263 // notation in their sequences of declarator specifiers to specify
4264 // variable length array types.
4265 QualType PType = Param->getOriginalType();
4266 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
4267 if (AT->getSizeModifier() == ArrayType::Star) {
4268 // FIXME: This diagnosic should point the the '[*]' if source-location
4269 // information is added for it.
4270 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
4271 }
4272 }
Mike Stumpf8c49212010-01-21 03:59:47 +00004273 }
4274
4275 return HasInvalidParm;
4276}
John McCallb7f4ffe2010-08-12 21:44:57 +00004277
4278/// CheckCastAlign - Implements -Wcast-align, which warns when a
4279/// pointer cast increases the alignment requirements.
4280void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
4281 // This is actually a lot of work to potentially be doing on every
4282 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00004283 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
4284 TRange.getBegin())
David Blaikied6471f72011-09-25 23:23:43 +00004285 == DiagnosticsEngine::Ignored)
John McCallb7f4ffe2010-08-12 21:44:57 +00004286 return;
4287
4288 // Ignore dependent types.
4289 if (T->isDependentType() || Op->getType()->isDependentType())
4290 return;
4291
4292 // Require that the destination be a pointer type.
4293 const PointerType *DestPtr = T->getAs<PointerType>();
4294 if (!DestPtr) return;
4295
4296 // If the destination has alignment 1, we're done.
4297 QualType DestPointee = DestPtr->getPointeeType();
4298 if (DestPointee->isIncompleteType()) return;
4299 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
4300 if (DestAlign.isOne()) return;
4301
4302 // Require that the source be a pointer type.
4303 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
4304 if (!SrcPtr) return;
4305 QualType SrcPointee = SrcPtr->getPointeeType();
4306
4307 // Whitelist casts from cv void*. We already implicitly
4308 // whitelisted casts to cv void*, since they have alignment 1.
4309 // Also whitelist casts involving incomplete types, which implicitly
4310 // includes 'void'.
4311 if (SrcPointee->isIncompleteType()) return;
4312
4313 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
4314 if (SrcAlign >= DestAlign) return;
4315
4316 Diag(TRange.getBegin(), diag::warn_cast_align)
4317 << Op->getType() << T
4318 << static_cast<unsigned>(SrcAlign.getQuantity())
4319 << static_cast<unsigned>(DestAlign.getQuantity())
4320 << TRange << Op->getSourceRange();
4321}
4322
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004323static const Type* getElementType(const Expr *BaseExpr) {
4324 const Type* EltType = BaseExpr->getType().getTypePtr();
4325 if (EltType->isAnyPointerType())
4326 return EltType->getPointeeType().getTypePtr();
4327 else if (EltType->isArrayType())
4328 return EltType->getBaseElementTypeUnsafe();
4329 return EltType;
4330}
4331
Chandler Carruthc2684342011-08-05 09:10:50 +00004332/// \brief Check whether this array fits the idiom of a size-one tail padded
4333/// array member of a struct.
4334///
4335/// We avoid emitting out-of-bounds access warnings for such arrays as they are
4336/// commonly used to emulate flexible arrays in C89 code.
4337static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
4338 const NamedDecl *ND) {
4339 if (Size != 1 || !ND) return false;
4340
4341 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
4342 if (!FD) return false;
4343
4344 // Don't consider sizes resulting from macro expansions or template argument
4345 // substitution to form C89 tail-padded arrays.
4346 ConstantArrayTypeLoc TL =
4347 cast<ConstantArrayTypeLoc>(FD->getTypeSourceInfo()->getTypeLoc());
4348 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(TL.getSizeExpr());
4349 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
4350 return false;
4351
4352 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gay381711c2011-11-29 22:43:53 +00004353 if (!RD) return false;
4354 if (RD->isUnion()) return false;
4355 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
4356 if (!CRD->isStandardLayout()) return false;
4357 }
Chandler Carruthc2684342011-08-05 09:10:50 +00004358
Benjamin Kramer22d4fed2011-08-06 03:04:42 +00004359 // See if this is the last field decl in the record.
4360 const Decl *D = FD;
4361 while ((D = D->getNextDeclInContext()))
4362 if (isa<FieldDecl>(D))
4363 return false;
4364 return true;
Chandler Carruthc2684342011-08-05 09:10:50 +00004365}
4366
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004367void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004368 const ArraySubscriptExpr *ASE,
Richard Smith25b009a2011-12-16 19:31:14 +00004369 bool AllowOnePastEnd, bool IndexNegated) {
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004370 IndexExpr = IndexExpr->IgnoreParenCasts();
4371 if (IndexExpr->isValueDependent())
4372 return;
4373
Matt Beaumont-Gay8ef8f432011-12-12 22:35:02 +00004374 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004375 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth34064582011-02-17 20:55:08 +00004376 const ConstantArrayType *ArrayTy =
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004377 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00004378 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00004379 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00004380
Chandler Carruth34064582011-02-17 20:55:08 +00004381 llvm::APSInt index;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004382 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00004383 return;
Richard Smith25b009a2011-12-16 19:31:14 +00004384 if (IndexNegated)
4385 index = -index;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00004386
Chandler Carruthba447122011-08-05 08:07:29 +00004387 const NamedDecl *ND = NULL;
Chandler Carruthba447122011-08-05 08:07:29 +00004388 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
4389 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruthc2684342011-08-05 09:10:50 +00004390 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruthba447122011-08-05 08:07:29 +00004391 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruthba447122011-08-05 08:07:29 +00004392
Ted Kremenek9e060ca2011-02-23 23:06:04 +00004393 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00004394 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00004395 if (!size.isStrictlyPositive())
4396 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004397
4398 const Type* BaseType = getElementType(BaseExpr);
Nico Weberde5998f2011-09-17 22:59:41 +00004399 if (BaseType != EffectiveType) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004400 // Make sure we're comparing apples to apples when comparing index to size
4401 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
4402 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhraind10f4bc2011-08-10 19:47:25 +00004403 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhrain18f16972011-08-10 18:49:28 +00004404 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004405 if (ptrarith_typesize != array_typesize) {
4406 // There's a cast to a different size type involved
4407 uint64_t ratio = array_typesize / ptrarith_typesize;
4408 // TODO: Be smarter about handling cases where array_typesize is not a
4409 // multiple of ptrarith_typesize
4410 if (ptrarith_typesize * ratio == array_typesize)
4411 size *= llvm::APInt(size.getBitWidth(), ratio);
4412 }
4413 }
4414
Chandler Carruth34064582011-02-17 20:55:08 +00004415 if (size.getBitWidth() > index.getBitWidth())
4416 index = index.sext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00004417 else if (size.getBitWidth() < index.getBitWidth())
4418 size = size.sext(index.getBitWidth());
4419
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004420 // For array subscripting the index must be less than size, but for pointer
4421 // arithmetic also allow the index (offset) to be equal to size since
4422 // computing the next address after the end of the array is legal and
4423 // commonly done e.g. in C++ iterators and range-based for loops.
4424 if (AllowOnePastEnd ? index.sle(size) : index.slt(size))
Chandler Carruthba447122011-08-05 08:07:29 +00004425 return;
4426
4427 // Also don't warn for arrays of size 1 which are members of some
4428 // structure. These are often used to approximate flexible arrays in C89
4429 // code.
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004430 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00004431 return;
Chandler Carruth34064582011-02-17 20:55:08 +00004432
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004433 // Suppress the warning if the subscript expression (as identified by the
4434 // ']' location) and the index expression are both from macro expansions
4435 // within a system header.
4436 if (ASE) {
4437 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
4438 ASE->getRBracketLoc());
4439 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
4440 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
4441 IndexExpr->getLocStart());
4442 if (SourceMgr.isFromSameFile(RBracketLoc, IndexLoc))
4443 return;
4444 }
4445 }
4446
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004447 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004448 if (ASE)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004449 DiagID = diag::warn_array_index_exceeds_bounds;
4450
4451 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
4452 PDiag(DiagID) << index.toString(10, true)
4453 << size.toString(10, true)
4454 << (unsigned)size.getLimitedValue(~0U)
4455 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00004456 } else {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004457 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004458 if (!ASE) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004459 DiagID = diag::warn_ptr_arith_precedes_bounds;
4460 if (index.isNegative()) index = -index;
4461 }
4462
4463 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
4464 PDiag(DiagID) << index.toString(10, true)
4465 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00004466 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00004467
Matt Beaumont-Gaycfbc5b52011-11-29 19:27:11 +00004468 if (!ND) {
4469 // Try harder to find a NamedDecl to point at in the note.
4470 while (const ArraySubscriptExpr *ASE =
4471 dyn_cast<ArraySubscriptExpr>(BaseExpr))
4472 BaseExpr = ASE->getBase()->IgnoreParenCasts();
4473 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
4474 ND = dyn_cast<NamedDecl>(DRE->getDecl());
4475 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
4476 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
4477 }
4478
Chandler Carruth35001ca2011-02-17 21:10:52 +00004479 if (ND)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004480 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
4481 PDiag(diag::note_array_index_out_of_bounds)
4482 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00004483}
4484
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004485void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004486 int AllowOnePastEnd = 0;
4487 while (expr) {
4488 expr = expr->IgnoreParenImpCasts();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004489 switch (expr->getStmtClass()) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004490 case Stmt::ArraySubscriptExprClass: {
4491 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004492 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004493 AllowOnePastEnd > 0);
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004494 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004495 }
4496 case Stmt::UnaryOperatorClass: {
4497 // Only unwrap the * and & unary operators
4498 const UnaryOperator *UO = cast<UnaryOperator>(expr);
4499 expr = UO->getSubExpr();
4500 switch (UO->getOpcode()) {
4501 case UO_AddrOf:
4502 AllowOnePastEnd++;
4503 break;
4504 case UO_Deref:
4505 AllowOnePastEnd--;
4506 break;
4507 default:
4508 return;
4509 }
4510 break;
4511 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004512 case Stmt::ConditionalOperatorClass: {
4513 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
4514 if (const Expr *lhs = cond->getLHS())
4515 CheckArrayAccess(lhs);
4516 if (const Expr *rhs = cond->getRHS())
4517 CheckArrayAccess(rhs);
4518 return;
4519 }
4520 default:
4521 return;
4522 }
Peter Collingbournef111d932011-04-15 00:35:48 +00004523 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004524}
John McCallf85e1932011-06-15 23:02:42 +00004525
4526//===--- CHECK: Objective-C retain cycles ----------------------------------//
4527
4528namespace {
4529 struct RetainCycleOwner {
4530 RetainCycleOwner() : Variable(0), Indirect(false) {}
4531 VarDecl *Variable;
4532 SourceRange Range;
4533 SourceLocation Loc;
4534 bool Indirect;
4535
4536 void setLocsFrom(Expr *e) {
4537 Loc = e->getExprLoc();
4538 Range = e->getSourceRange();
4539 }
4540 };
4541}
4542
4543/// Consider whether capturing the given variable can possibly lead to
4544/// a retain cycle.
4545static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
4546 // In ARC, it's captured strongly iff the variable has __strong
4547 // lifetime. In MRR, it's captured strongly if the variable is
4548 // __block and has an appropriate type.
4549 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
4550 return false;
4551
4552 owner.Variable = var;
4553 owner.setLocsFrom(ref);
4554 return true;
4555}
4556
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00004557static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCallf85e1932011-06-15 23:02:42 +00004558 while (true) {
4559 e = e->IgnoreParens();
4560 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
4561 switch (cast->getCastKind()) {
4562 case CK_BitCast:
4563 case CK_LValueBitCast:
4564 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00004565 case CK_ARCReclaimReturnedObject:
John McCallf85e1932011-06-15 23:02:42 +00004566 e = cast->getSubExpr();
4567 continue;
4568
John McCallf85e1932011-06-15 23:02:42 +00004569 default:
4570 return false;
4571 }
4572 }
4573
4574 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
4575 ObjCIvarDecl *ivar = ref->getDecl();
4576 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
4577 return false;
4578
4579 // Try to find a retain cycle in the base.
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00004580 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCallf85e1932011-06-15 23:02:42 +00004581 return false;
4582
4583 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
4584 owner.Indirect = true;
4585 return true;
4586 }
4587
4588 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
4589 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
4590 if (!var) return false;
4591 return considerVariable(var, ref, owner);
4592 }
4593
4594 if (BlockDeclRefExpr *ref = dyn_cast<BlockDeclRefExpr>(e)) {
4595 owner.Variable = ref->getDecl();
4596 owner.setLocsFrom(ref);
4597 return true;
4598 }
4599
4600 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
4601 if (member->isArrow()) return false;
4602
4603 // Don't count this as an indirect ownership.
4604 e = member->getBase();
4605 continue;
4606 }
4607
John McCall4b9c2d22011-11-06 09:01:30 +00004608 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
4609 // Only pay attention to pseudo-objects on property references.
4610 ObjCPropertyRefExpr *pre
4611 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
4612 ->IgnoreParens());
4613 if (!pre) return false;
4614 if (pre->isImplicitProperty()) return false;
4615 ObjCPropertyDecl *property = pre->getExplicitProperty();
4616 if (!property->isRetaining() &&
4617 !(property->getPropertyIvarDecl() &&
4618 property->getPropertyIvarDecl()->getType()
4619 .getObjCLifetime() == Qualifiers::OCL_Strong))
4620 return false;
4621
4622 owner.Indirect = true;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00004623 if (pre->isSuperReceiver()) {
4624 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
4625 if (!owner.Variable)
4626 return false;
4627 owner.Loc = pre->getLocation();
4628 owner.Range = pre->getSourceRange();
4629 return true;
4630 }
John McCall4b9c2d22011-11-06 09:01:30 +00004631 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
4632 ->getSourceExpr());
4633 continue;
4634 }
4635
John McCallf85e1932011-06-15 23:02:42 +00004636 // Array ivars?
4637
4638 return false;
4639 }
4640}
4641
4642namespace {
4643 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
4644 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
4645 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
4646 Variable(variable), Capturer(0) {}
4647
4648 VarDecl *Variable;
4649 Expr *Capturer;
4650
4651 void VisitDeclRefExpr(DeclRefExpr *ref) {
4652 if (ref->getDecl() == Variable && !Capturer)
4653 Capturer = ref;
4654 }
4655
4656 void VisitBlockDeclRefExpr(BlockDeclRefExpr *ref) {
4657 if (ref->getDecl() == Variable && !Capturer)
4658 Capturer = ref;
4659 }
4660
4661 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
4662 if (Capturer) return;
4663 Visit(ref->getBase());
4664 if (Capturer && ref->isFreeIvar())
4665 Capturer = ref;
4666 }
4667
4668 void VisitBlockExpr(BlockExpr *block) {
4669 // Look inside nested blocks
4670 if (block->getBlockDecl()->capturesVariable(Variable))
4671 Visit(block->getBlockDecl()->getBody());
4672 }
4673 };
4674}
4675
4676/// Check whether the given argument is a block which captures a
4677/// variable.
4678static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
4679 assert(owner.Variable && owner.Loc.isValid());
4680
4681 e = e->IgnoreParenCasts();
4682 BlockExpr *block = dyn_cast<BlockExpr>(e);
4683 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
4684 return 0;
4685
4686 FindCaptureVisitor visitor(S.Context, owner.Variable);
4687 visitor.Visit(block->getBlockDecl()->getBody());
4688 return visitor.Capturer;
4689}
4690
4691static void diagnoseRetainCycle(Sema &S, Expr *capturer,
4692 RetainCycleOwner &owner) {
4693 assert(capturer);
4694 assert(owner.Variable && owner.Loc.isValid());
4695
4696 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
4697 << owner.Variable << capturer->getSourceRange();
4698 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
4699 << owner.Indirect << owner.Range;
4700}
4701
4702/// Check for a keyword selector that starts with the word 'add' or
4703/// 'set'.
4704static bool isSetterLikeSelector(Selector sel) {
4705 if (sel.isUnarySelector()) return false;
4706
Chris Lattner5f9e2722011-07-23 10:55:15 +00004707 StringRef str = sel.getNameForSlot(0);
John McCallf85e1932011-06-15 23:02:42 +00004708 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00004709 if (str.startswith("set"))
John McCallf85e1932011-06-15 23:02:42 +00004710 str = str.substr(3);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00004711 else if (str.startswith("add")) {
4712 // Specially whitelist 'addOperationWithBlock:'.
4713 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
4714 return false;
4715 str = str.substr(3);
4716 }
John McCallf85e1932011-06-15 23:02:42 +00004717 else
4718 return false;
4719
4720 if (str.empty()) return true;
4721 return !islower(str.front());
4722}
4723
4724/// Check a message send to see if it's likely to cause a retain cycle.
4725void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
4726 // Only check instance methods whose selector looks like a setter.
4727 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
4728 return;
4729
4730 // Try to find a variable that the receiver is strongly owned by.
4731 RetainCycleOwner owner;
4732 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00004733 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCallf85e1932011-06-15 23:02:42 +00004734 return;
4735 } else {
4736 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
4737 owner.Variable = getCurMethodDecl()->getSelfDecl();
4738 owner.Loc = msg->getSuperLoc();
4739 owner.Range = msg->getSuperLoc();
4740 }
4741
4742 // Check whether the receiver is captured by any of the arguments.
4743 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
4744 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
4745 return diagnoseRetainCycle(*this, capturer, owner);
4746}
4747
4748/// Check a property assign to see if it's likely to cause a retain cycle.
4749void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
4750 RetainCycleOwner owner;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00004751 if (!findRetainCycleOwner(*this, receiver, owner))
John McCallf85e1932011-06-15 23:02:42 +00004752 return;
4753
4754 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
4755 diagnoseRetainCycle(*this, capturer, owner);
4756}
4757
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004758bool Sema::checkUnsafeAssigns(SourceLocation Loc,
John McCallf85e1932011-06-15 23:02:42 +00004759 QualType LHS, Expr *RHS) {
4760 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
4761 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004762 return false;
4763 // strip off any implicit cast added to get to the one arc-specific
4764 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00004765 if (cast->getCastKind() == CK_ARCConsumeObject) {
John McCallf85e1932011-06-15 23:02:42 +00004766 Diag(Loc, diag::warn_arc_retained_assign)
4767 << (LT == Qualifiers::OCL_ExplicitNone)
4768 << RHS->getSourceRange();
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004769 return true;
4770 }
4771 RHS = cast->getSubExpr();
4772 }
4773 return false;
John McCallf85e1932011-06-15 23:02:42 +00004774}
4775
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004776void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
4777 Expr *LHS, Expr *RHS) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00004778 QualType LHSType;
4779 // PropertyRef on LHS type need be directly obtained from
4780 // its declaration as it has a PsuedoType.
4781 ObjCPropertyRefExpr *PRE
4782 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
4783 if (PRE && !PRE->isImplicitProperty()) {
4784 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
4785 if (PD)
4786 LHSType = PD->getType();
4787 }
4788
4789 if (LHSType.isNull())
4790 LHSType = LHS->getType();
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004791 if (checkUnsafeAssigns(Loc, LHSType, RHS))
4792 return;
4793 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
4794 // FIXME. Check for other life times.
4795 if (LT != Qualifiers::OCL_None)
4796 return;
4797
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00004798 if (PRE) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004799 if (PRE->isImplicitProperty())
4800 return;
4801 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
4802 if (!PD)
4803 return;
4804
4805 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00004806 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
4807 // when 'assign' attribute was not explicitly specified
4808 // by user, ignore it and rely on property type itself
4809 // for lifetime info.
4810 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
4811 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
4812 LHSType->isObjCRetainableType())
4813 return;
4814
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004815 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00004816 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004817 Diag(Loc, diag::warn_arc_retained_property_assign)
4818 << RHS->getSourceRange();
4819 return;
4820 }
4821 RHS = cast->getSubExpr();
4822 }
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00004823 }
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004824 }
4825}