blob: 9bb532b5329f9151938f72ab629485de6e0142c8 [file] [log] [blame]
Chris Lattner59907c42007-08-10 20:18:51 +00001//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner59907c42007-08-10 20:18:51 +00007//
8//===----------------------------------------------------------------------===//
9//
Mike Stump1eb44332009-09-09 15:08:12 +000010// This file implements extra semantic analysis beyond what is enforced
Chris Lattner59907c42007-08-10 20:18:51 +000011// by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
John McCall5f8d6042011-08-27 01:09:30 +000015#include "clang/Sema/Initialization.h"
Douglas Gregore737f502010-08-12 20:07:10 +000016#include "clang/Sema/Sema.h"
John McCall2d887082010-08-25 22:03:47 +000017#include "clang/Sema/SemaInternal.h"
Eli Friedman276b0612011-10-11 02:20:01 +000018#include "clang/Sema/Initialization.h"
John McCall781472f2010-08-25 08:40:02 +000019#include "clang/Sema/ScopeInfo.h"
Ted Kremenek826a3452010-07-16 02:11:22 +000020#include "clang/Analysis/Analyses/FormatString.h"
Chris Lattner59907c42007-08-10 20:18:51 +000021#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000022#include "clang/AST/CharUnits.h"
John McCall384aff82010-08-25 07:42:41 +000023#include "clang/AST/DeclCXX.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000024#include "clang/AST/DeclObjC.h"
Ted Kremenek23245122007-08-20 16:18:38 +000025#include "clang/AST/ExprCXX.h"
Ted Kremenek7ff22b22008-06-16 18:00:42 +000026#include "clang/AST/ExprObjC.h"
John McCallf85e1932011-06-15 23:02:42 +000027#include "clang/AST/EvaluatedExprVisitor.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000028#include "clang/AST/DeclObjC.h"
29#include "clang/AST/StmtCXX.h"
30#include "clang/AST/StmtObjC.h"
Chris Lattner59907c42007-08-10 20:18:51 +000031#include "clang/Lex/Preprocessor.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000032#include "llvm/ADT/BitVector.h"
33#include "llvm/ADT/STLExtras.h"
Tom Care3bfc5f42010-06-09 04:11:11 +000034#include "llvm/Support/raw_ostream.h"
Eric Christopher691ebc32010-04-17 02:26:23 +000035#include "clang/Basic/TargetBuiltins.h"
Nate Begeman26a31422010-06-08 02:47:44 +000036#include "clang/Basic/TargetInfo.h"
Fariborz Jahanian7da71022010-09-07 19:38:13 +000037#include "clang/Basic/ConvertUTF.h"
Zhongxing Xua1f3dba2009-05-20 01:55:10 +000038#include <limits>
Chris Lattner59907c42007-08-10 20:18:51 +000039using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000040using namespace sema;
Chris Lattner59907c42007-08-10 20:18:51 +000041
Chris Lattner60800082009-02-18 17:49:48 +000042SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
43 unsigned ByteNo) const {
Chris Lattner08f92e32010-11-17 07:37:15 +000044 return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
45 PP.getLangOptions(), PP.getTargetInfo());
Chris Lattner60800082009-02-18 17:49:48 +000046}
Chris Lattner08f92e32010-11-17 07:37:15 +000047
Chris Lattner60800082009-02-18 17:49:48 +000048
Ryan Flynn4403a5e2009-08-06 03:00:50 +000049/// CheckablePrintfAttr - does a function call have a "printf" attribute
50/// and arguments that merit checking?
51bool Sema::CheckablePrintfAttr(const FormatAttr *Format, CallExpr *TheCall) {
52 if (Format->getType() == "printf") return true;
53 if (Format->getType() == "printf0") {
54 // printf0 allows null "format" string; if so don't check format/args
55 unsigned format_idx = Format->getFormatIdx() - 1;
Sebastian Redl4a2614e2009-11-17 18:02:24 +000056 // Does the index refer to the implicit object argument?
57 if (isa<CXXMemberCallExpr>(TheCall)) {
58 if (format_idx == 0)
59 return false;
60 --format_idx;
61 }
Ryan Flynn4403a5e2009-08-06 03:00:50 +000062 if (format_idx < TheCall->getNumArgs()) {
63 Expr *Format = TheCall->getArg(format_idx)->IgnoreParenCasts();
Ted Kremenekefaff192010-02-27 01:41:03 +000064 if (!Format->isNullPointerConstant(Context,
65 Expr::NPC_ValueDependentIsNull))
Ryan Flynn4403a5e2009-08-06 03:00:50 +000066 return true;
67 }
68 }
69 return false;
70}
Chris Lattner60800082009-02-18 17:49:48 +000071
John McCall8e10f3b2011-02-26 05:39:39 +000072/// Checks that a call expression's argument count is the desired number.
73/// This is useful when doing custom type-checking. Returns true on error.
74static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
75 unsigned argCount = call->getNumArgs();
76 if (argCount == desiredArgCount) return false;
77
78 if (argCount < desiredArgCount)
79 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
80 << 0 /*function call*/ << desiredArgCount << argCount
81 << call->getSourceRange();
82
83 // Highlight all the excess arguments.
84 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
85 call->getArg(argCount - 1)->getLocEnd());
86
87 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
88 << 0 /*function call*/ << desiredArgCount << argCount
89 << call->getArg(1)->getSourceRange();
90}
91
Julien Lerouge77f68bb2011-09-09 22:41:49 +000092/// CheckBuiltinAnnotationString - Checks that string argument to the builtin
93/// annotation is a non wide string literal.
94static bool CheckBuiltinAnnotationString(Sema &S, Expr *Arg) {
95 Arg = Arg->IgnoreParenCasts();
96 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
97 if (!Literal || !Literal->isAscii()) {
98 S.Diag(Arg->getLocStart(), diag::err_builtin_annotation_not_string_constant)
99 << Arg->getSourceRange();
100 return true;
101 }
102 return false;
103}
104
John McCall60d7b3a2010-08-24 06:29:42 +0000105ExprResult
Anders Carlssond406bf02009-08-16 01:56:34 +0000106Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
John McCall60d7b3a2010-08-24 06:29:42 +0000107 ExprResult TheCallResult(Owned(TheCall));
Douglas Gregor2def4832008-11-17 20:34:05 +0000108
Chris Lattner946928f2010-10-01 23:23:24 +0000109 // Find out if any arguments are required to be integer constant expressions.
110 unsigned ICEArguments = 0;
111 ASTContext::GetBuiltinTypeError Error;
112 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
113 if (Error != ASTContext::GE_None)
114 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
115
116 // If any arguments are required to be ICE's, check and diagnose.
117 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
118 // Skip arguments not required to be ICE's.
119 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
120
121 llvm::APSInt Result;
122 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
123 return true;
124 ICEArguments &= ~(1 << ArgNo);
125 }
126
Anders Carlssond406bf02009-08-16 01:56:34 +0000127 switch (BuiltinID) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000128 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +0000129 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +0000130 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner69039812009-02-18 06:01:06 +0000131 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000132 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000133 break;
Ted Kremenek49ff7a12008-07-09 17:58:53 +0000134 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +0000135 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000136 if (SemaBuiltinVAStart(TheCall))
137 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000138 break;
Chris Lattner1b9a0792007-12-20 00:26:33 +0000139 case Builtin::BI__builtin_isgreater:
140 case Builtin::BI__builtin_isgreaterequal:
141 case Builtin::BI__builtin_isless:
142 case Builtin::BI__builtin_islessequal:
143 case Builtin::BI__builtin_islessgreater:
144 case Builtin::BI__builtin_isunordered:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000145 if (SemaBuiltinUnorderedCompare(TheCall))
146 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000147 break;
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000148 case Builtin::BI__builtin_fpclassify:
149 if (SemaBuiltinFPClassification(TheCall, 6))
150 return ExprError();
151 break;
Eli Friedman9ac6f622009-08-31 20:06:00 +0000152 case Builtin::BI__builtin_isfinite:
153 case Builtin::BI__builtin_isinf:
154 case Builtin::BI__builtin_isinf_sign:
155 case Builtin::BI__builtin_isnan:
156 case Builtin::BI__builtin_isnormal:
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000157 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman9ac6f622009-08-31 20:06:00 +0000158 return ExprError();
159 break;
Eli Friedmand38617c2008-05-14 19:38:39 +0000160 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000161 return SemaBuiltinShuffleVector(TheCall);
162 // TheCall will be freed by the smart pointer here, but that's fine, since
163 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000164 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000165 if (SemaBuiltinPrefetch(TheCall))
166 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000167 break;
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000168 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000169 if (SemaBuiltinObjectSize(TheCall))
170 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000171 break;
Eli Friedmand875fed2009-05-03 04:46:36 +0000172 case Builtin::BI__builtin_longjmp:
173 if (SemaBuiltinLongjmp(TheCall))
174 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000175 break;
John McCall8e10f3b2011-02-26 05:39:39 +0000176
177 case Builtin::BI__builtin_classify_type:
178 if (checkArgCount(*this, TheCall, 1)) return true;
179 TheCall->setType(Context.IntTy);
180 break;
Chris Lattner75c29a02010-10-12 17:47:42 +0000181 case Builtin::BI__builtin_constant_p:
John McCall8e10f3b2011-02-26 05:39:39 +0000182 if (checkArgCount(*this, TheCall, 1)) return true;
183 TheCall->setType(Context.IntTy);
Chris Lattner75c29a02010-10-12 17:47:42 +0000184 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000185 case Builtin::BI__sync_fetch_and_add:
Douglas Gregora9766412011-11-28 16:30:08 +0000186 case Builtin::BI__sync_fetch_and_add_1:
187 case Builtin::BI__sync_fetch_and_add_2:
188 case Builtin::BI__sync_fetch_and_add_4:
189 case Builtin::BI__sync_fetch_and_add_8:
190 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000191 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregora9766412011-11-28 16:30:08 +0000192 case Builtin::BI__sync_fetch_and_sub_1:
193 case Builtin::BI__sync_fetch_and_sub_2:
194 case Builtin::BI__sync_fetch_and_sub_4:
195 case Builtin::BI__sync_fetch_and_sub_8:
196 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000197 case Builtin::BI__sync_fetch_and_or:
Douglas Gregora9766412011-11-28 16:30:08 +0000198 case Builtin::BI__sync_fetch_and_or_1:
199 case Builtin::BI__sync_fetch_and_or_2:
200 case Builtin::BI__sync_fetch_and_or_4:
201 case Builtin::BI__sync_fetch_and_or_8:
202 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000203 case Builtin::BI__sync_fetch_and_and:
Douglas Gregora9766412011-11-28 16:30:08 +0000204 case Builtin::BI__sync_fetch_and_and_1:
205 case Builtin::BI__sync_fetch_and_and_2:
206 case Builtin::BI__sync_fetch_and_and_4:
207 case Builtin::BI__sync_fetch_and_and_8:
208 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000209 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregora9766412011-11-28 16:30:08 +0000210 case Builtin::BI__sync_fetch_and_xor_1:
211 case Builtin::BI__sync_fetch_and_xor_2:
212 case Builtin::BI__sync_fetch_and_xor_4:
213 case Builtin::BI__sync_fetch_and_xor_8:
214 case Builtin::BI__sync_fetch_and_xor_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000215 case Builtin::BI__sync_add_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000216 case Builtin::BI__sync_add_and_fetch_1:
217 case Builtin::BI__sync_add_and_fetch_2:
218 case Builtin::BI__sync_add_and_fetch_4:
219 case Builtin::BI__sync_add_and_fetch_8:
220 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000221 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000222 case Builtin::BI__sync_sub_and_fetch_1:
223 case Builtin::BI__sync_sub_and_fetch_2:
224 case Builtin::BI__sync_sub_and_fetch_4:
225 case Builtin::BI__sync_sub_and_fetch_8:
226 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000227 case Builtin::BI__sync_and_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000228 case Builtin::BI__sync_and_and_fetch_1:
229 case Builtin::BI__sync_and_and_fetch_2:
230 case Builtin::BI__sync_and_and_fetch_4:
231 case Builtin::BI__sync_and_and_fetch_8:
232 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000233 case Builtin::BI__sync_or_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000234 case Builtin::BI__sync_or_and_fetch_1:
235 case Builtin::BI__sync_or_and_fetch_2:
236 case Builtin::BI__sync_or_and_fetch_4:
237 case Builtin::BI__sync_or_and_fetch_8:
238 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000239 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000240 case Builtin::BI__sync_xor_and_fetch_1:
241 case Builtin::BI__sync_xor_and_fetch_2:
242 case Builtin::BI__sync_xor_and_fetch_4:
243 case Builtin::BI__sync_xor_and_fetch_8:
244 case Builtin::BI__sync_xor_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000245 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000246 case Builtin::BI__sync_val_compare_and_swap_1:
247 case Builtin::BI__sync_val_compare_and_swap_2:
248 case Builtin::BI__sync_val_compare_and_swap_4:
249 case Builtin::BI__sync_val_compare_and_swap_8:
250 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000251 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000252 case Builtin::BI__sync_bool_compare_and_swap_1:
253 case Builtin::BI__sync_bool_compare_and_swap_2:
254 case Builtin::BI__sync_bool_compare_and_swap_4:
255 case Builtin::BI__sync_bool_compare_and_swap_8:
256 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000257 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregora9766412011-11-28 16:30:08 +0000258 case Builtin::BI__sync_lock_test_and_set_1:
259 case Builtin::BI__sync_lock_test_and_set_2:
260 case Builtin::BI__sync_lock_test_and_set_4:
261 case Builtin::BI__sync_lock_test_and_set_8:
262 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000263 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +0000264 case Builtin::BI__sync_lock_release_1:
265 case Builtin::BI__sync_lock_release_2:
266 case Builtin::BI__sync_lock_release_4:
267 case Builtin::BI__sync_lock_release_8:
268 case Builtin::BI__sync_lock_release_16:
Chris Lattner23aa9c82011-04-09 03:57:26 +0000269 case Builtin::BI__sync_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000270 case Builtin::BI__sync_swap_1:
271 case Builtin::BI__sync_swap_2:
272 case Builtin::BI__sync_swap_4:
273 case Builtin::BI__sync_swap_8:
274 case Builtin::BI__sync_swap_16:
Chandler Carruthd2014572010-07-09 18:59:35 +0000275 return SemaBuiltinAtomicOverloaded(move(TheCallResult));
Eli Friedman276b0612011-10-11 02:20:01 +0000276 case Builtin::BI__atomic_load:
277 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Load);
278 case Builtin::BI__atomic_store:
279 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Store);
280 case Builtin::BI__atomic_exchange:
281 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Xchg);
282 case Builtin::BI__atomic_compare_exchange_strong:
283 return SemaAtomicOpsOverloaded(move(TheCallResult),
284 AtomicExpr::CmpXchgStrong);
285 case Builtin::BI__atomic_compare_exchange_weak:
286 return SemaAtomicOpsOverloaded(move(TheCallResult),
287 AtomicExpr::CmpXchgWeak);
288 case Builtin::BI__atomic_fetch_add:
289 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Add);
290 case Builtin::BI__atomic_fetch_sub:
291 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Sub);
292 case Builtin::BI__atomic_fetch_and:
293 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::And);
294 case Builtin::BI__atomic_fetch_or:
295 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Or);
296 case Builtin::BI__atomic_fetch_xor:
297 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Xor);
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000298 case Builtin::BI__builtin_annotation:
299 if (CheckBuiltinAnnotationString(*this, TheCall->getArg(1)))
300 return ExprError();
301 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000302 }
303
304 // Since the target specific builtins for each arch overlap, only check those
305 // of the arch we are compiling for.
306 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000307 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman26a31422010-06-08 02:47:44 +0000308 case llvm::Triple::arm:
309 case llvm::Triple::thumb:
310 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
311 return ExprError();
312 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000313 default:
314 break;
315 }
316 }
317
318 return move(TheCallResult);
319}
320
Nate Begeman61eecf52010-06-14 05:21:25 +0000321// Get the valid immediate range for the specified NEON type code.
322static unsigned RFT(unsigned t, bool shift = false) {
Bob Wilsonda95f732011-11-08 01:16:11 +0000323 NeonTypeFlags Type(t);
324 int IsQuad = Type.isQuad();
325 switch (Type.getEltType()) {
326 case NeonTypeFlags::Int8:
327 case NeonTypeFlags::Poly8:
328 return shift ? 7 : (8 << IsQuad) - 1;
329 case NeonTypeFlags::Int16:
330 case NeonTypeFlags::Poly16:
331 return shift ? 15 : (4 << IsQuad) - 1;
332 case NeonTypeFlags::Int32:
333 return shift ? 31 : (2 << IsQuad) - 1;
334 case NeonTypeFlags::Int64:
335 return shift ? 63 : (1 << IsQuad) - 1;
336 case NeonTypeFlags::Float16:
337 assert(!shift && "cannot shift float types!");
338 return (4 << IsQuad) - 1;
339 case NeonTypeFlags::Float32:
340 assert(!shift && "cannot shift float types!");
341 return (2 << IsQuad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000342 }
343 return 0;
344}
345
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000346/// getNeonEltType - Return the QualType corresponding to the elements of
347/// the vector type specified by the NeonTypeFlags. This is used to check
348/// the pointer arguments for Neon load/store intrinsics.
349static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context) {
350 switch (Flags.getEltType()) {
351 case NeonTypeFlags::Int8:
352 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
353 case NeonTypeFlags::Int16:
354 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
355 case NeonTypeFlags::Int32:
356 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
357 case NeonTypeFlags::Int64:
358 return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy;
359 case NeonTypeFlags::Poly8:
360 return Context.SignedCharTy;
361 case NeonTypeFlags::Poly16:
362 return Context.ShortTy;
363 case NeonTypeFlags::Float16:
364 return Context.UnsignedShortTy;
365 case NeonTypeFlags::Float32:
366 return Context.FloatTy;
367 }
368 return QualType();
369}
370
Nate Begeman26a31422010-06-08 02:47:44 +0000371bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000372 llvm::APSInt Result;
373
Nate Begeman0d15c532010-06-13 04:47:52 +0000374 unsigned mask = 0;
Nate Begeman61eecf52010-06-14 05:21:25 +0000375 unsigned TV = 0;
Bob Wilson46482552011-11-16 21:32:23 +0000376 int PtrArgNum = -1;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000377 bool HasConstPtr = false;
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000378 switch (BuiltinID) {
Nate Begemana23326b2010-06-17 04:17:01 +0000379#define GET_NEON_OVERLOAD_CHECK
380#include "clang/Basic/arm_neon.inc"
381#undef GET_NEON_OVERLOAD_CHECK
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000382 }
383
Nate Begeman0d15c532010-06-13 04:47:52 +0000384 // For NEON intrinsics which are overloaded on vector element type, validate
385 // the immediate which specifies which variant to emit.
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000386 unsigned ImmArg = TheCall->getNumArgs()-1;
Nate Begeman0d15c532010-06-13 04:47:52 +0000387 if (mask) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000388 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
Nate Begeman0d15c532010-06-13 04:47:52 +0000389 return true;
390
Bob Wilsonda95f732011-11-08 01:16:11 +0000391 TV = Result.getLimitedValue(64);
392 if ((TV > 63) || (mask & (1 << TV)) == 0)
Nate Begeman0d15c532010-06-13 04:47:52 +0000393 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000394 << TheCall->getArg(ImmArg)->getSourceRange();
395 }
396
Bob Wilson46482552011-11-16 21:32:23 +0000397 if (PtrArgNum >= 0) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000398 // Check that pointer arguments have the specified type.
Bob Wilson46482552011-11-16 21:32:23 +0000399 Expr *Arg = TheCall->getArg(PtrArgNum);
400 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
401 Arg = ICE->getSubExpr();
402 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
403 QualType RHSTy = RHS.get()->getType();
404 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context);
405 if (HasConstPtr)
406 EltTy = EltTy.withConst();
407 QualType LHSTy = Context.getPointerType(EltTy);
408 AssignConvertType ConvTy;
409 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
410 if (RHS.isInvalid())
411 return true;
412 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
413 RHS.get(), AA_Assigning))
414 return true;
Nate Begeman0d15c532010-06-13 04:47:52 +0000415 }
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000416
Nate Begeman0d15c532010-06-13 04:47:52 +0000417 // For NEON intrinsics which take an immediate value as part of the
418 // instruction, range check them here.
Nate Begeman61eecf52010-06-14 05:21:25 +0000419 unsigned i = 0, l = 0, u = 0;
Nate Begeman0d15c532010-06-13 04:47:52 +0000420 switch (BuiltinID) {
421 default: return false;
Nate Begemanbb37f502010-07-29 22:48:34 +0000422 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
423 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begeman99c40bb2010-08-03 21:32:34 +0000424 case ARM::BI__builtin_arm_vcvtr_f:
425 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Nate Begemana23326b2010-06-17 04:17:01 +0000426#define GET_NEON_IMMEDIATE_CHECK
427#include "clang/Basic/arm_neon.inc"
428#undef GET_NEON_IMMEDIATE_CHECK
Nate Begeman0d15c532010-06-13 04:47:52 +0000429 };
430
Nate Begeman61eecf52010-06-14 05:21:25 +0000431 // Check that the immediate argument is actually a constant.
Nate Begeman0d15c532010-06-13 04:47:52 +0000432 if (SemaBuiltinConstantArg(TheCall, i, Result))
433 return true;
434
Nate Begeman61eecf52010-06-14 05:21:25 +0000435 // Range check against the upper/lower values for this isntruction.
Nate Begeman0d15c532010-06-13 04:47:52 +0000436 unsigned Val = Result.getZExtValue();
Nate Begeman61eecf52010-06-14 05:21:25 +0000437 if (Val < l || Val > (u + l))
Nate Begeman0d15c532010-06-13 04:47:52 +0000438 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramer476d8b82010-08-11 14:47:12 +0000439 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begeman0d15c532010-06-13 04:47:52 +0000440
Nate Begeman99c40bb2010-08-03 21:32:34 +0000441 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman26a31422010-06-08 02:47:44 +0000442 return false;
Anders Carlssond406bf02009-08-16 01:56:34 +0000443}
Daniel Dunbarde454282008-10-02 18:44:07 +0000444
Anders Carlssond406bf02009-08-16 01:56:34 +0000445/// CheckFunctionCall - Check a direct function call for various correctness
446/// and safety properties not strictly enforced by the C type system.
447bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
448 // Get the IdentifierInfo* for the called function.
449 IdentifierInfo *FnInfo = FDecl->getIdentifier();
450
451 // None of the checks below are needed for functions that don't have
452 // simple names (e.g., C++ conversion functions).
453 if (!FnInfo)
454 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000455
Daniel Dunbarde454282008-10-02 18:44:07 +0000456 // FIXME: This mechanism should be abstracted to be less fragile and
457 // more efficient. For example, just map function ids to custom
458 // handlers.
459
Ted Kremenekc82faca2010-09-09 04:33:05 +0000460 // Printf and scanf checking.
461 for (specific_attr_iterator<FormatAttr>
462 i = FDecl->specific_attr_begin<FormatAttr>(),
463 e = FDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) {
464
465 const FormatAttr *Format = *i;
Ted Kremenek826a3452010-07-16 02:11:22 +0000466 const bool b = Format->getType() == "scanf";
467 if (b || CheckablePrintfAttr(Format, TheCall)) {
Ted Kremenek3d692df2009-02-27 17:58:43 +0000468 bool HasVAListArg = Format->getFirstArg() == 0;
Ted Kremenek826a3452010-07-16 02:11:22 +0000469 CheckPrintfScanfArguments(TheCall, HasVAListArg,
470 Format->getFormatIdx() - 1,
471 HasVAListArg ? 0 : Format->getFirstArg() - 1,
472 !b);
Douglas Gregor3c385e52009-02-14 18:57:46 +0000473 }
Chris Lattner59907c42007-08-10 20:18:51 +0000474 }
Mike Stump1eb44332009-09-09 15:08:12 +0000475
Ted Kremenekc82faca2010-09-09 04:33:05 +0000476 for (specific_attr_iterator<NonNullAttr>
477 i = FDecl->specific_attr_begin<NonNullAttr>(),
478 e = FDecl->specific_attr_end<NonNullAttr>(); i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +0000479 CheckNonNullArguments(*i, TheCall->getArgs(),
480 TheCall->getCallee()->getLocStart());
Ted Kremenekc82faca2010-09-09 04:33:05 +0000481 }
Sebastian Redl0eb23302009-01-19 00:08:26 +0000482
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000483 // Builtin handling
Douglas Gregor707a23e2011-06-16 17:56:04 +0000484 int CMF = -1;
485 switch (FDecl->getBuiltinID()) {
486 case Builtin::BI__builtin_memset:
487 case Builtin::BI__builtin___memset_chk:
488 case Builtin::BImemset:
489 CMF = CMF_Memset;
490 break;
491
492 case Builtin::BI__builtin_memcpy:
493 case Builtin::BI__builtin___memcpy_chk:
494 case Builtin::BImemcpy:
495 CMF = CMF_Memcpy;
496 break;
497
498 case Builtin::BI__builtin_memmove:
499 case Builtin::BI__builtin___memmove_chk:
500 case Builtin::BImemmove:
501 CMF = CMF_Memmove;
502 break;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000503
504 case Builtin::BIstrlcpy:
505 case Builtin::BIstrlcat:
506 CheckStrlcpycatArguments(TheCall, FnInfo);
507 break;
Douglas Gregor707a23e2011-06-16 17:56:04 +0000508
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +0000509 case Builtin::BI__builtin_memcmp:
510 CMF = CMF_Memcmp;
511 break;
512
Nico Webercda57822011-10-13 22:30:23 +0000513 case Builtin::BI__builtin_strncpy:
514 case Builtin::BI__builtin___strncpy_chk:
515 case Builtin::BIstrncpy:
516 CMF = CMF_Strncpy;
517 break;
518
519 case Builtin::BI__builtin_strncmp:
520 CMF = CMF_Strncmp;
521 break;
522
523 case Builtin::BI__builtin_strncasecmp:
524 CMF = CMF_Strncasecmp;
525 break;
526
527 case Builtin::BI__builtin_strncat:
528 case Builtin::BIstrncat:
529 CMF = CMF_Strncat;
530 break;
531
532 case Builtin::BI__builtin_strndup:
533 case Builtin::BIstrndup:
534 CMF = CMF_Strndup;
535 break;
536
Douglas Gregor707a23e2011-06-16 17:56:04 +0000537 default:
538 if (FDecl->getLinkage() == ExternalLinkage &&
539 (!getLangOptions().CPlusPlus || FDecl->isExternC())) {
540 if (FnInfo->isStr("memset"))
541 CMF = CMF_Memset;
542 else if (FnInfo->isStr("memcpy"))
543 CMF = CMF_Memcpy;
544 else if (FnInfo->isStr("memmove"))
545 CMF = CMF_Memmove;
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +0000546 else if (FnInfo->isStr("memcmp"))
547 CMF = CMF_Memcmp;
Nico Webercda57822011-10-13 22:30:23 +0000548 else if (FnInfo->isStr("strncpy"))
549 CMF = CMF_Strncpy;
550 else if (FnInfo->isStr("strncmp"))
551 CMF = CMF_Strncmp;
552 else if (FnInfo->isStr("strncasecmp"))
553 CMF = CMF_Strncasecmp;
554 else if (FnInfo->isStr("strncat"))
555 CMF = CMF_Strncat;
556 else if (FnInfo->isStr("strndup"))
557 CMF = CMF_Strndup;
Douglas Gregor707a23e2011-06-16 17:56:04 +0000558 }
559 break;
Douglas Gregor06bc9eb2011-05-03 20:37:33 +0000560 }
Douglas Gregor707a23e2011-06-16 17:56:04 +0000561
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000562 // Memset/memcpy/memmove handling
Douglas Gregor707a23e2011-06-16 17:56:04 +0000563 if (CMF != -1)
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +0000564 CheckMemaccessArguments(TheCall, CheckedMemoryFunction(CMF), FnInfo);
Chandler Carruth7ccc95b2011-04-27 07:05:31 +0000565
Anders Carlssond406bf02009-08-16 01:56:34 +0000566 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000567}
568
Anders Carlssond406bf02009-08-16 01:56:34 +0000569bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000570 // Printf checking.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000571 const FormatAttr *Format = NDecl->getAttr<FormatAttr>();
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000572 if (!Format)
Anders Carlssond406bf02009-08-16 01:56:34 +0000573 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000574
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000575 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
576 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000577 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000578
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000579 QualType Ty = V->getType();
580 if (!Ty->isBlockPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000581 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000582
Ted Kremenek826a3452010-07-16 02:11:22 +0000583 const bool b = Format->getType() == "scanf";
584 if (!b && !CheckablePrintfAttr(Format, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +0000585 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000586
Anders Carlssond406bf02009-08-16 01:56:34 +0000587 bool HasVAListArg = Format->getFirstArg() == 0;
Ted Kremenek826a3452010-07-16 02:11:22 +0000588 CheckPrintfScanfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
589 HasVAListArg ? 0 : Format->getFirstArg() - 1, !b);
Anders Carlssond406bf02009-08-16 01:56:34 +0000590
591 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000592}
593
Eli Friedman276b0612011-10-11 02:20:01 +0000594ExprResult
595Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, AtomicExpr::AtomicOp Op) {
596 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
597 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedman276b0612011-10-11 02:20:01 +0000598
599 // All these operations take one of the following four forms:
600 // T __atomic_load(_Atomic(T)*, int) (loads)
601 // T* __atomic_add(_Atomic(T*)*, ptrdiff_t, int) (pointer add/sub)
602 // int __atomic_compare_exchange_strong(_Atomic(T)*, T*, T, int, int)
603 // (cmpxchg)
604 // T __atomic_exchange(_Atomic(T)*, T, int) (everything else)
605 // where T is an appropriate type, and the int paremeterss are for orderings.
606 unsigned NumVals = 1;
607 unsigned NumOrders = 1;
608 if (Op == AtomicExpr::Load) {
609 NumVals = 0;
610 } else if (Op == AtomicExpr::CmpXchgWeak || Op == AtomicExpr::CmpXchgStrong) {
611 NumVals = 2;
612 NumOrders = 2;
613 }
614
615 if (TheCall->getNumArgs() < NumVals+NumOrders+1) {
616 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
617 << 0 << NumVals+NumOrders+1 << TheCall->getNumArgs()
618 << TheCall->getCallee()->getSourceRange();
619 return ExprError();
620 } else if (TheCall->getNumArgs() > NumVals+NumOrders+1) {
621 Diag(TheCall->getArg(NumVals+NumOrders+1)->getLocStart(),
622 diag::err_typecheck_call_too_many_args)
623 << 0 << NumVals+NumOrders+1 << TheCall->getNumArgs()
624 << TheCall->getCallee()->getSourceRange();
625 return ExprError();
626 }
627
628 // Inspect the first argument of the atomic operation. This should always be
629 // a pointer to an _Atomic type.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000630 Expr *Ptr = TheCall->getArg(0);
Eli Friedman276b0612011-10-11 02:20:01 +0000631 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
632 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
633 if (!pointerType) {
634 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
635 << Ptr->getType() << Ptr->getSourceRange();
636 return ExprError();
637 }
638
639 QualType AtomTy = pointerType->getPointeeType();
640 if (!AtomTy->isAtomicType()) {
641 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
642 << Ptr->getType() << Ptr->getSourceRange();
643 return ExprError();
644 }
645 QualType ValType = AtomTy->getAs<AtomicType>()->getValueType();
646
647 if ((Op == AtomicExpr::Add || Op == AtomicExpr::Sub) &&
648 !ValType->isIntegerType() && !ValType->isPointerType()) {
649 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
650 << Ptr->getType() << Ptr->getSourceRange();
651 return ExprError();
652 }
653
654 if (!ValType->isIntegerType() &&
655 (Op == AtomicExpr::And || Op == AtomicExpr::Or || Op == AtomicExpr::Xor)){
656 Diag(DRE->getLocStart(), diag::err_atomic_op_logical_needs_atomic_int)
657 << Ptr->getType() << Ptr->getSourceRange();
658 return ExprError();
659 }
660
661 switch (ValType.getObjCLifetime()) {
662 case Qualifiers::OCL_None:
663 case Qualifiers::OCL_ExplicitNone:
664 // okay
665 break;
666
667 case Qualifiers::OCL_Weak:
668 case Qualifiers::OCL_Strong:
669 case Qualifiers::OCL_Autoreleasing:
670 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
671 << ValType << Ptr->getSourceRange();
672 return ExprError();
673 }
674
675 QualType ResultType = ValType;
676 if (Op == AtomicExpr::Store)
677 ResultType = Context.VoidTy;
678 else if (Op == AtomicExpr::CmpXchgWeak || Op == AtomicExpr::CmpXchgStrong)
679 ResultType = Context.BoolTy;
680
681 // The first argument --- the pointer --- has a fixed type; we
682 // deduce the types of the rest of the arguments accordingly. Walk
683 // the remaining arguments, converting them to the deduced value type.
684 for (unsigned i = 1; i != NumVals+NumOrders+1; ++i) {
685 ExprResult Arg = TheCall->getArg(i);
686 QualType Ty;
687 if (i < NumVals+1) {
688 // The second argument to a cmpxchg is a pointer to the data which will
689 // be exchanged. The second argument to a pointer add/subtract is the
690 // amount to add/subtract, which must be a ptrdiff_t. The third
691 // argument to a cmpxchg and the second argument in all other cases
692 // is the type of the value.
693 if (i == 1 && (Op == AtomicExpr::CmpXchgWeak ||
694 Op == AtomicExpr::CmpXchgStrong))
695 Ty = Context.getPointerType(ValType.getUnqualifiedType());
696 else if (!ValType->isIntegerType() &&
697 (Op == AtomicExpr::Add || Op == AtomicExpr::Sub))
698 Ty = Context.getPointerDiffType();
699 else
700 Ty = ValType;
701 } else {
702 // The order(s) are always converted to int.
703 Ty = Context.IntTy;
704 }
705 InitializedEntity Entity =
706 InitializedEntity::InitializeParameter(Context, Ty, false);
707 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
708 if (Arg.isInvalid())
709 return true;
710 TheCall->setArg(i, Arg.get());
711 }
712
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000713 SmallVector<Expr*, 5> SubExprs;
714 SubExprs.push_back(Ptr);
Eli Friedman276b0612011-10-11 02:20:01 +0000715 if (Op == AtomicExpr::Load) {
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000716 SubExprs.push_back(TheCall->getArg(1)); // Order
Eli Friedman276b0612011-10-11 02:20:01 +0000717 } else if (Op != AtomicExpr::CmpXchgWeak && Op != AtomicExpr::CmpXchgStrong) {
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000718 SubExprs.push_back(TheCall->getArg(2)); // Order
719 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman276b0612011-10-11 02:20:01 +0000720 } else {
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000721 SubExprs.push_back(TheCall->getArg(3)); // Order
722 SubExprs.push_back(TheCall->getArg(1)); // Val1
723 SubExprs.push_back(TheCall->getArg(2)); // Val2
724 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
Eli Friedman276b0612011-10-11 02:20:01 +0000725 }
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000726
727 return Owned(new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
728 SubExprs.data(), SubExprs.size(),
729 ResultType, Op,
730 TheCall->getRParenLoc()));
Eli Friedman276b0612011-10-11 02:20:01 +0000731}
732
733
John McCall5f8d6042011-08-27 01:09:30 +0000734/// checkBuiltinArgument - Given a call to a builtin function, perform
735/// normal type-checking on the given argument, updating the call in
736/// place. This is useful when a builtin function requires custom
737/// type-checking for some of its arguments but not necessarily all of
738/// them.
739///
740/// Returns true on error.
741static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
742 FunctionDecl *Fn = E->getDirectCallee();
743 assert(Fn && "builtin call without direct callee!");
744
745 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
746 InitializedEntity Entity =
747 InitializedEntity::InitializeParameter(S.Context, Param);
748
749 ExprResult Arg = E->getArg(0);
750 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
751 if (Arg.isInvalid())
752 return true;
753
754 E->setArg(ArgIndex, Arg.take());
755 return false;
756}
757
Chris Lattner5caa3702009-05-08 06:58:22 +0000758/// SemaBuiltinAtomicOverloaded - We have a call to a function like
759/// __sync_fetch_and_add, which is an overloaded function based on the pointer
760/// type of its first argument. The main ActOnCallExpr routines have already
761/// promoted the types of arguments because all of these calls are prototyped as
762/// void(...).
763///
764/// This function goes through and does final semantic checking for these
765/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +0000766ExprResult
767Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000768 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +0000769 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
770 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
771
772 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +0000773 if (TheCall->getNumArgs() < 1) {
774 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
775 << 0 << 1 << TheCall->getNumArgs()
776 << TheCall->getCallee()->getSourceRange();
777 return ExprError();
778 }
Mike Stump1eb44332009-09-09 15:08:12 +0000779
Chris Lattner5caa3702009-05-08 06:58:22 +0000780 // Inspect the first argument of the atomic builtin. This should always be
781 // a pointer type, whose element is an integral scalar or pointer type.
782 // Because it is a pointer type, we don't have to worry about any implicit
783 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +0000784 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +0000785 Expr *FirstArg = TheCall->getArg(0);
John McCallf85e1932011-06-15 23:02:42 +0000786 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
787 if (!pointerType) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000788 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
789 << FirstArg->getType() << FirstArg->getSourceRange();
790 return ExprError();
791 }
Mike Stump1eb44332009-09-09 15:08:12 +0000792
John McCallf85e1932011-06-15 23:02:42 +0000793 QualType ValType = pointerType->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +0000794 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +0000795 !ValType->isBlockPointerType()) {
796 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
797 << FirstArg->getType() << FirstArg->getSourceRange();
798 return ExprError();
799 }
Chris Lattner5caa3702009-05-08 06:58:22 +0000800
John McCallf85e1932011-06-15 23:02:42 +0000801 switch (ValType.getObjCLifetime()) {
802 case Qualifiers::OCL_None:
803 case Qualifiers::OCL_ExplicitNone:
804 // okay
805 break;
806
807 case Qualifiers::OCL_Weak:
808 case Qualifiers::OCL_Strong:
809 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +0000810 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCallf85e1932011-06-15 23:02:42 +0000811 << ValType << FirstArg->getSourceRange();
812 return ExprError();
813 }
814
John McCallb45ae252011-10-05 07:41:44 +0000815 // Strip any qualifiers off ValType.
816 ValType = ValType.getUnqualifiedType();
817
Chandler Carruth8d13d222010-07-18 20:54:12 +0000818 // The majority of builtins return a value, but a few have special return
819 // types, so allow them to override appropriately below.
820 QualType ResultType = ValType;
821
Chris Lattner5caa3702009-05-08 06:58:22 +0000822 // We need to figure out which concrete builtin this maps onto. For example,
823 // __sync_fetch_and_add with a 2 byte object turns into
824 // __sync_fetch_and_add_2.
825#define BUILTIN_ROW(x) \
826 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
827 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +0000828
Chris Lattner5caa3702009-05-08 06:58:22 +0000829 static const unsigned BuiltinIndices[][5] = {
830 BUILTIN_ROW(__sync_fetch_and_add),
831 BUILTIN_ROW(__sync_fetch_and_sub),
832 BUILTIN_ROW(__sync_fetch_and_or),
833 BUILTIN_ROW(__sync_fetch_and_and),
834 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +0000835
Chris Lattner5caa3702009-05-08 06:58:22 +0000836 BUILTIN_ROW(__sync_add_and_fetch),
837 BUILTIN_ROW(__sync_sub_and_fetch),
838 BUILTIN_ROW(__sync_and_and_fetch),
839 BUILTIN_ROW(__sync_or_and_fetch),
840 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +0000841
Chris Lattner5caa3702009-05-08 06:58:22 +0000842 BUILTIN_ROW(__sync_val_compare_and_swap),
843 BUILTIN_ROW(__sync_bool_compare_and_swap),
844 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner23aa9c82011-04-09 03:57:26 +0000845 BUILTIN_ROW(__sync_lock_release),
846 BUILTIN_ROW(__sync_swap)
Chris Lattner5caa3702009-05-08 06:58:22 +0000847 };
Mike Stump1eb44332009-09-09 15:08:12 +0000848#undef BUILTIN_ROW
849
Chris Lattner5caa3702009-05-08 06:58:22 +0000850 // Determine the index of the size.
851 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +0000852 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +0000853 case 1: SizeIndex = 0; break;
854 case 2: SizeIndex = 1; break;
855 case 4: SizeIndex = 2; break;
856 case 8: SizeIndex = 3; break;
857 case 16: SizeIndex = 4; break;
858 default:
Chandler Carruthd2014572010-07-09 18:59:35 +0000859 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
860 << FirstArg->getType() << FirstArg->getSourceRange();
861 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +0000862 }
Mike Stump1eb44332009-09-09 15:08:12 +0000863
Chris Lattner5caa3702009-05-08 06:58:22 +0000864 // Each of these builtins has one pointer argument, followed by some number of
865 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
866 // that we ignore. Find out which row of BuiltinIndices to read from as well
867 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +0000868 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +0000869 unsigned BuiltinIndex, NumFixed = 1;
870 switch (BuiltinID) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000871 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregora9766412011-11-28 16:30:08 +0000872 case Builtin::BI__sync_fetch_and_add:
873 case Builtin::BI__sync_fetch_and_add_1:
874 case Builtin::BI__sync_fetch_and_add_2:
875 case Builtin::BI__sync_fetch_and_add_4:
876 case Builtin::BI__sync_fetch_and_add_8:
877 case Builtin::BI__sync_fetch_and_add_16:
878 BuiltinIndex = 0;
879 break;
880
881 case Builtin::BI__sync_fetch_and_sub:
882 case Builtin::BI__sync_fetch_and_sub_1:
883 case Builtin::BI__sync_fetch_and_sub_2:
884 case Builtin::BI__sync_fetch_and_sub_4:
885 case Builtin::BI__sync_fetch_and_sub_8:
886 case Builtin::BI__sync_fetch_and_sub_16:
887 BuiltinIndex = 1;
888 break;
889
890 case Builtin::BI__sync_fetch_and_or:
891 case Builtin::BI__sync_fetch_and_or_1:
892 case Builtin::BI__sync_fetch_and_or_2:
893 case Builtin::BI__sync_fetch_and_or_4:
894 case Builtin::BI__sync_fetch_and_or_8:
895 case Builtin::BI__sync_fetch_and_or_16:
896 BuiltinIndex = 2;
897 break;
898
899 case Builtin::BI__sync_fetch_and_and:
900 case Builtin::BI__sync_fetch_and_and_1:
901 case Builtin::BI__sync_fetch_and_and_2:
902 case Builtin::BI__sync_fetch_and_and_4:
903 case Builtin::BI__sync_fetch_and_and_8:
904 case Builtin::BI__sync_fetch_and_and_16:
905 BuiltinIndex = 3;
906 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000907
Douglas Gregora9766412011-11-28 16:30:08 +0000908 case Builtin::BI__sync_fetch_and_xor:
909 case Builtin::BI__sync_fetch_and_xor_1:
910 case Builtin::BI__sync_fetch_and_xor_2:
911 case Builtin::BI__sync_fetch_and_xor_4:
912 case Builtin::BI__sync_fetch_and_xor_8:
913 case Builtin::BI__sync_fetch_and_xor_16:
914 BuiltinIndex = 4;
915 break;
916
917 case Builtin::BI__sync_add_and_fetch:
918 case Builtin::BI__sync_add_and_fetch_1:
919 case Builtin::BI__sync_add_and_fetch_2:
920 case Builtin::BI__sync_add_and_fetch_4:
921 case Builtin::BI__sync_add_and_fetch_8:
922 case Builtin::BI__sync_add_and_fetch_16:
923 BuiltinIndex = 5;
924 break;
925
926 case Builtin::BI__sync_sub_and_fetch:
927 case Builtin::BI__sync_sub_and_fetch_1:
928 case Builtin::BI__sync_sub_and_fetch_2:
929 case Builtin::BI__sync_sub_and_fetch_4:
930 case Builtin::BI__sync_sub_and_fetch_8:
931 case Builtin::BI__sync_sub_and_fetch_16:
932 BuiltinIndex = 6;
933 break;
934
935 case Builtin::BI__sync_and_and_fetch:
936 case Builtin::BI__sync_and_and_fetch_1:
937 case Builtin::BI__sync_and_and_fetch_2:
938 case Builtin::BI__sync_and_and_fetch_4:
939 case Builtin::BI__sync_and_and_fetch_8:
940 case Builtin::BI__sync_and_and_fetch_16:
941 BuiltinIndex = 7;
942 break;
943
944 case Builtin::BI__sync_or_and_fetch:
945 case Builtin::BI__sync_or_and_fetch_1:
946 case Builtin::BI__sync_or_and_fetch_2:
947 case Builtin::BI__sync_or_and_fetch_4:
948 case Builtin::BI__sync_or_and_fetch_8:
949 case Builtin::BI__sync_or_and_fetch_16:
950 BuiltinIndex = 8;
951 break;
952
953 case Builtin::BI__sync_xor_and_fetch:
954 case Builtin::BI__sync_xor_and_fetch_1:
955 case Builtin::BI__sync_xor_and_fetch_2:
956 case Builtin::BI__sync_xor_and_fetch_4:
957 case Builtin::BI__sync_xor_and_fetch_8:
958 case Builtin::BI__sync_xor_and_fetch_16:
959 BuiltinIndex = 9;
960 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000961
Chris Lattner5caa3702009-05-08 06:58:22 +0000962 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000963 case Builtin::BI__sync_val_compare_and_swap_1:
964 case Builtin::BI__sync_val_compare_and_swap_2:
965 case Builtin::BI__sync_val_compare_and_swap_4:
966 case Builtin::BI__sync_val_compare_and_swap_8:
967 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000968 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +0000969 NumFixed = 2;
970 break;
Douglas Gregora9766412011-11-28 16:30:08 +0000971
Chris Lattner5caa3702009-05-08 06:58:22 +0000972 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000973 case Builtin::BI__sync_bool_compare_and_swap_1:
974 case Builtin::BI__sync_bool_compare_and_swap_2:
975 case Builtin::BI__sync_bool_compare_and_swap_4:
976 case Builtin::BI__sync_bool_compare_and_swap_8:
977 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000978 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +0000979 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +0000980 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +0000981 break;
Douglas Gregora9766412011-11-28 16:30:08 +0000982
983 case Builtin::BI__sync_lock_test_and_set:
984 case Builtin::BI__sync_lock_test_and_set_1:
985 case Builtin::BI__sync_lock_test_and_set_2:
986 case Builtin::BI__sync_lock_test_and_set_4:
987 case Builtin::BI__sync_lock_test_and_set_8:
988 case Builtin::BI__sync_lock_test_and_set_16:
989 BuiltinIndex = 12;
990 break;
991
Chris Lattner5caa3702009-05-08 06:58:22 +0000992 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +0000993 case Builtin::BI__sync_lock_release_1:
994 case Builtin::BI__sync_lock_release_2:
995 case Builtin::BI__sync_lock_release_4:
996 case Builtin::BI__sync_lock_release_8:
997 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000998 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +0000999 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001000 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001001 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001002
1003 case Builtin::BI__sync_swap:
1004 case Builtin::BI__sync_swap_1:
1005 case Builtin::BI__sync_swap_2:
1006 case Builtin::BI__sync_swap_4:
1007 case Builtin::BI__sync_swap_8:
1008 case Builtin::BI__sync_swap_16:
1009 BuiltinIndex = 14;
1010 break;
Chris Lattner5caa3702009-05-08 06:58:22 +00001011 }
Mike Stump1eb44332009-09-09 15:08:12 +00001012
Chris Lattner5caa3702009-05-08 06:58:22 +00001013 // Now that we know how many fixed arguments we expect, first check that we
1014 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +00001015 if (TheCall->getNumArgs() < 1+NumFixed) {
1016 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1017 << 0 << 1+NumFixed << TheCall->getNumArgs()
1018 << TheCall->getCallee()->getSourceRange();
1019 return ExprError();
1020 }
Mike Stump1eb44332009-09-09 15:08:12 +00001021
Chris Lattnere7ac0a92009-05-08 15:36:58 +00001022 // Get the decl for the concrete builtin from this, we can tell what the
1023 // concrete integer type we should convert to is.
1024 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1025 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
1026 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
Mike Stump1eb44332009-09-09 15:08:12 +00001027 FunctionDecl *NewBuiltinDecl =
Chris Lattnere7ac0a92009-05-08 15:36:58 +00001028 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
1029 TUScope, false, DRE->getLocStart()));
Chandler Carruthd2014572010-07-09 18:59:35 +00001030
John McCallf871d0c2010-08-07 06:22:56 +00001031 // The first argument --- the pointer --- has a fixed type; we
1032 // deduce the types of the rest of the arguments accordingly. Walk
1033 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +00001034 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley429bb272011-04-08 18:41:53 +00001035 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +00001036
Chris Lattner5caa3702009-05-08 06:58:22 +00001037 // GCC does an implicit conversion to the pointer or integer ValType. This
1038 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb45ae252011-10-05 07:41:44 +00001039 // Initialize the argument.
1040 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1041 ValType, /*consume*/ false);
1042 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley429bb272011-04-08 18:41:53 +00001043 if (Arg.isInvalid())
Chandler Carruthd2014572010-07-09 18:59:35 +00001044 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001045
Chris Lattner5caa3702009-05-08 06:58:22 +00001046 // Okay, we have something that *can* be converted to the right type. Check
1047 // to see if there is a potentially weird extension going on here. This can
1048 // happen when you do an atomic operation on something like an char* and
1049 // pass in 42. The 42 gets converted to char. This is even more strange
1050 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +00001051 // FIXME: Do this check.
John McCallb45ae252011-10-05 07:41:44 +00001052 TheCall->setArg(i+1, Arg.take());
Chris Lattner5caa3702009-05-08 06:58:22 +00001053 }
Mike Stump1eb44332009-09-09 15:08:12 +00001054
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001055 ASTContext& Context = this->getASTContext();
1056
1057 // Create a new DeclRefExpr to refer to the new decl.
1058 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1059 Context,
1060 DRE->getQualifierLoc(),
1061 NewBuiltinDecl,
1062 DRE->getLocation(),
1063 NewBuiltinDecl->getType(),
1064 DRE->getValueKind());
Mike Stump1eb44332009-09-09 15:08:12 +00001065
Chris Lattner5caa3702009-05-08 06:58:22 +00001066 // Set the callee in the CallExpr.
1067 // FIXME: This leaks the original parens and implicit casts.
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001068 ExprResult PromotedCall = UsualUnaryConversions(NewDRE);
John Wiegley429bb272011-04-08 18:41:53 +00001069 if (PromotedCall.isInvalid())
1070 return ExprError();
1071 TheCall->setCallee(PromotedCall.take());
Mike Stump1eb44332009-09-09 15:08:12 +00001072
Chandler Carruthdb4325b2010-07-18 07:23:17 +00001073 // Change the result type of the call to match the original value type. This
1074 // is arbitrary, but the codegen for these builtins ins design to handle it
1075 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +00001076 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +00001077
1078 return move(TheCallResult);
Chris Lattner5caa3702009-05-08 06:58:22 +00001079}
1080
Chris Lattner69039812009-02-18 06:01:06 +00001081/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +00001082/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +00001083/// Note: It might also make sense to do the UTF-16 conversion here (would
1084/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +00001085bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +00001086 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +00001087 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1088
Douglas Gregor5cee1192011-07-27 05:40:30 +00001089 if (!Literal || !Literal->isAscii()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001090 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1091 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001092 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +00001093 }
Mike Stump1eb44332009-09-09 15:08:12 +00001094
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001095 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001096 StringRef String = Literal->getString();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001097 unsigned NumBytes = String.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001098 SmallVector<UTF16, 128> ToBuf(NumBytes);
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001099 const UTF8 *FromPtr = (UTF8 *)String.data();
1100 UTF16 *ToPtr = &ToBuf[0];
1101
1102 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1103 &ToPtr, ToPtr + NumBytes,
1104 strictConversion);
1105 // Check for conversion failure.
1106 if (Result != conversionOK)
1107 Diag(Arg->getLocStart(),
1108 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1109 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001110 return false;
Chris Lattner59907c42007-08-10 20:18:51 +00001111}
1112
Chris Lattnerc27c6652007-12-20 00:05:45 +00001113/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1114/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +00001115bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1116 Expr *Fn = TheCall->getCallee();
1117 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +00001118 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001119 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001120 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1121 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +00001122 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001123 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +00001124 return true;
1125 }
Eli Friedman56f20ae2008-12-15 22:05:35 +00001126
1127 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +00001128 return Diag(TheCall->getLocEnd(),
1129 diag::err_typecheck_call_too_few_args_at_least)
1130 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +00001131 }
1132
John McCall5f8d6042011-08-27 01:09:30 +00001133 // Type-check the first argument normally.
1134 if (checkBuiltinArgument(*this, TheCall, 0))
1135 return true;
1136
Chris Lattnerc27c6652007-12-20 00:05:45 +00001137 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001138 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +00001139 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001140 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +00001141 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +00001142 else if (FunctionDecl *FD = getCurFunctionDecl())
1143 isVariadic = FD->isVariadic();
1144 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001145 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +00001146
Chris Lattnerc27c6652007-12-20 00:05:45 +00001147 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001148 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1149 return true;
1150 }
Mike Stump1eb44332009-09-09 15:08:12 +00001151
Chris Lattner30ce3442007-12-19 23:59:04 +00001152 // Verify that the second argument to the builtin is the last argument of the
1153 // current function or method.
1154 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +00001155 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001156
Anders Carlsson88cf2262008-02-11 04:20:54 +00001157 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1158 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001159 // FIXME: This isn't correct for methods (results in bogus warning).
1160 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +00001161 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001162 if (CurBlock)
1163 LastArg = *(CurBlock->TheDecl->param_end()-1);
1164 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +00001165 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001166 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001167 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001168 SecondArgIsLastNamedArgument = PV == LastArg;
1169 }
1170 }
Mike Stump1eb44332009-09-09 15:08:12 +00001171
Chris Lattner30ce3442007-12-19 23:59:04 +00001172 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001173 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +00001174 diag::warn_second_parameter_of_va_start_not_last_named_argument);
1175 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +00001176}
Chris Lattner30ce3442007-12-19 23:59:04 +00001177
Chris Lattner1b9a0792007-12-20 00:26:33 +00001178/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1179/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +00001180bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1181 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +00001182 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001183 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +00001184 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +00001185 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001186 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001187 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001188 << SourceRange(TheCall->getArg(2)->getLocStart(),
1189 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001190
John Wiegley429bb272011-04-08 18:41:53 +00001191 ExprResult OrigArg0 = TheCall->getArg(0);
1192 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +00001193
Chris Lattner1b9a0792007-12-20 00:26:33 +00001194 // Do standard promotions between the two arguments, returning their common
1195 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +00001196 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley429bb272011-04-08 18:41:53 +00001197 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1198 return true;
Daniel Dunbar403bc2b2009-02-19 19:28:43 +00001199
1200 // Make sure any conversions are pushed back into the call; this is
1201 // type safe since unordered compare builtins are declared as "_Bool
1202 // foo(...)".
John Wiegley429bb272011-04-08 18:41:53 +00001203 TheCall->setArg(0, OrigArg0.get());
1204 TheCall->setArg(1, OrigArg1.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001205
John Wiegley429bb272011-04-08 18:41:53 +00001206 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorcde01732009-05-19 22:10:17 +00001207 return false;
1208
Chris Lattner1b9a0792007-12-20 00:26:33 +00001209 // If the common type isn't a real floating type, then the arguments were
1210 // invalid for this operation.
1211 if (!Res->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +00001212 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001213 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley429bb272011-04-08 18:41:53 +00001214 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1215 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001216
Chris Lattner1b9a0792007-12-20 00:26:33 +00001217 return false;
1218}
1219
Benjamin Kramere771a7a2010-02-15 22:42:31 +00001220/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1221/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001222/// to check everything. We expect the last argument to be a floating point
1223/// value.
1224bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1225 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +00001226 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001227 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001228 if (TheCall->getNumArgs() > NumArgs)
1229 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001230 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001231 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001232 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001233 (*(TheCall->arg_end()-1))->getLocEnd());
1234
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001235 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001236
Eli Friedman9ac6f622009-08-31 20:06:00 +00001237 if (OrigArg->isTypeDependent())
1238 return false;
1239
Chris Lattner81368fb2010-05-06 05:50:07 +00001240 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +00001241 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +00001242 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001243 diag::err_typecheck_call_invalid_unary_fp)
1244 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001245
Chris Lattner81368fb2010-05-06 05:50:07 +00001246 // If this is an implicit conversion from float -> double, remove it.
1247 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1248 Expr *CastArg = Cast->getSubExpr();
1249 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1250 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1251 "promotion from float to double is the only expected cast here");
1252 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +00001253 TheCall->setArg(NumArgs-1, CastArg);
1254 OrigArg = CastArg;
1255 }
1256 }
1257
Eli Friedman9ac6f622009-08-31 20:06:00 +00001258 return false;
1259}
1260
Eli Friedmand38617c2008-05-14 19:38:39 +00001261/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1262// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +00001263ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001264 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001265 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +00001266 diag::err_typecheck_call_too_few_args_at_least)
Nate Begeman37b6a572010-06-08 00:16:34 +00001267 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherd77b9a22010-04-16 04:48:22 +00001268 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001269
Nate Begeman37b6a572010-06-08 00:16:34 +00001270 // Determine which of the following types of shufflevector we're checking:
1271 // 1) unary, vector mask: (lhs, mask)
1272 // 2) binary, vector mask: (lhs, rhs, mask)
1273 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1274 QualType resType = TheCall->getArg(0)->getType();
1275 unsigned numElements = 0;
1276
Douglas Gregorcde01732009-05-19 22:10:17 +00001277 if (!TheCall->getArg(0)->isTypeDependent() &&
1278 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001279 QualType LHSType = TheCall->getArg(0)->getType();
1280 QualType RHSType = TheCall->getArg(1)->getType();
1281
1282 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001283 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001284 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001285 TheCall->getArg(1)->getLocEnd());
1286 return ExprError();
1287 }
Nate Begeman37b6a572010-06-08 00:16:34 +00001288
1289 numElements = LHSType->getAs<VectorType>()->getNumElements();
1290 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +00001291
Nate Begeman37b6a572010-06-08 00:16:34 +00001292 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1293 // with mask. If so, verify that RHS is an integer vector type with the
1294 // same number of elts as lhs.
1295 if (TheCall->getNumArgs() == 2) {
Douglas Gregorf6094622010-07-23 15:58:24 +00001296 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +00001297 RHSType->getAs<VectorType>()->getNumElements() != numElements)
1298 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
1299 << SourceRange(TheCall->getArg(1)->getLocStart(),
1300 TheCall->getArg(1)->getLocEnd());
1301 numResElements = numElements;
1302 }
1303 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001304 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001305 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001306 TheCall->getArg(1)->getLocEnd());
1307 return ExprError();
Nate Begeman37b6a572010-06-08 00:16:34 +00001308 } else if (numElements != numResElements) {
1309 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +00001310 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001311 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +00001312 }
Eli Friedmand38617c2008-05-14 19:38:39 +00001313 }
1314
1315 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001316 if (TheCall->getArg(i)->isTypeDependent() ||
1317 TheCall->getArg(i)->isValueDependent())
1318 continue;
1319
Nate Begeman37b6a572010-06-08 00:16:34 +00001320 llvm::APSInt Result(32);
1321 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1322 return ExprError(Diag(TheCall->getLocStart(),
1323 diag::err_shufflevector_nonconstant_argument)
1324 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001325
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001326 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001327 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001328 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001329 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001330 }
1331
Chris Lattner5f9e2722011-07-23 10:55:15 +00001332 SmallVector<Expr*, 32> exprs;
Eli Friedmand38617c2008-05-14 19:38:39 +00001333
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001334 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +00001335 exprs.push_back(TheCall->getArg(i));
1336 TheCall->setArg(i, 0);
1337 }
1338
Nate Begemana88dc302009-08-12 02:10:25 +00001339 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
Nate Begeman37b6a572010-06-08 00:16:34 +00001340 exprs.size(), resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001341 TheCall->getCallee()->getLocStart(),
1342 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +00001343}
Chris Lattner30ce3442007-12-19 23:59:04 +00001344
Daniel Dunbar4493f792008-07-21 22:59:13 +00001345/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1346// This is declared to take (const void*, ...) and can take two
1347// optional constant int args.
1348bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001349 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001350
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001351 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +00001352 return Diag(TheCall->getLocEnd(),
1353 diag::err_typecheck_call_too_many_args_at_most)
1354 << 0 /*function call*/ << 3 << NumArgs
1355 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001356
1357 // Argument 0 is checked for us and the remaining arguments must be
1358 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001359 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +00001360 Expr *Arg = TheCall->getArg(i);
Eric Christopher691ebc32010-04-17 02:26:23 +00001361
Eli Friedman9aef7262009-12-04 00:30:06 +00001362 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +00001363 if (SemaBuiltinConstantArg(TheCall, i, Result))
1364 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001365
Daniel Dunbar4493f792008-07-21 22:59:13 +00001366 // FIXME: gcc issues a warning and rewrites these to 0. These
1367 // seems especially odd for the third argument since the default
1368 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001369 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +00001370 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001371 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001372 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001373 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +00001374 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001375 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001376 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001377 }
1378 }
1379
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001380 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +00001381}
1382
Eric Christopher691ebc32010-04-17 02:26:23 +00001383/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1384/// TheCall is a constant expression.
1385bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1386 llvm::APSInt &Result) {
1387 Expr *Arg = TheCall->getArg(ArgNum);
1388 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1389 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1390
1391 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1392
1393 if (!Arg->isIntegerConstantExpr(Result, Context))
1394 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +00001395 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +00001396
Chris Lattner21fb98e2009-09-23 06:06:36 +00001397 return false;
1398}
1399
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001400/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1401/// int type). This simply type checks that type is one of the defined
1402/// constants (0-3).
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001403// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001404bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +00001405 llvm::APSInt Result;
1406
1407 // Check constant-ness first.
1408 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1409 return true;
1410
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001411 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001412 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001413 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1414 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001415 }
1416
1417 return false;
1418}
1419
Eli Friedman586d6a82009-05-03 06:04:26 +00001420/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +00001421/// This checks that val is a constant 1.
1422bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1423 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +00001424 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +00001425
Eric Christopher691ebc32010-04-17 02:26:23 +00001426 // TODO: This is less than ideal. Overload this to take a value.
1427 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1428 return true;
1429
1430 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +00001431 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1432 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1433
1434 return false;
1435}
1436
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001437// Handle i > 1 ? "x" : "y", recursively.
Ted Kremenek082d9362009-03-20 21:35:28 +00001438bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
1439 bool HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00001440 unsigned format_idx, unsigned firstDataArg,
Richard Trieu55733de2011-10-28 00:41:25 +00001441 bool isPrintf, bool inFunctionCall) {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001442 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +00001443 if (E->isTypeDependent() || E->isValueDependent())
1444 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001445
Peter Collingbournef111d932011-04-15 00:35:48 +00001446 E = E->IgnoreParens();
1447
Ted Kremenekd30ef872009-01-12 23:09:09 +00001448 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +00001449 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +00001450 case Stmt::ConditionalOperatorClass: {
John McCall56ca35d2011-02-17 10:25:35 +00001451 const AbstractConditionalOperator *C = cast<AbstractConditionalOperator>(E);
Ted Kremenek826a3452010-07-16 02:11:22 +00001452 return SemaCheckStringLiteral(C->getTrueExpr(), TheCall, HasVAListArg,
Richard Trieu55733de2011-10-28 00:41:25 +00001453 format_idx, firstDataArg, isPrintf,
1454 inFunctionCall)
John McCall56ca35d2011-02-17 10:25:35 +00001455 && SemaCheckStringLiteral(C->getFalseExpr(), TheCall, HasVAListArg,
Richard Trieu55733de2011-10-28 00:41:25 +00001456 format_idx, firstDataArg, isPrintf,
1457 inFunctionCall);
Ted Kremenekd30ef872009-01-12 23:09:09 +00001458 }
1459
Ted Kremenek95355bb2010-09-09 03:51:42 +00001460 case Stmt::IntegerLiteralClass:
1461 // Technically -Wformat-nonliteral does not warn about this case.
1462 // The behavior of printf and friends in this case is implementation
1463 // dependent. Ideally if the format string cannot be null then
1464 // it should have a 'nonnull' attribute in the function prototype.
1465 return true;
1466
Ted Kremenekd30ef872009-01-12 23:09:09 +00001467 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001468 E = cast<ImplicitCastExpr>(E)->getSubExpr();
1469 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001470 }
1471
John McCall56ca35d2011-02-17 10:25:35 +00001472 case Stmt::OpaqueValueExprClass:
1473 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
1474 E = src;
1475 goto tryAgain;
1476 }
1477 return false;
1478
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001479 case Stmt::PredefinedExprClass:
1480 // While __func__, etc., are technically not string literals, they
1481 // cannot contain format specifiers and thus are not a security
1482 // liability.
1483 return true;
1484
Ted Kremenek082d9362009-03-20 21:35:28 +00001485 case Stmt::DeclRefExprClass: {
1486 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001487
Ted Kremenek082d9362009-03-20 21:35:28 +00001488 // As an exception, do not flag errors for variables binding to
1489 // const string literals.
1490 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1491 bool isConstant = false;
1492 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001493
Ted Kremenek082d9362009-03-20 21:35:28 +00001494 if (const ArrayType *AT = Context.getAsArrayType(T)) {
1495 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001496 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001497 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +00001498 PT->getPointeeType().isConstant(Context);
1499 }
Mike Stump1eb44332009-09-09 15:08:12 +00001500
Ted Kremenek082d9362009-03-20 21:35:28 +00001501 if (isConstant) {
Sebastian Redl31310a22010-02-01 20:16:42 +00001502 if (const Expr *Init = VD->getAnyInitializer())
Ted Kremenek082d9362009-03-20 21:35:28 +00001503 return SemaCheckStringLiteral(Init, TheCall,
Ted Kremenek826a3452010-07-16 02:11:22 +00001504 HasVAListArg, format_idx, firstDataArg,
Richard Trieu55733de2011-10-28 00:41:25 +00001505 isPrintf, /*inFunctionCall*/false);
Ted Kremenek082d9362009-03-20 21:35:28 +00001506 }
Mike Stump1eb44332009-09-09 15:08:12 +00001507
Anders Carlssond966a552009-06-28 19:55:58 +00001508 // For vprintf* functions (i.e., HasVAListArg==true), we add a
1509 // special check to see if the format string is a function parameter
1510 // of the function calling the printf function. If the function
1511 // has an attribute indicating it is a printf-like function, then we
1512 // should suppress warnings concerning non-literals being used in a call
1513 // to a vprintf function. For example:
1514 //
1515 // void
1516 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
1517 // va_list ap;
1518 // va_start(ap, fmt);
1519 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
1520 // ...
1521 //
1522 //
1523 // FIXME: We don't have full attribute support yet, so just check to see
1524 // if the argument is a DeclRefExpr that references a parameter. We'll
1525 // add proper support for checking the attribute later.
1526 if (HasVAListArg)
1527 if (isa<ParmVarDecl>(VD))
1528 return true;
Ted Kremenek082d9362009-03-20 21:35:28 +00001529 }
Mike Stump1eb44332009-09-09 15:08:12 +00001530
Ted Kremenek082d9362009-03-20 21:35:28 +00001531 return false;
1532 }
Ted Kremenekd30ef872009-01-12 23:09:09 +00001533
Anders Carlsson8f031b32009-06-27 04:05:33 +00001534 case Stmt::CallExprClass: {
1535 const CallExpr *CE = cast<CallExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001536 if (const ImplicitCastExpr *ICE
Anders Carlsson8f031b32009-06-27 04:05:33 +00001537 = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
1538 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
1539 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001540 if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
Anders Carlsson8f031b32009-06-27 04:05:33 +00001541 unsigned ArgIndex = FA->getFormatIdx();
1542 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001543
1544 return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg,
Richard Trieu55733de2011-10-28 00:41:25 +00001545 format_idx, firstDataArg, isPrintf,
1546 inFunctionCall);
Anders Carlsson8f031b32009-06-27 04:05:33 +00001547 }
1548 }
1549 }
1550 }
Mike Stump1eb44332009-09-09 15:08:12 +00001551
Anders Carlsson8f031b32009-06-27 04:05:33 +00001552 return false;
1553 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001554 case Stmt::ObjCStringLiteralClass:
1555 case Stmt::StringLiteralClass: {
1556 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001557
Ted Kremenek082d9362009-03-20 21:35:28 +00001558 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00001559 StrE = ObjCFExpr->getString();
1560 else
Ted Kremenek082d9362009-03-20 21:35:28 +00001561 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001562
Ted Kremenekd30ef872009-01-12 23:09:09 +00001563 if (StrE) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001564 CheckFormatString(StrE, E, TheCall, HasVAListArg, format_idx,
Richard Trieu55733de2011-10-28 00:41:25 +00001565 firstDataArg, isPrintf, inFunctionCall);
Ted Kremenekd30ef872009-01-12 23:09:09 +00001566 return true;
1567 }
Mike Stump1eb44332009-09-09 15:08:12 +00001568
Ted Kremenekd30ef872009-01-12 23:09:09 +00001569 return false;
1570 }
Mike Stump1eb44332009-09-09 15:08:12 +00001571
Ted Kremenek082d9362009-03-20 21:35:28 +00001572 default:
1573 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001574 }
1575}
1576
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001577void
Mike Stump1eb44332009-09-09 15:08:12 +00001578Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewycky909a70d2011-03-25 01:44:32 +00001579 const Expr * const *ExprArgs,
1580 SourceLocation CallSiteLoc) {
Sean Huntcf807c42010-08-18 23:23:40 +00001581 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1582 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001583 i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +00001584 const Expr *ArgExpr = ExprArgs[*i];
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001585 if (ArgExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00001586 Expr::NPC_ValueDependentIsNotNull))
Nick Lewycky909a70d2011-03-25 01:44:32 +00001587 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001588 }
1589}
Ted Kremenekd30ef872009-01-12 23:09:09 +00001590
Ted Kremenek826a3452010-07-16 02:11:22 +00001591/// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar
1592/// functions) for correct use of format strings.
Chris Lattner59907c42007-08-10 20:18:51 +00001593void
Ted Kremenek826a3452010-07-16 02:11:22 +00001594Sema::CheckPrintfScanfArguments(const CallExpr *TheCall, bool HasVAListArg,
1595 unsigned format_idx, unsigned firstDataArg,
1596 bool isPrintf) {
1597
Ted Kremenek082d9362009-03-20 21:35:28 +00001598 const Expr *Fn = TheCall->getCallee();
Chris Lattner925e60d2007-12-28 05:29:59 +00001599
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001600 // The way the format attribute works in GCC, the implicit this argument
1601 // of member functions is counted. However, it doesn't appear in our own
1602 // lists, so decrement format_idx in that case.
1603 if (isa<CXXMemberCallExpr>(TheCall)) {
Chandler Carruth9263a302010-11-16 08:49:43 +00001604 const CXXMethodDecl *method_decl =
1605 dyn_cast<CXXMethodDecl>(TheCall->getCalleeDecl());
1606 if (method_decl && method_decl->isInstance()) {
1607 // Catch a format attribute mistakenly referring to the object argument.
1608 if (format_idx == 0)
1609 return;
1610 --format_idx;
1611 if(firstDataArg != 0)
1612 --firstDataArg;
1613 }
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001614 }
1615
Ted Kremenek826a3452010-07-16 02:11:22 +00001616 // CHECK: printf/scanf-like function is called with no format string.
Chris Lattner925e60d2007-12-28 05:29:59 +00001617 if (format_idx >= TheCall->getNumArgs()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001618 Diag(TheCall->getRParenLoc(), diag::warn_missing_format_string)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001619 << Fn->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001620 return;
1621 }
Mike Stump1eb44332009-09-09 15:08:12 +00001622
Ted Kremenek082d9362009-03-20 21:35:28 +00001623 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001624
Chris Lattner59907c42007-08-10 20:18:51 +00001625 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001626 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001627 // Dynamically generated format strings are difficult to
1628 // automatically vet at compile time. Requiring that format strings
1629 // are string literals: (1) permits the checking of format strings by
1630 // the compiler and thereby (2) can practically remove the source of
1631 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001632
Mike Stump1eb44332009-09-09 15:08:12 +00001633 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001634 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001635 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001636 // the same format string checking logic for both ObjC and C strings.
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001637 if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
Ted Kremenek826a3452010-07-16 02:11:22 +00001638 firstDataArg, isPrintf))
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001639 return; // Literal format string found, check done!
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001640
Chris Lattner655f1412009-04-29 04:59:47 +00001641 // If there are no arguments specified, warn with -Wformat-security, otherwise
1642 // warn only with -Wformat-nonliteral.
1643 if (TheCall->getNumArgs() == format_idx+1)
Mike Stump1eb44332009-09-09 15:08:12 +00001644 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001645 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00001646 << OrigFormatExpr->getSourceRange();
1647 else
Mike Stump1eb44332009-09-09 15:08:12 +00001648 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001649 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00001650 << OrigFormatExpr->getSourceRange();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001651}
Ted Kremenek71895b92007-08-14 17:39:48 +00001652
Ted Kremeneke0e53132010-01-28 23:39:18 +00001653namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00001654class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1655protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00001656 Sema &S;
1657 const StringLiteral *FExpr;
1658 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00001659 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001660 const unsigned NumDataArgs;
1661 const bool IsObjCLiteral;
1662 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00001663 const bool HasVAListArg;
1664 const CallExpr *TheCall;
1665 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001666 llvm::BitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00001667 bool usesPositionalArgs;
1668 bool atFirstArg;
Richard Trieu55733de2011-10-28 00:41:25 +00001669 bool inFunctionCall;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001670public:
Ted Kremenek826a3452010-07-16 02:11:22 +00001671 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00001672 const Expr *origFormatExpr, unsigned firstDataArg,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001673 unsigned numDataArgs, bool isObjCLiteral,
Ted Kremenek0d277352010-01-29 01:06:55 +00001674 const char *beg, bool hasVAListArg,
Richard Trieu55733de2011-10-28 00:41:25 +00001675 const CallExpr *theCall, unsigned formatIdx,
1676 bool inFunctionCall)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001677 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Ted Kremenek6ee76532010-03-25 03:59:12 +00001678 FirstDataArg(firstDataArg),
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001679 NumDataArgs(numDataArgs),
Ted Kremenek0d277352010-01-29 01:06:55 +00001680 IsObjCLiteral(isObjCLiteral), Beg(beg),
1681 HasVAListArg(hasVAListArg),
Ted Kremenekefaff192010-02-27 01:41:03 +00001682 TheCall(theCall), FormatIdx(formatIdx),
Richard Trieu55733de2011-10-28 00:41:25 +00001683 usesPositionalArgs(false), atFirstArg(true),
1684 inFunctionCall(inFunctionCall) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001685 CoveredArgs.resize(numDataArgs);
1686 CoveredArgs.reset();
1687 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001688
Ted Kremenek07d161f2010-01-29 01:50:07 +00001689 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001690
Ted Kremenek826a3452010-07-16 02:11:22 +00001691 void HandleIncompleteSpecifier(const char *startSpecifier,
1692 unsigned specifierLen);
1693
Ted Kremenekefaff192010-02-27 01:41:03 +00001694 virtual void HandleInvalidPosition(const char *startSpecifier,
1695 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00001696 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00001697
1698 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1699
Ted Kremeneke0e53132010-01-28 23:39:18 +00001700 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001701
Richard Trieu55733de2011-10-28 00:41:25 +00001702 template <typename Range>
1703 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
1704 const Expr *ArgumentExpr,
1705 PartialDiagnostic PDiag,
1706 SourceLocation StringLoc,
1707 bool IsStringLocation, Range StringRange,
1708 FixItHint Fixit = FixItHint());
1709
Ted Kremenek826a3452010-07-16 02:11:22 +00001710protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001711 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
1712 const char *startSpec,
1713 unsigned specifierLen,
1714 const char *csStart, unsigned csLen);
Richard Trieu55733de2011-10-28 00:41:25 +00001715
1716 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
1717 const char *startSpec,
1718 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001719
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001720 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00001721 CharSourceRange getSpecifierRange(const char *startSpecifier,
1722 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001723 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001724
Ted Kremenek0d277352010-01-29 01:06:55 +00001725 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00001726
1727 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
1728 const analyze_format_string::ConversionSpecifier &CS,
1729 const char *startSpecifier, unsigned specifierLen,
1730 unsigned argIndex);
Richard Trieu55733de2011-10-28 00:41:25 +00001731
1732 template <typename Range>
1733 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
1734 bool IsStringLocation, Range StringRange,
1735 FixItHint Fixit = FixItHint());
1736
1737 void CheckPositionalAndNonpositionalArgs(
1738 const analyze_format_string::FormatSpecifier *FS);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001739};
1740}
1741
Ted Kremenek826a3452010-07-16 02:11:22 +00001742SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00001743 return OrigFormatExpr->getSourceRange();
1744}
1745
Ted Kremenek826a3452010-07-16 02:11:22 +00001746CharSourceRange CheckFormatHandler::
1747getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00001748 SourceLocation Start = getLocationOfByte(startSpecifier);
1749 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
1750
1751 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001752 End = End.getLocWithOffset(1);
Tom Care45f9b7e2010-06-21 21:21:01 +00001753
1754 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001755}
1756
Ted Kremenek826a3452010-07-16 02:11:22 +00001757SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001758 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001759}
1760
Ted Kremenek826a3452010-07-16 02:11:22 +00001761void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
1762 unsigned specifierLen){
Richard Trieu55733de2011-10-28 00:41:25 +00001763 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
1764 getLocationOfByte(startSpecifier),
1765 /*IsStringLocation*/true,
1766 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek808015a2010-01-29 03:16:21 +00001767}
1768
Ted Kremenekefaff192010-02-27 01:41:03 +00001769void
Ted Kremenek826a3452010-07-16 02:11:22 +00001770CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
1771 analyze_format_string::PositionContext p) {
Richard Trieu55733de2011-10-28 00:41:25 +00001772 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
1773 << (unsigned) p,
1774 getLocationOfByte(startPos), /*IsStringLocation*/true,
1775 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00001776}
1777
Ted Kremenek826a3452010-07-16 02:11:22 +00001778void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00001779 unsigned posLen) {
Richard Trieu55733de2011-10-28 00:41:25 +00001780 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
1781 getLocationOfByte(startPos),
1782 /*IsStringLocation*/true,
1783 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00001784}
1785
Ted Kremenek826a3452010-07-16 02:11:22 +00001786void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Ted Kremenek0c069442011-03-15 21:18:48 +00001787 if (!IsObjCLiteral) {
1788 // The presence of a null character is likely an error.
Richard Trieu55733de2011-10-28 00:41:25 +00001789 EmitFormatDiagnostic(
1790 S.PDiag(diag::warn_printf_format_string_contains_null_char),
1791 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
1792 getFormatStringRange());
Ted Kremenek0c069442011-03-15 21:18:48 +00001793 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001794}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001795
Ted Kremenek826a3452010-07-16 02:11:22 +00001796const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
1797 return TheCall->getArg(FirstDataArg + i);
1798}
1799
1800void CheckFormatHandler::DoneProcessing() {
1801 // Does the number of data arguments exceed the number of
1802 // format conversions in the format string?
1803 if (!HasVAListArg) {
1804 // Find any arguments that weren't covered.
1805 CoveredArgs.flip();
1806 signed notCoveredArg = CoveredArgs.find_first();
1807 if (notCoveredArg >= 0) {
1808 assert((unsigned)notCoveredArg < NumDataArgs);
Richard Trieu55733de2011-10-28 00:41:25 +00001809 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
1810 getDataArg((unsigned) notCoveredArg)->getLocStart(),
1811 /*IsStringLocation*/false, getFormatStringRange());
Ted Kremenek826a3452010-07-16 02:11:22 +00001812 }
1813 }
1814}
1815
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001816bool
1817CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
1818 SourceLocation Loc,
1819 const char *startSpec,
1820 unsigned specifierLen,
1821 const char *csStart,
1822 unsigned csLen) {
1823
1824 bool keepGoing = true;
1825 if (argIndex < NumDataArgs) {
1826 // Consider the argument coverered, even though the specifier doesn't
1827 // make sense.
1828 CoveredArgs.set(argIndex);
1829 }
1830 else {
1831 // If argIndex exceeds the number of data arguments we
1832 // don't issue a warning because that is just a cascade of warnings (and
1833 // they may have intended '%%' anyway). We don't want to continue processing
1834 // the format string after this point, however, as we will like just get
1835 // gibberish when trying to match arguments.
1836 keepGoing = false;
1837 }
1838
Richard Trieu55733de2011-10-28 00:41:25 +00001839 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
1840 << StringRef(csStart, csLen),
1841 Loc, /*IsStringLocation*/true,
1842 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001843
1844 return keepGoing;
1845}
1846
Richard Trieu55733de2011-10-28 00:41:25 +00001847void
1848CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
1849 const char *startSpec,
1850 unsigned specifierLen) {
1851 EmitFormatDiagnostic(
1852 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
1853 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
1854}
1855
Ted Kremenek666a1972010-07-26 19:45:42 +00001856bool
1857CheckFormatHandler::CheckNumArgs(
1858 const analyze_format_string::FormatSpecifier &FS,
1859 const analyze_format_string::ConversionSpecifier &CS,
1860 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
1861
1862 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00001863 PartialDiagnostic PDiag = FS.usesPositionalArg()
1864 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
1865 << (argIndex+1) << NumDataArgs)
1866 : S.PDiag(diag::warn_printf_insufficient_data_args);
1867 EmitFormatDiagnostic(
1868 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
1869 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek666a1972010-07-26 19:45:42 +00001870 return false;
1871 }
1872 return true;
1873}
1874
Richard Trieu55733de2011-10-28 00:41:25 +00001875template<typename Range>
1876void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
1877 SourceLocation Loc,
1878 bool IsStringLocation,
1879 Range StringRange,
1880 FixItHint FixIt) {
1881 EmitFormatDiagnostic(S, inFunctionCall, TheCall->getArg(FormatIdx), PDiag,
1882 Loc, IsStringLocation, StringRange, FixIt);
1883}
1884
1885/// \brief If the format string is not within the funcion call, emit a note
1886/// so that the function call and string are in diagnostic messages.
1887///
1888/// \param inFunctionCall if true, the format string is within the function
1889/// call and only one diagnostic message will be produced. Otherwise, an
1890/// extra note will be emitted pointing to location of the format string.
1891///
1892/// \param ArgumentExpr the expression that is passed as the format string
1893/// argument in the function call. Used for getting locations when two
1894/// diagnostics are emitted.
1895///
1896/// \param PDiag the callee should already have provided any strings for the
1897/// diagnostic message. This function only adds locations and fixits
1898/// to diagnostics.
1899///
1900/// \param Loc primary location for diagnostic. If two diagnostics are
1901/// required, one will be at Loc and a new SourceLocation will be created for
1902/// the other one.
1903///
1904/// \param IsStringLocation if true, Loc points to the format string should be
1905/// used for the note. Otherwise, Loc points to the argument list and will
1906/// be used with PDiag.
1907///
1908/// \param StringRange some or all of the string to highlight. This is
1909/// templated so it can accept either a CharSourceRange or a SourceRange.
1910///
1911/// \param Fixit optional fix it hint for the format string.
1912template<typename Range>
1913void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
1914 const Expr *ArgumentExpr,
1915 PartialDiagnostic PDiag,
1916 SourceLocation Loc,
1917 bool IsStringLocation,
1918 Range StringRange,
1919 FixItHint FixIt) {
1920 if (InFunctionCall)
1921 S.Diag(Loc, PDiag) << StringRange << FixIt;
1922 else {
1923 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
1924 << ArgumentExpr->getSourceRange();
1925 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
1926 diag::note_format_string_defined)
1927 << StringRange << FixIt;
1928 }
1929}
1930
Ted Kremenek826a3452010-07-16 02:11:22 +00001931//===--- CHECK: Printf format string checking ------------------------------===//
1932
1933namespace {
1934class CheckPrintfHandler : public CheckFormatHandler {
1935public:
1936 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
1937 const Expr *origFormatExpr, unsigned firstDataArg,
1938 unsigned numDataArgs, bool isObjCLiteral,
1939 const char *beg, bool hasVAListArg,
Richard Trieu55733de2011-10-28 00:41:25 +00001940 const CallExpr *theCall, unsigned formatIdx,
1941 bool inFunctionCall)
Ted Kremenek826a3452010-07-16 02:11:22 +00001942 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1943 numDataArgs, isObjCLiteral, beg, hasVAListArg,
Richard Trieu55733de2011-10-28 00:41:25 +00001944 theCall, formatIdx, inFunctionCall) {}
Ted Kremenek826a3452010-07-16 02:11:22 +00001945
1946
1947 bool HandleInvalidPrintfConversionSpecifier(
1948 const analyze_printf::PrintfSpecifier &FS,
1949 const char *startSpecifier,
1950 unsigned specifierLen);
1951
1952 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
1953 const char *startSpecifier,
1954 unsigned specifierLen);
1955
1956 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
1957 const char *startSpecifier, unsigned specifierLen);
1958 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
1959 const analyze_printf::OptionalAmount &Amt,
1960 unsigned type,
1961 const char *startSpecifier, unsigned specifierLen);
1962 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
1963 const analyze_printf::OptionalFlag &flag,
1964 const char *startSpecifier, unsigned specifierLen);
1965 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
1966 const analyze_printf::OptionalFlag &ignoredFlag,
1967 const analyze_printf::OptionalFlag &flag,
1968 const char *startSpecifier, unsigned specifierLen);
1969};
1970}
1971
1972bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
1973 const analyze_printf::PrintfSpecifier &FS,
1974 const char *startSpecifier,
1975 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001976 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001977 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00001978
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001979 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1980 getLocationOfByte(CS.getStart()),
1981 startSpecifier, specifierLen,
1982 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001983}
1984
Ted Kremenek826a3452010-07-16 02:11:22 +00001985bool CheckPrintfHandler::HandleAmount(
1986 const analyze_format_string::OptionalAmount &Amt,
1987 unsigned k, const char *startSpecifier,
1988 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001989
1990 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001991 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001992 unsigned argIndex = Amt.getArgIndex();
1993 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00001994 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
1995 << k,
1996 getLocationOfByte(Amt.getStart()),
1997 /*IsStringLocation*/true,
1998 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00001999 // Don't do any more checking. We will just emit
2000 // spurious errors.
2001 return false;
2002 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002003
Ted Kremenek0d277352010-01-29 01:06:55 +00002004 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00002005 // Although not in conformance with C99, we also allow the argument to be
2006 // an 'unsigned int' as that is a reasonably safe case. GCC also
2007 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002008 CoveredArgs.set(argIndex);
2009 const Expr *Arg = getDataArg(argIndex);
Ted Kremenek0d277352010-01-29 01:06:55 +00002010 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002011
2012 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
2013 assert(ATR.isValid());
2014
2015 if (!ATR.matchesType(S.Context, T)) {
Richard Trieu55733de2011-10-28 00:41:25 +00002016 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborga792aff2011-12-07 10:33:11 +00002017 << k << ATR.getRepresentativeTypeName(S.Context)
Richard Trieu55733de2011-10-28 00:41:25 +00002018 << T << Arg->getSourceRange(),
2019 getLocationOfByte(Amt.getStart()),
2020 /*IsStringLocation*/true,
2021 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002022 // Don't do any more checking. We will just emit
2023 // spurious errors.
2024 return false;
2025 }
2026 }
2027 }
2028 return true;
2029}
Ted Kremenek0d277352010-01-29 01:06:55 +00002030
Tom Caree4ee9662010-06-17 19:00:27 +00002031void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00002032 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002033 const analyze_printf::OptionalAmount &Amt,
2034 unsigned type,
2035 const char *startSpecifier,
2036 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002037 const analyze_printf::PrintfConversionSpecifier &CS =
2038 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00002039
Richard Trieu55733de2011-10-28 00:41:25 +00002040 FixItHint fixit =
2041 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2042 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2043 Amt.getConstantLength()))
2044 : FixItHint();
2045
2046 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2047 << type << CS.toString(),
2048 getLocationOfByte(Amt.getStart()),
2049 /*IsStringLocation*/true,
2050 getSpecifierRange(startSpecifier, specifierLen),
2051 fixit);
Tom Caree4ee9662010-06-17 19:00:27 +00002052}
2053
Ted Kremenek826a3452010-07-16 02:11:22 +00002054void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002055 const analyze_printf::OptionalFlag &flag,
2056 const char *startSpecifier,
2057 unsigned specifierLen) {
2058 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002059 const analyze_printf::PrintfConversionSpecifier &CS =
2060 FS.getConversionSpecifier();
Richard Trieu55733de2011-10-28 00:41:25 +00002061 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2062 << flag.toString() << CS.toString(),
2063 getLocationOfByte(flag.getPosition()),
2064 /*IsStringLocation*/true,
2065 getSpecifierRange(startSpecifier, specifierLen),
2066 FixItHint::CreateRemoval(
2067 getSpecifierRange(flag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002068}
2069
2070void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00002071 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002072 const analyze_printf::OptionalFlag &ignoredFlag,
2073 const analyze_printf::OptionalFlag &flag,
2074 const char *startSpecifier,
2075 unsigned specifierLen) {
2076 // Warn about ignored flag with a fixit removal.
Richard Trieu55733de2011-10-28 00:41:25 +00002077 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2078 << ignoredFlag.toString() << flag.toString(),
2079 getLocationOfByte(ignoredFlag.getPosition()),
2080 /*IsStringLocation*/true,
2081 getSpecifierRange(startSpecifier, specifierLen),
2082 FixItHint::CreateRemoval(
2083 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002084}
2085
Ted Kremeneke0e53132010-01-28 23:39:18 +00002086bool
Ted Kremenek826a3452010-07-16 02:11:22 +00002087CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00002088 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00002089 const char *startSpecifier,
2090 unsigned specifierLen) {
2091
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002092 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00002093 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002094 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00002095
Ted Kremenekbaa40062010-07-19 22:01:06 +00002096 if (FS.consumesDataArgument()) {
2097 if (atFirstArg) {
2098 atFirstArg = false;
2099 usesPositionalArgs = FS.usesPositionalArg();
2100 }
2101 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002102 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2103 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002104 return false;
2105 }
Ted Kremenek0d277352010-01-29 01:06:55 +00002106 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002107
Ted Kremenekefaff192010-02-27 01:41:03 +00002108 // First check if the field width, precision, and conversion specifier
2109 // have matching data arguments.
2110 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2111 startSpecifier, specifierLen)) {
2112 return false;
2113 }
2114
2115 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2116 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002117 return false;
2118 }
2119
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002120 if (!CS.consumesDataArgument()) {
2121 // FIXME: Technically specifying a precision or field width here
2122 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002123 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002124 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002125
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002126 // Consume the argument.
2127 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00002128 if (argIndex < NumDataArgs) {
2129 // The check to see if the argIndex is valid will come later.
2130 // We set the bit here because we may exit early from this
2131 // function if we encounter some other error.
2132 CoveredArgs.set(argIndex);
2133 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002134
2135 // Check for using an Objective-C specific conversion specifier
2136 // in a non-ObjC literal.
2137 if (!IsObjCLiteral && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002138 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
2139 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002140 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002141
Tom Caree4ee9662010-06-17 19:00:27 +00002142 // Check for invalid use of field width
2143 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002144 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00002145 startSpecifier, specifierLen);
2146 }
2147
2148 // Check for invalid use of precision
2149 if (!FS.hasValidPrecision()) {
2150 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
2151 startSpecifier, specifierLen);
2152 }
2153
2154 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00002155 if (!FS.hasValidThousandsGroupingPrefix())
2156 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002157 if (!FS.hasValidLeadingZeros())
2158 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
2159 if (!FS.hasValidPlusPrefix())
2160 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00002161 if (!FS.hasValidSpacePrefix())
2162 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002163 if (!FS.hasValidAlternativeForm())
2164 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
2165 if (!FS.hasValidLeftJustified())
2166 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
2167
2168 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00002169 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
2170 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
2171 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002172 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
2173 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
2174 startSpecifier, specifierLen);
2175
2176 // Check the length modifier is valid with the given conversion specifier.
2177 const LengthModifier &LM = FS.getLengthModifier();
2178 if (!FS.hasValidLengthModifier())
Richard Trieu55733de2011-10-28 00:41:25 +00002179 EmitFormatDiagnostic(S.PDiag(diag::warn_format_nonsensical_length)
2180 << LM.toString() << CS.toString(),
2181 getLocationOfByte(LM.getStart()),
2182 /*IsStringLocation*/true,
2183 getSpecifierRange(startSpecifier, specifierLen),
2184 FixItHint::CreateRemoval(
2185 getSpecifierRange(LM.getStart(),
2186 LM.getLength())));
Tom Caree4ee9662010-06-17 19:00:27 +00002187
2188 // Are we using '%n'?
Ted Kremenek35d353b2010-07-20 20:04:10 +00002189 if (CS.getKind() == ConversionSpecifier::nArg) {
Tom Caree4ee9662010-06-17 19:00:27 +00002190 // Issue a warning about this being a possible security issue.
Richard Trieu55733de2011-10-28 00:41:25 +00002191 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_write_back),
2192 getLocationOfByte(CS.getStart()),
2193 /*IsStringLocation*/true,
2194 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremeneke82d8042010-01-29 01:35:25 +00002195 // Continue checking the other format specifiers.
2196 return true;
2197 }
Ted Kremenek5c41ee82010-02-11 09:27:41 +00002198
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002199 // The remaining checks depend on the data arguments.
2200 if (HasVAListArg)
2201 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002202
Ted Kremenek666a1972010-07-26 19:45:42 +00002203 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002204 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002205
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002206 // Now type check the data expression that matches the
2207 // format specifier.
2208 const Expr *Ex = getDataArg(argIndex);
Nick Lewycky687b5df2011-12-02 23:21:43 +00002209 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002210 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
2211 // Check if we didn't match because of an implicit cast from a 'char'
2212 // or 'short' to an 'int'. This is done because printf is a varargs
2213 // function.
2214 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00002215 if (ICE->getType() == S.Context.IntTy) {
2216 // All further checking is done on the subexpression.
2217 Ex = ICE->getSubExpr();
2218 if (ATR.matchesType(S.Context, Ex->getType()))
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002219 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00002220 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002221
2222 // We may be able to offer a FixItHint if it is a supported type.
2223 PrintfSpecifier fixedFS = FS;
Hans Wennborga7da2152011-10-18 08:10:06 +00002224 bool success = fixedFS.fixType(Ex->getType(), S.getLangOptions());
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002225
2226 if (success) {
2227 // Get the fix string from the fixed format specifier
2228 llvm::SmallString<128> buf;
2229 llvm::raw_svector_ostream os(buf);
2230 fixedFS.toString(os);
2231
Richard Trieu55733de2011-10-28 00:41:25 +00002232 EmitFormatDiagnostic(
2233 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborga792aff2011-12-07 10:33:11 +00002234 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
Richard Trieu55733de2011-10-28 00:41:25 +00002235 << Ex->getSourceRange(),
2236 getLocationOfByte(CS.getStart()),
2237 /*IsStringLocation*/true,
2238 getSpecifierRange(startSpecifier, specifierLen),
2239 FixItHint::CreateReplacement(
2240 getSpecifierRange(startSpecifier, specifierLen),
2241 os.str()));
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002242 }
2243 else {
2244 S.Diag(getLocationOfByte(CS.getStart()),
2245 diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborga792aff2011-12-07 10:33:11 +00002246 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002247 << getSpecifierRange(startSpecifier, specifierLen)
2248 << Ex->getSourceRange();
2249 }
2250 }
2251
Ted Kremeneke0e53132010-01-28 23:39:18 +00002252 return true;
2253}
2254
Ted Kremenek826a3452010-07-16 02:11:22 +00002255//===--- CHECK: Scanf format string checking ------------------------------===//
2256
2257namespace {
2258class CheckScanfHandler : public CheckFormatHandler {
2259public:
2260 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
2261 const Expr *origFormatExpr, unsigned firstDataArg,
2262 unsigned numDataArgs, bool isObjCLiteral,
2263 const char *beg, bool hasVAListArg,
Richard Trieu55733de2011-10-28 00:41:25 +00002264 const CallExpr *theCall, unsigned formatIdx,
2265 bool inFunctionCall)
Ted Kremenek826a3452010-07-16 02:11:22 +00002266 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2267 numDataArgs, isObjCLiteral, beg, hasVAListArg,
Richard Trieu55733de2011-10-28 00:41:25 +00002268 theCall, formatIdx, inFunctionCall) {}
Ted Kremenek826a3452010-07-16 02:11:22 +00002269
2270 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
2271 const char *startSpecifier,
2272 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002273
2274 bool HandleInvalidScanfConversionSpecifier(
2275 const analyze_scanf::ScanfSpecifier &FS,
2276 const char *startSpecifier,
2277 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00002278
2279 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00002280};
Ted Kremenek07d161f2010-01-29 01:50:07 +00002281}
Ted Kremeneke0e53132010-01-28 23:39:18 +00002282
Ted Kremenekb7c21012010-07-16 18:28:03 +00002283void CheckScanfHandler::HandleIncompleteScanList(const char *start,
2284 const char *end) {
Richard Trieu55733de2011-10-28 00:41:25 +00002285 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
2286 getLocationOfByte(end), /*IsStringLocation*/true,
2287 getSpecifierRange(start, end - start));
Ted Kremenekb7c21012010-07-16 18:28:03 +00002288}
2289
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002290bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
2291 const analyze_scanf::ScanfSpecifier &FS,
2292 const char *startSpecifier,
2293 unsigned specifierLen) {
2294
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002295 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002296 FS.getConversionSpecifier();
2297
2298 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2299 getLocationOfByte(CS.getStart()),
2300 startSpecifier, specifierLen,
2301 CS.getStart(), CS.getLength());
2302}
2303
Ted Kremenek826a3452010-07-16 02:11:22 +00002304bool CheckScanfHandler::HandleScanfSpecifier(
2305 const analyze_scanf::ScanfSpecifier &FS,
2306 const char *startSpecifier,
2307 unsigned specifierLen) {
2308
2309 using namespace analyze_scanf;
2310 using namespace analyze_format_string;
2311
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002312 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002313
Ted Kremenekbaa40062010-07-19 22:01:06 +00002314 // Handle case where '%' and '*' don't consume an argument. These shouldn't
2315 // be used to decide if we are using positional arguments consistently.
2316 if (FS.consumesDataArgument()) {
2317 if (atFirstArg) {
2318 atFirstArg = false;
2319 usesPositionalArgs = FS.usesPositionalArg();
2320 }
2321 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002322 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2323 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002324 return false;
2325 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002326 }
2327
2328 // Check if the field with is non-zero.
2329 const OptionalAmount &Amt = FS.getFieldWidth();
2330 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
2331 if (Amt.getConstantAmount() == 0) {
2332 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
2333 Amt.getConstantLength());
Richard Trieu55733de2011-10-28 00:41:25 +00002334 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
2335 getLocationOfByte(Amt.getStart()),
2336 /*IsStringLocation*/true, R,
2337 FixItHint::CreateRemoval(R));
Ted Kremenek826a3452010-07-16 02:11:22 +00002338 }
2339 }
2340
2341 if (!FS.consumesDataArgument()) {
2342 // FIXME: Technically specifying a precision or field width here
2343 // makes no sense. Worth issuing a warning at some point.
2344 return true;
2345 }
2346
2347 // Consume the argument.
2348 unsigned argIndex = FS.getArgIndex();
2349 if (argIndex < NumDataArgs) {
2350 // The check to see if the argIndex is valid will come later.
2351 // We set the bit here because we may exit early from this
2352 // function if we encounter some other error.
2353 CoveredArgs.set(argIndex);
2354 }
2355
Ted Kremenek1e51c202010-07-20 20:04:47 +00002356 // Check the length modifier is valid with the given conversion specifier.
2357 const LengthModifier &LM = FS.getLengthModifier();
2358 if (!FS.hasValidLengthModifier()) {
2359 S.Diag(getLocationOfByte(LM.getStart()),
2360 diag::warn_format_nonsensical_length)
2361 << LM.toString() << CS.toString()
2362 << getSpecifierRange(startSpecifier, specifierLen)
2363 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
2364 LM.getLength()));
2365 }
2366
Ted Kremenek826a3452010-07-16 02:11:22 +00002367 // The remaining checks depend on the data arguments.
2368 if (HasVAListArg)
2369 return true;
2370
Ted Kremenek666a1972010-07-26 19:45:42 +00002371 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00002372 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00002373
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002374 // Check that the argument type matches the format specifier.
2375 const Expr *Ex = getDataArg(argIndex);
2376 const analyze_scanf::ScanfArgTypeResult &ATR = FS.getArgType(S.Context);
2377 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
2378 ScanfSpecifier fixedFS = FS;
2379 bool success = fixedFS.fixType(Ex->getType(), S.getLangOptions());
2380
2381 if (success) {
2382 // Get the fix string from the fixed format specifier.
2383 llvm::SmallString<128> buf;
2384 llvm::raw_svector_ostream os(buf);
2385 fixedFS.toString(os);
2386
2387 EmitFormatDiagnostic(
2388 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2389 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
2390 << Ex->getSourceRange(),
2391 getLocationOfByte(CS.getStart()),
2392 /*IsStringLocation*/true,
2393 getSpecifierRange(startSpecifier, specifierLen),
2394 FixItHint::CreateReplacement(
2395 getSpecifierRange(startSpecifier, specifierLen),
2396 os.str()));
2397 } else {
2398 S.Diag(getLocationOfByte(CS.getStart()),
2399 diag::warn_printf_conversion_argument_type_mismatch)
2400 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
2401 << getSpecifierRange(startSpecifier, specifierLen)
2402 << Ex->getSourceRange();
2403 }
2404 }
2405
Ted Kremenek826a3452010-07-16 02:11:22 +00002406 return true;
2407}
2408
2409void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002410 const Expr *OrigFormatExpr,
2411 const CallExpr *TheCall, bool HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00002412 unsigned format_idx, unsigned firstDataArg,
Richard Trieu55733de2011-10-28 00:41:25 +00002413 bool isPrintf, bool inFunctionCall) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002414
Ted Kremeneke0e53132010-01-28 23:39:18 +00002415 // CHECK: is the format string a wide literal?
Douglas Gregor5cee1192011-07-27 05:40:30 +00002416 if (!FExpr->isAscii()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002417 CheckFormatHandler::EmitFormatDiagnostic(
2418 *this, inFunctionCall, TheCall->getArg(format_idx),
2419 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
2420 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00002421 return;
2422 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002423
Ted Kremeneke0e53132010-01-28 23:39:18 +00002424 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner5f9e2722011-07-23 10:55:15 +00002425 StringRef StrRef = FExpr->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00002426 const char *Str = StrRef.data();
2427 unsigned StrLen = StrRef.size();
Ted Kremenek4cd57912011-09-29 05:52:16 +00002428 const unsigned numDataArgs = TheCall->getNumArgs() - firstDataArg;
Ted Kremenek826a3452010-07-16 02:11:22 +00002429
Ted Kremeneke0e53132010-01-28 23:39:18 +00002430 // CHECK: empty format string?
Ted Kremenek4cd57912011-09-29 05:52:16 +00002431 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu55733de2011-10-28 00:41:25 +00002432 CheckFormatHandler::EmitFormatDiagnostic(
2433 *this, inFunctionCall, TheCall->getArg(format_idx),
2434 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
2435 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00002436 return;
2437 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002438
2439 if (isPrintf) {
2440 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Ted Kremenek4cd57912011-09-29 05:52:16 +00002441 numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr),
Richard Trieu55733de2011-10-28 00:41:25 +00002442 Str, HasVAListArg, TheCall, format_idx,
2443 inFunctionCall);
Ted Kremenek826a3452010-07-16 02:11:22 +00002444
Hans Wennborgd02deeb2011-12-15 10:25:47 +00002445 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
2446 getLangOptions()))
Ted Kremenek826a3452010-07-16 02:11:22 +00002447 H.DoneProcessing();
2448 }
2449 else {
2450 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Ted Kremenek4cd57912011-09-29 05:52:16 +00002451 numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr),
Richard Trieu55733de2011-10-28 00:41:25 +00002452 Str, HasVAListArg, TheCall, format_idx,
2453 inFunctionCall);
Ted Kremenek826a3452010-07-16 02:11:22 +00002454
Hans Wennborgd02deeb2011-12-15 10:25:47 +00002455 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
2456 getLangOptions()))
Ted Kremenek826a3452010-07-16 02:11:22 +00002457 H.DoneProcessing();
2458 }
Ted Kremenekce7024e2010-01-28 01:18:22 +00002459}
2460
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002461//===--- CHECK: Standard memory functions ---------------------------------===//
2462
Douglas Gregor2a053a32011-05-03 20:05:22 +00002463/// \brief Determine whether the given type is a dynamic class type (e.g.,
2464/// whether it has a vtable).
2465static bool isDynamicClassType(QualType T) {
2466 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
2467 if (CXXRecordDecl *Definition = Record->getDefinition())
2468 if (Definition->isDynamicClass())
2469 return true;
2470
2471 return false;
2472}
2473
Chandler Carrutha72a12f2011-06-21 23:04:20 +00002474/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth000d4282011-06-16 09:09:40 +00002475/// otherwise returns NULL.
2476static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Webere4a1c642011-06-14 16:14:58 +00002477 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth000d4282011-06-16 09:09:40 +00002478 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2479 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
2480 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00002481
Chandler Carruth000d4282011-06-16 09:09:40 +00002482 return 0;
2483}
2484
Chandler Carrutha72a12f2011-06-21 23:04:20 +00002485/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth000d4282011-06-16 09:09:40 +00002486static QualType getSizeOfArgType(const Expr* E) {
2487 if (const UnaryExprOrTypeTraitExpr *SizeOf =
2488 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2489 if (SizeOf->getKind() == clang::UETT_SizeOf)
2490 return SizeOf->getTypeOfArgument();
2491
2492 return QualType();
Nico Webere4a1c642011-06-14 16:14:58 +00002493}
2494
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002495/// \brief Check for dangerous or invalid arguments to memset().
2496///
Chandler Carruth929f0132011-06-03 06:23:57 +00002497/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002498/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
2499/// function calls.
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002500///
2501/// \param Call The call expression to diagnose.
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002502void Sema::CheckMemaccessArguments(const CallExpr *Call,
2503 CheckedMemoryFunction CMF,
2504 IdentifierInfo *FnName) {
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00002505 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor707a23e2011-06-16 17:56:04 +00002506 // we have enough arguments, and if not, abort further checking.
Nico Webercda57822011-10-13 22:30:23 +00002507 unsigned ExpectedNumArgs = (CMF == CMF_Strndup ? 2 : 3);
2508 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00002509 return;
2510
Nico Webercda57822011-10-13 22:30:23 +00002511 unsigned LastArg = (CMF == CMF_Memset || CMF == CMF_Strndup ? 1 : 2);
2512 unsigned LenArg = (CMF == CMF_Strndup ? 1 : 2);
2513 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth000d4282011-06-16 09:09:40 +00002514
2515 // We have special checking when the length is a sizeof expression.
2516 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
2517 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
2518 llvm::FoldingSetNodeID SizeOfArgID;
2519
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002520 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
2521 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00002522 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002523
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002524 QualType DestTy = Dest->getType();
2525 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
2526 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00002527
Chandler Carruth000d4282011-06-16 09:09:40 +00002528 // Never warn about void type pointers. This can be used to suppress
2529 // false positives.
2530 if (PointeeTy->isVoidType())
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002531 continue;
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002532
Chandler Carruth000d4282011-06-16 09:09:40 +00002533 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
2534 // actually comparing the expressions for equality. Because computing the
2535 // expression IDs can be expensive, we only do this if the diagnostic is
2536 // enabled.
2537 if (SizeOfArg &&
2538 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
2539 SizeOfArg->getExprLoc())) {
2540 // We only compute IDs for expressions if the warning is enabled, and
2541 // cache the sizeof arg's ID.
2542 if (SizeOfArgID == llvm::FoldingSetNodeID())
2543 SizeOfArg->Profile(SizeOfArgID, Context, true);
2544 llvm::FoldingSetNodeID DestID;
2545 Dest->Profile(DestID, Context, true);
2546 if (DestID == SizeOfArgID) {
Nico Webercda57822011-10-13 22:30:23 +00002547 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
2548 // over sizeof(src) as well.
Chandler Carruth000d4282011-06-16 09:09:40 +00002549 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
2550 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
2551 if (UnaryOp->getOpcode() == UO_AddrOf)
2552 ActionIdx = 1; // If its an address-of operator, just remove it.
2553 if (Context.getTypeSize(PointeeTy) == Context.getCharWidth())
2554 ActionIdx = 2; // If the pointee's size is sizeof(char),
2555 // suggest an explicit length.
Nico Webercda57822011-10-13 22:30:23 +00002556 unsigned DestSrcSelect = (CMF == CMF_Strndup ? 1 : ArgIdx);
Chandler Carruth000d4282011-06-16 09:09:40 +00002557 DiagRuntimeBehavior(SizeOfArg->getExprLoc(), Dest,
2558 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Nico Webercda57822011-10-13 22:30:23 +00002559 << FnName << DestSrcSelect << ActionIdx
Chandler Carruth000d4282011-06-16 09:09:40 +00002560 << Dest->getSourceRange()
2561 << SizeOfArg->getSourceRange());
2562 break;
2563 }
2564 }
2565
2566 // Also check for cases where the sizeof argument is the exact same
2567 // type as the memory argument, and where it points to a user-defined
2568 // record type.
2569 if (SizeOfArgTy != QualType()) {
2570 if (PointeeTy->isRecordType() &&
2571 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
2572 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
2573 PDiag(diag::warn_sizeof_pointer_type_memaccess)
2574 << FnName << SizeOfArgTy << ArgIdx
2575 << PointeeTy << Dest->getSourceRange()
2576 << LenExpr->getSourceRange());
2577 break;
2578 }
Nico Webere4a1c642011-06-14 16:14:58 +00002579 }
2580
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002581 // Always complain about dynamic classes.
John McCallf85e1932011-06-15 23:02:42 +00002582 if (isDynamicClassType(PointeeTy))
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00002583 DiagRuntimeBehavior(
2584 Dest->getExprLoc(), Dest,
2585 PDiag(diag::warn_dyn_class_memaccess)
2586 << (CMF == CMF_Memcmp ? ArgIdx + 2 : ArgIdx) << FnName << PointeeTy
2587 // "overwritten" if we're warning about the destination for any call
2588 // but memcmp; otherwise a verb appropriate to the call.
2589 << (ArgIdx == 0 && CMF != CMF_Memcmp ? 0 : (unsigned)CMF)
2590 << Call->getCallee()->getSourceRange());
Douglas Gregor707a23e2011-06-16 17:56:04 +00002591 else if (PointeeTy.hasNonTrivialObjCLifetime() && CMF != CMF_Memset)
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00002592 DiagRuntimeBehavior(
2593 Dest->getExprLoc(), Dest,
2594 PDiag(diag::warn_arc_object_memaccess)
2595 << ArgIdx << FnName << PointeeTy
2596 << Call->getCallee()->getSourceRange());
John McCallf85e1932011-06-15 23:02:42 +00002597 else
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002598 continue;
John McCallf85e1932011-06-15 23:02:42 +00002599
2600 DiagRuntimeBehavior(
2601 Dest->getExprLoc(), Dest,
Chandler Carruth929f0132011-06-03 06:23:57 +00002602 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002603 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
2604 break;
2605 }
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002606 }
2607}
2608
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002609// A little helper routine: ignore addition and subtraction of integer literals.
2610// This intentionally does not ignore all integer constant expressions because
2611// we don't want to remove sizeof().
2612static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
2613 Ex = Ex->IgnoreParenCasts();
2614
2615 for (;;) {
2616 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
2617 if (!BO || !BO->isAdditiveOp())
2618 break;
2619
2620 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
2621 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
2622
2623 if (isa<IntegerLiteral>(RHS))
2624 Ex = LHS;
2625 else if (isa<IntegerLiteral>(LHS))
2626 Ex = RHS;
2627 else
2628 break;
2629 }
2630
2631 return Ex;
2632}
2633
2634// Warn if the user has made the 'size' argument to strlcpy or strlcat
2635// be the size of the source, instead of the destination.
2636void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
2637 IdentifierInfo *FnName) {
2638
2639 // Don't crash if the user has the wrong number of arguments
2640 if (Call->getNumArgs() != 3)
2641 return;
2642
2643 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
2644 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
2645 const Expr *CompareWithSrc = NULL;
2646
2647 // Look for 'strlcpy(dst, x, sizeof(x))'
2648 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
2649 CompareWithSrc = Ex;
2650 else {
2651 // Look for 'strlcpy(dst, x, strlen(x))'
2652 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Richard Smith180f4792011-11-10 06:34:14 +00002653 if (SizeCall->isBuiltinCall() == Builtin::BIstrlen
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002654 && SizeCall->getNumArgs() == 1)
2655 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
2656 }
2657 }
2658
2659 if (!CompareWithSrc)
2660 return;
2661
2662 // Determine if the argument to sizeof/strlen is equal to the source
2663 // argument. In principle there's all kinds of things you could do
2664 // here, for instance creating an == expression and evaluating it with
2665 // EvaluateAsBooleanCondition, but this uses a more direct technique:
2666 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
2667 if (!SrcArgDRE)
2668 return;
2669
2670 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
2671 if (!CompareWithSrcDRE ||
2672 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
2673 return;
2674
2675 const Expr *OriginalSizeArg = Call->getArg(2);
2676 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
2677 << OriginalSizeArg->getSourceRange() << FnName;
2678
2679 // Output a FIXIT hint if the destination is an array (rather than a
2680 // pointer to an array). This could be enhanced to handle some
2681 // pointers if we know the actual size, like if DstArg is 'array+2'
2682 // we could say 'sizeof(array)-2'.
2683 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Ted Kremenek8f746222011-08-18 22:48:41 +00002684 QualType DstArgTy = DstArg->getType();
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002685
Ted Kremenek8f746222011-08-18 22:48:41 +00002686 // Only handle constant-sized or VLAs, but not flexible members.
2687 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(DstArgTy)) {
2688 // Only issue the FIXIT for arrays of size > 1.
2689 if (CAT->getSize().getSExtValue() <= 1)
2690 return;
2691 } else if (!DstArgTy->isVariableArrayType()) {
2692 return;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002693 }
Ted Kremenek8f746222011-08-18 22:48:41 +00002694
2695 llvm::SmallString<128> sizeString;
2696 llvm::raw_svector_ostream OS(sizeString);
2697 OS << "sizeof(";
Douglas Gregor8987b232011-09-27 23:30:47 +00002698 DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
Ted Kremenek8f746222011-08-18 22:48:41 +00002699 OS << ")";
2700
2701 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
2702 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
2703 OS.str());
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002704}
2705
Ted Kremenek06de2762007-08-17 16:46:58 +00002706//===--- CHECK: Return Address of Stack Variable --------------------------===//
2707
Chris Lattner5f9e2722011-07-23 10:55:15 +00002708static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars);
2709static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002710
2711/// CheckReturnStackAddr - Check if a return statement returns the address
2712/// of a stack variable.
2713void
2714Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
2715 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00002716
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002717 Expr *stackE = 0;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002718 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002719
2720 // Perform checking for returned stack addresses, local blocks,
2721 // label addresses or references to temporaries.
John McCallf85e1932011-06-15 23:02:42 +00002722 if (lhsType->isPointerType() ||
2723 (!getLangOptions().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002724 stackE = EvalAddr(RetValExp, refVars);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002725 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002726 stackE = EvalVal(RetValExp, refVars);
2727 }
2728
2729 if (stackE == 0)
2730 return; // Nothing suspicious was found.
2731
2732 SourceLocation diagLoc;
2733 SourceRange diagRange;
2734 if (refVars.empty()) {
2735 diagLoc = stackE->getLocStart();
2736 diagRange = stackE->getSourceRange();
2737 } else {
2738 // We followed through a reference variable. 'stackE' contains the
2739 // problematic expression but we will warn at the return statement pointing
2740 // at the reference variable. We will later display the "trail" of
2741 // reference variables using notes.
2742 diagLoc = refVars[0]->getLocStart();
2743 diagRange = refVars[0]->getSourceRange();
2744 }
2745
2746 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
2747 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
2748 : diag::warn_ret_stack_addr)
2749 << DR->getDecl()->getDeclName() << diagRange;
2750 } else if (isa<BlockExpr>(stackE)) { // local block.
2751 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
2752 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
2753 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
2754 } else { // local temporary.
2755 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
2756 : diag::warn_ret_local_temp_addr)
2757 << diagRange;
2758 }
2759
2760 // Display the "trail" of reference variables that we followed until we
2761 // found the problematic expression using notes.
2762 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
2763 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
2764 // If this var binds to another reference var, show the range of the next
2765 // var, otherwise the var binds to the problematic expression, in which case
2766 // show the range of the expression.
2767 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
2768 : stackE->getSourceRange();
2769 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
2770 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00002771 }
2772}
2773
2774/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
2775/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002776/// to a location on the stack, a local block, an address of a label, or a
2777/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00002778/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002779/// encounter a subexpression that (1) clearly does not lead to one of the
2780/// above problematic expressions (2) is something we cannot determine leads to
2781/// a problematic expression based on such local checking.
2782///
2783/// Both EvalAddr and EvalVal follow through reference variables to evaluate
2784/// the expression that they point to. Such variables are added to the
2785/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00002786///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00002787/// EvalAddr processes expressions that are pointers that are used as
2788/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002789/// At the base case of the recursion is a check for the above problematic
2790/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00002791///
2792/// This implementation handles:
2793///
2794/// * pointer-to-pointer casts
2795/// * implicit conversions from array references to pointers
2796/// * taking the address of fields
2797/// * arbitrary interplay between "&" and "*" operators
2798/// * pointer arithmetic from an address of a stack variable
2799/// * taking the address of an array element where the array is on the stack
Chris Lattner5f9e2722011-07-23 10:55:15 +00002800static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002801 if (E->isTypeDependent())
2802 return NULL;
2803
Ted Kremenek06de2762007-08-17 16:46:58 +00002804 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00002805 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00002806 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002807 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002808 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00002809
Peter Collingbournef111d932011-04-15 00:35:48 +00002810 E = E->IgnoreParens();
2811
Ted Kremenek06de2762007-08-17 16:46:58 +00002812 // Our "symbolic interpreter" is just a dispatch off the currently
2813 // viewed AST node. We then recursively traverse the AST by calling
2814 // EvalAddr and EvalVal appropriately.
2815 switch (E->getStmtClass()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002816 case Stmt::DeclRefExprClass: {
2817 DeclRefExpr *DR = cast<DeclRefExpr>(E);
2818
2819 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
2820 // If this is a reference variable, follow through to the expression that
2821 // it points to.
2822 if (V->hasLocalStorage() &&
2823 V->getType()->isReferenceType() && V->hasInit()) {
2824 // Add the reference variable to the "trail".
2825 refVars.push_back(DR);
2826 return EvalAddr(V->getInit(), refVars);
2827 }
2828
2829 return NULL;
2830 }
Ted Kremenek06de2762007-08-17 16:46:58 +00002831
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002832 case Stmt::UnaryOperatorClass: {
2833 // The only unary operator that make sense to handle here
2834 // is AddrOf. All others don't make sense as pointers.
2835 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002836
John McCall2de56d12010-08-25 11:45:40 +00002837 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002838 return EvalVal(U->getSubExpr(), refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002839 else
Ted Kremenek06de2762007-08-17 16:46:58 +00002840 return NULL;
2841 }
Mike Stump1eb44332009-09-09 15:08:12 +00002842
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002843 case Stmt::BinaryOperatorClass: {
2844 // Handle pointer arithmetic. All other binary operators are not valid
2845 // in this context.
2846 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00002847 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00002848
John McCall2de56d12010-08-25 11:45:40 +00002849 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002850 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00002851
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002852 Expr *Base = B->getLHS();
2853
2854 // Determine which argument is the real pointer base. It could be
2855 // the RHS argument instead of the LHS.
2856 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00002857
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002858 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002859 return EvalAddr(Base, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002860 }
Steve Naroff61f40a22008-09-10 19:17:48 +00002861
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002862 // For conditional operators we need to see if either the LHS or RHS are
2863 // valid DeclRefExpr*s. If one of them is valid, we return it.
2864 case Stmt::ConditionalOperatorClass: {
2865 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002866
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002867 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00002868 if (Expr *lhsExpr = C->getLHS()) {
2869 // In C++, we can have a throw-expression, which has 'void' type.
2870 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002871 if (Expr* LHS = EvalAddr(lhsExpr, refVars))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00002872 return LHS;
2873 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002874
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00002875 // In C++, we can have a throw-expression, which has 'void' type.
2876 if (C->getRHS()->getType()->isVoidType())
2877 return NULL;
2878
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002879 return EvalAddr(C->getRHS(), refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002880 }
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002881
2882 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00002883 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002884 return E; // local block.
2885 return NULL;
2886
2887 case Stmt::AddrLabelExprClass:
2888 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00002889
John McCall80ee6e82011-11-10 05:35:25 +00002890 case Stmt::ExprWithCleanupsClass:
2891 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars);
2892
Ted Kremenek54b52742008-08-07 00:49:01 +00002893 // For casts, we need to handle conversions from arrays to
2894 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00002895 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002896 case Stmt::CStyleCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00002897 case Stmt::CXXFunctionalCastExprClass:
2898 case Stmt::ObjCBridgedCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002899 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenek54b52742008-08-07 00:49:01 +00002900 QualType T = SubExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002901
Steve Naroffdd972f22008-09-05 22:11:13 +00002902 if (SubExpr->getType()->isPointerType() ||
2903 SubExpr->getType()->isBlockPointerType() ||
2904 SubExpr->getType()->isObjCQualifiedIdType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002905 return EvalAddr(SubExpr, refVars);
Ted Kremenek54b52742008-08-07 00:49:01 +00002906 else if (T->isArrayType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002907 return EvalVal(SubExpr, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002908 else
Ted Kremenek54b52742008-08-07 00:49:01 +00002909 return 0;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002910 }
Mike Stump1eb44332009-09-09 15:08:12 +00002911
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002912 // C++ casts. For dynamic casts, static casts, and const casts, we
2913 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor49badde2008-10-27 19:41:14 +00002914 // through the cast. In the case the dynamic cast doesn't fail (and
2915 // return NULL), we take the conservative route and report cases
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002916 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor49badde2008-10-27 19:41:14 +00002917 // FIXME: The comment about is wrong; we're not always converting
2918 // from pointer to pointer. I'm guessing that this code should also
Mike Stump1eb44332009-09-09 15:08:12 +00002919 // handle references to objects.
2920 case Stmt::CXXStaticCastExprClass:
2921 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00002922 case Stmt::CXXConstCastExprClass:
2923 case Stmt::CXXReinterpretCastExprClass: {
2924 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffdd972f22008-09-05 22:11:13 +00002925 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002926 return EvalAddr(S, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002927 else
2928 return NULL;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002929 }
Mike Stump1eb44332009-09-09 15:08:12 +00002930
Douglas Gregor03e80032011-06-21 17:03:29 +00002931 case Stmt::MaterializeTemporaryExprClass:
2932 if (Expr *Result = EvalAddr(
2933 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
2934 refVars))
2935 return Result;
2936
2937 return E;
2938
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002939 // Everything else: we simply don't reason about them.
2940 default:
2941 return NULL;
2942 }
Ted Kremenek06de2762007-08-17 16:46:58 +00002943}
Mike Stump1eb44332009-09-09 15:08:12 +00002944
Ted Kremenek06de2762007-08-17 16:46:58 +00002945
2946/// EvalVal - This function is complements EvalAddr in the mutual recursion.
2947/// See the comments for EvalAddr for more details.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002948static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002949do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00002950 // We should only be called for evaluating non-pointer expressions, or
2951 // expressions with a pointer type that are not used as references but instead
2952 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00002953
Ted Kremenek06de2762007-08-17 16:46:58 +00002954 // Our "symbolic interpreter" is just a dispatch off the currently
2955 // viewed AST node. We then recursively traverse the AST by calling
2956 // EvalAddr and EvalVal appropriately.
Peter Collingbournef111d932011-04-15 00:35:48 +00002957
2958 E = E->IgnoreParens();
Ted Kremenek06de2762007-08-17 16:46:58 +00002959 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002960 case Stmt::ImplicitCastExprClass: {
2961 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00002962 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002963 E = IE->getSubExpr();
2964 continue;
2965 }
2966 return NULL;
2967 }
2968
John McCall80ee6e82011-11-10 05:35:25 +00002969 case Stmt::ExprWithCleanupsClass:
2970 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars);
2971
Douglas Gregora2813ce2009-10-23 18:54:35 +00002972 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002973 // When we hit a DeclRefExpr we are looking at code that refers to a
2974 // variable's name. If it's not a reference variable we check if it has
2975 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00002976 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002977
Ted Kremenek06de2762007-08-17 16:46:58 +00002978 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002979 if (V->hasLocalStorage()) {
2980 if (!V->getType()->isReferenceType())
2981 return DR;
2982
2983 // Reference variable, follow through to the expression that
2984 // it points to.
2985 if (V->hasInit()) {
2986 // Add the reference variable to the "trail".
2987 refVars.push_back(DR);
2988 return EvalVal(V->getInit(), refVars);
2989 }
2990 }
Mike Stump1eb44332009-09-09 15:08:12 +00002991
Ted Kremenek06de2762007-08-17 16:46:58 +00002992 return NULL;
2993 }
Mike Stump1eb44332009-09-09 15:08:12 +00002994
Ted Kremenek06de2762007-08-17 16:46:58 +00002995 case Stmt::UnaryOperatorClass: {
2996 // The only unary operator that make sense to handle here
2997 // is Deref. All others don't resolve to a "name." This includes
2998 // handling all sorts of rvalues passed to a unary operator.
2999 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003000
John McCall2de56d12010-08-25 11:45:40 +00003001 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003002 return EvalAddr(U->getSubExpr(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00003003
3004 return NULL;
3005 }
Mike Stump1eb44332009-09-09 15:08:12 +00003006
Ted Kremenek06de2762007-08-17 16:46:58 +00003007 case Stmt::ArraySubscriptExprClass: {
3008 // Array subscripts are potential references to data on the stack. We
3009 // retrieve the DeclRefExpr* for the array variable if it indeed
3010 // has local storage.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003011 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00003012 }
Mike Stump1eb44332009-09-09 15:08:12 +00003013
Ted Kremenek06de2762007-08-17 16:46:58 +00003014 case Stmt::ConditionalOperatorClass: {
3015 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003016 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00003017 ConditionalOperator *C = cast<ConditionalOperator>(E);
3018
Anders Carlsson39073232007-11-30 19:04:31 +00003019 // Handle the GNU extension for missing LHS.
3020 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003021 if (Expr *LHS = EvalVal(lhsExpr, refVars))
Anders Carlsson39073232007-11-30 19:04:31 +00003022 return LHS;
3023
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003024 return EvalVal(C->getRHS(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00003025 }
Mike Stump1eb44332009-09-09 15:08:12 +00003026
Ted Kremenek06de2762007-08-17 16:46:58 +00003027 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00003028 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00003029 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003030
Ted Kremenek06de2762007-08-17 16:46:58 +00003031 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00003032 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00003033 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00003034
3035 // Check whether the member type is itself a reference, in which case
3036 // we're not going to refer to the member, but to what the member refers to.
3037 if (M->getMemberDecl()->getType()->isReferenceType())
3038 return NULL;
3039
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003040 return EvalVal(M->getBase(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00003041 }
Mike Stump1eb44332009-09-09 15:08:12 +00003042
Douglas Gregor03e80032011-06-21 17:03:29 +00003043 case Stmt::MaterializeTemporaryExprClass:
3044 if (Expr *Result = EvalVal(
3045 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
3046 refVars))
3047 return Result;
3048
3049 return E;
3050
Ted Kremenek06de2762007-08-17 16:46:58 +00003051 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003052 // Check that we don't return or take the address of a reference to a
3053 // temporary. This is only useful in C++.
3054 if (!E->isTypeDependent() && E->isRValue())
3055 return E;
3056
3057 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00003058 return NULL;
3059 }
Ted Kremenek68957a92010-08-04 20:01:07 +00003060} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00003061}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003062
3063//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
3064
3065/// Check for comparisons of floating point operands using != and ==.
3066/// Issue a warning if these are no self-comparisons, as they are not likely
3067/// to do what the programmer intended.
Richard Trieudd225092011-09-15 21:56:47 +00003068void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003069 bool EmitWarning = true;
Mike Stump1eb44332009-09-09 15:08:12 +00003070
Richard Trieudd225092011-09-15 21:56:47 +00003071 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
3072 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003073
3074 // Special case: check for x == x (which is OK).
3075 // Do not emit warnings for such cases.
3076 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
3077 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
3078 if (DRL->getDecl() == DRR->getDecl())
3079 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003080
3081
Ted Kremenek1b500bb2007-11-29 00:59:04 +00003082 // Special case: check for comparisons against literals that can be exactly
3083 // represented by APFloat. In such cases, do not emit a warning. This
3084 // is a heuristic: often comparison against such literals are used to
3085 // detect if a value in a variable has not changed. This clearly can
3086 // lead to false negatives.
3087 if (EmitWarning) {
3088 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
3089 if (FLL->isExact())
3090 EmitWarning = false;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003091 } else
Ted Kremenek1b500bb2007-11-29 00:59:04 +00003092 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
3093 if (FLR->isExact())
3094 EmitWarning = false;
3095 }
3096 }
Mike Stump1eb44332009-09-09 15:08:12 +00003097
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003098 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003099 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003100 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Richard Smith180f4792011-11-10 06:34:14 +00003101 if (CL->isBuiltinCall())
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003102 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003103
Sebastian Redl0eb23302009-01-19 00:08:26 +00003104 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003105 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Richard Smith180f4792011-11-10 06:34:14 +00003106 if (CR->isBuiltinCall())
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003107 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003108
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003109 // Emit the diagnostic.
3110 if (EmitWarning)
Richard Trieudd225092011-09-15 21:56:47 +00003111 Diag(Loc, diag::warn_floatingpoint_eq)
3112 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003113}
John McCallba26e582010-01-04 23:21:16 +00003114
John McCallf2370c92010-01-06 05:24:50 +00003115//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
3116//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00003117
John McCallf2370c92010-01-06 05:24:50 +00003118namespace {
John McCallba26e582010-01-04 23:21:16 +00003119
John McCallf2370c92010-01-06 05:24:50 +00003120/// Structure recording the 'active' range of an integer-valued
3121/// expression.
3122struct IntRange {
3123 /// The number of bits active in the int.
3124 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00003125
John McCallf2370c92010-01-06 05:24:50 +00003126 /// True if the int is known not to have negative values.
3127 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00003128
John McCallf2370c92010-01-06 05:24:50 +00003129 IntRange(unsigned Width, bool NonNegative)
3130 : Width(Width), NonNegative(NonNegative)
3131 {}
John McCallba26e582010-01-04 23:21:16 +00003132
John McCall1844a6e2010-11-10 23:38:19 +00003133 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00003134 static IntRange forBoolType() {
3135 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00003136 }
3137
John McCall1844a6e2010-11-10 23:38:19 +00003138 /// Returns the range of an opaque value of the given integral type.
3139 static IntRange forValueOfType(ASTContext &C, QualType T) {
3140 return forValueOfCanonicalType(C,
3141 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00003142 }
3143
John McCall1844a6e2010-11-10 23:38:19 +00003144 /// Returns the range of an opaque value of a canonical integral type.
3145 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00003146 assert(T->isCanonicalUnqualified());
3147
3148 if (const VectorType *VT = dyn_cast<VectorType>(T))
3149 T = VT->getElementType().getTypePtr();
3150 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
3151 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00003152
John McCall091f23f2010-11-09 22:22:12 +00003153 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00003154 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
3155 EnumDecl *Enum = ET->getDecl();
John McCall5e1cdac2011-10-07 06:10:15 +00003156 if (!Enum->isCompleteDefinition())
John McCall091f23f2010-11-09 22:22:12 +00003157 return IntRange(C.getIntWidth(QualType(T, 0)), false);
3158
John McCall323ed742010-05-06 08:58:33 +00003159 unsigned NumPositive = Enum->getNumPositiveBits();
3160 unsigned NumNegative = Enum->getNumNegativeBits();
3161
3162 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
3163 }
John McCallf2370c92010-01-06 05:24:50 +00003164
3165 const BuiltinType *BT = cast<BuiltinType>(T);
3166 assert(BT->isInteger());
3167
3168 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
3169 }
3170
John McCall1844a6e2010-11-10 23:38:19 +00003171 /// Returns the "target" range of a canonical integral type, i.e.
3172 /// the range of values expressible in the type.
3173 ///
3174 /// This matches forValueOfCanonicalType except that enums have the
3175 /// full range of their type, not the range of their enumerators.
3176 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
3177 assert(T->isCanonicalUnqualified());
3178
3179 if (const VectorType *VT = dyn_cast<VectorType>(T))
3180 T = VT->getElementType().getTypePtr();
3181 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
3182 T = CT->getElementType().getTypePtr();
3183 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor69ff26b2011-09-08 23:29:05 +00003184 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall1844a6e2010-11-10 23:38:19 +00003185
3186 const BuiltinType *BT = cast<BuiltinType>(T);
3187 assert(BT->isInteger());
3188
3189 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
3190 }
3191
3192 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00003193 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00003194 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00003195 L.NonNegative && R.NonNegative);
3196 }
3197
John McCall1844a6e2010-11-10 23:38:19 +00003198 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00003199 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00003200 return IntRange(std::min(L.Width, R.Width),
3201 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00003202 }
3203};
3204
3205IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
3206 if (value.isSigned() && value.isNegative())
3207 return IntRange(value.getMinSignedBits(), false);
3208
3209 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00003210 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00003211
3212 // isNonNegative() just checks the sign bit without considering
3213 // signedness.
3214 return IntRange(value.getActiveBits(), true);
3215}
3216
John McCall0acc3112010-01-06 22:57:21 +00003217IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
John McCallf2370c92010-01-06 05:24:50 +00003218 unsigned MaxWidth) {
3219 if (result.isInt())
3220 return GetValueRange(C, result.getInt(), MaxWidth);
3221
3222 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00003223 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
3224 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
3225 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
3226 R = IntRange::join(R, El);
3227 }
John McCallf2370c92010-01-06 05:24:50 +00003228 return R;
3229 }
3230
3231 if (result.isComplexInt()) {
3232 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
3233 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
3234 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00003235 }
3236
3237 // This can happen with lossless casts to intptr_t of "based" lvalues.
3238 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00003239 // FIXME: The only reason we need to pass the type in here is to get
3240 // the sign right on this one case. It would be nice if APValue
3241 // preserved this.
John McCallf2370c92010-01-06 05:24:50 +00003242 assert(result.isLValue());
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00003243 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall51313c32010-01-04 23:31:57 +00003244}
John McCallf2370c92010-01-06 05:24:50 +00003245
3246/// Pseudo-evaluate the given integer expression, estimating the
3247/// range of values it might take.
3248///
3249/// \param MaxWidth - the width to which the value will be truncated
3250IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
3251 E = E->IgnoreParens();
3252
3253 // Try a full evaluation first.
3254 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00003255 if (E->EvaluateAsRValue(result, C))
John McCall0acc3112010-01-06 22:57:21 +00003256 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00003257
3258 // I think we only want to look through implicit casts here; if the
3259 // user has an explicit widening cast, we should treat the value as
3260 // being of the new, wider type.
3261 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedmanb17ee5b2011-12-15 02:41:52 +00003262 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCallf2370c92010-01-06 05:24:50 +00003263 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
3264
John McCall1844a6e2010-11-10 23:38:19 +00003265 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
John McCallf2370c92010-01-06 05:24:50 +00003266
John McCall2de56d12010-08-25 11:45:40 +00003267 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00003268
John McCallf2370c92010-01-06 05:24:50 +00003269 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00003270 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00003271 return OutputTypeRange;
3272
3273 IntRange SubRange
3274 = GetExprRange(C, CE->getSubExpr(),
3275 std::min(MaxWidth, OutputTypeRange.Width));
3276
3277 // Bail out if the subexpr's range is as wide as the cast type.
3278 if (SubRange.Width >= OutputTypeRange.Width)
3279 return OutputTypeRange;
3280
3281 // Otherwise, we take the smaller width, and we're non-negative if
3282 // either the output type or the subexpr is.
3283 return IntRange(SubRange.Width,
3284 SubRange.NonNegative || OutputTypeRange.NonNegative);
3285 }
3286
3287 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3288 // If we can fold the condition, just take that operand.
3289 bool CondResult;
3290 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
3291 return GetExprRange(C, CondResult ? CO->getTrueExpr()
3292 : CO->getFalseExpr(),
3293 MaxWidth);
3294
3295 // Otherwise, conservatively merge.
3296 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
3297 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
3298 return IntRange::join(L, R);
3299 }
3300
3301 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3302 switch (BO->getOpcode()) {
3303
3304 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00003305 case BO_LAnd:
3306 case BO_LOr:
3307 case BO_LT:
3308 case BO_GT:
3309 case BO_LE:
3310 case BO_GE:
3311 case BO_EQ:
3312 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00003313 return IntRange::forBoolType();
3314
John McCall862ff872011-07-13 06:35:24 +00003315 // The type of the assignments is the type of the LHS, so the RHS
3316 // is not necessarily the same type.
John McCall2de56d12010-08-25 11:45:40 +00003317 case BO_MulAssign:
3318 case BO_DivAssign:
3319 case BO_RemAssign:
3320 case BO_AddAssign:
3321 case BO_SubAssign:
John McCall862ff872011-07-13 06:35:24 +00003322 case BO_XorAssign:
3323 case BO_OrAssign:
3324 // TODO: bitfields?
John McCall1844a6e2010-11-10 23:38:19 +00003325 return IntRange::forValueOfType(C, E->getType());
John McCallc0cd21d2010-02-23 19:22:29 +00003326
John McCall862ff872011-07-13 06:35:24 +00003327 // Simple assignments just pass through the RHS, which will have
3328 // been coerced to the LHS type.
3329 case BO_Assign:
3330 // TODO: bitfields?
3331 return GetExprRange(C, BO->getRHS(), MaxWidth);
3332
John McCallf2370c92010-01-06 05:24:50 +00003333 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00003334 case BO_PtrMemD:
3335 case BO_PtrMemI:
John McCall1844a6e2010-11-10 23:38:19 +00003336 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003337
John McCall60fad452010-01-06 22:07:33 +00003338 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00003339 case BO_And:
3340 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00003341 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
3342 GetExprRange(C, BO->getRHS(), MaxWidth));
3343
John McCallf2370c92010-01-06 05:24:50 +00003344 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00003345 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00003346 // ...except that we want to treat '1 << (blah)' as logically
3347 // positive. It's an important idiom.
3348 if (IntegerLiteral *I
3349 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
3350 if (I->getValue() == 1) {
John McCall1844a6e2010-11-10 23:38:19 +00003351 IntRange R = IntRange::forValueOfType(C, E->getType());
John McCall3aae6092010-04-07 01:14:35 +00003352 return IntRange(R.Width, /*NonNegative*/ true);
3353 }
3354 }
3355 // fallthrough
3356
John McCall2de56d12010-08-25 11:45:40 +00003357 case BO_ShlAssign:
John McCall1844a6e2010-11-10 23:38:19 +00003358 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003359
John McCall60fad452010-01-06 22:07:33 +00003360 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00003361 case BO_Shr:
3362 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00003363 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3364
3365 // If the shift amount is a positive constant, drop the width by
3366 // that much.
3367 llvm::APSInt shift;
3368 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
3369 shift.isNonNegative()) {
3370 unsigned zext = shift.getZExtValue();
3371 if (zext >= L.Width)
3372 L.Width = (L.NonNegative ? 0 : 1);
3373 else
3374 L.Width -= zext;
3375 }
3376
3377 return L;
3378 }
3379
3380 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00003381 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00003382 return GetExprRange(C, BO->getRHS(), MaxWidth);
3383
John McCall60fad452010-01-06 22:07:33 +00003384 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00003385 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00003386 if (BO->getLHS()->getType()->isPointerType())
John McCall1844a6e2010-11-10 23:38:19 +00003387 return IntRange::forValueOfType(C, E->getType());
John McCall00fe7612011-07-14 22:39:48 +00003388 break;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003389
John McCall00fe7612011-07-14 22:39:48 +00003390 // The width of a division result is mostly determined by the size
3391 // of the LHS.
3392 case BO_Div: {
3393 // Don't 'pre-truncate' the operands.
3394 unsigned opWidth = C.getIntWidth(E->getType());
3395 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3396
3397 // If the divisor is constant, use that.
3398 llvm::APSInt divisor;
3399 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
3400 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
3401 if (log2 >= L.Width)
3402 L.Width = (L.NonNegative ? 0 : 1);
3403 else
3404 L.Width = std::min(L.Width - log2, MaxWidth);
3405 return L;
3406 }
3407
3408 // Otherwise, just use the LHS's width.
3409 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3410 return IntRange(L.Width, L.NonNegative && R.NonNegative);
3411 }
3412
3413 // The result of a remainder can't be larger than the result of
3414 // either side.
3415 case BO_Rem: {
3416 // Don't 'pre-truncate' the operands.
3417 unsigned opWidth = C.getIntWidth(E->getType());
3418 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3419 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3420
3421 IntRange meet = IntRange::meet(L, R);
3422 meet.Width = std::min(meet.Width, MaxWidth);
3423 return meet;
3424 }
3425
3426 // The default behavior is okay for these.
3427 case BO_Mul:
3428 case BO_Add:
3429 case BO_Xor:
3430 case BO_Or:
John McCallf2370c92010-01-06 05:24:50 +00003431 break;
3432 }
3433
John McCall00fe7612011-07-14 22:39:48 +00003434 // The default case is to treat the operation as if it were closed
3435 // on the narrowest type that encompasses both operands.
John McCallf2370c92010-01-06 05:24:50 +00003436 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3437 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
3438 return IntRange::join(L, R);
3439 }
3440
3441 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
3442 switch (UO->getOpcode()) {
3443 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00003444 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00003445 return IntRange::forBoolType();
3446
3447 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00003448 case UO_Deref:
3449 case UO_AddrOf: // should be impossible
John McCall1844a6e2010-11-10 23:38:19 +00003450 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003451
3452 default:
3453 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
3454 }
3455 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003456
3457 if (dyn_cast<OffsetOfExpr>(E)) {
John McCall1844a6e2010-11-10 23:38:19 +00003458 IntRange::forValueOfType(C, E->getType());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003459 }
John McCallf2370c92010-01-06 05:24:50 +00003460
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003461 if (FieldDecl *BitField = E->getBitField())
3462 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00003463 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCallf2370c92010-01-06 05:24:50 +00003464
John McCall1844a6e2010-11-10 23:38:19 +00003465 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003466}
John McCall51313c32010-01-04 23:31:57 +00003467
John McCall323ed742010-05-06 08:58:33 +00003468IntRange GetExprRange(ASTContext &C, Expr *E) {
3469 return GetExprRange(C, E, C.getIntWidth(E->getType()));
3470}
3471
John McCall51313c32010-01-04 23:31:57 +00003472/// Checks whether the given value, which currently has the given
3473/// source semantics, has the same value when coerced through the
3474/// target semantics.
John McCallf2370c92010-01-06 05:24:50 +00003475bool IsSameFloatAfterCast(const llvm::APFloat &value,
3476 const llvm::fltSemantics &Src,
3477 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00003478 llvm::APFloat truncated = value;
3479
3480 bool ignored;
3481 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
3482 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
3483
3484 return truncated.bitwiseIsEqual(value);
3485}
3486
3487/// Checks whether the given value, which currently has the given
3488/// source semantics, has the same value when coerced through the
3489/// target semantics.
3490///
3491/// The value might be a vector of floats (or a complex number).
John McCallf2370c92010-01-06 05:24:50 +00003492bool IsSameFloatAfterCast(const APValue &value,
3493 const llvm::fltSemantics &Src,
3494 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00003495 if (value.isFloat())
3496 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
3497
3498 if (value.isVector()) {
3499 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
3500 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
3501 return false;
3502 return true;
3503 }
3504
3505 assert(value.isComplexFloat());
3506 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
3507 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
3508}
3509
John McCallb4eb64d2010-10-08 02:01:28 +00003510void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00003511
Ted Kremeneke3b159c2010-09-23 21:43:44 +00003512static bool IsZero(Sema &S, Expr *E) {
3513 // Suppress cases where we are comparing against an enum constant.
3514 if (const DeclRefExpr *DR =
3515 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
3516 if (isa<EnumConstantDecl>(DR->getDecl()))
3517 return false;
3518
3519 // Suppress cases where the '0' value is expanded from a macro.
3520 if (E->getLocStart().isMacroID())
3521 return false;
3522
John McCall323ed742010-05-06 08:58:33 +00003523 llvm::APSInt Value;
3524 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
3525}
3526
John McCall372e1032010-10-06 00:25:24 +00003527static bool HasEnumType(Expr *E) {
3528 // Strip off implicit integral promotions.
3529 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00003530 if (ICE->getCastKind() != CK_IntegralCast &&
3531 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00003532 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00003533 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00003534 }
3535
3536 return E->getType()->isEnumeralType();
3537}
3538
John McCall323ed742010-05-06 08:58:33 +00003539void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00003540 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00003541 if (E->isValueDependent())
3542 return;
3543
John McCall2de56d12010-08-25 11:45:40 +00003544 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00003545 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003546 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00003547 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00003548 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00003549 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003550 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00003551 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00003552 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00003553 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003554 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00003555 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00003556 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00003557 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003558 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00003559 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
3560 }
3561}
3562
3563/// Analyze the operands of the given comparison. Implements the
3564/// fallback case from AnalyzeComparison.
3565void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00003566 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
3567 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00003568}
John McCall51313c32010-01-04 23:31:57 +00003569
John McCallba26e582010-01-04 23:21:16 +00003570/// \brief Implements -Wsign-compare.
3571///
Richard Trieudd225092011-09-15 21:56:47 +00003572/// \param E the binary operator to check for warnings
John McCall323ed742010-05-06 08:58:33 +00003573void AnalyzeComparison(Sema &S, BinaryOperator *E) {
3574 // The type the comparison is being performed in.
3575 QualType T = E->getLHS()->getType();
3576 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
3577 && "comparison with mismatched types");
John McCallba26e582010-01-04 23:21:16 +00003578
John McCall323ed742010-05-06 08:58:33 +00003579 // We don't do anything special if this isn't an unsigned integral
3580 // comparison: we're only interested in integral comparisons, and
3581 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00003582 //
3583 // We also don't care about value-dependent expressions or expressions
3584 // whose result is a constant.
3585 if (!T->hasUnsignedIntegerRepresentation()
3586 || E->isValueDependent() || E->isIntegerConstantExpr(S.Context))
John McCall323ed742010-05-06 08:58:33 +00003587 return AnalyzeImpConvsInComparison(S, E);
John McCallf2370c92010-01-06 05:24:50 +00003588
Richard Trieudd225092011-09-15 21:56:47 +00003589 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
3590 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
John McCallba26e582010-01-04 23:21:16 +00003591
John McCall323ed742010-05-06 08:58:33 +00003592 // Check to see if one of the (unmodified) operands is of different
3593 // signedness.
3594 Expr *signedOperand, *unsignedOperand;
Richard Trieudd225092011-09-15 21:56:47 +00003595 if (LHS->getType()->hasSignedIntegerRepresentation()) {
3596 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00003597 "unsigned comparison between two signed integer expressions?");
Richard Trieudd225092011-09-15 21:56:47 +00003598 signedOperand = LHS;
3599 unsignedOperand = RHS;
3600 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
3601 signedOperand = RHS;
3602 unsignedOperand = LHS;
John McCallba26e582010-01-04 23:21:16 +00003603 } else {
John McCall323ed742010-05-06 08:58:33 +00003604 CheckTrivialUnsignedComparison(S, E);
3605 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00003606 }
3607
John McCall323ed742010-05-06 08:58:33 +00003608 // Otherwise, calculate the effective range of the signed operand.
3609 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00003610
John McCall323ed742010-05-06 08:58:33 +00003611 // Go ahead and analyze implicit conversions in the operands. Note
3612 // that we skip the implicit conversions on both sides.
Richard Trieudd225092011-09-15 21:56:47 +00003613 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
3614 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00003615
John McCall323ed742010-05-06 08:58:33 +00003616 // If the signed range is non-negative, -Wsign-compare won't fire,
3617 // but we should still check for comparisons which are always true
3618 // or false.
3619 if (signedRange.NonNegative)
3620 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00003621
3622 // For (in)equality comparisons, if the unsigned operand is a
3623 // constant which cannot collide with a overflowed signed operand,
3624 // then reinterpreting the signed operand as unsigned will not
3625 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00003626 if (E->isEqualityOp()) {
3627 unsigned comparisonWidth = S.Context.getIntWidth(T);
3628 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00003629
John McCall323ed742010-05-06 08:58:33 +00003630 // We should never be unable to prove that the unsigned operand is
3631 // non-negative.
3632 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
3633
3634 if (unsignedRange.Width < comparisonWidth)
3635 return;
3636 }
3637
3638 S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison)
Richard Trieudd225092011-09-15 21:56:47 +00003639 << LHS->getType() << RHS->getType()
3640 << LHS->getSourceRange() << RHS->getSourceRange();
John McCallba26e582010-01-04 23:21:16 +00003641}
3642
John McCall15d7d122010-11-11 03:21:53 +00003643/// Analyzes an attempt to assign the given value to a bitfield.
3644///
3645/// Returns true if there was something fishy about the attempt.
3646bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
3647 SourceLocation InitLoc) {
3648 assert(Bitfield->isBitField());
3649 if (Bitfield->isInvalidDecl())
3650 return false;
3651
John McCall91b60142010-11-11 05:33:51 +00003652 // White-list bool bitfields.
3653 if (Bitfield->getType()->isBooleanType())
3654 return false;
3655
Douglas Gregor46ff3032011-02-04 13:09:01 +00003656 // Ignore value- or type-dependent expressions.
3657 if (Bitfield->getBitWidth()->isValueDependent() ||
3658 Bitfield->getBitWidth()->isTypeDependent() ||
3659 Init->isValueDependent() ||
3660 Init->isTypeDependent())
3661 return false;
3662
John McCall15d7d122010-11-11 03:21:53 +00003663 Expr *OriginalInit = Init->IgnoreParenImpCasts();
3664
John McCall15d7d122010-11-11 03:21:53 +00003665 Expr::EvalResult InitValue;
Richard Smith51f47082011-10-29 00:50:52 +00003666 if (!OriginalInit->EvaluateAsRValue(InitValue, S.Context) ||
John McCall15d7d122010-11-11 03:21:53 +00003667 !InitValue.Val.isInt())
3668 return false;
3669
3670 const llvm::APSInt &Value = InitValue.Val.getInt();
3671 unsigned OriginalWidth = Value.getBitWidth();
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003672 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall15d7d122010-11-11 03:21:53 +00003673
3674 if (OriginalWidth <= FieldWidth)
3675 return false;
3676
Jay Foad9f71a8f2010-12-07 08:25:34 +00003677 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
John McCall15d7d122010-11-11 03:21:53 +00003678
3679 // It's fairly common to write values into signed bitfields
3680 // that, if sign-extended, would end up becoming a different
3681 // value. We don't want to warn about that.
3682 if (Value.isSigned() && Value.isNegative())
Jay Foad9f71a8f2010-12-07 08:25:34 +00003683 TruncatedValue = TruncatedValue.sext(OriginalWidth);
John McCall15d7d122010-11-11 03:21:53 +00003684 else
Jay Foad9f71a8f2010-12-07 08:25:34 +00003685 TruncatedValue = TruncatedValue.zext(OriginalWidth);
John McCall15d7d122010-11-11 03:21:53 +00003686
3687 if (Value == TruncatedValue)
3688 return false;
3689
3690 std::string PrettyValue = Value.toString(10);
3691 std::string PrettyTrunc = TruncatedValue.toString(10);
3692
3693 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
3694 << PrettyValue << PrettyTrunc << OriginalInit->getType()
3695 << Init->getSourceRange();
3696
3697 return true;
3698}
3699
John McCallbeb22aa2010-11-09 23:24:47 +00003700/// Analyze the given simple or compound assignment for warning-worthy
3701/// operations.
3702void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
3703 // Just recurse on the LHS.
3704 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
3705
3706 // We want to recurse on the RHS as normal unless we're assigning to
3707 // a bitfield.
3708 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
John McCall15d7d122010-11-11 03:21:53 +00003709 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
3710 E->getOperatorLoc())) {
3711 // Recurse, ignoring any implicit conversions on the RHS.
3712 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
3713 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00003714 }
3715 }
3716
3717 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
3718}
3719
John McCall51313c32010-01-04 23:31:57 +00003720/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00003721void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
3722 SourceLocation CContext, unsigned diag) {
3723 S.Diag(E->getExprLoc(), diag)
3724 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
3725}
3726
Chandler Carruthe1b02e02011-04-05 06:47:57 +00003727/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
3728void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
3729 unsigned diag) {
3730 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag);
3731}
3732
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003733/// Diagnose an implicit cast from a literal expression. Does not warn when the
3734/// cast wouldn't lose information.
Chandler Carruthf65076e2011-04-10 08:36:24 +00003735void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
3736 SourceLocation CContext) {
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003737 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruthf65076e2011-04-10 08:36:24 +00003738 bool isExact = false;
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003739 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00003740 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
3741 T->hasUnsignedIntegerRepresentation());
3742 if (Value.convertToInteger(IntegerValue,
Chandler Carruthf65076e2011-04-10 08:36:24 +00003743 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003744 == llvm::APFloat::opOK && isExact)
Chandler Carruthf65076e2011-04-10 08:36:24 +00003745 return;
3746
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003747 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
3748 << FL->getType() << T << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruthf65076e2011-04-10 08:36:24 +00003749}
3750
John McCall091f23f2010-11-09 22:22:12 +00003751std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
3752 if (!Range.Width) return "0";
3753
3754 llvm::APSInt ValueInRange = Value;
3755 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00003756 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00003757 return ValueInRange.toString(10);
3758}
3759
Ted Kremenekef9ff882011-03-10 20:03:42 +00003760static bool isFromSystemMacro(Sema &S, SourceLocation loc) {
3761 SourceManager &smgr = S.Context.getSourceManager();
3762 return loc.isMacroID() && smgr.isInSystemHeader(smgr.getSpellingLoc(loc));
3763}
Chandler Carruthf65076e2011-04-10 08:36:24 +00003764
John McCall323ed742010-05-06 08:58:33 +00003765void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00003766 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00003767 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00003768
John McCall323ed742010-05-06 08:58:33 +00003769 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
3770 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
3771 if (Source == Target) return;
3772 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00003773
Chandler Carruth108f7562011-07-26 05:40:03 +00003774 // If the conversion context location is invalid don't complain. We also
3775 // don't want to emit a warning if the issue occurs from the expansion of
3776 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
3777 // delay this check as long as possible. Once we detect we are in that
3778 // scenario, we just return.
Ted Kremenekef9ff882011-03-10 20:03:42 +00003779 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00003780 return;
3781
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00003782 // Diagnose implicit casts to bool.
3783 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
3784 if (isa<StringLiteral>(E))
3785 // Warn on string literal to bool. Checks for string literals in logical
3786 // expressions, for instances, assert(0 && "error here"), is prevented
3787 // by a check in AnalyzeImplicitConversions().
3788 return DiagnoseImpCast(S, E, T, CC,
3789 diag::warn_impcast_string_literal_to_bool);
Lang Hamese14ca9f2011-12-05 20:49:50 +00003790 if (Source->isFunctionType()) {
3791 // Warn on function to bool. Checks free functions and static member
3792 // functions. Weakly imported functions are excluded from the check,
3793 // since it's common to test their value to check whether the linker
3794 // found a definition for them.
3795 ValueDecl *D = 0;
3796 if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
3797 D = R->getDecl();
3798 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
3799 D = M->getMemberDecl();
3800 }
3801
3802 if (D && !D->isWeak()) {
Richard Trieu26b45d82011-12-06 04:48:01 +00003803 if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
3804 S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
3805 << F << E->getSourceRange() << SourceRange(CC);
David Blaikie2def7732011-12-09 21:42:37 +00003806 S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
3807 << FixItHint::CreateInsertion(E->getExprLoc(), "&");
3808 QualType ReturnType;
3809 UnresolvedSet<4> NonTemplateOverloads;
3810 S.isExprCallable(*E, ReturnType, NonTemplateOverloads);
3811 if (!ReturnType.isNull()
3812 && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
3813 S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
3814 << FixItHint::CreateInsertion(
3815 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu26b45d82011-12-06 04:48:01 +00003816 return;
3817 }
Lang Hamese14ca9f2011-12-05 20:49:50 +00003818 }
3819 }
David Blaikiee37cdc42011-09-29 04:06:47 +00003820 return; // Other casts to bool are not checked.
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00003821 }
John McCall51313c32010-01-04 23:31:57 +00003822
3823 // Strip vector types.
3824 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003825 if (!isa<VectorType>(Target)) {
3826 if (isFromSystemMacro(S, CC))
3827 return;
John McCallb4eb64d2010-10-08 02:01:28 +00003828 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00003829 }
Chris Lattnerb792b302011-06-14 04:51:15 +00003830
3831 // If the vector cast is cast between two vectors of the same size, it is
3832 // a bitcast, not a conversion.
3833 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
3834 return;
John McCall51313c32010-01-04 23:31:57 +00003835
3836 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
3837 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
3838 }
3839
3840 // Strip complex types.
3841 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003842 if (!isa<ComplexType>(Target)) {
3843 if (isFromSystemMacro(S, CC))
3844 return;
3845
John McCallb4eb64d2010-10-08 02:01:28 +00003846 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00003847 }
John McCall51313c32010-01-04 23:31:57 +00003848
3849 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
3850 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
3851 }
3852
3853 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
3854 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
3855
3856 // If the source is floating point...
3857 if (SourceBT && SourceBT->isFloatingPoint()) {
3858 // ...and the target is floating point...
3859 if (TargetBT && TargetBT->isFloatingPoint()) {
3860 // ...then warn if we're dropping FP rank.
3861
3862 // Builtin FP kinds are ordered by increasing FP rank.
3863 if (SourceBT->getKind() > TargetBT->getKind()) {
3864 // Don't warn about float constants that are precisely
3865 // representable in the target type.
3866 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00003867 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00003868 // Value might be a float, a float vector, or a float complex.
3869 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00003870 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
3871 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00003872 return;
3873 }
3874
Ted Kremenekef9ff882011-03-10 20:03:42 +00003875 if (isFromSystemMacro(S, CC))
3876 return;
3877
John McCallb4eb64d2010-10-08 02:01:28 +00003878 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00003879 }
3880 return;
3881 }
3882
Ted Kremenekef9ff882011-03-10 20:03:42 +00003883 // If the target is integral, always warn.
Chandler Carrutha5b93322011-02-17 11:05:49 +00003884 if ((TargetBT && TargetBT->isInteger())) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003885 if (isFromSystemMacro(S, CC))
3886 return;
3887
Chandler Carrutha5b93322011-02-17 11:05:49 +00003888 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay634c8af2011-09-08 22:30:47 +00003889 // We also want to warn on, e.g., "int i = -1.234"
3890 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
3891 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
3892 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
3893
Chandler Carruthf65076e2011-04-10 08:36:24 +00003894 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
3895 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00003896 } else {
3897 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
3898 }
3899 }
John McCall51313c32010-01-04 23:31:57 +00003900
3901 return;
3902 }
3903
John McCallf2370c92010-01-06 05:24:50 +00003904 if (!Source->isIntegerType() || !Target->isIntegerType())
John McCall51313c32010-01-04 23:31:57 +00003905 return;
3906
Richard Trieu1838ca52011-05-29 19:59:02 +00003907 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
3908 == Expr::NPCK_GNUNull) && Target->isIntegerType()) {
3909 S.Diag(E->getExprLoc(), diag::warn_impcast_null_pointer_to_integer)
3910 << E->getSourceRange() << clang::SourceRange(CC);
3911 return;
3912 }
3913
John McCall323ed742010-05-06 08:58:33 +00003914 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00003915 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00003916
3917 if (SourceRange.Width > TargetRange.Width) {
John McCall091f23f2010-11-09 22:22:12 +00003918 // If the source is a constant, use a default-on diagnostic.
3919 // TODO: this should happen for bitfield stores, too.
3920 llvm::APSInt Value(32);
3921 if (E->isIntegerConstantExpr(Value, S.Context)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003922 if (isFromSystemMacro(S, CC))
3923 return;
3924
John McCall091f23f2010-11-09 22:22:12 +00003925 std::string PrettySourceValue = Value.toString(10);
3926 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
3927
Ted Kremenek5e745da2011-10-22 02:37:33 +00003928 S.DiagRuntimeBehavior(E->getExprLoc(), E,
3929 S.PDiag(diag::warn_impcast_integer_precision_constant)
3930 << PrettySourceValue << PrettyTargetValue
3931 << E->getType() << T << E->getSourceRange()
3932 << clang::SourceRange(CC));
John McCall091f23f2010-11-09 22:22:12 +00003933 return;
3934 }
3935
Chris Lattnerb792b302011-06-14 04:51:15 +00003936 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
Ted Kremenekef9ff882011-03-10 20:03:42 +00003937 if (isFromSystemMacro(S, CC))
3938 return;
3939
John McCallf2370c92010-01-06 05:24:50 +00003940 if (SourceRange.Width == 64 && TargetRange.Width == 32)
John McCallb4eb64d2010-10-08 02:01:28 +00003941 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32);
3942 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00003943 }
3944
3945 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
3946 (!TargetRange.NonNegative && SourceRange.NonNegative &&
3947 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003948
3949 if (isFromSystemMacro(S, CC))
3950 return;
3951
John McCall323ed742010-05-06 08:58:33 +00003952 unsigned DiagID = diag::warn_impcast_integer_sign;
3953
3954 // Traditionally, gcc has warned about this under -Wsign-compare.
3955 // We also want to warn about it in -Wconversion.
3956 // So if -Wconversion is off, use a completely identical diagnostic
3957 // in the sign-compare group.
3958 // The conditional-checking code will
3959 if (ICContext) {
3960 DiagID = diag::warn_impcast_integer_sign_conditional;
3961 *ICContext = true;
3962 }
3963
John McCallb4eb64d2010-10-08 02:01:28 +00003964 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00003965 }
3966
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003967 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00003968 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
3969 // type, to give us better diagnostics.
3970 QualType SourceType = E->getType();
3971 if (!S.getLangOptions().CPlusPlus) {
3972 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3973 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3974 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
3975 SourceType = S.Context.getTypeDeclType(Enum);
3976 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
3977 }
3978 }
3979
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003980 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
3981 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
3982 if ((SourceEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00003983 SourceEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003984 (TargetEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00003985 TargetEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00003986 SourceEnum != TargetEnum) {
3987 if (isFromSystemMacro(S, CC))
3988 return;
3989
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00003990 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003991 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00003992 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003993
John McCall51313c32010-01-04 23:31:57 +00003994 return;
3995}
3996
John McCall323ed742010-05-06 08:58:33 +00003997void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T);
3998
3999void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00004000 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00004001 E = E->IgnoreParenImpCasts();
4002
4003 if (isa<ConditionalOperator>(E))
4004 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T);
4005
John McCallb4eb64d2010-10-08 02:01:28 +00004006 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00004007 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00004008 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00004009 return;
4010}
4011
4012void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00004013 SourceLocation CC = E->getQuestionLoc();
4014
4015 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00004016
4017 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00004018 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
4019 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00004020
4021 // If -Wconversion would have warned about either of the candidates
4022 // for a signedness conversion to the context type...
4023 if (!Suspicious) return;
4024
4025 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00004026 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
4027 CC))
John McCall323ed742010-05-06 08:58:33 +00004028 return;
4029
John McCall323ed742010-05-06 08:58:33 +00004030 // ...then check whether it would have warned about either of the
4031 // candidates for a signedness conversion to the condition type.
Richard Trieu52541612011-07-21 02:46:28 +00004032 if (E->getType() == T) return;
4033
4034 Suspicious = false;
4035 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
4036 E->getType(), CC, &Suspicious);
4037 if (!Suspicious)
4038 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00004039 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00004040}
4041
4042/// AnalyzeImplicitConversions - Find and report any interesting
4043/// implicit conversions in the given expression. There are a couple
4044/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00004045void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00004046 QualType T = OrigE->getType();
4047 Expr *E = OrigE->IgnoreParenImpCasts();
4048
Douglas Gregorf8b6e152011-10-10 17:38:18 +00004049 if (E->isTypeDependent() || E->isValueDependent())
4050 return;
4051
John McCall323ed742010-05-06 08:58:33 +00004052 // For conditional operators, we analyze the arguments as if they
4053 // were being fed directly into the output.
4054 if (isa<ConditionalOperator>(E)) {
4055 ConditionalOperator *CO = cast<ConditionalOperator>(E);
4056 CheckConditionalOperator(S, CO, T);
4057 return;
4058 }
4059
4060 // Go ahead and check any implicit conversions we might have skipped.
4061 // The non-canonical typecheck is just an optimization;
4062 // CheckImplicitConversion will filter out dead implicit conversions.
4063 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00004064 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00004065
4066 // Now continue drilling into this expression.
4067
4068 // Skip past explicit casts.
4069 if (isa<ExplicitCastExpr>(E)) {
4070 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00004071 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00004072 }
4073
John McCallbeb22aa2010-11-09 23:24:47 +00004074 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4075 // Do a somewhat different check with comparison operators.
4076 if (BO->isComparisonOp())
4077 return AnalyzeComparison(S, BO);
4078
4079 // And with assignments and compound assignments.
4080 if (BO->isAssignmentOp())
4081 return AnalyzeAssignment(S, BO);
4082 }
John McCall323ed742010-05-06 08:58:33 +00004083
4084 // These break the otherwise-useful invariant below. Fortunately,
4085 // we don't really need to recurse into them, because any internal
4086 // expressions should have been analyzed already when they were
4087 // built into statements.
4088 if (isa<StmtExpr>(E)) return;
4089
4090 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004091 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00004092
4093 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00004094 CC = E->getExprLoc();
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004095 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
4096 bool IsLogicalOperator = BO && BO->isLogicalOp();
4097 for (Stmt::child_range I = E->children(); I; ++I) {
4098 Expr *ChildExpr = cast<Expr>(*I);
4099 if (IsLogicalOperator &&
4100 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
4101 // Ignore checking string literals that are in logical operators.
4102 continue;
4103 AnalyzeImplicitConversions(S, ChildExpr, CC);
4104 }
John McCall323ed742010-05-06 08:58:33 +00004105}
4106
4107} // end anonymous namespace
4108
4109/// Diagnoses "dangerous" implicit conversions within the given
4110/// expression (which is a full expression). Implements -Wconversion
4111/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00004112///
4113/// \param CC the "context" location of the implicit conversion, i.e.
4114/// the most location of the syntactic entity requiring the implicit
4115/// conversion
4116void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00004117 // Don't diagnose in unevaluated contexts.
4118 if (ExprEvalContexts.back().Context == Sema::Unevaluated)
4119 return;
4120
4121 // Don't diagnose for value- or type-dependent expressions.
4122 if (E->isTypeDependent() || E->isValueDependent())
4123 return;
4124
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004125 // Check for array bounds violations in cases where the check isn't triggered
4126 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
4127 // ArraySubscriptExpr is on the RHS of a variable initialization.
4128 CheckArrayAccess(E);
4129
John McCallb4eb64d2010-10-08 02:01:28 +00004130 // This is not the right CC for (e.g.) a variable initialization.
4131 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00004132}
4133
John McCall15d7d122010-11-11 03:21:53 +00004134void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
4135 FieldDecl *BitField,
4136 Expr *Init) {
4137 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
4138}
4139
Mike Stumpf8c49212010-01-21 03:59:47 +00004140/// CheckParmsForFunctionDef - Check that the parameters of the given
4141/// function are appropriate for the definition of a function. This
4142/// takes care of any checks that cannot be performed on the
4143/// declaration itself, e.g., that the types of each of the function
4144/// parameters are complete.
Douglas Gregor82aa7132010-11-01 18:37:59 +00004145bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
4146 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00004147 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00004148 for (; P != PEnd; ++P) {
4149 ParmVarDecl *Param = *P;
4150
Mike Stumpf8c49212010-01-21 03:59:47 +00004151 // C99 6.7.5.3p4: the parameters in a parameter type list in a
4152 // function declarator that is part of a function definition of
4153 // that function shall not have incomplete type.
4154 //
4155 // This is also C++ [dcl.fct]p6.
4156 if (!Param->isInvalidDecl() &&
4157 RequireCompleteType(Param->getLocation(), Param->getType(),
4158 diag::err_typecheck_decl_incomplete_type)) {
4159 Param->setInvalidDecl();
4160 HasInvalidParm = true;
4161 }
4162
4163 // C99 6.9.1p5: If the declarator includes a parameter type list, the
4164 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00004165 if (CheckParameterNames &&
4166 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00004167 !Param->isImplicit() &&
4168 !getLangOptions().CPlusPlus)
4169 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00004170
4171 // C99 6.7.5.3p12:
4172 // If the function declarator is not part of a definition of that
4173 // function, parameters may have incomplete type and may use the [*]
4174 // notation in their sequences of declarator specifiers to specify
4175 // variable length array types.
4176 QualType PType = Param->getOriginalType();
4177 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
4178 if (AT->getSizeModifier() == ArrayType::Star) {
4179 // FIXME: This diagnosic should point the the '[*]' if source-location
4180 // information is added for it.
4181 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
4182 }
4183 }
Mike Stumpf8c49212010-01-21 03:59:47 +00004184 }
4185
4186 return HasInvalidParm;
4187}
John McCallb7f4ffe2010-08-12 21:44:57 +00004188
4189/// CheckCastAlign - Implements -Wcast-align, which warns when a
4190/// pointer cast increases the alignment requirements.
4191void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
4192 // This is actually a lot of work to potentially be doing on every
4193 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00004194 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
4195 TRange.getBegin())
David Blaikied6471f72011-09-25 23:23:43 +00004196 == DiagnosticsEngine::Ignored)
John McCallb7f4ffe2010-08-12 21:44:57 +00004197 return;
4198
4199 // Ignore dependent types.
4200 if (T->isDependentType() || Op->getType()->isDependentType())
4201 return;
4202
4203 // Require that the destination be a pointer type.
4204 const PointerType *DestPtr = T->getAs<PointerType>();
4205 if (!DestPtr) return;
4206
4207 // If the destination has alignment 1, we're done.
4208 QualType DestPointee = DestPtr->getPointeeType();
4209 if (DestPointee->isIncompleteType()) return;
4210 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
4211 if (DestAlign.isOne()) return;
4212
4213 // Require that the source be a pointer type.
4214 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
4215 if (!SrcPtr) return;
4216 QualType SrcPointee = SrcPtr->getPointeeType();
4217
4218 // Whitelist casts from cv void*. We already implicitly
4219 // whitelisted casts to cv void*, since they have alignment 1.
4220 // Also whitelist casts involving incomplete types, which implicitly
4221 // includes 'void'.
4222 if (SrcPointee->isIncompleteType()) return;
4223
4224 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
4225 if (SrcAlign >= DestAlign) return;
4226
4227 Diag(TRange.getBegin(), diag::warn_cast_align)
4228 << Op->getType() << T
4229 << static_cast<unsigned>(SrcAlign.getQuantity())
4230 << static_cast<unsigned>(DestAlign.getQuantity())
4231 << TRange << Op->getSourceRange();
4232}
4233
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004234static const Type* getElementType(const Expr *BaseExpr) {
4235 const Type* EltType = BaseExpr->getType().getTypePtr();
4236 if (EltType->isAnyPointerType())
4237 return EltType->getPointeeType().getTypePtr();
4238 else if (EltType->isArrayType())
4239 return EltType->getBaseElementTypeUnsafe();
4240 return EltType;
4241}
4242
Chandler Carruthc2684342011-08-05 09:10:50 +00004243/// \brief Check whether this array fits the idiom of a size-one tail padded
4244/// array member of a struct.
4245///
4246/// We avoid emitting out-of-bounds access warnings for such arrays as they are
4247/// commonly used to emulate flexible arrays in C89 code.
4248static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
4249 const NamedDecl *ND) {
4250 if (Size != 1 || !ND) return false;
4251
4252 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
4253 if (!FD) return false;
4254
4255 // Don't consider sizes resulting from macro expansions or template argument
4256 // substitution to form C89 tail-padded arrays.
4257 ConstantArrayTypeLoc TL =
4258 cast<ConstantArrayTypeLoc>(FD->getTypeSourceInfo()->getTypeLoc());
4259 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(TL.getSizeExpr());
4260 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
4261 return false;
4262
4263 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gay381711c2011-11-29 22:43:53 +00004264 if (!RD) return false;
4265 if (RD->isUnion()) return false;
4266 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
4267 if (!CRD->isStandardLayout()) return false;
4268 }
Chandler Carruthc2684342011-08-05 09:10:50 +00004269
Benjamin Kramer22d4fed2011-08-06 03:04:42 +00004270 // See if this is the last field decl in the record.
4271 const Decl *D = FD;
4272 while ((D = D->getNextDeclInContext()))
4273 if (isa<FieldDecl>(D))
4274 return false;
4275 return true;
Chandler Carruthc2684342011-08-05 09:10:50 +00004276}
4277
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004278void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004279 const ArraySubscriptExpr *ASE,
Richard Smith25b009a2011-12-16 19:31:14 +00004280 bool AllowOnePastEnd, bool IndexNegated) {
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004281 IndexExpr = IndexExpr->IgnoreParenCasts();
4282 if (IndexExpr->isValueDependent())
4283 return;
4284
Matt Beaumont-Gay8ef8f432011-12-12 22:35:02 +00004285 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004286 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth34064582011-02-17 20:55:08 +00004287 const ConstantArrayType *ArrayTy =
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004288 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00004289 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00004290 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00004291
Chandler Carruth34064582011-02-17 20:55:08 +00004292 llvm::APSInt index;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004293 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00004294 return;
Richard Smith25b009a2011-12-16 19:31:14 +00004295 if (IndexNegated)
4296 index = -index;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00004297
Chandler Carruthba447122011-08-05 08:07:29 +00004298 const NamedDecl *ND = NULL;
Chandler Carruthba447122011-08-05 08:07:29 +00004299 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
4300 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruthc2684342011-08-05 09:10:50 +00004301 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruthba447122011-08-05 08:07:29 +00004302 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruthba447122011-08-05 08:07:29 +00004303
Ted Kremenek9e060ca2011-02-23 23:06:04 +00004304 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00004305 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00004306 if (!size.isStrictlyPositive())
4307 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004308
4309 const Type* BaseType = getElementType(BaseExpr);
Nico Weberde5998f2011-09-17 22:59:41 +00004310 if (BaseType != EffectiveType) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004311 // Make sure we're comparing apples to apples when comparing index to size
4312 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
4313 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhraind10f4bc2011-08-10 19:47:25 +00004314 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhrain18f16972011-08-10 18:49:28 +00004315 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004316 if (ptrarith_typesize != array_typesize) {
4317 // There's a cast to a different size type involved
4318 uint64_t ratio = array_typesize / ptrarith_typesize;
4319 // TODO: Be smarter about handling cases where array_typesize is not a
4320 // multiple of ptrarith_typesize
4321 if (ptrarith_typesize * ratio == array_typesize)
4322 size *= llvm::APInt(size.getBitWidth(), ratio);
4323 }
4324 }
4325
Chandler Carruth34064582011-02-17 20:55:08 +00004326 if (size.getBitWidth() > index.getBitWidth())
4327 index = index.sext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00004328 else if (size.getBitWidth() < index.getBitWidth())
4329 size = size.sext(index.getBitWidth());
4330
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004331 // For array subscripting the index must be less than size, but for pointer
4332 // arithmetic also allow the index (offset) to be equal to size since
4333 // computing the next address after the end of the array is legal and
4334 // commonly done e.g. in C++ iterators and range-based for loops.
4335 if (AllowOnePastEnd ? index.sle(size) : index.slt(size))
Chandler Carruthba447122011-08-05 08:07:29 +00004336 return;
4337
4338 // Also don't warn for arrays of size 1 which are members of some
4339 // structure. These are often used to approximate flexible arrays in C89
4340 // code.
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004341 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00004342 return;
Chandler Carruth34064582011-02-17 20:55:08 +00004343
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004344 // Suppress the warning if the subscript expression (as identified by the
4345 // ']' location) and the index expression are both from macro expansions
4346 // within a system header.
4347 if (ASE) {
4348 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
4349 ASE->getRBracketLoc());
4350 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
4351 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
4352 IndexExpr->getLocStart());
4353 if (SourceMgr.isFromSameFile(RBracketLoc, IndexLoc))
4354 return;
4355 }
4356 }
4357
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004358 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004359 if (ASE)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004360 DiagID = diag::warn_array_index_exceeds_bounds;
4361
4362 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
4363 PDiag(DiagID) << index.toString(10, true)
4364 << size.toString(10, true)
4365 << (unsigned)size.getLimitedValue(~0U)
4366 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00004367 } else {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004368 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004369 if (!ASE) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004370 DiagID = diag::warn_ptr_arith_precedes_bounds;
4371 if (index.isNegative()) index = -index;
4372 }
4373
4374 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
4375 PDiag(DiagID) << index.toString(10, true)
4376 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00004377 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00004378
Matt Beaumont-Gaycfbc5b52011-11-29 19:27:11 +00004379 if (!ND) {
4380 // Try harder to find a NamedDecl to point at in the note.
4381 while (const ArraySubscriptExpr *ASE =
4382 dyn_cast<ArraySubscriptExpr>(BaseExpr))
4383 BaseExpr = ASE->getBase()->IgnoreParenCasts();
4384 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
4385 ND = dyn_cast<NamedDecl>(DRE->getDecl());
4386 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
4387 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
4388 }
4389
Chandler Carruth35001ca2011-02-17 21:10:52 +00004390 if (ND)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004391 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
4392 PDiag(diag::note_array_index_out_of_bounds)
4393 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00004394}
4395
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004396void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004397 int AllowOnePastEnd = 0;
4398 while (expr) {
4399 expr = expr->IgnoreParenImpCasts();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004400 switch (expr->getStmtClass()) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004401 case Stmt::ArraySubscriptExprClass: {
4402 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004403 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004404 AllowOnePastEnd > 0);
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004405 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004406 }
4407 case Stmt::UnaryOperatorClass: {
4408 // Only unwrap the * and & unary operators
4409 const UnaryOperator *UO = cast<UnaryOperator>(expr);
4410 expr = UO->getSubExpr();
4411 switch (UO->getOpcode()) {
4412 case UO_AddrOf:
4413 AllowOnePastEnd++;
4414 break;
4415 case UO_Deref:
4416 AllowOnePastEnd--;
4417 break;
4418 default:
4419 return;
4420 }
4421 break;
4422 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004423 case Stmt::ConditionalOperatorClass: {
4424 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
4425 if (const Expr *lhs = cond->getLHS())
4426 CheckArrayAccess(lhs);
4427 if (const Expr *rhs = cond->getRHS())
4428 CheckArrayAccess(rhs);
4429 return;
4430 }
4431 default:
4432 return;
4433 }
Peter Collingbournef111d932011-04-15 00:35:48 +00004434 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004435}
John McCallf85e1932011-06-15 23:02:42 +00004436
4437//===--- CHECK: Objective-C retain cycles ----------------------------------//
4438
4439namespace {
4440 struct RetainCycleOwner {
4441 RetainCycleOwner() : Variable(0), Indirect(false) {}
4442 VarDecl *Variable;
4443 SourceRange Range;
4444 SourceLocation Loc;
4445 bool Indirect;
4446
4447 void setLocsFrom(Expr *e) {
4448 Loc = e->getExprLoc();
4449 Range = e->getSourceRange();
4450 }
4451 };
4452}
4453
4454/// Consider whether capturing the given variable can possibly lead to
4455/// a retain cycle.
4456static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
4457 // In ARC, it's captured strongly iff the variable has __strong
4458 // lifetime. In MRR, it's captured strongly if the variable is
4459 // __block and has an appropriate type.
4460 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
4461 return false;
4462
4463 owner.Variable = var;
4464 owner.setLocsFrom(ref);
4465 return true;
4466}
4467
4468static bool findRetainCycleOwner(Expr *e, RetainCycleOwner &owner) {
4469 while (true) {
4470 e = e->IgnoreParens();
4471 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
4472 switch (cast->getCastKind()) {
4473 case CK_BitCast:
4474 case CK_LValueBitCast:
4475 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00004476 case CK_ARCReclaimReturnedObject:
John McCallf85e1932011-06-15 23:02:42 +00004477 e = cast->getSubExpr();
4478 continue;
4479
John McCallf85e1932011-06-15 23:02:42 +00004480 default:
4481 return false;
4482 }
4483 }
4484
4485 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
4486 ObjCIvarDecl *ivar = ref->getDecl();
4487 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
4488 return false;
4489
4490 // Try to find a retain cycle in the base.
4491 if (!findRetainCycleOwner(ref->getBase(), owner))
4492 return false;
4493
4494 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
4495 owner.Indirect = true;
4496 return true;
4497 }
4498
4499 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
4500 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
4501 if (!var) return false;
4502 return considerVariable(var, ref, owner);
4503 }
4504
4505 if (BlockDeclRefExpr *ref = dyn_cast<BlockDeclRefExpr>(e)) {
4506 owner.Variable = ref->getDecl();
4507 owner.setLocsFrom(ref);
4508 return true;
4509 }
4510
4511 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
4512 if (member->isArrow()) return false;
4513
4514 // Don't count this as an indirect ownership.
4515 e = member->getBase();
4516 continue;
4517 }
4518
John McCall4b9c2d22011-11-06 09:01:30 +00004519 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
4520 // Only pay attention to pseudo-objects on property references.
4521 ObjCPropertyRefExpr *pre
4522 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
4523 ->IgnoreParens());
4524 if (!pre) return false;
4525 if (pre->isImplicitProperty()) return false;
4526 ObjCPropertyDecl *property = pre->getExplicitProperty();
4527 if (!property->isRetaining() &&
4528 !(property->getPropertyIvarDecl() &&
4529 property->getPropertyIvarDecl()->getType()
4530 .getObjCLifetime() == Qualifiers::OCL_Strong))
4531 return false;
4532
4533 owner.Indirect = true;
4534 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
4535 ->getSourceExpr());
4536 continue;
4537 }
4538
John McCallf85e1932011-06-15 23:02:42 +00004539 // Array ivars?
4540
4541 return false;
4542 }
4543}
4544
4545namespace {
4546 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
4547 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
4548 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
4549 Variable(variable), Capturer(0) {}
4550
4551 VarDecl *Variable;
4552 Expr *Capturer;
4553
4554 void VisitDeclRefExpr(DeclRefExpr *ref) {
4555 if (ref->getDecl() == Variable && !Capturer)
4556 Capturer = ref;
4557 }
4558
4559 void VisitBlockDeclRefExpr(BlockDeclRefExpr *ref) {
4560 if (ref->getDecl() == Variable && !Capturer)
4561 Capturer = ref;
4562 }
4563
4564 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
4565 if (Capturer) return;
4566 Visit(ref->getBase());
4567 if (Capturer && ref->isFreeIvar())
4568 Capturer = ref;
4569 }
4570
4571 void VisitBlockExpr(BlockExpr *block) {
4572 // Look inside nested blocks
4573 if (block->getBlockDecl()->capturesVariable(Variable))
4574 Visit(block->getBlockDecl()->getBody());
4575 }
4576 };
4577}
4578
4579/// Check whether the given argument is a block which captures a
4580/// variable.
4581static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
4582 assert(owner.Variable && owner.Loc.isValid());
4583
4584 e = e->IgnoreParenCasts();
4585 BlockExpr *block = dyn_cast<BlockExpr>(e);
4586 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
4587 return 0;
4588
4589 FindCaptureVisitor visitor(S.Context, owner.Variable);
4590 visitor.Visit(block->getBlockDecl()->getBody());
4591 return visitor.Capturer;
4592}
4593
4594static void diagnoseRetainCycle(Sema &S, Expr *capturer,
4595 RetainCycleOwner &owner) {
4596 assert(capturer);
4597 assert(owner.Variable && owner.Loc.isValid());
4598
4599 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
4600 << owner.Variable << capturer->getSourceRange();
4601 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
4602 << owner.Indirect << owner.Range;
4603}
4604
4605/// Check for a keyword selector that starts with the word 'add' or
4606/// 'set'.
4607static bool isSetterLikeSelector(Selector sel) {
4608 if (sel.isUnarySelector()) return false;
4609
Chris Lattner5f9e2722011-07-23 10:55:15 +00004610 StringRef str = sel.getNameForSlot(0);
John McCallf85e1932011-06-15 23:02:42 +00004611 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00004612 if (str.startswith("set"))
John McCallf85e1932011-06-15 23:02:42 +00004613 str = str.substr(3);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00004614 else if (str.startswith("add")) {
4615 // Specially whitelist 'addOperationWithBlock:'.
4616 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
4617 return false;
4618 str = str.substr(3);
4619 }
John McCallf85e1932011-06-15 23:02:42 +00004620 else
4621 return false;
4622
4623 if (str.empty()) return true;
4624 return !islower(str.front());
4625}
4626
4627/// Check a message send to see if it's likely to cause a retain cycle.
4628void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
4629 // Only check instance methods whose selector looks like a setter.
4630 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
4631 return;
4632
4633 // Try to find a variable that the receiver is strongly owned by.
4634 RetainCycleOwner owner;
4635 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
4636 if (!findRetainCycleOwner(msg->getInstanceReceiver(), owner))
4637 return;
4638 } else {
4639 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
4640 owner.Variable = getCurMethodDecl()->getSelfDecl();
4641 owner.Loc = msg->getSuperLoc();
4642 owner.Range = msg->getSuperLoc();
4643 }
4644
4645 // Check whether the receiver is captured by any of the arguments.
4646 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
4647 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
4648 return diagnoseRetainCycle(*this, capturer, owner);
4649}
4650
4651/// Check a property assign to see if it's likely to cause a retain cycle.
4652void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
4653 RetainCycleOwner owner;
4654 if (!findRetainCycleOwner(receiver, owner))
4655 return;
4656
4657 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
4658 diagnoseRetainCycle(*this, capturer, owner);
4659}
4660
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004661bool Sema::checkUnsafeAssigns(SourceLocation Loc,
John McCallf85e1932011-06-15 23:02:42 +00004662 QualType LHS, Expr *RHS) {
4663 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
4664 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004665 return false;
4666 // strip off any implicit cast added to get to the one arc-specific
4667 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00004668 if (cast->getCastKind() == CK_ARCConsumeObject) {
John McCallf85e1932011-06-15 23:02:42 +00004669 Diag(Loc, diag::warn_arc_retained_assign)
4670 << (LT == Qualifiers::OCL_ExplicitNone)
4671 << RHS->getSourceRange();
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004672 return true;
4673 }
4674 RHS = cast->getSubExpr();
4675 }
4676 return false;
John McCallf85e1932011-06-15 23:02:42 +00004677}
4678
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004679void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
4680 Expr *LHS, Expr *RHS) {
4681 QualType LHSType = LHS->getType();
4682 if (checkUnsafeAssigns(Loc, LHSType, RHS))
4683 return;
4684 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
4685 // FIXME. Check for other life times.
4686 if (LT != Qualifiers::OCL_None)
4687 return;
4688
John McCall3c3b7f92011-10-25 17:37:35 +00004689 if (ObjCPropertyRefExpr *PRE
4690 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens())) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004691 if (PRE->isImplicitProperty())
4692 return;
4693 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
4694 if (!PD)
4695 return;
4696
4697 unsigned Attributes = PD->getPropertyAttributes();
4698 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign)
4699 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00004700 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004701 Diag(Loc, diag::warn_arc_retained_property_assign)
4702 << RHS->getSourceRange();
4703 return;
4704 }
4705 RHS = cast->getSubExpr();
4706 }
4707 }
4708}