blob: af0eedd791d8c8e6f18162ebf72b60548b78fea6 [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);
David Chisnall7a7ee302012-01-16 17:27:18 +0000280 case Builtin::BI__atomic_init:
281 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Init);
Eli Friedman276b0612011-10-11 02:20:01 +0000282 case Builtin::BI__atomic_exchange:
283 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Xchg);
284 case Builtin::BI__atomic_compare_exchange_strong:
285 return SemaAtomicOpsOverloaded(move(TheCallResult),
286 AtomicExpr::CmpXchgStrong);
287 case Builtin::BI__atomic_compare_exchange_weak:
288 return SemaAtomicOpsOverloaded(move(TheCallResult),
289 AtomicExpr::CmpXchgWeak);
290 case Builtin::BI__atomic_fetch_add:
291 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Add);
292 case Builtin::BI__atomic_fetch_sub:
293 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Sub);
294 case Builtin::BI__atomic_fetch_and:
295 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::And);
296 case Builtin::BI__atomic_fetch_or:
297 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Or);
298 case Builtin::BI__atomic_fetch_xor:
299 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Xor);
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000300 case Builtin::BI__builtin_annotation:
301 if (CheckBuiltinAnnotationString(*this, TheCall->getArg(1)))
302 return ExprError();
303 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000304 }
305
306 // Since the target specific builtins for each arch overlap, only check those
307 // of the arch we are compiling for.
308 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000309 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman26a31422010-06-08 02:47:44 +0000310 case llvm::Triple::arm:
311 case llvm::Triple::thumb:
312 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
313 return ExprError();
314 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000315 default:
316 break;
317 }
318 }
319
320 return move(TheCallResult);
321}
322
Nate Begeman61eecf52010-06-14 05:21:25 +0000323// Get the valid immediate range for the specified NEON type code.
324static unsigned RFT(unsigned t, bool shift = false) {
Bob Wilsonda95f732011-11-08 01:16:11 +0000325 NeonTypeFlags Type(t);
326 int IsQuad = Type.isQuad();
327 switch (Type.getEltType()) {
328 case NeonTypeFlags::Int8:
329 case NeonTypeFlags::Poly8:
330 return shift ? 7 : (8 << IsQuad) - 1;
331 case NeonTypeFlags::Int16:
332 case NeonTypeFlags::Poly16:
333 return shift ? 15 : (4 << IsQuad) - 1;
334 case NeonTypeFlags::Int32:
335 return shift ? 31 : (2 << IsQuad) - 1;
336 case NeonTypeFlags::Int64:
337 return shift ? 63 : (1 << IsQuad) - 1;
338 case NeonTypeFlags::Float16:
339 assert(!shift && "cannot shift float types!");
340 return (4 << IsQuad) - 1;
341 case NeonTypeFlags::Float32:
342 assert(!shift && "cannot shift float types!");
343 return (2 << IsQuad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000344 }
345 return 0;
346}
347
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000348/// getNeonEltType - Return the QualType corresponding to the elements of
349/// the vector type specified by the NeonTypeFlags. This is used to check
350/// the pointer arguments for Neon load/store intrinsics.
351static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context) {
352 switch (Flags.getEltType()) {
353 case NeonTypeFlags::Int8:
354 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
355 case NeonTypeFlags::Int16:
356 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
357 case NeonTypeFlags::Int32:
358 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
359 case NeonTypeFlags::Int64:
360 return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy;
361 case NeonTypeFlags::Poly8:
362 return Context.SignedCharTy;
363 case NeonTypeFlags::Poly16:
364 return Context.ShortTy;
365 case NeonTypeFlags::Float16:
366 return Context.UnsignedShortTy;
367 case NeonTypeFlags::Float32:
368 return Context.FloatTy;
369 }
370 return QualType();
371}
372
Nate Begeman26a31422010-06-08 02:47:44 +0000373bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000374 llvm::APSInt Result;
375
Nate Begeman0d15c532010-06-13 04:47:52 +0000376 unsigned mask = 0;
Nate Begeman61eecf52010-06-14 05:21:25 +0000377 unsigned TV = 0;
Bob Wilson46482552011-11-16 21:32:23 +0000378 int PtrArgNum = -1;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000379 bool HasConstPtr = false;
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000380 switch (BuiltinID) {
Nate Begemana23326b2010-06-17 04:17:01 +0000381#define GET_NEON_OVERLOAD_CHECK
382#include "clang/Basic/arm_neon.inc"
383#undef GET_NEON_OVERLOAD_CHECK
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000384 }
385
Nate Begeman0d15c532010-06-13 04:47:52 +0000386 // For NEON intrinsics which are overloaded on vector element type, validate
387 // the immediate which specifies which variant to emit.
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000388 unsigned ImmArg = TheCall->getNumArgs()-1;
Nate Begeman0d15c532010-06-13 04:47:52 +0000389 if (mask) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000390 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
Nate Begeman0d15c532010-06-13 04:47:52 +0000391 return true;
392
Bob Wilsonda95f732011-11-08 01:16:11 +0000393 TV = Result.getLimitedValue(64);
394 if ((TV > 63) || (mask & (1 << TV)) == 0)
Nate Begeman0d15c532010-06-13 04:47:52 +0000395 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000396 << TheCall->getArg(ImmArg)->getSourceRange();
397 }
398
Bob Wilson46482552011-11-16 21:32:23 +0000399 if (PtrArgNum >= 0) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000400 // Check that pointer arguments have the specified type.
Bob Wilson46482552011-11-16 21:32:23 +0000401 Expr *Arg = TheCall->getArg(PtrArgNum);
402 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
403 Arg = ICE->getSubExpr();
404 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
405 QualType RHSTy = RHS.get()->getType();
406 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context);
407 if (HasConstPtr)
408 EltTy = EltTy.withConst();
409 QualType LHSTy = Context.getPointerType(EltTy);
410 AssignConvertType ConvTy;
411 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
412 if (RHS.isInvalid())
413 return true;
414 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
415 RHS.get(), AA_Assigning))
416 return true;
Nate Begeman0d15c532010-06-13 04:47:52 +0000417 }
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000418
Nate Begeman0d15c532010-06-13 04:47:52 +0000419 // For NEON intrinsics which take an immediate value as part of the
420 // instruction, range check them here.
Nate Begeman61eecf52010-06-14 05:21:25 +0000421 unsigned i = 0, l = 0, u = 0;
Nate Begeman0d15c532010-06-13 04:47:52 +0000422 switch (BuiltinID) {
423 default: return false;
Nate Begemanbb37f502010-07-29 22:48:34 +0000424 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
425 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begeman99c40bb2010-08-03 21:32:34 +0000426 case ARM::BI__builtin_arm_vcvtr_f:
427 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Nate Begemana23326b2010-06-17 04:17:01 +0000428#define GET_NEON_IMMEDIATE_CHECK
429#include "clang/Basic/arm_neon.inc"
430#undef GET_NEON_IMMEDIATE_CHECK
Nate Begeman0d15c532010-06-13 04:47:52 +0000431 };
432
Nate Begeman61eecf52010-06-14 05:21:25 +0000433 // Check that the immediate argument is actually a constant.
Nate Begeman0d15c532010-06-13 04:47:52 +0000434 if (SemaBuiltinConstantArg(TheCall, i, Result))
435 return true;
436
Nate Begeman61eecf52010-06-14 05:21:25 +0000437 // Range check against the upper/lower values for this isntruction.
Nate Begeman0d15c532010-06-13 04:47:52 +0000438 unsigned Val = Result.getZExtValue();
Nate Begeman61eecf52010-06-14 05:21:25 +0000439 if (Val < l || Val > (u + l))
Nate Begeman0d15c532010-06-13 04:47:52 +0000440 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramer476d8b82010-08-11 14:47:12 +0000441 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begeman0d15c532010-06-13 04:47:52 +0000442
Nate Begeman99c40bb2010-08-03 21:32:34 +0000443 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman26a31422010-06-08 02:47:44 +0000444 return false;
Anders Carlssond406bf02009-08-16 01:56:34 +0000445}
Daniel Dunbarde454282008-10-02 18:44:07 +0000446
Anders Carlssond406bf02009-08-16 01:56:34 +0000447/// CheckFunctionCall - Check a direct function call for various correctness
448/// and safety properties not strictly enforced by the C type system.
449bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
450 // Get the IdentifierInfo* for the called function.
451 IdentifierInfo *FnInfo = FDecl->getIdentifier();
452
453 // None of the checks below are needed for functions that don't have
454 // simple names (e.g., C++ conversion functions).
455 if (!FnInfo)
456 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000457
Daniel Dunbarde454282008-10-02 18:44:07 +0000458 // FIXME: This mechanism should be abstracted to be less fragile and
459 // more efficient. For example, just map function ids to custom
460 // handlers.
461
Ted Kremenekc82faca2010-09-09 04:33:05 +0000462 // Printf and scanf checking.
463 for (specific_attr_iterator<FormatAttr>
464 i = FDecl->specific_attr_begin<FormatAttr>(),
465 e = FDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) {
466
467 const FormatAttr *Format = *i;
Ted Kremenek826a3452010-07-16 02:11:22 +0000468 const bool b = Format->getType() == "scanf";
469 if (b || CheckablePrintfAttr(Format, TheCall)) {
Ted Kremenek3d692df2009-02-27 17:58:43 +0000470 bool HasVAListArg = Format->getFirstArg() == 0;
Ted Kremenek826a3452010-07-16 02:11:22 +0000471 CheckPrintfScanfArguments(TheCall, HasVAListArg,
472 Format->getFormatIdx() - 1,
473 HasVAListArg ? 0 : Format->getFirstArg() - 1,
474 !b);
Douglas Gregor3c385e52009-02-14 18:57:46 +0000475 }
Chris Lattner59907c42007-08-10 20:18:51 +0000476 }
Mike Stump1eb44332009-09-09 15:08:12 +0000477
Ted Kremenekc82faca2010-09-09 04:33:05 +0000478 for (specific_attr_iterator<NonNullAttr>
479 i = FDecl->specific_attr_begin<NonNullAttr>(),
480 e = FDecl->specific_attr_end<NonNullAttr>(); i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +0000481 CheckNonNullArguments(*i, TheCall->getArgs(),
482 TheCall->getCallee()->getLocStart());
Ted Kremenekc82faca2010-09-09 04:33:05 +0000483 }
Sebastian Redl0eb23302009-01-19 00:08:26 +0000484
Anna Zaks0a151a12012-01-17 00:37:07 +0000485 unsigned CMId = FDecl->getMemoryFunctionKind();
486 if (CMId == 0)
Anna Zaksd9b859a2012-01-13 21:52:01 +0000487 return false;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000488
Anna Zaksd9b859a2012-01-13 21:52:01 +0000489 // Handle memory setting and copying functions.
Anna Zaks0a151a12012-01-17 00:37:07 +0000490 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000491 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaksd9b859a2012-01-13 21:52:01 +0000492 else
Anna Zaks0a151a12012-01-17 00:37:07 +0000493 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth7ccc95b2011-04-27 07:05:31 +0000494
Anders Carlssond406bf02009-08-16 01:56:34 +0000495 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000496}
497
Anders Carlssond406bf02009-08-16 01:56:34 +0000498bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000499 // Printf checking.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000500 const FormatAttr *Format = NDecl->getAttr<FormatAttr>();
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000501 if (!Format)
Anders Carlssond406bf02009-08-16 01:56:34 +0000502 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000503
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000504 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
505 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000506 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000507
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000508 QualType Ty = V->getType();
509 if (!Ty->isBlockPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000510 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000511
Ted Kremenek826a3452010-07-16 02:11:22 +0000512 const bool b = Format->getType() == "scanf";
513 if (!b && !CheckablePrintfAttr(Format, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +0000514 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000515
Anders Carlssond406bf02009-08-16 01:56:34 +0000516 bool HasVAListArg = Format->getFirstArg() == 0;
Ted Kremenek826a3452010-07-16 02:11:22 +0000517 CheckPrintfScanfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
518 HasVAListArg ? 0 : Format->getFirstArg() - 1, !b);
Anders Carlssond406bf02009-08-16 01:56:34 +0000519
520 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000521}
522
Eli Friedman276b0612011-10-11 02:20:01 +0000523ExprResult
524Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, AtomicExpr::AtomicOp Op) {
525 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
526 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedman276b0612011-10-11 02:20:01 +0000527
528 // All these operations take one of the following four forms:
529 // T __atomic_load(_Atomic(T)*, int) (loads)
530 // T* __atomic_add(_Atomic(T*)*, ptrdiff_t, int) (pointer add/sub)
531 // int __atomic_compare_exchange_strong(_Atomic(T)*, T*, T, int, int)
532 // (cmpxchg)
533 // T __atomic_exchange(_Atomic(T)*, T, int) (everything else)
534 // where T is an appropriate type, and the int paremeterss are for orderings.
535 unsigned NumVals = 1;
536 unsigned NumOrders = 1;
537 if (Op == AtomicExpr::Load) {
538 NumVals = 0;
539 } else if (Op == AtomicExpr::CmpXchgWeak || Op == AtomicExpr::CmpXchgStrong) {
540 NumVals = 2;
541 NumOrders = 2;
542 }
David Chisnall7a7ee302012-01-16 17:27:18 +0000543 if (Op == AtomicExpr::Init)
544 NumOrders = 0;
Eli Friedman276b0612011-10-11 02:20:01 +0000545
546 if (TheCall->getNumArgs() < NumVals+NumOrders+1) {
547 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
548 << 0 << NumVals+NumOrders+1 << TheCall->getNumArgs()
549 << TheCall->getCallee()->getSourceRange();
550 return ExprError();
551 } else if (TheCall->getNumArgs() > NumVals+NumOrders+1) {
552 Diag(TheCall->getArg(NumVals+NumOrders+1)->getLocStart(),
553 diag::err_typecheck_call_too_many_args)
554 << 0 << NumVals+NumOrders+1 << TheCall->getNumArgs()
555 << TheCall->getCallee()->getSourceRange();
556 return ExprError();
557 }
558
559 // Inspect the first argument of the atomic operation. This should always be
560 // a pointer to an _Atomic type.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000561 Expr *Ptr = TheCall->getArg(0);
Eli Friedman276b0612011-10-11 02:20:01 +0000562 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
563 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
564 if (!pointerType) {
565 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
566 << Ptr->getType() << Ptr->getSourceRange();
567 return ExprError();
568 }
569
570 QualType AtomTy = pointerType->getPointeeType();
571 if (!AtomTy->isAtomicType()) {
572 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
573 << Ptr->getType() << Ptr->getSourceRange();
574 return ExprError();
575 }
576 QualType ValType = AtomTy->getAs<AtomicType>()->getValueType();
577
578 if ((Op == AtomicExpr::Add || Op == AtomicExpr::Sub) &&
579 !ValType->isIntegerType() && !ValType->isPointerType()) {
580 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
581 << Ptr->getType() << Ptr->getSourceRange();
582 return ExprError();
583 }
584
585 if (!ValType->isIntegerType() &&
586 (Op == AtomicExpr::And || Op == AtomicExpr::Or || Op == AtomicExpr::Xor)){
587 Diag(DRE->getLocStart(), diag::err_atomic_op_logical_needs_atomic_int)
588 << Ptr->getType() << Ptr->getSourceRange();
589 return ExprError();
590 }
591
592 switch (ValType.getObjCLifetime()) {
593 case Qualifiers::OCL_None:
594 case Qualifiers::OCL_ExplicitNone:
595 // okay
596 break;
597
598 case Qualifiers::OCL_Weak:
599 case Qualifiers::OCL_Strong:
600 case Qualifiers::OCL_Autoreleasing:
601 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
602 << ValType << Ptr->getSourceRange();
603 return ExprError();
604 }
605
606 QualType ResultType = ValType;
David Chisnall7a7ee302012-01-16 17:27:18 +0000607 if (Op == AtomicExpr::Store || Op == AtomicExpr::Init)
Eli Friedman276b0612011-10-11 02:20:01 +0000608 ResultType = Context.VoidTy;
609 else if (Op == AtomicExpr::CmpXchgWeak || Op == AtomicExpr::CmpXchgStrong)
610 ResultType = Context.BoolTy;
611
612 // The first argument --- the pointer --- has a fixed type; we
613 // deduce the types of the rest of the arguments accordingly. Walk
614 // the remaining arguments, converting them to the deduced value type.
615 for (unsigned i = 1; i != NumVals+NumOrders+1; ++i) {
616 ExprResult Arg = TheCall->getArg(i);
617 QualType Ty;
618 if (i < NumVals+1) {
619 // The second argument to a cmpxchg is a pointer to the data which will
620 // be exchanged. The second argument to a pointer add/subtract is the
621 // amount to add/subtract, which must be a ptrdiff_t. The third
622 // argument to a cmpxchg and the second argument in all other cases
623 // is the type of the value.
624 if (i == 1 && (Op == AtomicExpr::CmpXchgWeak ||
625 Op == AtomicExpr::CmpXchgStrong))
626 Ty = Context.getPointerType(ValType.getUnqualifiedType());
627 else if (!ValType->isIntegerType() &&
628 (Op == AtomicExpr::Add || Op == AtomicExpr::Sub))
629 Ty = Context.getPointerDiffType();
630 else
631 Ty = ValType;
632 } else {
633 // The order(s) are always converted to int.
634 Ty = Context.IntTy;
635 }
636 InitializedEntity Entity =
637 InitializedEntity::InitializeParameter(Context, Ty, false);
638 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
639 if (Arg.isInvalid())
640 return true;
641 TheCall->setArg(i, Arg.get());
642 }
643
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000644 SmallVector<Expr*, 5> SubExprs;
645 SubExprs.push_back(Ptr);
Eli Friedman276b0612011-10-11 02:20:01 +0000646 if (Op == AtomicExpr::Load) {
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000647 SubExprs.push_back(TheCall->getArg(1)); // Order
David Chisnall7a7ee302012-01-16 17:27:18 +0000648 } else if (Op == AtomicExpr::Init) {
649 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman276b0612011-10-11 02:20:01 +0000650 } else if (Op != AtomicExpr::CmpXchgWeak && Op != AtomicExpr::CmpXchgStrong) {
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000651 SubExprs.push_back(TheCall->getArg(2)); // Order
652 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman276b0612011-10-11 02:20:01 +0000653 } else {
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000654 SubExprs.push_back(TheCall->getArg(3)); // Order
655 SubExprs.push_back(TheCall->getArg(1)); // Val1
656 SubExprs.push_back(TheCall->getArg(2)); // Val2
657 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
Eli Friedman276b0612011-10-11 02:20:01 +0000658 }
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000659
660 return Owned(new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
661 SubExprs.data(), SubExprs.size(),
662 ResultType, Op,
663 TheCall->getRParenLoc()));
Eli Friedman276b0612011-10-11 02:20:01 +0000664}
665
666
John McCall5f8d6042011-08-27 01:09:30 +0000667/// checkBuiltinArgument - Given a call to a builtin function, perform
668/// normal type-checking on the given argument, updating the call in
669/// place. This is useful when a builtin function requires custom
670/// type-checking for some of its arguments but not necessarily all of
671/// them.
672///
673/// Returns true on error.
674static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
675 FunctionDecl *Fn = E->getDirectCallee();
676 assert(Fn && "builtin call without direct callee!");
677
678 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
679 InitializedEntity Entity =
680 InitializedEntity::InitializeParameter(S.Context, Param);
681
682 ExprResult Arg = E->getArg(0);
683 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
684 if (Arg.isInvalid())
685 return true;
686
687 E->setArg(ArgIndex, Arg.take());
688 return false;
689}
690
Chris Lattner5caa3702009-05-08 06:58:22 +0000691/// SemaBuiltinAtomicOverloaded - We have a call to a function like
692/// __sync_fetch_and_add, which is an overloaded function based on the pointer
693/// type of its first argument. The main ActOnCallExpr routines have already
694/// promoted the types of arguments because all of these calls are prototyped as
695/// void(...).
696///
697/// This function goes through and does final semantic checking for these
698/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +0000699ExprResult
700Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000701 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +0000702 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
703 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
704
705 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +0000706 if (TheCall->getNumArgs() < 1) {
707 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
708 << 0 << 1 << TheCall->getNumArgs()
709 << TheCall->getCallee()->getSourceRange();
710 return ExprError();
711 }
Mike Stump1eb44332009-09-09 15:08:12 +0000712
Chris Lattner5caa3702009-05-08 06:58:22 +0000713 // Inspect the first argument of the atomic builtin. This should always be
714 // a pointer type, whose element is an integral scalar or pointer type.
715 // Because it is a pointer type, we don't have to worry about any implicit
716 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +0000717 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +0000718 Expr *FirstArg = TheCall->getArg(0);
John McCallf85e1932011-06-15 23:02:42 +0000719 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
720 if (!pointerType) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000721 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
722 << FirstArg->getType() << FirstArg->getSourceRange();
723 return ExprError();
724 }
Mike Stump1eb44332009-09-09 15:08:12 +0000725
John McCallf85e1932011-06-15 23:02:42 +0000726 QualType ValType = pointerType->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +0000727 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +0000728 !ValType->isBlockPointerType()) {
729 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
730 << FirstArg->getType() << FirstArg->getSourceRange();
731 return ExprError();
732 }
Chris Lattner5caa3702009-05-08 06:58:22 +0000733
John McCallf85e1932011-06-15 23:02:42 +0000734 switch (ValType.getObjCLifetime()) {
735 case Qualifiers::OCL_None:
736 case Qualifiers::OCL_ExplicitNone:
737 // okay
738 break;
739
740 case Qualifiers::OCL_Weak:
741 case Qualifiers::OCL_Strong:
742 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +0000743 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCallf85e1932011-06-15 23:02:42 +0000744 << ValType << FirstArg->getSourceRange();
745 return ExprError();
746 }
747
John McCallb45ae252011-10-05 07:41:44 +0000748 // Strip any qualifiers off ValType.
749 ValType = ValType.getUnqualifiedType();
750
Chandler Carruth8d13d222010-07-18 20:54:12 +0000751 // The majority of builtins return a value, but a few have special return
752 // types, so allow them to override appropriately below.
753 QualType ResultType = ValType;
754
Chris Lattner5caa3702009-05-08 06:58:22 +0000755 // We need to figure out which concrete builtin this maps onto. For example,
756 // __sync_fetch_and_add with a 2 byte object turns into
757 // __sync_fetch_and_add_2.
758#define BUILTIN_ROW(x) \
759 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
760 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +0000761
Chris Lattner5caa3702009-05-08 06:58:22 +0000762 static const unsigned BuiltinIndices[][5] = {
763 BUILTIN_ROW(__sync_fetch_and_add),
764 BUILTIN_ROW(__sync_fetch_and_sub),
765 BUILTIN_ROW(__sync_fetch_and_or),
766 BUILTIN_ROW(__sync_fetch_and_and),
767 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +0000768
Chris Lattner5caa3702009-05-08 06:58:22 +0000769 BUILTIN_ROW(__sync_add_and_fetch),
770 BUILTIN_ROW(__sync_sub_and_fetch),
771 BUILTIN_ROW(__sync_and_and_fetch),
772 BUILTIN_ROW(__sync_or_and_fetch),
773 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +0000774
Chris Lattner5caa3702009-05-08 06:58:22 +0000775 BUILTIN_ROW(__sync_val_compare_and_swap),
776 BUILTIN_ROW(__sync_bool_compare_and_swap),
777 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner23aa9c82011-04-09 03:57:26 +0000778 BUILTIN_ROW(__sync_lock_release),
779 BUILTIN_ROW(__sync_swap)
Chris Lattner5caa3702009-05-08 06:58:22 +0000780 };
Mike Stump1eb44332009-09-09 15:08:12 +0000781#undef BUILTIN_ROW
782
Chris Lattner5caa3702009-05-08 06:58:22 +0000783 // Determine the index of the size.
784 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +0000785 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +0000786 case 1: SizeIndex = 0; break;
787 case 2: SizeIndex = 1; break;
788 case 4: SizeIndex = 2; break;
789 case 8: SizeIndex = 3; break;
790 case 16: SizeIndex = 4; break;
791 default:
Chandler Carruthd2014572010-07-09 18:59:35 +0000792 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
793 << FirstArg->getType() << FirstArg->getSourceRange();
794 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +0000795 }
Mike Stump1eb44332009-09-09 15:08:12 +0000796
Chris Lattner5caa3702009-05-08 06:58:22 +0000797 // Each of these builtins has one pointer argument, followed by some number of
798 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
799 // that we ignore. Find out which row of BuiltinIndices to read from as well
800 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +0000801 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +0000802 unsigned BuiltinIndex, NumFixed = 1;
803 switch (BuiltinID) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000804 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregora9766412011-11-28 16:30:08 +0000805 case Builtin::BI__sync_fetch_and_add:
806 case Builtin::BI__sync_fetch_and_add_1:
807 case Builtin::BI__sync_fetch_and_add_2:
808 case Builtin::BI__sync_fetch_and_add_4:
809 case Builtin::BI__sync_fetch_and_add_8:
810 case Builtin::BI__sync_fetch_and_add_16:
811 BuiltinIndex = 0;
812 break;
813
814 case Builtin::BI__sync_fetch_and_sub:
815 case Builtin::BI__sync_fetch_and_sub_1:
816 case Builtin::BI__sync_fetch_and_sub_2:
817 case Builtin::BI__sync_fetch_and_sub_4:
818 case Builtin::BI__sync_fetch_and_sub_8:
819 case Builtin::BI__sync_fetch_and_sub_16:
820 BuiltinIndex = 1;
821 break;
822
823 case Builtin::BI__sync_fetch_and_or:
824 case Builtin::BI__sync_fetch_and_or_1:
825 case Builtin::BI__sync_fetch_and_or_2:
826 case Builtin::BI__sync_fetch_and_or_4:
827 case Builtin::BI__sync_fetch_and_or_8:
828 case Builtin::BI__sync_fetch_and_or_16:
829 BuiltinIndex = 2;
830 break;
831
832 case Builtin::BI__sync_fetch_and_and:
833 case Builtin::BI__sync_fetch_and_and_1:
834 case Builtin::BI__sync_fetch_and_and_2:
835 case Builtin::BI__sync_fetch_and_and_4:
836 case Builtin::BI__sync_fetch_and_and_8:
837 case Builtin::BI__sync_fetch_and_and_16:
838 BuiltinIndex = 3;
839 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000840
Douglas Gregora9766412011-11-28 16:30:08 +0000841 case Builtin::BI__sync_fetch_and_xor:
842 case Builtin::BI__sync_fetch_and_xor_1:
843 case Builtin::BI__sync_fetch_and_xor_2:
844 case Builtin::BI__sync_fetch_and_xor_4:
845 case Builtin::BI__sync_fetch_and_xor_8:
846 case Builtin::BI__sync_fetch_and_xor_16:
847 BuiltinIndex = 4;
848 break;
849
850 case Builtin::BI__sync_add_and_fetch:
851 case Builtin::BI__sync_add_and_fetch_1:
852 case Builtin::BI__sync_add_and_fetch_2:
853 case Builtin::BI__sync_add_and_fetch_4:
854 case Builtin::BI__sync_add_and_fetch_8:
855 case Builtin::BI__sync_add_and_fetch_16:
856 BuiltinIndex = 5;
857 break;
858
859 case Builtin::BI__sync_sub_and_fetch:
860 case Builtin::BI__sync_sub_and_fetch_1:
861 case Builtin::BI__sync_sub_and_fetch_2:
862 case Builtin::BI__sync_sub_and_fetch_4:
863 case Builtin::BI__sync_sub_and_fetch_8:
864 case Builtin::BI__sync_sub_and_fetch_16:
865 BuiltinIndex = 6;
866 break;
867
868 case Builtin::BI__sync_and_and_fetch:
869 case Builtin::BI__sync_and_and_fetch_1:
870 case Builtin::BI__sync_and_and_fetch_2:
871 case Builtin::BI__sync_and_and_fetch_4:
872 case Builtin::BI__sync_and_and_fetch_8:
873 case Builtin::BI__sync_and_and_fetch_16:
874 BuiltinIndex = 7;
875 break;
876
877 case Builtin::BI__sync_or_and_fetch:
878 case Builtin::BI__sync_or_and_fetch_1:
879 case Builtin::BI__sync_or_and_fetch_2:
880 case Builtin::BI__sync_or_and_fetch_4:
881 case Builtin::BI__sync_or_and_fetch_8:
882 case Builtin::BI__sync_or_and_fetch_16:
883 BuiltinIndex = 8;
884 break;
885
886 case Builtin::BI__sync_xor_and_fetch:
887 case Builtin::BI__sync_xor_and_fetch_1:
888 case Builtin::BI__sync_xor_and_fetch_2:
889 case Builtin::BI__sync_xor_and_fetch_4:
890 case Builtin::BI__sync_xor_and_fetch_8:
891 case Builtin::BI__sync_xor_and_fetch_16:
892 BuiltinIndex = 9;
893 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000894
Chris Lattner5caa3702009-05-08 06:58:22 +0000895 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000896 case Builtin::BI__sync_val_compare_and_swap_1:
897 case Builtin::BI__sync_val_compare_and_swap_2:
898 case Builtin::BI__sync_val_compare_and_swap_4:
899 case Builtin::BI__sync_val_compare_and_swap_8:
900 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000901 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +0000902 NumFixed = 2;
903 break;
Douglas Gregora9766412011-11-28 16:30:08 +0000904
Chris Lattner5caa3702009-05-08 06:58:22 +0000905 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000906 case Builtin::BI__sync_bool_compare_and_swap_1:
907 case Builtin::BI__sync_bool_compare_and_swap_2:
908 case Builtin::BI__sync_bool_compare_and_swap_4:
909 case Builtin::BI__sync_bool_compare_and_swap_8:
910 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000911 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +0000912 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +0000913 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +0000914 break;
Douglas Gregora9766412011-11-28 16:30:08 +0000915
916 case Builtin::BI__sync_lock_test_and_set:
917 case Builtin::BI__sync_lock_test_and_set_1:
918 case Builtin::BI__sync_lock_test_and_set_2:
919 case Builtin::BI__sync_lock_test_and_set_4:
920 case Builtin::BI__sync_lock_test_and_set_8:
921 case Builtin::BI__sync_lock_test_and_set_16:
922 BuiltinIndex = 12;
923 break;
924
Chris Lattner5caa3702009-05-08 06:58:22 +0000925 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +0000926 case Builtin::BI__sync_lock_release_1:
927 case Builtin::BI__sync_lock_release_2:
928 case Builtin::BI__sync_lock_release_4:
929 case Builtin::BI__sync_lock_release_8:
930 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000931 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +0000932 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +0000933 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +0000934 break;
Douglas Gregora9766412011-11-28 16:30:08 +0000935
936 case Builtin::BI__sync_swap:
937 case Builtin::BI__sync_swap_1:
938 case Builtin::BI__sync_swap_2:
939 case Builtin::BI__sync_swap_4:
940 case Builtin::BI__sync_swap_8:
941 case Builtin::BI__sync_swap_16:
942 BuiltinIndex = 14;
943 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000944 }
Mike Stump1eb44332009-09-09 15:08:12 +0000945
Chris Lattner5caa3702009-05-08 06:58:22 +0000946 // Now that we know how many fixed arguments we expect, first check that we
947 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +0000948 if (TheCall->getNumArgs() < 1+NumFixed) {
949 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
950 << 0 << 1+NumFixed << TheCall->getNumArgs()
951 << TheCall->getCallee()->getSourceRange();
952 return ExprError();
953 }
Mike Stump1eb44332009-09-09 15:08:12 +0000954
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000955 // Get the decl for the concrete builtin from this, we can tell what the
956 // concrete integer type we should convert to is.
957 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
958 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
959 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
Mike Stump1eb44332009-09-09 15:08:12 +0000960 FunctionDecl *NewBuiltinDecl =
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000961 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
962 TUScope, false, DRE->getLocStart()));
Chandler Carruthd2014572010-07-09 18:59:35 +0000963
John McCallf871d0c2010-08-07 06:22:56 +0000964 // The first argument --- the pointer --- has a fixed type; we
965 // deduce the types of the rest of the arguments accordingly. Walk
966 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +0000967 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley429bb272011-04-08 18:41:53 +0000968 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +0000969
Chris Lattner5caa3702009-05-08 06:58:22 +0000970 // GCC does an implicit conversion to the pointer or integer ValType. This
971 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb45ae252011-10-05 07:41:44 +0000972 // Initialize the argument.
973 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
974 ValType, /*consume*/ false);
975 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley429bb272011-04-08 18:41:53 +0000976 if (Arg.isInvalid())
Chandler Carruthd2014572010-07-09 18:59:35 +0000977 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000978
Chris Lattner5caa3702009-05-08 06:58:22 +0000979 // Okay, we have something that *can* be converted to the right type. Check
980 // to see if there is a potentially weird extension going on here. This can
981 // happen when you do an atomic operation on something like an char* and
982 // pass in 42. The 42 gets converted to char. This is even more strange
983 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +0000984 // FIXME: Do this check.
John McCallb45ae252011-10-05 07:41:44 +0000985 TheCall->setArg(i+1, Arg.take());
Chris Lattner5caa3702009-05-08 06:58:22 +0000986 }
Mike Stump1eb44332009-09-09 15:08:12 +0000987
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +0000988 ASTContext& Context = this->getASTContext();
989
990 // Create a new DeclRefExpr to refer to the new decl.
991 DeclRefExpr* NewDRE = DeclRefExpr::Create(
992 Context,
993 DRE->getQualifierLoc(),
994 NewBuiltinDecl,
995 DRE->getLocation(),
996 NewBuiltinDecl->getType(),
997 DRE->getValueKind());
Mike Stump1eb44332009-09-09 15:08:12 +0000998
Chris Lattner5caa3702009-05-08 06:58:22 +0000999 // Set the callee in the CallExpr.
1000 // FIXME: This leaks the original parens and implicit casts.
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001001 ExprResult PromotedCall = UsualUnaryConversions(NewDRE);
John Wiegley429bb272011-04-08 18:41:53 +00001002 if (PromotedCall.isInvalid())
1003 return ExprError();
1004 TheCall->setCallee(PromotedCall.take());
Mike Stump1eb44332009-09-09 15:08:12 +00001005
Chandler Carruthdb4325b2010-07-18 07:23:17 +00001006 // Change the result type of the call to match the original value type. This
1007 // is arbitrary, but the codegen for these builtins ins design to handle it
1008 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +00001009 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +00001010
1011 return move(TheCallResult);
Chris Lattner5caa3702009-05-08 06:58:22 +00001012}
1013
Chris Lattner69039812009-02-18 06:01:06 +00001014/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +00001015/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +00001016/// Note: It might also make sense to do the UTF-16 conversion here (would
1017/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +00001018bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +00001019 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +00001020 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1021
Douglas Gregor5cee1192011-07-27 05:40:30 +00001022 if (!Literal || !Literal->isAscii()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001023 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1024 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001025 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +00001026 }
Mike Stump1eb44332009-09-09 15:08:12 +00001027
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001028 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001029 StringRef String = Literal->getString();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001030 unsigned NumBytes = String.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001031 SmallVector<UTF16, 128> ToBuf(NumBytes);
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001032 const UTF8 *FromPtr = (UTF8 *)String.data();
1033 UTF16 *ToPtr = &ToBuf[0];
1034
1035 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1036 &ToPtr, ToPtr + NumBytes,
1037 strictConversion);
1038 // Check for conversion failure.
1039 if (Result != conversionOK)
1040 Diag(Arg->getLocStart(),
1041 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1042 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001043 return false;
Chris Lattner59907c42007-08-10 20:18:51 +00001044}
1045
Chris Lattnerc27c6652007-12-20 00:05:45 +00001046/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1047/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +00001048bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1049 Expr *Fn = TheCall->getCallee();
1050 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +00001051 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001052 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001053 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1054 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +00001055 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001056 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +00001057 return true;
1058 }
Eli Friedman56f20ae2008-12-15 22:05:35 +00001059
1060 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +00001061 return Diag(TheCall->getLocEnd(),
1062 diag::err_typecheck_call_too_few_args_at_least)
1063 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +00001064 }
1065
John McCall5f8d6042011-08-27 01:09:30 +00001066 // Type-check the first argument normally.
1067 if (checkBuiltinArgument(*this, TheCall, 0))
1068 return true;
1069
Chris Lattnerc27c6652007-12-20 00:05:45 +00001070 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001071 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +00001072 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001073 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +00001074 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +00001075 else if (FunctionDecl *FD = getCurFunctionDecl())
1076 isVariadic = FD->isVariadic();
1077 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001078 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +00001079
Chris Lattnerc27c6652007-12-20 00:05:45 +00001080 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001081 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1082 return true;
1083 }
Mike Stump1eb44332009-09-09 15:08:12 +00001084
Chris Lattner30ce3442007-12-19 23:59:04 +00001085 // Verify that the second argument to the builtin is the last argument of the
1086 // current function or method.
1087 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +00001088 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001089
Anders Carlsson88cf2262008-02-11 04:20:54 +00001090 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1091 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001092 // FIXME: This isn't correct for methods (results in bogus warning).
1093 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +00001094 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001095 if (CurBlock)
1096 LastArg = *(CurBlock->TheDecl->param_end()-1);
1097 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +00001098 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001099 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001100 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001101 SecondArgIsLastNamedArgument = PV == LastArg;
1102 }
1103 }
Mike Stump1eb44332009-09-09 15:08:12 +00001104
Chris Lattner30ce3442007-12-19 23:59:04 +00001105 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001106 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +00001107 diag::warn_second_parameter_of_va_start_not_last_named_argument);
1108 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +00001109}
Chris Lattner30ce3442007-12-19 23:59:04 +00001110
Chris Lattner1b9a0792007-12-20 00:26:33 +00001111/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1112/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +00001113bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1114 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +00001115 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001116 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +00001117 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +00001118 return 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()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001121 << SourceRange(TheCall->getArg(2)->getLocStart(),
1122 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001123
John Wiegley429bb272011-04-08 18:41:53 +00001124 ExprResult OrigArg0 = TheCall->getArg(0);
1125 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +00001126
Chris Lattner1b9a0792007-12-20 00:26:33 +00001127 // Do standard promotions between the two arguments, returning their common
1128 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +00001129 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley429bb272011-04-08 18:41:53 +00001130 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1131 return true;
Daniel Dunbar403bc2b2009-02-19 19:28:43 +00001132
1133 // Make sure any conversions are pushed back into the call; this is
1134 // type safe since unordered compare builtins are declared as "_Bool
1135 // foo(...)".
John Wiegley429bb272011-04-08 18:41:53 +00001136 TheCall->setArg(0, OrigArg0.get());
1137 TheCall->setArg(1, OrigArg1.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001138
John Wiegley429bb272011-04-08 18:41:53 +00001139 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorcde01732009-05-19 22:10:17 +00001140 return false;
1141
Chris Lattner1b9a0792007-12-20 00:26:33 +00001142 // If the common type isn't a real floating type, then the arguments were
1143 // invalid for this operation.
1144 if (!Res->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +00001145 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001146 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley429bb272011-04-08 18:41:53 +00001147 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1148 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001149
Chris Lattner1b9a0792007-12-20 00:26:33 +00001150 return false;
1151}
1152
Benjamin Kramere771a7a2010-02-15 22:42:31 +00001153/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1154/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001155/// to check everything. We expect the last argument to be a floating point
1156/// value.
1157bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1158 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +00001159 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001160 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001161 if (TheCall->getNumArgs() > NumArgs)
1162 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001163 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001164 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001165 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001166 (*(TheCall->arg_end()-1))->getLocEnd());
1167
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001168 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001169
Eli Friedman9ac6f622009-08-31 20:06:00 +00001170 if (OrigArg->isTypeDependent())
1171 return false;
1172
Chris Lattner81368fb2010-05-06 05:50:07 +00001173 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +00001174 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +00001175 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001176 diag::err_typecheck_call_invalid_unary_fp)
1177 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001178
Chris Lattner81368fb2010-05-06 05:50:07 +00001179 // If this is an implicit conversion from float -> double, remove it.
1180 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1181 Expr *CastArg = Cast->getSubExpr();
1182 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1183 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1184 "promotion from float to double is the only expected cast here");
1185 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +00001186 TheCall->setArg(NumArgs-1, CastArg);
1187 OrigArg = CastArg;
1188 }
1189 }
1190
Eli Friedman9ac6f622009-08-31 20:06:00 +00001191 return false;
1192}
1193
Eli Friedmand38617c2008-05-14 19:38:39 +00001194/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1195// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +00001196ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001197 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001198 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +00001199 diag::err_typecheck_call_too_few_args_at_least)
Nate Begeman37b6a572010-06-08 00:16:34 +00001200 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherd77b9a22010-04-16 04:48:22 +00001201 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001202
Nate Begeman37b6a572010-06-08 00:16:34 +00001203 // Determine which of the following types of shufflevector we're checking:
1204 // 1) unary, vector mask: (lhs, mask)
1205 // 2) binary, vector mask: (lhs, rhs, mask)
1206 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1207 QualType resType = TheCall->getArg(0)->getType();
1208 unsigned numElements = 0;
1209
Douglas Gregorcde01732009-05-19 22:10:17 +00001210 if (!TheCall->getArg(0)->isTypeDependent() &&
1211 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001212 QualType LHSType = TheCall->getArg(0)->getType();
1213 QualType RHSType = TheCall->getArg(1)->getType();
1214
1215 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001216 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001217 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001218 TheCall->getArg(1)->getLocEnd());
1219 return ExprError();
1220 }
Nate Begeman37b6a572010-06-08 00:16:34 +00001221
1222 numElements = LHSType->getAs<VectorType>()->getNumElements();
1223 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +00001224
Nate Begeman37b6a572010-06-08 00:16:34 +00001225 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1226 // with mask. If so, verify that RHS is an integer vector type with the
1227 // same number of elts as lhs.
1228 if (TheCall->getNumArgs() == 2) {
Douglas Gregorf6094622010-07-23 15:58:24 +00001229 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +00001230 RHSType->getAs<VectorType>()->getNumElements() != numElements)
1231 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
1232 << SourceRange(TheCall->getArg(1)->getLocStart(),
1233 TheCall->getArg(1)->getLocEnd());
1234 numResElements = numElements;
1235 }
1236 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001237 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001238 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001239 TheCall->getArg(1)->getLocEnd());
1240 return ExprError();
Nate Begeman37b6a572010-06-08 00:16:34 +00001241 } else if (numElements != numResElements) {
1242 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +00001243 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001244 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +00001245 }
Eli Friedmand38617c2008-05-14 19:38:39 +00001246 }
1247
1248 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001249 if (TheCall->getArg(i)->isTypeDependent() ||
1250 TheCall->getArg(i)->isValueDependent())
1251 continue;
1252
Nate Begeman37b6a572010-06-08 00:16:34 +00001253 llvm::APSInt Result(32);
1254 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1255 return ExprError(Diag(TheCall->getLocStart(),
1256 diag::err_shufflevector_nonconstant_argument)
1257 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001258
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001259 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001260 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001261 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001262 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001263 }
1264
Chris Lattner5f9e2722011-07-23 10:55:15 +00001265 SmallVector<Expr*, 32> exprs;
Eli Friedmand38617c2008-05-14 19:38:39 +00001266
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001267 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +00001268 exprs.push_back(TheCall->getArg(i));
1269 TheCall->setArg(i, 0);
1270 }
1271
Nate Begemana88dc302009-08-12 02:10:25 +00001272 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
Nate Begeman37b6a572010-06-08 00:16:34 +00001273 exprs.size(), resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001274 TheCall->getCallee()->getLocStart(),
1275 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +00001276}
Chris Lattner30ce3442007-12-19 23:59:04 +00001277
Daniel Dunbar4493f792008-07-21 22:59:13 +00001278/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1279// This is declared to take (const void*, ...) and can take two
1280// optional constant int args.
1281bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001282 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001283
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001284 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +00001285 return Diag(TheCall->getLocEnd(),
1286 diag::err_typecheck_call_too_many_args_at_most)
1287 << 0 /*function call*/ << 3 << NumArgs
1288 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001289
1290 // Argument 0 is checked for us and the remaining arguments must be
1291 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001292 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +00001293 Expr *Arg = TheCall->getArg(i);
Eric Christopher691ebc32010-04-17 02:26:23 +00001294
Eli Friedman9aef7262009-12-04 00:30:06 +00001295 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +00001296 if (SemaBuiltinConstantArg(TheCall, i, Result))
1297 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001298
Daniel Dunbar4493f792008-07-21 22:59:13 +00001299 // FIXME: gcc issues a warning and rewrites these to 0. These
1300 // seems especially odd for the third argument since the default
1301 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001302 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +00001303 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001304 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001305 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001306 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +00001307 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001308 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001309 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001310 }
1311 }
1312
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001313 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +00001314}
1315
Eric Christopher691ebc32010-04-17 02:26:23 +00001316/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1317/// TheCall is a constant expression.
1318bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1319 llvm::APSInt &Result) {
1320 Expr *Arg = TheCall->getArg(ArgNum);
1321 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1322 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1323
1324 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1325
1326 if (!Arg->isIntegerConstantExpr(Result, Context))
1327 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +00001328 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +00001329
Chris Lattner21fb98e2009-09-23 06:06:36 +00001330 return false;
1331}
1332
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001333/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1334/// int type). This simply type checks that type is one of the defined
1335/// constants (0-3).
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001336// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001337bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +00001338 llvm::APSInt Result;
1339
1340 // Check constant-ness first.
1341 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1342 return true;
1343
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001344 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001345 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001346 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1347 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001348 }
1349
1350 return false;
1351}
1352
Eli Friedman586d6a82009-05-03 06:04:26 +00001353/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +00001354/// This checks that val is a constant 1.
1355bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1356 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +00001357 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +00001358
Eric Christopher691ebc32010-04-17 02:26:23 +00001359 // TODO: This is less than ideal. Overload this to take a value.
1360 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1361 return true;
1362
1363 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +00001364 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1365 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1366
1367 return false;
1368}
1369
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001370// Handle i > 1 ? "x" : "y", recursively.
Ted Kremenek082d9362009-03-20 21:35:28 +00001371bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
1372 bool HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00001373 unsigned format_idx, unsigned firstDataArg,
Richard Trieu55733de2011-10-28 00:41:25 +00001374 bool isPrintf, bool inFunctionCall) {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001375 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +00001376 if (E->isTypeDependent() || E->isValueDependent())
1377 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001378
Peter Collingbournef111d932011-04-15 00:35:48 +00001379 E = E->IgnoreParens();
1380
Ted Kremenekd30ef872009-01-12 23:09:09 +00001381 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +00001382 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +00001383 case Stmt::ConditionalOperatorClass: {
John McCall56ca35d2011-02-17 10:25:35 +00001384 const AbstractConditionalOperator *C = cast<AbstractConditionalOperator>(E);
Ted Kremenek826a3452010-07-16 02:11:22 +00001385 return SemaCheckStringLiteral(C->getTrueExpr(), TheCall, HasVAListArg,
Richard Trieu55733de2011-10-28 00:41:25 +00001386 format_idx, firstDataArg, isPrintf,
1387 inFunctionCall)
John McCall56ca35d2011-02-17 10:25:35 +00001388 && SemaCheckStringLiteral(C->getFalseExpr(), TheCall, HasVAListArg,
Richard Trieu55733de2011-10-28 00:41:25 +00001389 format_idx, firstDataArg, isPrintf,
1390 inFunctionCall);
Ted Kremenekd30ef872009-01-12 23:09:09 +00001391 }
1392
Ted Kremenek95355bb2010-09-09 03:51:42 +00001393 case Stmt::IntegerLiteralClass:
1394 // Technically -Wformat-nonliteral does not warn about this case.
1395 // The behavior of printf and friends in this case is implementation
1396 // dependent. Ideally if the format string cannot be null then
1397 // it should have a 'nonnull' attribute in the function prototype.
1398 return true;
1399
Ted Kremenekd30ef872009-01-12 23:09:09 +00001400 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001401 E = cast<ImplicitCastExpr>(E)->getSubExpr();
1402 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001403 }
1404
John McCall56ca35d2011-02-17 10:25:35 +00001405 case Stmt::OpaqueValueExprClass:
1406 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
1407 E = src;
1408 goto tryAgain;
1409 }
1410 return false;
1411
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001412 case Stmt::PredefinedExprClass:
1413 // While __func__, etc., are technically not string literals, they
1414 // cannot contain format specifiers and thus are not a security
1415 // liability.
1416 return true;
1417
Ted Kremenek082d9362009-03-20 21:35:28 +00001418 case Stmt::DeclRefExprClass: {
1419 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001420
Ted Kremenek082d9362009-03-20 21:35:28 +00001421 // As an exception, do not flag errors for variables binding to
1422 // const string literals.
1423 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1424 bool isConstant = false;
1425 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001426
Ted Kremenek082d9362009-03-20 21:35:28 +00001427 if (const ArrayType *AT = Context.getAsArrayType(T)) {
1428 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001429 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001430 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +00001431 PT->getPointeeType().isConstant(Context);
1432 }
Mike Stump1eb44332009-09-09 15:08:12 +00001433
Ted Kremenek082d9362009-03-20 21:35:28 +00001434 if (isConstant) {
Sebastian Redl31310a22010-02-01 20:16:42 +00001435 if (const Expr *Init = VD->getAnyInitializer())
Ted Kremenek082d9362009-03-20 21:35:28 +00001436 return SemaCheckStringLiteral(Init, TheCall,
Ted Kremenek826a3452010-07-16 02:11:22 +00001437 HasVAListArg, format_idx, firstDataArg,
Richard Trieu55733de2011-10-28 00:41:25 +00001438 isPrintf, /*inFunctionCall*/false);
Ted Kremenek082d9362009-03-20 21:35:28 +00001439 }
Mike Stump1eb44332009-09-09 15:08:12 +00001440
Anders Carlssond966a552009-06-28 19:55:58 +00001441 // For vprintf* functions (i.e., HasVAListArg==true), we add a
1442 // special check to see if the format string is a function parameter
1443 // of the function calling the printf function. If the function
1444 // has an attribute indicating it is a printf-like function, then we
1445 // should suppress warnings concerning non-literals being used in a call
1446 // to a vprintf function. For example:
1447 //
1448 // void
1449 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
1450 // va_list ap;
1451 // va_start(ap, fmt);
1452 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
1453 // ...
1454 //
1455 //
1456 // FIXME: We don't have full attribute support yet, so just check to see
1457 // if the argument is a DeclRefExpr that references a parameter. We'll
1458 // add proper support for checking the attribute later.
1459 if (HasVAListArg)
1460 if (isa<ParmVarDecl>(VD))
1461 return true;
Ted Kremenek082d9362009-03-20 21:35:28 +00001462 }
Mike Stump1eb44332009-09-09 15:08:12 +00001463
Ted Kremenek082d9362009-03-20 21:35:28 +00001464 return false;
1465 }
Ted Kremenekd30ef872009-01-12 23:09:09 +00001466
Anders Carlsson8f031b32009-06-27 04:05:33 +00001467 case Stmt::CallExprClass: {
1468 const CallExpr *CE = cast<CallExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001469 if (const ImplicitCastExpr *ICE
Anders Carlsson8f031b32009-06-27 04:05:33 +00001470 = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
1471 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
1472 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001473 if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
Anders Carlsson8f031b32009-06-27 04:05:33 +00001474 unsigned ArgIndex = FA->getFormatIdx();
1475 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001476
1477 return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg,
Richard Trieu55733de2011-10-28 00:41:25 +00001478 format_idx, firstDataArg, isPrintf,
1479 inFunctionCall);
Anders Carlsson8f031b32009-06-27 04:05:33 +00001480 }
1481 }
1482 }
1483 }
Mike Stump1eb44332009-09-09 15:08:12 +00001484
Anders Carlsson8f031b32009-06-27 04:05:33 +00001485 return false;
1486 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001487 case Stmt::ObjCStringLiteralClass:
1488 case Stmt::StringLiteralClass: {
1489 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001490
Ted Kremenek082d9362009-03-20 21:35:28 +00001491 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00001492 StrE = ObjCFExpr->getString();
1493 else
Ted Kremenek082d9362009-03-20 21:35:28 +00001494 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001495
Ted Kremenekd30ef872009-01-12 23:09:09 +00001496 if (StrE) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001497 CheckFormatString(StrE, E, TheCall, HasVAListArg, format_idx,
Richard Trieu55733de2011-10-28 00:41:25 +00001498 firstDataArg, isPrintf, inFunctionCall);
Ted Kremenekd30ef872009-01-12 23:09:09 +00001499 return true;
1500 }
Mike Stump1eb44332009-09-09 15:08:12 +00001501
Ted Kremenekd30ef872009-01-12 23:09:09 +00001502 return false;
1503 }
Mike Stump1eb44332009-09-09 15:08:12 +00001504
Ted Kremenek082d9362009-03-20 21:35:28 +00001505 default:
1506 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001507 }
1508}
1509
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001510void
Mike Stump1eb44332009-09-09 15:08:12 +00001511Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewycky909a70d2011-03-25 01:44:32 +00001512 const Expr * const *ExprArgs,
1513 SourceLocation CallSiteLoc) {
Sean Huntcf807c42010-08-18 23:23:40 +00001514 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1515 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001516 i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +00001517 const Expr *ArgExpr = ExprArgs[*i];
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001518 if (ArgExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00001519 Expr::NPC_ValueDependentIsNotNull))
Nick Lewycky909a70d2011-03-25 01:44:32 +00001520 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001521 }
1522}
Ted Kremenekd30ef872009-01-12 23:09:09 +00001523
Ted Kremenek826a3452010-07-16 02:11:22 +00001524/// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar
1525/// functions) for correct use of format strings.
Chris Lattner59907c42007-08-10 20:18:51 +00001526void
Ted Kremenek826a3452010-07-16 02:11:22 +00001527Sema::CheckPrintfScanfArguments(const CallExpr *TheCall, bool HasVAListArg,
1528 unsigned format_idx, unsigned firstDataArg,
1529 bool isPrintf) {
1530
Ted Kremenek082d9362009-03-20 21:35:28 +00001531 const Expr *Fn = TheCall->getCallee();
Chris Lattner925e60d2007-12-28 05:29:59 +00001532
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001533 // The way the format attribute works in GCC, the implicit this argument
1534 // of member functions is counted. However, it doesn't appear in our own
1535 // lists, so decrement format_idx in that case.
1536 if (isa<CXXMemberCallExpr>(TheCall)) {
Chandler Carruth9263a302010-11-16 08:49:43 +00001537 const CXXMethodDecl *method_decl =
1538 dyn_cast<CXXMethodDecl>(TheCall->getCalleeDecl());
1539 if (method_decl && method_decl->isInstance()) {
1540 // Catch a format attribute mistakenly referring to the object argument.
1541 if (format_idx == 0)
1542 return;
1543 --format_idx;
1544 if(firstDataArg != 0)
1545 --firstDataArg;
1546 }
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001547 }
1548
Ted Kremenek826a3452010-07-16 02:11:22 +00001549 // CHECK: printf/scanf-like function is called with no format string.
Chris Lattner925e60d2007-12-28 05:29:59 +00001550 if (format_idx >= TheCall->getNumArgs()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001551 Diag(TheCall->getRParenLoc(), diag::warn_missing_format_string)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001552 << Fn->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001553 return;
1554 }
Mike Stump1eb44332009-09-09 15:08:12 +00001555
Ted Kremenek082d9362009-03-20 21:35:28 +00001556 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001557
Chris Lattner59907c42007-08-10 20:18:51 +00001558 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001559 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001560 // Dynamically generated format strings are difficult to
1561 // automatically vet at compile time. Requiring that format strings
1562 // are string literals: (1) permits the checking of format strings by
1563 // the compiler and thereby (2) can practically remove the source of
1564 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001565
Mike Stump1eb44332009-09-09 15:08:12 +00001566 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001567 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001568 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001569 // the same format string checking logic for both ObjC and C strings.
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001570 if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
Ted Kremenek826a3452010-07-16 02:11:22 +00001571 firstDataArg, isPrintf))
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001572 return; // Literal format string found, check done!
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001573
Chris Lattner655f1412009-04-29 04:59:47 +00001574 // If there are no arguments specified, warn with -Wformat-security, otherwise
1575 // warn only with -Wformat-nonliteral.
1576 if (TheCall->getNumArgs() == format_idx+1)
Mike Stump1eb44332009-09-09 15:08:12 +00001577 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001578 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00001579 << OrigFormatExpr->getSourceRange();
1580 else
Mike Stump1eb44332009-09-09 15:08:12 +00001581 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001582 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00001583 << OrigFormatExpr->getSourceRange();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001584}
Ted Kremenek71895b92007-08-14 17:39:48 +00001585
Ted Kremeneke0e53132010-01-28 23:39:18 +00001586namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00001587class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1588protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00001589 Sema &S;
1590 const StringLiteral *FExpr;
1591 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00001592 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001593 const unsigned NumDataArgs;
1594 const bool IsObjCLiteral;
1595 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00001596 const bool HasVAListArg;
1597 const CallExpr *TheCall;
1598 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001599 llvm::BitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00001600 bool usesPositionalArgs;
1601 bool atFirstArg;
Richard Trieu55733de2011-10-28 00:41:25 +00001602 bool inFunctionCall;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001603public:
Ted Kremenek826a3452010-07-16 02:11:22 +00001604 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00001605 const Expr *origFormatExpr, unsigned firstDataArg,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001606 unsigned numDataArgs, bool isObjCLiteral,
Ted Kremenek0d277352010-01-29 01:06:55 +00001607 const char *beg, bool hasVAListArg,
Richard Trieu55733de2011-10-28 00:41:25 +00001608 const CallExpr *theCall, unsigned formatIdx,
1609 bool inFunctionCall)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001610 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Ted Kremenek6ee76532010-03-25 03:59:12 +00001611 FirstDataArg(firstDataArg),
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001612 NumDataArgs(numDataArgs),
Ted Kremenek0d277352010-01-29 01:06:55 +00001613 IsObjCLiteral(isObjCLiteral), Beg(beg),
1614 HasVAListArg(hasVAListArg),
Ted Kremenekefaff192010-02-27 01:41:03 +00001615 TheCall(theCall), FormatIdx(formatIdx),
Richard Trieu55733de2011-10-28 00:41:25 +00001616 usesPositionalArgs(false), atFirstArg(true),
1617 inFunctionCall(inFunctionCall) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001618 CoveredArgs.resize(numDataArgs);
1619 CoveredArgs.reset();
1620 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001621
Ted Kremenek07d161f2010-01-29 01:50:07 +00001622 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001623
Ted Kremenek826a3452010-07-16 02:11:22 +00001624 void HandleIncompleteSpecifier(const char *startSpecifier,
1625 unsigned specifierLen);
1626
Ted Kremenekefaff192010-02-27 01:41:03 +00001627 virtual void HandleInvalidPosition(const char *startSpecifier,
1628 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00001629 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00001630
1631 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1632
Ted Kremeneke0e53132010-01-28 23:39:18 +00001633 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001634
Richard Trieu55733de2011-10-28 00:41:25 +00001635 template <typename Range>
1636 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
1637 const Expr *ArgumentExpr,
1638 PartialDiagnostic PDiag,
1639 SourceLocation StringLoc,
1640 bool IsStringLocation, Range StringRange,
1641 FixItHint Fixit = FixItHint());
1642
Ted Kremenek826a3452010-07-16 02:11:22 +00001643protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001644 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
1645 const char *startSpec,
1646 unsigned specifierLen,
1647 const char *csStart, unsigned csLen);
Richard Trieu55733de2011-10-28 00:41:25 +00001648
1649 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
1650 const char *startSpec,
1651 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001652
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001653 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00001654 CharSourceRange getSpecifierRange(const char *startSpecifier,
1655 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001656 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001657
Ted Kremenek0d277352010-01-29 01:06:55 +00001658 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00001659
1660 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
1661 const analyze_format_string::ConversionSpecifier &CS,
1662 const char *startSpecifier, unsigned specifierLen,
1663 unsigned argIndex);
Richard Trieu55733de2011-10-28 00:41:25 +00001664
1665 template <typename Range>
1666 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
1667 bool IsStringLocation, Range StringRange,
1668 FixItHint Fixit = FixItHint());
1669
1670 void CheckPositionalAndNonpositionalArgs(
1671 const analyze_format_string::FormatSpecifier *FS);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001672};
1673}
1674
Ted Kremenek826a3452010-07-16 02:11:22 +00001675SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00001676 return OrigFormatExpr->getSourceRange();
1677}
1678
Ted Kremenek826a3452010-07-16 02:11:22 +00001679CharSourceRange CheckFormatHandler::
1680getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00001681 SourceLocation Start = getLocationOfByte(startSpecifier);
1682 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
1683
1684 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001685 End = End.getLocWithOffset(1);
Tom Care45f9b7e2010-06-21 21:21:01 +00001686
1687 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001688}
1689
Ted Kremenek826a3452010-07-16 02:11:22 +00001690SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001691 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001692}
1693
Ted Kremenek826a3452010-07-16 02:11:22 +00001694void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
1695 unsigned specifierLen){
Richard Trieu55733de2011-10-28 00:41:25 +00001696 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
1697 getLocationOfByte(startSpecifier),
1698 /*IsStringLocation*/true,
1699 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek808015a2010-01-29 03:16:21 +00001700}
1701
Ted Kremenekefaff192010-02-27 01:41:03 +00001702void
Ted Kremenek826a3452010-07-16 02:11:22 +00001703CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
1704 analyze_format_string::PositionContext p) {
Richard Trieu55733de2011-10-28 00:41:25 +00001705 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
1706 << (unsigned) p,
1707 getLocationOfByte(startPos), /*IsStringLocation*/true,
1708 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00001709}
1710
Ted Kremenek826a3452010-07-16 02:11:22 +00001711void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00001712 unsigned posLen) {
Richard Trieu55733de2011-10-28 00:41:25 +00001713 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
1714 getLocationOfByte(startPos),
1715 /*IsStringLocation*/true,
1716 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00001717}
1718
Ted Kremenek826a3452010-07-16 02:11:22 +00001719void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Ted Kremenek0c069442011-03-15 21:18:48 +00001720 if (!IsObjCLiteral) {
1721 // The presence of a null character is likely an error.
Richard Trieu55733de2011-10-28 00:41:25 +00001722 EmitFormatDiagnostic(
1723 S.PDiag(diag::warn_printf_format_string_contains_null_char),
1724 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
1725 getFormatStringRange());
Ted Kremenek0c069442011-03-15 21:18:48 +00001726 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001727}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001728
Ted Kremenek826a3452010-07-16 02:11:22 +00001729const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
1730 return TheCall->getArg(FirstDataArg + i);
1731}
1732
1733void CheckFormatHandler::DoneProcessing() {
1734 // Does the number of data arguments exceed the number of
1735 // format conversions in the format string?
1736 if (!HasVAListArg) {
1737 // Find any arguments that weren't covered.
1738 CoveredArgs.flip();
1739 signed notCoveredArg = CoveredArgs.find_first();
1740 if (notCoveredArg >= 0) {
1741 assert((unsigned)notCoveredArg < NumDataArgs);
Richard Trieu55733de2011-10-28 00:41:25 +00001742 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
1743 getDataArg((unsigned) notCoveredArg)->getLocStart(),
1744 /*IsStringLocation*/false, getFormatStringRange());
Ted Kremenek826a3452010-07-16 02:11:22 +00001745 }
1746 }
1747}
1748
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001749bool
1750CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
1751 SourceLocation Loc,
1752 const char *startSpec,
1753 unsigned specifierLen,
1754 const char *csStart,
1755 unsigned csLen) {
1756
1757 bool keepGoing = true;
1758 if (argIndex < NumDataArgs) {
1759 // Consider the argument coverered, even though the specifier doesn't
1760 // make sense.
1761 CoveredArgs.set(argIndex);
1762 }
1763 else {
1764 // If argIndex exceeds the number of data arguments we
1765 // don't issue a warning because that is just a cascade of warnings (and
1766 // they may have intended '%%' anyway). We don't want to continue processing
1767 // the format string after this point, however, as we will like just get
1768 // gibberish when trying to match arguments.
1769 keepGoing = false;
1770 }
1771
Richard Trieu55733de2011-10-28 00:41:25 +00001772 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
1773 << StringRef(csStart, csLen),
1774 Loc, /*IsStringLocation*/true,
1775 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001776
1777 return keepGoing;
1778}
1779
Richard Trieu55733de2011-10-28 00:41:25 +00001780void
1781CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
1782 const char *startSpec,
1783 unsigned specifierLen) {
1784 EmitFormatDiagnostic(
1785 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
1786 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
1787}
1788
Ted Kremenek666a1972010-07-26 19:45:42 +00001789bool
1790CheckFormatHandler::CheckNumArgs(
1791 const analyze_format_string::FormatSpecifier &FS,
1792 const analyze_format_string::ConversionSpecifier &CS,
1793 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
1794
1795 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00001796 PartialDiagnostic PDiag = FS.usesPositionalArg()
1797 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
1798 << (argIndex+1) << NumDataArgs)
1799 : S.PDiag(diag::warn_printf_insufficient_data_args);
1800 EmitFormatDiagnostic(
1801 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
1802 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek666a1972010-07-26 19:45:42 +00001803 return false;
1804 }
1805 return true;
1806}
1807
Richard Trieu55733de2011-10-28 00:41:25 +00001808template<typename Range>
1809void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
1810 SourceLocation Loc,
1811 bool IsStringLocation,
1812 Range StringRange,
1813 FixItHint FixIt) {
1814 EmitFormatDiagnostic(S, inFunctionCall, TheCall->getArg(FormatIdx), PDiag,
1815 Loc, IsStringLocation, StringRange, FixIt);
1816}
1817
1818/// \brief If the format string is not within the funcion call, emit a note
1819/// so that the function call and string are in diagnostic messages.
1820///
1821/// \param inFunctionCall if true, the format string is within the function
1822/// call and only one diagnostic message will be produced. Otherwise, an
1823/// extra note will be emitted pointing to location of the format string.
1824///
1825/// \param ArgumentExpr the expression that is passed as the format string
1826/// argument in the function call. Used for getting locations when two
1827/// diagnostics are emitted.
1828///
1829/// \param PDiag the callee should already have provided any strings for the
1830/// diagnostic message. This function only adds locations and fixits
1831/// to diagnostics.
1832///
1833/// \param Loc primary location for diagnostic. If two diagnostics are
1834/// required, one will be at Loc and a new SourceLocation will be created for
1835/// the other one.
1836///
1837/// \param IsStringLocation if true, Loc points to the format string should be
1838/// used for the note. Otherwise, Loc points to the argument list and will
1839/// be used with PDiag.
1840///
1841/// \param StringRange some or all of the string to highlight. This is
1842/// templated so it can accept either a CharSourceRange or a SourceRange.
1843///
1844/// \param Fixit optional fix it hint for the format string.
1845template<typename Range>
1846void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
1847 const Expr *ArgumentExpr,
1848 PartialDiagnostic PDiag,
1849 SourceLocation Loc,
1850 bool IsStringLocation,
1851 Range StringRange,
1852 FixItHint FixIt) {
1853 if (InFunctionCall)
1854 S.Diag(Loc, PDiag) << StringRange << FixIt;
1855 else {
1856 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
1857 << ArgumentExpr->getSourceRange();
1858 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
1859 diag::note_format_string_defined)
1860 << StringRange << FixIt;
1861 }
1862}
1863
Ted Kremenek826a3452010-07-16 02:11:22 +00001864//===--- CHECK: Printf format string checking ------------------------------===//
1865
1866namespace {
1867class CheckPrintfHandler : public CheckFormatHandler {
1868public:
1869 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
1870 const Expr *origFormatExpr, unsigned firstDataArg,
1871 unsigned numDataArgs, bool isObjCLiteral,
1872 const char *beg, bool hasVAListArg,
Richard Trieu55733de2011-10-28 00:41:25 +00001873 const CallExpr *theCall, unsigned formatIdx,
1874 bool inFunctionCall)
Ted Kremenek826a3452010-07-16 02:11:22 +00001875 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1876 numDataArgs, isObjCLiteral, beg, hasVAListArg,
Richard Trieu55733de2011-10-28 00:41:25 +00001877 theCall, formatIdx, inFunctionCall) {}
Ted Kremenek826a3452010-07-16 02:11:22 +00001878
1879
1880 bool HandleInvalidPrintfConversionSpecifier(
1881 const analyze_printf::PrintfSpecifier &FS,
1882 const char *startSpecifier,
1883 unsigned specifierLen);
1884
1885 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
1886 const char *startSpecifier,
1887 unsigned specifierLen);
1888
1889 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
1890 const char *startSpecifier, unsigned specifierLen);
1891 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
1892 const analyze_printf::OptionalAmount &Amt,
1893 unsigned type,
1894 const char *startSpecifier, unsigned specifierLen);
1895 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
1896 const analyze_printf::OptionalFlag &flag,
1897 const char *startSpecifier, unsigned specifierLen);
1898 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
1899 const analyze_printf::OptionalFlag &ignoredFlag,
1900 const analyze_printf::OptionalFlag &flag,
1901 const char *startSpecifier, unsigned specifierLen);
1902};
1903}
1904
1905bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
1906 const analyze_printf::PrintfSpecifier &FS,
1907 const char *startSpecifier,
1908 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001909 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001910 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00001911
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001912 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1913 getLocationOfByte(CS.getStart()),
1914 startSpecifier, specifierLen,
1915 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001916}
1917
Ted Kremenek826a3452010-07-16 02:11:22 +00001918bool CheckPrintfHandler::HandleAmount(
1919 const analyze_format_string::OptionalAmount &Amt,
1920 unsigned k, const char *startSpecifier,
1921 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001922
1923 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001924 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001925 unsigned argIndex = Amt.getArgIndex();
1926 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00001927 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
1928 << k,
1929 getLocationOfByte(Amt.getStart()),
1930 /*IsStringLocation*/true,
1931 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00001932 // Don't do any more checking. We will just emit
1933 // spurious errors.
1934 return false;
1935 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001936
Ted Kremenek0d277352010-01-29 01:06:55 +00001937 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00001938 // Although not in conformance with C99, we also allow the argument to be
1939 // an 'unsigned int' as that is a reasonably safe case. GCC also
1940 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001941 CoveredArgs.set(argIndex);
1942 const Expr *Arg = getDataArg(argIndex);
Ted Kremenek0d277352010-01-29 01:06:55 +00001943 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001944
1945 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
1946 assert(ATR.isValid());
1947
1948 if (!ATR.matchesType(S.Context, T)) {
Richard Trieu55733de2011-10-28 00:41:25 +00001949 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborga792aff2011-12-07 10:33:11 +00001950 << k << ATR.getRepresentativeTypeName(S.Context)
Richard Trieu55733de2011-10-28 00:41:25 +00001951 << T << Arg->getSourceRange(),
1952 getLocationOfByte(Amt.getStart()),
1953 /*IsStringLocation*/true,
1954 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00001955 // Don't do any more checking. We will just emit
1956 // spurious errors.
1957 return false;
1958 }
1959 }
1960 }
1961 return true;
1962}
Ted Kremenek0d277352010-01-29 01:06:55 +00001963
Tom Caree4ee9662010-06-17 19:00:27 +00001964void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00001965 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001966 const analyze_printf::OptionalAmount &Amt,
1967 unsigned type,
1968 const char *startSpecifier,
1969 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001970 const analyze_printf::PrintfConversionSpecifier &CS =
1971 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00001972
Richard Trieu55733de2011-10-28 00:41:25 +00001973 FixItHint fixit =
1974 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
1975 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
1976 Amt.getConstantLength()))
1977 : FixItHint();
1978
1979 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
1980 << type << CS.toString(),
1981 getLocationOfByte(Amt.getStart()),
1982 /*IsStringLocation*/true,
1983 getSpecifierRange(startSpecifier, specifierLen),
1984 fixit);
Tom Caree4ee9662010-06-17 19:00:27 +00001985}
1986
Ted Kremenek826a3452010-07-16 02:11:22 +00001987void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001988 const analyze_printf::OptionalFlag &flag,
1989 const char *startSpecifier,
1990 unsigned specifierLen) {
1991 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001992 const analyze_printf::PrintfConversionSpecifier &CS =
1993 FS.getConversionSpecifier();
Richard Trieu55733de2011-10-28 00:41:25 +00001994 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
1995 << flag.toString() << CS.toString(),
1996 getLocationOfByte(flag.getPosition()),
1997 /*IsStringLocation*/true,
1998 getSpecifierRange(startSpecifier, specifierLen),
1999 FixItHint::CreateRemoval(
2000 getSpecifierRange(flag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002001}
2002
2003void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00002004 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002005 const analyze_printf::OptionalFlag &ignoredFlag,
2006 const analyze_printf::OptionalFlag &flag,
2007 const char *startSpecifier,
2008 unsigned specifierLen) {
2009 // Warn about ignored flag with a fixit removal.
Richard Trieu55733de2011-10-28 00:41:25 +00002010 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2011 << ignoredFlag.toString() << flag.toString(),
2012 getLocationOfByte(ignoredFlag.getPosition()),
2013 /*IsStringLocation*/true,
2014 getSpecifierRange(startSpecifier, specifierLen),
2015 FixItHint::CreateRemoval(
2016 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002017}
2018
Ted Kremeneke0e53132010-01-28 23:39:18 +00002019bool
Ted Kremenek826a3452010-07-16 02:11:22 +00002020CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00002021 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00002022 const char *startSpecifier,
2023 unsigned specifierLen) {
2024
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002025 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00002026 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002027 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00002028
Ted Kremenekbaa40062010-07-19 22:01:06 +00002029 if (FS.consumesDataArgument()) {
2030 if (atFirstArg) {
2031 atFirstArg = false;
2032 usesPositionalArgs = FS.usesPositionalArg();
2033 }
2034 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002035 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2036 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002037 return false;
2038 }
Ted Kremenek0d277352010-01-29 01:06:55 +00002039 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002040
Ted Kremenekefaff192010-02-27 01:41:03 +00002041 // First check if the field width, precision, and conversion specifier
2042 // have matching data arguments.
2043 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2044 startSpecifier, specifierLen)) {
2045 return false;
2046 }
2047
2048 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2049 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002050 return false;
2051 }
2052
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002053 if (!CS.consumesDataArgument()) {
2054 // FIXME: Technically specifying a precision or field width here
2055 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002056 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002057 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002058
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002059 // Consume the argument.
2060 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00002061 if (argIndex < NumDataArgs) {
2062 // The check to see if the argIndex is valid will come later.
2063 // We set the bit here because we may exit early from this
2064 // function if we encounter some other error.
2065 CoveredArgs.set(argIndex);
2066 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002067
2068 // Check for using an Objective-C specific conversion specifier
2069 // in a non-ObjC literal.
2070 if (!IsObjCLiteral && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002071 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
2072 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002073 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002074
Tom Caree4ee9662010-06-17 19:00:27 +00002075 // Check for invalid use of field width
2076 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002077 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00002078 startSpecifier, specifierLen);
2079 }
2080
2081 // Check for invalid use of precision
2082 if (!FS.hasValidPrecision()) {
2083 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
2084 startSpecifier, specifierLen);
2085 }
2086
2087 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00002088 if (!FS.hasValidThousandsGroupingPrefix())
2089 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002090 if (!FS.hasValidLeadingZeros())
2091 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
2092 if (!FS.hasValidPlusPrefix())
2093 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00002094 if (!FS.hasValidSpacePrefix())
2095 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002096 if (!FS.hasValidAlternativeForm())
2097 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
2098 if (!FS.hasValidLeftJustified())
2099 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
2100
2101 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00002102 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
2103 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
2104 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002105 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
2106 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
2107 startSpecifier, specifierLen);
2108
2109 // Check the length modifier is valid with the given conversion specifier.
2110 const LengthModifier &LM = FS.getLengthModifier();
2111 if (!FS.hasValidLengthModifier())
Richard Trieu55733de2011-10-28 00:41:25 +00002112 EmitFormatDiagnostic(S.PDiag(diag::warn_format_nonsensical_length)
2113 << LM.toString() << CS.toString(),
2114 getLocationOfByte(LM.getStart()),
2115 /*IsStringLocation*/true,
2116 getSpecifierRange(startSpecifier, specifierLen),
2117 FixItHint::CreateRemoval(
2118 getSpecifierRange(LM.getStart(),
2119 LM.getLength())));
Tom Caree4ee9662010-06-17 19:00:27 +00002120
2121 // Are we using '%n'?
Ted Kremenek35d353b2010-07-20 20:04:10 +00002122 if (CS.getKind() == ConversionSpecifier::nArg) {
Tom Caree4ee9662010-06-17 19:00:27 +00002123 // Issue a warning about this being a possible security issue.
Richard Trieu55733de2011-10-28 00:41:25 +00002124 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_write_back),
2125 getLocationOfByte(CS.getStart()),
2126 /*IsStringLocation*/true,
2127 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremeneke82d8042010-01-29 01:35:25 +00002128 // Continue checking the other format specifiers.
2129 return true;
2130 }
Ted Kremenek5c41ee82010-02-11 09:27:41 +00002131
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002132 // The remaining checks depend on the data arguments.
2133 if (HasVAListArg)
2134 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002135
Ted Kremenek666a1972010-07-26 19:45:42 +00002136 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002137 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002138
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002139 // Now type check the data expression that matches the
2140 // format specifier.
2141 const Expr *Ex = getDataArg(argIndex);
Nick Lewycky687b5df2011-12-02 23:21:43 +00002142 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002143 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
2144 // Check if we didn't match because of an implicit cast from a 'char'
2145 // or 'short' to an 'int'. This is done because printf is a varargs
2146 // function.
2147 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00002148 if (ICE->getType() == S.Context.IntTy) {
2149 // All further checking is done on the subexpression.
2150 Ex = ICE->getSubExpr();
2151 if (ATR.matchesType(S.Context, Ex->getType()))
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002152 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00002153 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002154
2155 // We may be able to offer a FixItHint if it is a supported type.
2156 PrintfSpecifier fixedFS = FS;
Hans Wennborga7da2152011-10-18 08:10:06 +00002157 bool success = fixedFS.fixType(Ex->getType(), S.getLangOptions());
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002158
2159 if (success) {
2160 // Get the fix string from the fixed format specifier
2161 llvm::SmallString<128> buf;
2162 llvm::raw_svector_ostream os(buf);
2163 fixedFS.toString(os);
2164
Richard Trieu55733de2011-10-28 00:41:25 +00002165 EmitFormatDiagnostic(
2166 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborga792aff2011-12-07 10:33:11 +00002167 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
Richard Trieu55733de2011-10-28 00:41:25 +00002168 << Ex->getSourceRange(),
2169 getLocationOfByte(CS.getStart()),
2170 /*IsStringLocation*/true,
2171 getSpecifierRange(startSpecifier, specifierLen),
2172 FixItHint::CreateReplacement(
2173 getSpecifierRange(startSpecifier, specifierLen),
2174 os.str()));
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002175 }
2176 else {
2177 S.Diag(getLocationOfByte(CS.getStart()),
2178 diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborga792aff2011-12-07 10:33:11 +00002179 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002180 << getSpecifierRange(startSpecifier, specifierLen)
2181 << Ex->getSourceRange();
2182 }
2183 }
2184
Ted Kremeneke0e53132010-01-28 23:39:18 +00002185 return true;
2186}
2187
Ted Kremenek826a3452010-07-16 02:11:22 +00002188//===--- CHECK: Scanf format string checking ------------------------------===//
2189
2190namespace {
2191class CheckScanfHandler : public CheckFormatHandler {
2192public:
2193 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
2194 const Expr *origFormatExpr, unsigned firstDataArg,
2195 unsigned numDataArgs, bool isObjCLiteral,
2196 const char *beg, bool hasVAListArg,
Richard Trieu55733de2011-10-28 00:41:25 +00002197 const CallExpr *theCall, unsigned formatIdx,
2198 bool inFunctionCall)
Ted Kremenek826a3452010-07-16 02:11:22 +00002199 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2200 numDataArgs, isObjCLiteral, beg, hasVAListArg,
Richard Trieu55733de2011-10-28 00:41:25 +00002201 theCall, formatIdx, inFunctionCall) {}
Ted Kremenek826a3452010-07-16 02:11:22 +00002202
2203 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
2204 const char *startSpecifier,
2205 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002206
2207 bool HandleInvalidScanfConversionSpecifier(
2208 const analyze_scanf::ScanfSpecifier &FS,
2209 const char *startSpecifier,
2210 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00002211
2212 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00002213};
Ted Kremenek07d161f2010-01-29 01:50:07 +00002214}
Ted Kremeneke0e53132010-01-28 23:39:18 +00002215
Ted Kremenekb7c21012010-07-16 18:28:03 +00002216void CheckScanfHandler::HandleIncompleteScanList(const char *start,
2217 const char *end) {
Richard Trieu55733de2011-10-28 00:41:25 +00002218 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
2219 getLocationOfByte(end), /*IsStringLocation*/true,
2220 getSpecifierRange(start, end - start));
Ted Kremenekb7c21012010-07-16 18:28:03 +00002221}
2222
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002223bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
2224 const analyze_scanf::ScanfSpecifier &FS,
2225 const char *startSpecifier,
2226 unsigned specifierLen) {
2227
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002228 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002229 FS.getConversionSpecifier();
2230
2231 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2232 getLocationOfByte(CS.getStart()),
2233 startSpecifier, specifierLen,
2234 CS.getStart(), CS.getLength());
2235}
2236
Ted Kremenek826a3452010-07-16 02:11:22 +00002237bool CheckScanfHandler::HandleScanfSpecifier(
2238 const analyze_scanf::ScanfSpecifier &FS,
2239 const char *startSpecifier,
2240 unsigned specifierLen) {
2241
2242 using namespace analyze_scanf;
2243 using namespace analyze_format_string;
2244
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002245 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002246
Ted Kremenekbaa40062010-07-19 22:01:06 +00002247 // Handle case where '%' and '*' don't consume an argument. These shouldn't
2248 // be used to decide if we are using positional arguments consistently.
2249 if (FS.consumesDataArgument()) {
2250 if (atFirstArg) {
2251 atFirstArg = false;
2252 usesPositionalArgs = FS.usesPositionalArg();
2253 }
2254 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002255 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2256 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002257 return false;
2258 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002259 }
2260
2261 // Check if the field with is non-zero.
2262 const OptionalAmount &Amt = FS.getFieldWidth();
2263 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
2264 if (Amt.getConstantAmount() == 0) {
2265 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
2266 Amt.getConstantLength());
Richard Trieu55733de2011-10-28 00:41:25 +00002267 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
2268 getLocationOfByte(Amt.getStart()),
2269 /*IsStringLocation*/true, R,
2270 FixItHint::CreateRemoval(R));
Ted Kremenek826a3452010-07-16 02:11:22 +00002271 }
2272 }
2273
2274 if (!FS.consumesDataArgument()) {
2275 // FIXME: Technically specifying a precision or field width here
2276 // makes no sense. Worth issuing a warning at some point.
2277 return true;
2278 }
2279
2280 // Consume the argument.
2281 unsigned argIndex = FS.getArgIndex();
2282 if (argIndex < NumDataArgs) {
2283 // The check to see if the argIndex is valid will come later.
2284 // We set the bit here because we may exit early from this
2285 // function if we encounter some other error.
2286 CoveredArgs.set(argIndex);
2287 }
2288
Ted Kremenek1e51c202010-07-20 20:04:47 +00002289 // Check the length modifier is valid with the given conversion specifier.
2290 const LengthModifier &LM = FS.getLengthModifier();
2291 if (!FS.hasValidLengthModifier()) {
2292 S.Diag(getLocationOfByte(LM.getStart()),
2293 diag::warn_format_nonsensical_length)
2294 << LM.toString() << CS.toString()
2295 << getSpecifierRange(startSpecifier, specifierLen)
2296 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
2297 LM.getLength()));
2298 }
2299
Ted Kremenek826a3452010-07-16 02:11:22 +00002300 // The remaining checks depend on the data arguments.
2301 if (HasVAListArg)
2302 return true;
2303
Ted Kremenek666a1972010-07-26 19:45:42 +00002304 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00002305 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00002306
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002307 // Check that the argument type matches the format specifier.
2308 const Expr *Ex = getDataArg(argIndex);
2309 const analyze_scanf::ScanfArgTypeResult &ATR = FS.getArgType(S.Context);
2310 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
2311 ScanfSpecifier fixedFS = FS;
2312 bool success = fixedFS.fixType(Ex->getType(), S.getLangOptions());
2313
2314 if (success) {
2315 // Get the fix string from the fixed format specifier.
2316 llvm::SmallString<128> buf;
2317 llvm::raw_svector_ostream os(buf);
2318 fixedFS.toString(os);
2319
2320 EmitFormatDiagnostic(
2321 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2322 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
2323 << Ex->getSourceRange(),
2324 getLocationOfByte(CS.getStart()),
2325 /*IsStringLocation*/true,
2326 getSpecifierRange(startSpecifier, specifierLen),
2327 FixItHint::CreateReplacement(
2328 getSpecifierRange(startSpecifier, specifierLen),
2329 os.str()));
2330 } else {
2331 S.Diag(getLocationOfByte(CS.getStart()),
2332 diag::warn_printf_conversion_argument_type_mismatch)
2333 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
2334 << getSpecifierRange(startSpecifier, specifierLen)
2335 << Ex->getSourceRange();
2336 }
2337 }
2338
Ted Kremenek826a3452010-07-16 02:11:22 +00002339 return true;
2340}
2341
2342void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002343 const Expr *OrigFormatExpr,
2344 const CallExpr *TheCall, bool HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00002345 unsigned format_idx, unsigned firstDataArg,
Richard Trieu55733de2011-10-28 00:41:25 +00002346 bool isPrintf, bool inFunctionCall) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002347
Ted Kremeneke0e53132010-01-28 23:39:18 +00002348 // CHECK: is the format string a wide literal?
Douglas Gregor5cee1192011-07-27 05:40:30 +00002349 if (!FExpr->isAscii()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002350 CheckFormatHandler::EmitFormatDiagnostic(
2351 *this, inFunctionCall, TheCall->getArg(format_idx),
2352 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
2353 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00002354 return;
2355 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002356
Ted Kremeneke0e53132010-01-28 23:39:18 +00002357 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner5f9e2722011-07-23 10:55:15 +00002358 StringRef StrRef = FExpr->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00002359 const char *Str = StrRef.data();
2360 unsigned StrLen = StrRef.size();
Ted Kremenek4cd57912011-09-29 05:52:16 +00002361 const unsigned numDataArgs = TheCall->getNumArgs() - firstDataArg;
Ted Kremenek826a3452010-07-16 02:11:22 +00002362
Ted Kremeneke0e53132010-01-28 23:39:18 +00002363 // CHECK: empty format string?
Ted Kremenek4cd57912011-09-29 05:52:16 +00002364 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu55733de2011-10-28 00:41:25 +00002365 CheckFormatHandler::EmitFormatDiagnostic(
2366 *this, inFunctionCall, TheCall->getArg(format_idx),
2367 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
2368 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00002369 return;
2370 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002371
2372 if (isPrintf) {
2373 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Ted Kremenek4cd57912011-09-29 05:52:16 +00002374 numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr),
Richard Trieu55733de2011-10-28 00:41:25 +00002375 Str, HasVAListArg, TheCall, format_idx,
2376 inFunctionCall);
Ted Kremenek826a3452010-07-16 02:11:22 +00002377
Hans Wennborgd02deeb2011-12-15 10:25:47 +00002378 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
2379 getLangOptions()))
Ted Kremenek826a3452010-07-16 02:11:22 +00002380 H.DoneProcessing();
2381 }
2382 else {
2383 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Ted Kremenek4cd57912011-09-29 05:52:16 +00002384 numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr),
Richard Trieu55733de2011-10-28 00:41:25 +00002385 Str, HasVAListArg, TheCall, format_idx,
2386 inFunctionCall);
Ted Kremenek826a3452010-07-16 02:11:22 +00002387
Hans Wennborgd02deeb2011-12-15 10:25:47 +00002388 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
2389 getLangOptions()))
Ted Kremenek826a3452010-07-16 02:11:22 +00002390 H.DoneProcessing();
2391 }
Ted Kremenekce7024e2010-01-28 01:18:22 +00002392}
2393
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002394//===--- CHECK: Standard memory functions ---------------------------------===//
2395
Douglas Gregor2a053a32011-05-03 20:05:22 +00002396/// \brief Determine whether the given type is a dynamic class type (e.g.,
2397/// whether it has a vtable).
2398static bool isDynamicClassType(QualType T) {
2399 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
2400 if (CXXRecordDecl *Definition = Record->getDefinition())
2401 if (Definition->isDynamicClass())
2402 return true;
2403
2404 return false;
2405}
2406
Chandler Carrutha72a12f2011-06-21 23:04:20 +00002407/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth000d4282011-06-16 09:09:40 +00002408/// otherwise returns NULL.
2409static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Webere4a1c642011-06-14 16:14:58 +00002410 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth000d4282011-06-16 09:09:40 +00002411 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2412 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
2413 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00002414
Chandler Carruth000d4282011-06-16 09:09:40 +00002415 return 0;
2416}
2417
Chandler Carrutha72a12f2011-06-21 23:04:20 +00002418/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth000d4282011-06-16 09:09:40 +00002419static QualType getSizeOfArgType(const Expr* E) {
2420 if (const UnaryExprOrTypeTraitExpr *SizeOf =
2421 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2422 if (SizeOf->getKind() == clang::UETT_SizeOf)
2423 return SizeOf->getTypeOfArgument();
2424
2425 return QualType();
Nico Webere4a1c642011-06-14 16:14:58 +00002426}
2427
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002428/// \brief Check for dangerous or invalid arguments to memset().
2429///
Chandler Carruth929f0132011-06-03 06:23:57 +00002430/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002431/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
2432/// function calls.
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002433///
2434/// \param Call The call expression to diagnose.
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002435void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks0a151a12012-01-17 00:37:07 +00002436 unsigned BId,
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002437 IdentifierInfo *FnName) {
Anna Zaks0a151a12012-01-17 00:37:07 +00002438 assert(BId != 0);
2439
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00002440 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor707a23e2011-06-16 17:56:04 +00002441 // we have enough arguments, and if not, abort further checking.
Anna Zaks0a151a12012-01-17 00:37:07 +00002442 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Webercda57822011-10-13 22:30:23 +00002443 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00002444 return;
2445
Anna Zaks0a151a12012-01-17 00:37:07 +00002446 unsigned LastArg = (BId == Builtin::BImemset ||
2447 BId == Builtin::BIstrndup ? 1 : 2);
2448 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Webercda57822011-10-13 22:30:23 +00002449 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth000d4282011-06-16 09:09:40 +00002450
2451 // We have special checking when the length is a sizeof expression.
2452 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
2453 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
2454 llvm::FoldingSetNodeID SizeOfArgID;
2455
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002456 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
2457 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00002458 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002459
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002460 QualType DestTy = Dest->getType();
2461 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
2462 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00002463
Chandler Carruth000d4282011-06-16 09:09:40 +00002464 // Never warn about void type pointers. This can be used to suppress
2465 // false positives.
2466 if (PointeeTy->isVoidType())
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002467 continue;
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002468
Chandler Carruth000d4282011-06-16 09:09:40 +00002469 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
2470 // actually comparing the expressions for equality. Because computing the
2471 // expression IDs can be expensive, we only do this if the diagnostic is
2472 // enabled.
2473 if (SizeOfArg &&
2474 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
2475 SizeOfArg->getExprLoc())) {
2476 // We only compute IDs for expressions if the warning is enabled, and
2477 // cache the sizeof arg's ID.
2478 if (SizeOfArgID == llvm::FoldingSetNodeID())
2479 SizeOfArg->Profile(SizeOfArgID, Context, true);
2480 llvm::FoldingSetNodeID DestID;
2481 Dest->Profile(DestID, Context, true);
2482 if (DestID == SizeOfArgID) {
Nico Webercda57822011-10-13 22:30:23 +00002483 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
2484 // over sizeof(src) as well.
Chandler Carruth000d4282011-06-16 09:09:40 +00002485 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
2486 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
2487 if (UnaryOp->getOpcode() == UO_AddrOf)
2488 ActionIdx = 1; // If its an address-of operator, just remove it.
2489 if (Context.getTypeSize(PointeeTy) == Context.getCharWidth())
2490 ActionIdx = 2; // If the pointee's size is sizeof(char),
2491 // suggest an explicit length.
Anna Zaksd9b859a2012-01-13 21:52:01 +00002492 unsigned DestSrcSelect =
Anna Zaks0a151a12012-01-17 00:37:07 +00002493 (BId == Builtin::BIstrndup ? 1 : ArgIdx);
Chandler Carruth000d4282011-06-16 09:09:40 +00002494 DiagRuntimeBehavior(SizeOfArg->getExprLoc(), Dest,
2495 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Nico Webercda57822011-10-13 22:30:23 +00002496 << FnName << DestSrcSelect << ActionIdx
Chandler Carruth000d4282011-06-16 09:09:40 +00002497 << Dest->getSourceRange()
2498 << SizeOfArg->getSourceRange());
2499 break;
2500 }
2501 }
2502
2503 // Also check for cases where the sizeof argument is the exact same
2504 // type as the memory argument, and where it points to a user-defined
2505 // record type.
2506 if (SizeOfArgTy != QualType()) {
2507 if (PointeeTy->isRecordType() &&
2508 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
2509 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
2510 PDiag(diag::warn_sizeof_pointer_type_memaccess)
2511 << FnName << SizeOfArgTy << ArgIdx
2512 << PointeeTy << Dest->getSourceRange()
2513 << LenExpr->getSourceRange());
2514 break;
2515 }
Nico Webere4a1c642011-06-14 16:14:58 +00002516 }
2517
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002518 // Always complain about dynamic classes.
Anna Zaks0a151a12012-01-17 00:37:07 +00002519 if (isDynamicClassType(PointeeTy)) {
2520
2521 unsigned OperationType = 0;
2522 // "overwritten" if we're warning about the destination for any call
2523 // but memcmp; otherwise a verb appropriate to the call.
2524 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
2525 if (BId == Builtin::BImemcpy)
2526 OperationType = 1;
2527 else if(BId == Builtin::BImemmove)
2528 OperationType = 2;
2529 else if (BId == Builtin::BImemcmp)
2530 OperationType = 3;
2531 }
2532
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00002533 DiagRuntimeBehavior(
2534 Dest->getExprLoc(), Dest,
2535 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks0a151a12012-01-17 00:37:07 +00002536 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Anna Zaksd9b859a2012-01-13 21:52:01 +00002537 << FnName << PointeeTy
Anna Zaks0a151a12012-01-17 00:37:07 +00002538 << OperationType
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00002539 << Call->getCallee()->getSourceRange());
Anna Zaks0a151a12012-01-17 00:37:07 +00002540 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
2541 BId != Builtin::BImemset)
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00002542 DiagRuntimeBehavior(
2543 Dest->getExprLoc(), Dest,
2544 PDiag(diag::warn_arc_object_memaccess)
2545 << ArgIdx << FnName << PointeeTy
2546 << Call->getCallee()->getSourceRange());
John McCallf85e1932011-06-15 23:02:42 +00002547 else
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002548 continue;
John McCallf85e1932011-06-15 23:02:42 +00002549
2550 DiagRuntimeBehavior(
2551 Dest->getExprLoc(), Dest,
Chandler Carruth929f0132011-06-03 06:23:57 +00002552 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002553 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
2554 break;
2555 }
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002556 }
2557}
2558
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002559// A little helper routine: ignore addition and subtraction of integer literals.
2560// This intentionally does not ignore all integer constant expressions because
2561// we don't want to remove sizeof().
2562static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
2563 Ex = Ex->IgnoreParenCasts();
2564
2565 for (;;) {
2566 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
2567 if (!BO || !BO->isAdditiveOp())
2568 break;
2569
2570 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
2571 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
2572
2573 if (isa<IntegerLiteral>(RHS))
2574 Ex = LHS;
2575 else if (isa<IntegerLiteral>(LHS))
2576 Ex = RHS;
2577 else
2578 break;
2579 }
2580
2581 return Ex;
2582}
2583
2584// Warn if the user has made the 'size' argument to strlcpy or strlcat
2585// be the size of the source, instead of the destination.
2586void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
2587 IdentifierInfo *FnName) {
2588
2589 // Don't crash if the user has the wrong number of arguments
2590 if (Call->getNumArgs() != 3)
2591 return;
2592
2593 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
2594 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
2595 const Expr *CompareWithSrc = NULL;
2596
2597 // Look for 'strlcpy(dst, x, sizeof(x))'
2598 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
2599 CompareWithSrc = Ex;
2600 else {
2601 // Look for 'strlcpy(dst, x, strlen(x))'
2602 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Richard Smith180f4792011-11-10 06:34:14 +00002603 if (SizeCall->isBuiltinCall() == Builtin::BIstrlen
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002604 && SizeCall->getNumArgs() == 1)
2605 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
2606 }
2607 }
2608
2609 if (!CompareWithSrc)
2610 return;
2611
2612 // Determine if the argument to sizeof/strlen is equal to the source
2613 // argument. In principle there's all kinds of things you could do
2614 // here, for instance creating an == expression and evaluating it with
2615 // EvaluateAsBooleanCondition, but this uses a more direct technique:
2616 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
2617 if (!SrcArgDRE)
2618 return;
2619
2620 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
2621 if (!CompareWithSrcDRE ||
2622 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
2623 return;
2624
2625 const Expr *OriginalSizeArg = Call->getArg(2);
2626 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
2627 << OriginalSizeArg->getSourceRange() << FnName;
2628
2629 // Output a FIXIT hint if the destination is an array (rather than a
2630 // pointer to an array). This could be enhanced to handle some
2631 // pointers if we know the actual size, like if DstArg is 'array+2'
2632 // we could say 'sizeof(array)-2'.
2633 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Ted Kremenek8f746222011-08-18 22:48:41 +00002634 QualType DstArgTy = DstArg->getType();
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002635
Ted Kremenek8f746222011-08-18 22:48:41 +00002636 // Only handle constant-sized or VLAs, but not flexible members.
2637 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(DstArgTy)) {
2638 // Only issue the FIXIT for arrays of size > 1.
2639 if (CAT->getSize().getSExtValue() <= 1)
2640 return;
2641 } else if (!DstArgTy->isVariableArrayType()) {
2642 return;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002643 }
Ted Kremenek8f746222011-08-18 22:48:41 +00002644
2645 llvm::SmallString<128> sizeString;
2646 llvm::raw_svector_ostream OS(sizeString);
2647 OS << "sizeof(";
Douglas Gregor8987b232011-09-27 23:30:47 +00002648 DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
Ted Kremenek8f746222011-08-18 22:48:41 +00002649 OS << ")";
2650
2651 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
2652 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
2653 OS.str());
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002654}
2655
Ted Kremenek06de2762007-08-17 16:46:58 +00002656//===--- CHECK: Return Address of Stack Variable --------------------------===//
2657
Chris Lattner5f9e2722011-07-23 10:55:15 +00002658static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars);
2659static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002660
2661/// CheckReturnStackAddr - Check if a return statement returns the address
2662/// of a stack variable.
2663void
2664Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
2665 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00002666
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002667 Expr *stackE = 0;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002668 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002669
2670 // Perform checking for returned stack addresses, local blocks,
2671 // label addresses or references to temporaries.
John McCallf85e1932011-06-15 23:02:42 +00002672 if (lhsType->isPointerType() ||
2673 (!getLangOptions().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002674 stackE = EvalAddr(RetValExp, refVars);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002675 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002676 stackE = EvalVal(RetValExp, refVars);
2677 }
2678
2679 if (stackE == 0)
2680 return; // Nothing suspicious was found.
2681
2682 SourceLocation diagLoc;
2683 SourceRange diagRange;
2684 if (refVars.empty()) {
2685 diagLoc = stackE->getLocStart();
2686 diagRange = stackE->getSourceRange();
2687 } else {
2688 // We followed through a reference variable. 'stackE' contains the
2689 // problematic expression but we will warn at the return statement pointing
2690 // at the reference variable. We will later display the "trail" of
2691 // reference variables using notes.
2692 diagLoc = refVars[0]->getLocStart();
2693 diagRange = refVars[0]->getSourceRange();
2694 }
2695
2696 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
2697 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
2698 : diag::warn_ret_stack_addr)
2699 << DR->getDecl()->getDeclName() << diagRange;
2700 } else if (isa<BlockExpr>(stackE)) { // local block.
2701 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
2702 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
2703 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
2704 } else { // local temporary.
2705 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
2706 : diag::warn_ret_local_temp_addr)
2707 << diagRange;
2708 }
2709
2710 // Display the "trail" of reference variables that we followed until we
2711 // found the problematic expression using notes.
2712 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
2713 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
2714 // If this var binds to another reference var, show the range of the next
2715 // var, otherwise the var binds to the problematic expression, in which case
2716 // show the range of the expression.
2717 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
2718 : stackE->getSourceRange();
2719 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
2720 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00002721 }
2722}
2723
2724/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
2725/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002726/// to a location on the stack, a local block, an address of a label, or a
2727/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00002728/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002729/// encounter a subexpression that (1) clearly does not lead to one of the
2730/// above problematic expressions (2) is something we cannot determine leads to
2731/// a problematic expression based on such local checking.
2732///
2733/// Both EvalAddr and EvalVal follow through reference variables to evaluate
2734/// the expression that they point to. Such variables are added to the
2735/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00002736///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00002737/// EvalAddr processes expressions that are pointers that are used as
2738/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002739/// At the base case of the recursion is a check for the above problematic
2740/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00002741///
2742/// This implementation handles:
2743///
2744/// * pointer-to-pointer casts
2745/// * implicit conversions from array references to pointers
2746/// * taking the address of fields
2747/// * arbitrary interplay between "&" and "*" operators
2748/// * pointer arithmetic from an address of a stack variable
2749/// * taking the address of an array element where the array is on the stack
Chris Lattner5f9e2722011-07-23 10:55:15 +00002750static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002751 if (E->isTypeDependent())
2752 return NULL;
2753
Ted Kremenek06de2762007-08-17 16:46:58 +00002754 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00002755 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00002756 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002757 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002758 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00002759
Peter Collingbournef111d932011-04-15 00:35:48 +00002760 E = E->IgnoreParens();
2761
Ted Kremenek06de2762007-08-17 16:46:58 +00002762 // Our "symbolic interpreter" is just a dispatch off the currently
2763 // viewed AST node. We then recursively traverse the AST by calling
2764 // EvalAddr and EvalVal appropriately.
2765 switch (E->getStmtClass()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002766 case Stmt::DeclRefExprClass: {
2767 DeclRefExpr *DR = cast<DeclRefExpr>(E);
2768
2769 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
2770 // If this is a reference variable, follow through to the expression that
2771 // it points to.
2772 if (V->hasLocalStorage() &&
2773 V->getType()->isReferenceType() && V->hasInit()) {
2774 // Add the reference variable to the "trail".
2775 refVars.push_back(DR);
2776 return EvalAddr(V->getInit(), refVars);
2777 }
2778
2779 return NULL;
2780 }
Ted Kremenek06de2762007-08-17 16:46:58 +00002781
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002782 case Stmt::UnaryOperatorClass: {
2783 // The only unary operator that make sense to handle here
2784 // is AddrOf. All others don't make sense as pointers.
2785 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002786
John McCall2de56d12010-08-25 11:45:40 +00002787 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002788 return EvalVal(U->getSubExpr(), refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002789 else
Ted Kremenek06de2762007-08-17 16:46:58 +00002790 return NULL;
2791 }
Mike Stump1eb44332009-09-09 15:08:12 +00002792
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002793 case Stmt::BinaryOperatorClass: {
2794 // Handle pointer arithmetic. All other binary operators are not valid
2795 // in this context.
2796 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00002797 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00002798
John McCall2de56d12010-08-25 11:45:40 +00002799 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002800 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00002801
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002802 Expr *Base = B->getLHS();
2803
2804 // Determine which argument is the real pointer base. It could be
2805 // the RHS argument instead of the LHS.
2806 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00002807
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002808 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002809 return EvalAddr(Base, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002810 }
Steve Naroff61f40a22008-09-10 19:17:48 +00002811
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002812 // For conditional operators we need to see if either the LHS or RHS are
2813 // valid DeclRefExpr*s. If one of them is valid, we return it.
2814 case Stmt::ConditionalOperatorClass: {
2815 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002816
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002817 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00002818 if (Expr *lhsExpr = C->getLHS()) {
2819 // In C++, we can have a throw-expression, which has 'void' type.
2820 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002821 if (Expr* LHS = EvalAddr(lhsExpr, refVars))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00002822 return LHS;
2823 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002824
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00002825 // In C++, we can have a throw-expression, which has 'void' type.
2826 if (C->getRHS()->getType()->isVoidType())
2827 return NULL;
2828
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002829 return EvalAddr(C->getRHS(), refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002830 }
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002831
2832 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00002833 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002834 return E; // local block.
2835 return NULL;
2836
2837 case Stmt::AddrLabelExprClass:
2838 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00002839
John McCall80ee6e82011-11-10 05:35:25 +00002840 case Stmt::ExprWithCleanupsClass:
2841 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars);
2842
Ted Kremenek54b52742008-08-07 00:49:01 +00002843 // For casts, we need to handle conversions from arrays to
2844 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00002845 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002846 case Stmt::CStyleCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00002847 case Stmt::CXXFunctionalCastExprClass:
2848 case Stmt::ObjCBridgedCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002849 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenek54b52742008-08-07 00:49:01 +00002850 QualType T = SubExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002851
Steve Naroffdd972f22008-09-05 22:11:13 +00002852 if (SubExpr->getType()->isPointerType() ||
2853 SubExpr->getType()->isBlockPointerType() ||
2854 SubExpr->getType()->isObjCQualifiedIdType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002855 return EvalAddr(SubExpr, refVars);
Ted Kremenek54b52742008-08-07 00:49:01 +00002856 else if (T->isArrayType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002857 return EvalVal(SubExpr, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002858 else
Ted Kremenek54b52742008-08-07 00:49:01 +00002859 return 0;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002860 }
Mike Stump1eb44332009-09-09 15:08:12 +00002861
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002862 // C++ casts. For dynamic casts, static casts, and const casts, we
2863 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor49badde2008-10-27 19:41:14 +00002864 // through the cast. In the case the dynamic cast doesn't fail (and
2865 // return NULL), we take the conservative route and report cases
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002866 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor49badde2008-10-27 19:41:14 +00002867 // FIXME: The comment about is wrong; we're not always converting
2868 // from pointer to pointer. I'm guessing that this code should also
Mike Stump1eb44332009-09-09 15:08:12 +00002869 // handle references to objects.
2870 case Stmt::CXXStaticCastExprClass:
2871 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00002872 case Stmt::CXXConstCastExprClass:
2873 case Stmt::CXXReinterpretCastExprClass: {
2874 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffdd972f22008-09-05 22:11:13 +00002875 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002876 return EvalAddr(S, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002877 else
2878 return NULL;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002879 }
Mike Stump1eb44332009-09-09 15:08:12 +00002880
Douglas Gregor03e80032011-06-21 17:03:29 +00002881 case Stmt::MaterializeTemporaryExprClass:
2882 if (Expr *Result = EvalAddr(
2883 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
2884 refVars))
2885 return Result;
2886
2887 return E;
2888
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002889 // Everything else: we simply don't reason about them.
2890 default:
2891 return NULL;
2892 }
Ted Kremenek06de2762007-08-17 16:46:58 +00002893}
Mike Stump1eb44332009-09-09 15:08:12 +00002894
Ted Kremenek06de2762007-08-17 16:46:58 +00002895
2896/// EvalVal - This function is complements EvalAddr in the mutual recursion.
2897/// See the comments for EvalAddr for more details.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002898static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002899do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00002900 // We should only be called for evaluating non-pointer expressions, or
2901 // expressions with a pointer type that are not used as references but instead
2902 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00002903
Ted Kremenek06de2762007-08-17 16:46:58 +00002904 // Our "symbolic interpreter" is just a dispatch off the currently
2905 // viewed AST node. We then recursively traverse the AST by calling
2906 // EvalAddr and EvalVal appropriately.
Peter Collingbournef111d932011-04-15 00:35:48 +00002907
2908 E = E->IgnoreParens();
Ted Kremenek06de2762007-08-17 16:46:58 +00002909 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002910 case Stmt::ImplicitCastExprClass: {
2911 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00002912 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002913 E = IE->getSubExpr();
2914 continue;
2915 }
2916 return NULL;
2917 }
2918
John McCall80ee6e82011-11-10 05:35:25 +00002919 case Stmt::ExprWithCleanupsClass:
2920 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars);
2921
Douglas Gregora2813ce2009-10-23 18:54:35 +00002922 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002923 // When we hit a DeclRefExpr we are looking at code that refers to a
2924 // variable's name. If it's not a reference variable we check if it has
2925 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00002926 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002927
Ted Kremenek06de2762007-08-17 16:46:58 +00002928 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002929 if (V->hasLocalStorage()) {
2930 if (!V->getType()->isReferenceType())
2931 return DR;
2932
2933 // Reference variable, follow through to the expression that
2934 // it points to.
2935 if (V->hasInit()) {
2936 // Add the reference variable to the "trail".
2937 refVars.push_back(DR);
2938 return EvalVal(V->getInit(), refVars);
2939 }
2940 }
Mike Stump1eb44332009-09-09 15:08:12 +00002941
Ted Kremenek06de2762007-08-17 16:46:58 +00002942 return NULL;
2943 }
Mike Stump1eb44332009-09-09 15:08:12 +00002944
Ted Kremenek06de2762007-08-17 16:46:58 +00002945 case Stmt::UnaryOperatorClass: {
2946 // The only unary operator that make sense to handle here
2947 // is Deref. All others don't resolve to a "name." This includes
2948 // handling all sorts of rvalues passed to a unary operator.
2949 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002950
John McCall2de56d12010-08-25 11:45:40 +00002951 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002952 return EvalAddr(U->getSubExpr(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002953
2954 return NULL;
2955 }
Mike Stump1eb44332009-09-09 15:08:12 +00002956
Ted Kremenek06de2762007-08-17 16:46:58 +00002957 case Stmt::ArraySubscriptExprClass: {
2958 // Array subscripts are potential references to data on the stack. We
2959 // retrieve the DeclRefExpr* for the array variable if it indeed
2960 // has local storage.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002961 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002962 }
Mike Stump1eb44332009-09-09 15:08:12 +00002963
Ted Kremenek06de2762007-08-17 16:46:58 +00002964 case Stmt::ConditionalOperatorClass: {
2965 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002966 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00002967 ConditionalOperator *C = cast<ConditionalOperator>(E);
2968
Anders Carlsson39073232007-11-30 19:04:31 +00002969 // Handle the GNU extension for missing LHS.
2970 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002971 if (Expr *LHS = EvalVal(lhsExpr, refVars))
Anders Carlsson39073232007-11-30 19:04:31 +00002972 return LHS;
2973
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002974 return EvalVal(C->getRHS(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002975 }
Mike Stump1eb44332009-09-09 15:08:12 +00002976
Ted Kremenek06de2762007-08-17 16:46:58 +00002977 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00002978 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00002979 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002980
Ted Kremenek06de2762007-08-17 16:46:58 +00002981 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00002982 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00002983 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00002984
2985 // Check whether the member type is itself a reference, in which case
2986 // we're not going to refer to the member, but to what the member refers to.
2987 if (M->getMemberDecl()->getType()->isReferenceType())
2988 return NULL;
2989
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002990 return EvalVal(M->getBase(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002991 }
Mike Stump1eb44332009-09-09 15:08:12 +00002992
Douglas Gregor03e80032011-06-21 17:03:29 +00002993 case Stmt::MaterializeTemporaryExprClass:
2994 if (Expr *Result = EvalVal(
2995 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
2996 refVars))
2997 return Result;
2998
2999 return E;
3000
Ted Kremenek06de2762007-08-17 16:46:58 +00003001 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003002 // Check that we don't return or take the address of a reference to a
3003 // temporary. This is only useful in C++.
3004 if (!E->isTypeDependent() && E->isRValue())
3005 return E;
3006
3007 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00003008 return NULL;
3009 }
Ted Kremenek68957a92010-08-04 20:01:07 +00003010} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00003011}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003012
3013//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
3014
3015/// Check for comparisons of floating point operands using != and ==.
3016/// Issue a warning if these are no self-comparisons, as they are not likely
3017/// to do what the programmer intended.
Richard Trieudd225092011-09-15 21:56:47 +00003018void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003019 bool EmitWarning = true;
Mike Stump1eb44332009-09-09 15:08:12 +00003020
Richard Trieudd225092011-09-15 21:56:47 +00003021 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
3022 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003023
3024 // Special case: check for x == x (which is OK).
3025 // Do not emit warnings for such cases.
3026 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
3027 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
3028 if (DRL->getDecl() == DRR->getDecl())
3029 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003030
3031
Ted Kremenek1b500bb2007-11-29 00:59:04 +00003032 // Special case: check for comparisons against literals that can be exactly
3033 // represented by APFloat. In such cases, do not emit a warning. This
3034 // is a heuristic: often comparison against such literals are used to
3035 // detect if a value in a variable has not changed. This clearly can
3036 // lead to false negatives.
3037 if (EmitWarning) {
3038 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
3039 if (FLL->isExact())
3040 EmitWarning = false;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003041 } else
Ted Kremenek1b500bb2007-11-29 00:59:04 +00003042 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
3043 if (FLR->isExact())
3044 EmitWarning = false;
3045 }
3046 }
Mike Stump1eb44332009-09-09 15:08:12 +00003047
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003048 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003049 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003050 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Richard Smith180f4792011-11-10 06:34:14 +00003051 if (CL->isBuiltinCall())
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003052 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003053
Sebastian Redl0eb23302009-01-19 00:08:26 +00003054 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003055 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Richard Smith180f4792011-11-10 06:34:14 +00003056 if (CR->isBuiltinCall())
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003057 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003058
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003059 // Emit the diagnostic.
3060 if (EmitWarning)
Richard Trieudd225092011-09-15 21:56:47 +00003061 Diag(Loc, diag::warn_floatingpoint_eq)
3062 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003063}
John McCallba26e582010-01-04 23:21:16 +00003064
John McCallf2370c92010-01-06 05:24:50 +00003065//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
3066//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00003067
John McCallf2370c92010-01-06 05:24:50 +00003068namespace {
John McCallba26e582010-01-04 23:21:16 +00003069
John McCallf2370c92010-01-06 05:24:50 +00003070/// Structure recording the 'active' range of an integer-valued
3071/// expression.
3072struct IntRange {
3073 /// The number of bits active in the int.
3074 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00003075
John McCallf2370c92010-01-06 05:24:50 +00003076 /// True if the int is known not to have negative values.
3077 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00003078
John McCallf2370c92010-01-06 05:24:50 +00003079 IntRange(unsigned Width, bool NonNegative)
3080 : Width(Width), NonNegative(NonNegative)
3081 {}
John McCallba26e582010-01-04 23:21:16 +00003082
John McCall1844a6e2010-11-10 23:38:19 +00003083 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00003084 static IntRange forBoolType() {
3085 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00003086 }
3087
John McCall1844a6e2010-11-10 23:38:19 +00003088 /// Returns the range of an opaque value of the given integral type.
3089 static IntRange forValueOfType(ASTContext &C, QualType T) {
3090 return forValueOfCanonicalType(C,
3091 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00003092 }
3093
John McCall1844a6e2010-11-10 23:38:19 +00003094 /// Returns the range of an opaque value of a canonical integral type.
3095 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00003096 assert(T->isCanonicalUnqualified());
3097
3098 if (const VectorType *VT = dyn_cast<VectorType>(T))
3099 T = VT->getElementType().getTypePtr();
3100 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
3101 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00003102
John McCall091f23f2010-11-09 22:22:12 +00003103 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00003104 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
3105 EnumDecl *Enum = ET->getDecl();
John McCall5e1cdac2011-10-07 06:10:15 +00003106 if (!Enum->isCompleteDefinition())
John McCall091f23f2010-11-09 22:22:12 +00003107 return IntRange(C.getIntWidth(QualType(T, 0)), false);
3108
John McCall323ed742010-05-06 08:58:33 +00003109 unsigned NumPositive = Enum->getNumPositiveBits();
3110 unsigned NumNegative = Enum->getNumNegativeBits();
3111
3112 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
3113 }
John McCallf2370c92010-01-06 05:24:50 +00003114
3115 const BuiltinType *BT = cast<BuiltinType>(T);
3116 assert(BT->isInteger());
3117
3118 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
3119 }
3120
John McCall1844a6e2010-11-10 23:38:19 +00003121 /// Returns the "target" range of a canonical integral type, i.e.
3122 /// the range of values expressible in the type.
3123 ///
3124 /// This matches forValueOfCanonicalType except that enums have the
3125 /// full range of their type, not the range of their enumerators.
3126 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
3127 assert(T->isCanonicalUnqualified());
3128
3129 if (const VectorType *VT = dyn_cast<VectorType>(T))
3130 T = VT->getElementType().getTypePtr();
3131 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
3132 T = CT->getElementType().getTypePtr();
3133 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor69ff26b2011-09-08 23:29:05 +00003134 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall1844a6e2010-11-10 23:38:19 +00003135
3136 const BuiltinType *BT = cast<BuiltinType>(T);
3137 assert(BT->isInteger());
3138
3139 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
3140 }
3141
3142 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00003143 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00003144 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00003145 L.NonNegative && R.NonNegative);
3146 }
3147
John McCall1844a6e2010-11-10 23:38:19 +00003148 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00003149 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00003150 return IntRange(std::min(L.Width, R.Width),
3151 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00003152 }
3153};
3154
3155IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
3156 if (value.isSigned() && value.isNegative())
3157 return IntRange(value.getMinSignedBits(), false);
3158
3159 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00003160 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00003161
3162 // isNonNegative() just checks the sign bit without considering
3163 // signedness.
3164 return IntRange(value.getActiveBits(), true);
3165}
3166
John McCall0acc3112010-01-06 22:57:21 +00003167IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
John McCallf2370c92010-01-06 05:24:50 +00003168 unsigned MaxWidth) {
3169 if (result.isInt())
3170 return GetValueRange(C, result.getInt(), MaxWidth);
3171
3172 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00003173 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
3174 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
3175 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
3176 R = IntRange::join(R, El);
3177 }
John McCallf2370c92010-01-06 05:24:50 +00003178 return R;
3179 }
3180
3181 if (result.isComplexInt()) {
3182 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
3183 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
3184 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00003185 }
3186
3187 // This can happen with lossless casts to intptr_t of "based" lvalues.
3188 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00003189 // FIXME: The only reason we need to pass the type in here is to get
3190 // the sign right on this one case. It would be nice if APValue
3191 // preserved this.
Eli Friedman65639282012-01-04 23:13:47 +00003192 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00003193 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall51313c32010-01-04 23:31:57 +00003194}
John McCallf2370c92010-01-06 05:24:50 +00003195
3196/// Pseudo-evaluate the given integer expression, estimating the
3197/// range of values it might take.
3198///
3199/// \param MaxWidth - the width to which the value will be truncated
3200IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
3201 E = E->IgnoreParens();
3202
3203 // Try a full evaluation first.
3204 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00003205 if (E->EvaluateAsRValue(result, C))
John McCall0acc3112010-01-06 22:57:21 +00003206 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00003207
3208 // I think we only want to look through implicit casts here; if the
3209 // user has an explicit widening cast, we should treat the value as
3210 // being of the new, wider type.
3211 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedmanb17ee5b2011-12-15 02:41:52 +00003212 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCallf2370c92010-01-06 05:24:50 +00003213 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
3214
John McCall1844a6e2010-11-10 23:38:19 +00003215 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
John McCallf2370c92010-01-06 05:24:50 +00003216
John McCall2de56d12010-08-25 11:45:40 +00003217 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00003218
John McCallf2370c92010-01-06 05:24:50 +00003219 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00003220 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00003221 return OutputTypeRange;
3222
3223 IntRange SubRange
3224 = GetExprRange(C, CE->getSubExpr(),
3225 std::min(MaxWidth, OutputTypeRange.Width));
3226
3227 // Bail out if the subexpr's range is as wide as the cast type.
3228 if (SubRange.Width >= OutputTypeRange.Width)
3229 return OutputTypeRange;
3230
3231 // Otherwise, we take the smaller width, and we're non-negative if
3232 // either the output type or the subexpr is.
3233 return IntRange(SubRange.Width,
3234 SubRange.NonNegative || OutputTypeRange.NonNegative);
3235 }
3236
3237 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3238 // If we can fold the condition, just take that operand.
3239 bool CondResult;
3240 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
3241 return GetExprRange(C, CondResult ? CO->getTrueExpr()
3242 : CO->getFalseExpr(),
3243 MaxWidth);
3244
3245 // Otherwise, conservatively merge.
3246 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
3247 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
3248 return IntRange::join(L, R);
3249 }
3250
3251 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3252 switch (BO->getOpcode()) {
3253
3254 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00003255 case BO_LAnd:
3256 case BO_LOr:
3257 case BO_LT:
3258 case BO_GT:
3259 case BO_LE:
3260 case BO_GE:
3261 case BO_EQ:
3262 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00003263 return IntRange::forBoolType();
3264
John McCall862ff872011-07-13 06:35:24 +00003265 // The type of the assignments is the type of the LHS, so the RHS
3266 // is not necessarily the same type.
John McCall2de56d12010-08-25 11:45:40 +00003267 case BO_MulAssign:
3268 case BO_DivAssign:
3269 case BO_RemAssign:
3270 case BO_AddAssign:
3271 case BO_SubAssign:
John McCall862ff872011-07-13 06:35:24 +00003272 case BO_XorAssign:
3273 case BO_OrAssign:
3274 // TODO: bitfields?
John McCall1844a6e2010-11-10 23:38:19 +00003275 return IntRange::forValueOfType(C, E->getType());
John McCallc0cd21d2010-02-23 19:22:29 +00003276
John McCall862ff872011-07-13 06:35:24 +00003277 // Simple assignments just pass through the RHS, which will have
3278 // been coerced to the LHS type.
3279 case BO_Assign:
3280 // TODO: bitfields?
3281 return GetExprRange(C, BO->getRHS(), MaxWidth);
3282
John McCallf2370c92010-01-06 05:24:50 +00003283 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00003284 case BO_PtrMemD:
3285 case BO_PtrMemI:
John McCall1844a6e2010-11-10 23:38:19 +00003286 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003287
John McCall60fad452010-01-06 22:07:33 +00003288 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00003289 case BO_And:
3290 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00003291 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
3292 GetExprRange(C, BO->getRHS(), MaxWidth));
3293
John McCallf2370c92010-01-06 05:24:50 +00003294 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00003295 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00003296 // ...except that we want to treat '1 << (blah)' as logically
3297 // positive. It's an important idiom.
3298 if (IntegerLiteral *I
3299 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
3300 if (I->getValue() == 1) {
John McCall1844a6e2010-11-10 23:38:19 +00003301 IntRange R = IntRange::forValueOfType(C, E->getType());
John McCall3aae6092010-04-07 01:14:35 +00003302 return IntRange(R.Width, /*NonNegative*/ true);
3303 }
3304 }
3305 // fallthrough
3306
John McCall2de56d12010-08-25 11:45:40 +00003307 case BO_ShlAssign:
John McCall1844a6e2010-11-10 23:38:19 +00003308 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003309
John McCall60fad452010-01-06 22:07:33 +00003310 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00003311 case BO_Shr:
3312 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00003313 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3314
3315 // If the shift amount is a positive constant, drop the width by
3316 // that much.
3317 llvm::APSInt shift;
3318 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
3319 shift.isNonNegative()) {
3320 unsigned zext = shift.getZExtValue();
3321 if (zext >= L.Width)
3322 L.Width = (L.NonNegative ? 0 : 1);
3323 else
3324 L.Width -= zext;
3325 }
3326
3327 return L;
3328 }
3329
3330 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00003331 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00003332 return GetExprRange(C, BO->getRHS(), MaxWidth);
3333
John McCall60fad452010-01-06 22:07:33 +00003334 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00003335 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00003336 if (BO->getLHS()->getType()->isPointerType())
John McCall1844a6e2010-11-10 23:38:19 +00003337 return IntRange::forValueOfType(C, E->getType());
John McCall00fe7612011-07-14 22:39:48 +00003338 break;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003339
John McCall00fe7612011-07-14 22:39:48 +00003340 // The width of a division result is mostly determined by the size
3341 // of the LHS.
3342 case BO_Div: {
3343 // Don't 'pre-truncate' the operands.
3344 unsigned opWidth = C.getIntWidth(E->getType());
3345 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3346
3347 // If the divisor is constant, use that.
3348 llvm::APSInt divisor;
3349 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
3350 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
3351 if (log2 >= L.Width)
3352 L.Width = (L.NonNegative ? 0 : 1);
3353 else
3354 L.Width = std::min(L.Width - log2, MaxWidth);
3355 return L;
3356 }
3357
3358 // Otherwise, just use the LHS's width.
3359 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3360 return IntRange(L.Width, L.NonNegative && R.NonNegative);
3361 }
3362
3363 // The result of a remainder can't be larger than the result of
3364 // either side.
3365 case BO_Rem: {
3366 // Don't 'pre-truncate' the operands.
3367 unsigned opWidth = C.getIntWidth(E->getType());
3368 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3369 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3370
3371 IntRange meet = IntRange::meet(L, R);
3372 meet.Width = std::min(meet.Width, MaxWidth);
3373 return meet;
3374 }
3375
3376 // The default behavior is okay for these.
3377 case BO_Mul:
3378 case BO_Add:
3379 case BO_Xor:
3380 case BO_Or:
John McCallf2370c92010-01-06 05:24:50 +00003381 break;
3382 }
3383
John McCall00fe7612011-07-14 22:39:48 +00003384 // The default case is to treat the operation as if it were closed
3385 // on the narrowest type that encompasses both operands.
John McCallf2370c92010-01-06 05:24:50 +00003386 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3387 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
3388 return IntRange::join(L, R);
3389 }
3390
3391 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
3392 switch (UO->getOpcode()) {
3393 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00003394 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00003395 return IntRange::forBoolType();
3396
3397 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00003398 case UO_Deref:
3399 case UO_AddrOf: // should be impossible
John McCall1844a6e2010-11-10 23:38:19 +00003400 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003401
3402 default:
3403 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
3404 }
3405 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003406
3407 if (dyn_cast<OffsetOfExpr>(E)) {
John McCall1844a6e2010-11-10 23:38:19 +00003408 IntRange::forValueOfType(C, E->getType());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003409 }
John McCallf2370c92010-01-06 05:24:50 +00003410
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003411 if (FieldDecl *BitField = E->getBitField())
3412 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00003413 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCallf2370c92010-01-06 05:24:50 +00003414
John McCall1844a6e2010-11-10 23:38:19 +00003415 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003416}
John McCall51313c32010-01-04 23:31:57 +00003417
John McCall323ed742010-05-06 08:58:33 +00003418IntRange GetExprRange(ASTContext &C, Expr *E) {
3419 return GetExprRange(C, E, C.getIntWidth(E->getType()));
3420}
3421
John McCall51313c32010-01-04 23:31:57 +00003422/// Checks whether the given value, which currently has the given
3423/// source semantics, has the same value when coerced through the
3424/// target semantics.
John McCallf2370c92010-01-06 05:24:50 +00003425bool IsSameFloatAfterCast(const llvm::APFloat &value,
3426 const llvm::fltSemantics &Src,
3427 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00003428 llvm::APFloat truncated = value;
3429
3430 bool ignored;
3431 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
3432 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
3433
3434 return truncated.bitwiseIsEqual(value);
3435}
3436
3437/// Checks whether the given value, which currently has the given
3438/// source semantics, has the same value when coerced through the
3439/// target semantics.
3440///
3441/// The value might be a vector of floats (or a complex number).
John McCallf2370c92010-01-06 05:24:50 +00003442bool IsSameFloatAfterCast(const APValue &value,
3443 const llvm::fltSemantics &Src,
3444 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00003445 if (value.isFloat())
3446 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
3447
3448 if (value.isVector()) {
3449 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
3450 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
3451 return false;
3452 return true;
3453 }
3454
3455 assert(value.isComplexFloat());
3456 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
3457 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
3458}
3459
John McCallb4eb64d2010-10-08 02:01:28 +00003460void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00003461
Ted Kremeneke3b159c2010-09-23 21:43:44 +00003462static bool IsZero(Sema &S, Expr *E) {
3463 // Suppress cases where we are comparing against an enum constant.
3464 if (const DeclRefExpr *DR =
3465 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
3466 if (isa<EnumConstantDecl>(DR->getDecl()))
3467 return false;
3468
3469 // Suppress cases where the '0' value is expanded from a macro.
3470 if (E->getLocStart().isMacroID())
3471 return false;
3472
John McCall323ed742010-05-06 08:58:33 +00003473 llvm::APSInt Value;
3474 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
3475}
3476
John McCall372e1032010-10-06 00:25:24 +00003477static bool HasEnumType(Expr *E) {
3478 // Strip off implicit integral promotions.
3479 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00003480 if (ICE->getCastKind() != CK_IntegralCast &&
3481 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00003482 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00003483 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00003484 }
3485
3486 return E->getType()->isEnumeralType();
3487}
3488
John McCall323ed742010-05-06 08:58:33 +00003489void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00003490 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00003491 if (E->isValueDependent())
3492 return;
3493
John McCall2de56d12010-08-25 11:45:40 +00003494 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00003495 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003496 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00003497 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00003498 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00003499 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003500 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00003501 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00003502 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00003503 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003504 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00003505 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00003506 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00003507 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003508 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00003509 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
3510 }
3511}
3512
3513/// Analyze the operands of the given comparison. Implements the
3514/// fallback case from AnalyzeComparison.
3515void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00003516 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
3517 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00003518}
John McCall51313c32010-01-04 23:31:57 +00003519
John McCallba26e582010-01-04 23:21:16 +00003520/// \brief Implements -Wsign-compare.
3521///
Richard Trieudd225092011-09-15 21:56:47 +00003522/// \param E the binary operator to check for warnings
John McCall323ed742010-05-06 08:58:33 +00003523void AnalyzeComparison(Sema &S, BinaryOperator *E) {
3524 // The type the comparison is being performed in.
3525 QualType T = E->getLHS()->getType();
3526 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
3527 && "comparison with mismatched types");
John McCallba26e582010-01-04 23:21:16 +00003528
John McCall323ed742010-05-06 08:58:33 +00003529 // We don't do anything special if this isn't an unsigned integral
3530 // comparison: we're only interested in integral comparisons, and
3531 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00003532 //
3533 // We also don't care about value-dependent expressions or expressions
3534 // whose result is a constant.
3535 if (!T->hasUnsignedIntegerRepresentation()
3536 || E->isValueDependent() || E->isIntegerConstantExpr(S.Context))
John McCall323ed742010-05-06 08:58:33 +00003537 return AnalyzeImpConvsInComparison(S, E);
John McCallf2370c92010-01-06 05:24:50 +00003538
Richard Trieudd225092011-09-15 21:56:47 +00003539 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
3540 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
John McCallba26e582010-01-04 23:21:16 +00003541
John McCall323ed742010-05-06 08:58:33 +00003542 // Check to see if one of the (unmodified) operands is of different
3543 // signedness.
3544 Expr *signedOperand, *unsignedOperand;
Richard Trieudd225092011-09-15 21:56:47 +00003545 if (LHS->getType()->hasSignedIntegerRepresentation()) {
3546 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00003547 "unsigned comparison between two signed integer expressions?");
Richard Trieudd225092011-09-15 21:56:47 +00003548 signedOperand = LHS;
3549 unsignedOperand = RHS;
3550 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
3551 signedOperand = RHS;
3552 unsignedOperand = LHS;
John McCallba26e582010-01-04 23:21:16 +00003553 } else {
John McCall323ed742010-05-06 08:58:33 +00003554 CheckTrivialUnsignedComparison(S, E);
3555 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00003556 }
3557
John McCall323ed742010-05-06 08:58:33 +00003558 // Otherwise, calculate the effective range of the signed operand.
3559 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00003560
John McCall323ed742010-05-06 08:58:33 +00003561 // Go ahead and analyze implicit conversions in the operands. Note
3562 // that we skip the implicit conversions on both sides.
Richard Trieudd225092011-09-15 21:56:47 +00003563 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
3564 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00003565
John McCall323ed742010-05-06 08:58:33 +00003566 // If the signed range is non-negative, -Wsign-compare won't fire,
3567 // but we should still check for comparisons which are always true
3568 // or false.
3569 if (signedRange.NonNegative)
3570 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00003571
3572 // For (in)equality comparisons, if the unsigned operand is a
3573 // constant which cannot collide with a overflowed signed operand,
3574 // then reinterpreting the signed operand as unsigned will not
3575 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00003576 if (E->isEqualityOp()) {
3577 unsigned comparisonWidth = S.Context.getIntWidth(T);
3578 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00003579
John McCall323ed742010-05-06 08:58:33 +00003580 // We should never be unable to prove that the unsigned operand is
3581 // non-negative.
3582 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
3583
3584 if (unsignedRange.Width < comparisonWidth)
3585 return;
3586 }
3587
3588 S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison)
Richard Trieudd225092011-09-15 21:56:47 +00003589 << LHS->getType() << RHS->getType()
3590 << LHS->getSourceRange() << RHS->getSourceRange();
John McCallba26e582010-01-04 23:21:16 +00003591}
3592
John McCall15d7d122010-11-11 03:21:53 +00003593/// Analyzes an attempt to assign the given value to a bitfield.
3594///
3595/// Returns true if there was something fishy about the attempt.
3596bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
3597 SourceLocation InitLoc) {
3598 assert(Bitfield->isBitField());
3599 if (Bitfield->isInvalidDecl())
3600 return false;
3601
John McCall91b60142010-11-11 05:33:51 +00003602 // White-list bool bitfields.
3603 if (Bitfield->getType()->isBooleanType())
3604 return false;
3605
Douglas Gregor46ff3032011-02-04 13:09:01 +00003606 // Ignore value- or type-dependent expressions.
3607 if (Bitfield->getBitWidth()->isValueDependent() ||
3608 Bitfield->getBitWidth()->isTypeDependent() ||
3609 Init->isValueDependent() ||
3610 Init->isTypeDependent())
3611 return false;
3612
John McCall15d7d122010-11-11 03:21:53 +00003613 Expr *OriginalInit = Init->IgnoreParenImpCasts();
3614
Richard Smith80d4b552011-12-28 19:48:30 +00003615 llvm::APSInt Value;
3616 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall15d7d122010-11-11 03:21:53 +00003617 return false;
3618
John McCall15d7d122010-11-11 03:21:53 +00003619 unsigned OriginalWidth = Value.getBitWidth();
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003620 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall15d7d122010-11-11 03:21:53 +00003621
3622 if (OriginalWidth <= FieldWidth)
3623 return false;
3624
Jay Foad9f71a8f2010-12-07 08:25:34 +00003625 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
John McCall15d7d122010-11-11 03:21:53 +00003626
3627 // It's fairly common to write values into signed bitfields
3628 // that, if sign-extended, would end up becoming a different
3629 // value. We don't want to warn about that.
3630 if (Value.isSigned() && Value.isNegative())
Jay Foad9f71a8f2010-12-07 08:25:34 +00003631 TruncatedValue = TruncatedValue.sext(OriginalWidth);
John McCall15d7d122010-11-11 03:21:53 +00003632 else
Jay Foad9f71a8f2010-12-07 08:25:34 +00003633 TruncatedValue = TruncatedValue.zext(OriginalWidth);
John McCall15d7d122010-11-11 03:21:53 +00003634
3635 if (Value == TruncatedValue)
3636 return false;
3637
3638 std::string PrettyValue = Value.toString(10);
3639 std::string PrettyTrunc = TruncatedValue.toString(10);
3640
3641 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
3642 << PrettyValue << PrettyTrunc << OriginalInit->getType()
3643 << Init->getSourceRange();
3644
3645 return true;
3646}
3647
John McCallbeb22aa2010-11-09 23:24:47 +00003648/// Analyze the given simple or compound assignment for warning-worthy
3649/// operations.
3650void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
3651 // Just recurse on the LHS.
3652 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
3653
3654 // We want to recurse on the RHS as normal unless we're assigning to
3655 // a bitfield.
3656 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
John McCall15d7d122010-11-11 03:21:53 +00003657 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
3658 E->getOperatorLoc())) {
3659 // Recurse, ignoring any implicit conversions on the RHS.
3660 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
3661 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00003662 }
3663 }
3664
3665 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
3666}
3667
John McCall51313c32010-01-04 23:31:57 +00003668/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00003669void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
3670 SourceLocation CContext, unsigned diag) {
3671 S.Diag(E->getExprLoc(), diag)
3672 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
3673}
3674
Chandler Carruthe1b02e02011-04-05 06:47:57 +00003675/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
3676void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
3677 unsigned diag) {
3678 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag);
3679}
3680
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003681/// Diagnose an implicit cast from a literal expression. Does not warn when the
3682/// cast wouldn't lose information.
Chandler Carruthf65076e2011-04-10 08:36:24 +00003683void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
3684 SourceLocation CContext) {
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003685 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruthf65076e2011-04-10 08:36:24 +00003686 bool isExact = false;
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003687 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00003688 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
3689 T->hasUnsignedIntegerRepresentation());
3690 if (Value.convertToInteger(IntegerValue,
Chandler Carruthf65076e2011-04-10 08:36:24 +00003691 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003692 == llvm::APFloat::opOK && isExact)
Chandler Carruthf65076e2011-04-10 08:36:24 +00003693 return;
3694
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003695 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
3696 << FL->getType() << T << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruthf65076e2011-04-10 08:36:24 +00003697}
3698
John McCall091f23f2010-11-09 22:22:12 +00003699std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
3700 if (!Range.Width) return "0";
3701
3702 llvm::APSInt ValueInRange = Value;
3703 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00003704 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00003705 return ValueInRange.toString(10);
3706}
3707
John McCall323ed742010-05-06 08:58:33 +00003708void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00003709 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00003710 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00003711
John McCall323ed742010-05-06 08:58:33 +00003712 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
3713 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
3714 if (Source == Target) return;
3715 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00003716
Chandler Carruth108f7562011-07-26 05:40:03 +00003717 // If the conversion context location is invalid don't complain. We also
3718 // don't want to emit a warning if the issue occurs from the expansion of
3719 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
3720 // delay this check as long as possible. Once we detect we are in that
3721 // scenario, we just return.
Ted Kremenekef9ff882011-03-10 20:03:42 +00003722 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00003723 return;
3724
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00003725 // Diagnose implicit casts to bool.
3726 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
3727 if (isa<StringLiteral>(E))
3728 // Warn on string literal to bool. Checks for string literals in logical
3729 // expressions, for instances, assert(0 && "error here"), is prevented
3730 // by a check in AnalyzeImplicitConversions().
3731 return DiagnoseImpCast(S, E, T, CC,
3732 diag::warn_impcast_string_literal_to_bool);
Lang Hamese14ca9f2011-12-05 20:49:50 +00003733 if (Source->isFunctionType()) {
3734 // Warn on function to bool. Checks free functions and static member
3735 // functions. Weakly imported functions are excluded from the check,
3736 // since it's common to test their value to check whether the linker
3737 // found a definition for them.
3738 ValueDecl *D = 0;
3739 if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
3740 D = R->getDecl();
3741 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
3742 D = M->getMemberDecl();
3743 }
3744
3745 if (D && !D->isWeak()) {
Richard Trieu26b45d82011-12-06 04:48:01 +00003746 if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
3747 S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
3748 << F << E->getSourceRange() << SourceRange(CC);
David Blaikie2def7732011-12-09 21:42:37 +00003749 S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
3750 << FixItHint::CreateInsertion(E->getExprLoc(), "&");
3751 QualType ReturnType;
3752 UnresolvedSet<4> NonTemplateOverloads;
3753 S.isExprCallable(*E, ReturnType, NonTemplateOverloads);
3754 if (!ReturnType.isNull()
3755 && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
3756 S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
3757 << FixItHint::CreateInsertion(
3758 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu26b45d82011-12-06 04:48:01 +00003759 return;
3760 }
Lang Hamese14ca9f2011-12-05 20:49:50 +00003761 }
3762 }
David Blaikiee37cdc42011-09-29 04:06:47 +00003763 return; // Other casts to bool are not checked.
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00003764 }
John McCall51313c32010-01-04 23:31:57 +00003765
3766 // Strip vector types.
3767 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003768 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00003769 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00003770 return;
John McCallb4eb64d2010-10-08 02:01:28 +00003771 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00003772 }
Chris Lattnerb792b302011-06-14 04:51:15 +00003773
3774 // If the vector cast is cast between two vectors of the same size, it is
3775 // a bitcast, not a conversion.
3776 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
3777 return;
John McCall51313c32010-01-04 23:31:57 +00003778
3779 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
3780 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
3781 }
3782
3783 // Strip complex types.
3784 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003785 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00003786 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00003787 return;
3788
John McCallb4eb64d2010-10-08 02:01:28 +00003789 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00003790 }
John McCall51313c32010-01-04 23:31:57 +00003791
3792 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
3793 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
3794 }
3795
3796 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
3797 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
3798
3799 // If the source is floating point...
3800 if (SourceBT && SourceBT->isFloatingPoint()) {
3801 // ...and the target is floating point...
3802 if (TargetBT && TargetBT->isFloatingPoint()) {
3803 // ...then warn if we're dropping FP rank.
3804
3805 // Builtin FP kinds are ordered by increasing FP rank.
3806 if (SourceBT->getKind() > TargetBT->getKind()) {
3807 // Don't warn about float constants that are precisely
3808 // representable in the target type.
3809 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00003810 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00003811 // Value might be a float, a float vector, or a float complex.
3812 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00003813 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
3814 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00003815 return;
3816 }
3817
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00003818 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00003819 return;
3820
John McCallb4eb64d2010-10-08 02:01:28 +00003821 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00003822 }
3823 return;
3824 }
3825
Ted Kremenekef9ff882011-03-10 20:03:42 +00003826 // If the target is integral, always warn.
Chandler Carrutha5b93322011-02-17 11:05:49 +00003827 if ((TargetBT && TargetBT->isInteger())) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00003828 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00003829 return;
3830
Chandler Carrutha5b93322011-02-17 11:05:49 +00003831 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay634c8af2011-09-08 22:30:47 +00003832 // We also want to warn on, e.g., "int i = -1.234"
3833 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
3834 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
3835 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
3836
Chandler Carruthf65076e2011-04-10 08:36:24 +00003837 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
3838 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00003839 } else {
3840 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
3841 }
3842 }
John McCall51313c32010-01-04 23:31:57 +00003843
3844 return;
3845 }
3846
John McCallf2370c92010-01-06 05:24:50 +00003847 if (!Source->isIntegerType() || !Target->isIntegerType())
John McCall51313c32010-01-04 23:31:57 +00003848 return;
3849
Richard Trieu1838ca52011-05-29 19:59:02 +00003850 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
3851 == Expr::NPCK_GNUNull) && Target->isIntegerType()) {
3852 S.Diag(E->getExprLoc(), diag::warn_impcast_null_pointer_to_integer)
3853 << E->getSourceRange() << clang::SourceRange(CC);
3854 return;
3855 }
3856
John McCall323ed742010-05-06 08:58:33 +00003857 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00003858 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00003859
3860 if (SourceRange.Width > TargetRange.Width) {
John McCall091f23f2010-11-09 22:22:12 +00003861 // If the source is a constant, use a default-on diagnostic.
3862 // TODO: this should happen for bitfield stores, too.
3863 llvm::APSInt Value(32);
3864 if (E->isIntegerConstantExpr(Value, S.Context)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00003865 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00003866 return;
3867
John McCall091f23f2010-11-09 22:22:12 +00003868 std::string PrettySourceValue = Value.toString(10);
3869 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
3870
Ted Kremenek5e745da2011-10-22 02:37:33 +00003871 S.DiagRuntimeBehavior(E->getExprLoc(), E,
3872 S.PDiag(diag::warn_impcast_integer_precision_constant)
3873 << PrettySourceValue << PrettyTargetValue
3874 << E->getType() << T << E->getSourceRange()
3875 << clang::SourceRange(CC));
John McCall091f23f2010-11-09 22:22:12 +00003876 return;
3877 }
3878
Chris Lattnerb792b302011-06-14 04:51:15 +00003879 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00003880 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00003881 return;
3882
John McCallf2370c92010-01-06 05:24:50 +00003883 if (SourceRange.Width == 64 && TargetRange.Width == 32)
John McCallb4eb64d2010-10-08 02:01:28 +00003884 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32);
3885 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00003886 }
3887
3888 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
3889 (!TargetRange.NonNegative && SourceRange.NonNegative &&
3890 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003891
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00003892 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00003893 return;
3894
John McCall323ed742010-05-06 08:58:33 +00003895 unsigned DiagID = diag::warn_impcast_integer_sign;
3896
3897 // Traditionally, gcc has warned about this under -Wsign-compare.
3898 // We also want to warn about it in -Wconversion.
3899 // So if -Wconversion is off, use a completely identical diagnostic
3900 // in the sign-compare group.
3901 // The conditional-checking code will
3902 if (ICContext) {
3903 DiagID = diag::warn_impcast_integer_sign_conditional;
3904 *ICContext = true;
3905 }
3906
John McCallb4eb64d2010-10-08 02:01:28 +00003907 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00003908 }
3909
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003910 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00003911 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
3912 // type, to give us better diagnostics.
3913 QualType SourceType = E->getType();
3914 if (!S.getLangOptions().CPlusPlus) {
3915 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3916 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3917 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
3918 SourceType = S.Context.getTypeDeclType(Enum);
3919 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
3920 }
3921 }
3922
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003923 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
3924 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
3925 if ((SourceEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00003926 SourceEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003927 (TargetEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00003928 TargetEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00003929 SourceEnum != TargetEnum) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00003930 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00003931 return;
3932
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00003933 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003934 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00003935 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003936
John McCall51313c32010-01-04 23:31:57 +00003937 return;
3938}
3939
John McCall323ed742010-05-06 08:58:33 +00003940void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T);
3941
3942void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00003943 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00003944 E = E->IgnoreParenImpCasts();
3945
3946 if (isa<ConditionalOperator>(E))
3947 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T);
3948
John McCallb4eb64d2010-10-08 02:01:28 +00003949 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00003950 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00003951 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00003952 return;
3953}
3954
3955void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00003956 SourceLocation CC = E->getQuestionLoc();
3957
3958 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00003959
3960 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00003961 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
3962 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00003963
3964 // If -Wconversion would have warned about either of the candidates
3965 // for a signedness conversion to the context type...
3966 if (!Suspicious) return;
3967
3968 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003969 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
3970 CC))
John McCall323ed742010-05-06 08:58:33 +00003971 return;
3972
John McCall323ed742010-05-06 08:58:33 +00003973 // ...then check whether it would have warned about either of the
3974 // candidates for a signedness conversion to the condition type.
Richard Trieu52541612011-07-21 02:46:28 +00003975 if (E->getType() == T) return;
3976
3977 Suspicious = false;
3978 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
3979 E->getType(), CC, &Suspicious);
3980 if (!Suspicious)
3981 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00003982 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00003983}
3984
3985/// AnalyzeImplicitConversions - Find and report any interesting
3986/// implicit conversions in the given expression. There are a couple
3987/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00003988void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00003989 QualType T = OrigE->getType();
3990 Expr *E = OrigE->IgnoreParenImpCasts();
3991
Douglas Gregorf8b6e152011-10-10 17:38:18 +00003992 if (E->isTypeDependent() || E->isValueDependent())
3993 return;
3994
John McCall323ed742010-05-06 08:58:33 +00003995 // For conditional operators, we analyze the arguments as if they
3996 // were being fed directly into the output.
3997 if (isa<ConditionalOperator>(E)) {
3998 ConditionalOperator *CO = cast<ConditionalOperator>(E);
3999 CheckConditionalOperator(S, CO, T);
4000 return;
4001 }
4002
4003 // Go ahead and check any implicit conversions we might have skipped.
4004 // The non-canonical typecheck is just an optimization;
4005 // CheckImplicitConversion will filter out dead implicit conversions.
4006 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00004007 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00004008
4009 // Now continue drilling into this expression.
4010
4011 // Skip past explicit casts.
4012 if (isa<ExplicitCastExpr>(E)) {
4013 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00004014 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00004015 }
4016
John McCallbeb22aa2010-11-09 23:24:47 +00004017 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4018 // Do a somewhat different check with comparison operators.
4019 if (BO->isComparisonOp())
4020 return AnalyzeComparison(S, BO);
4021
4022 // And with assignments and compound assignments.
4023 if (BO->isAssignmentOp())
4024 return AnalyzeAssignment(S, BO);
4025 }
John McCall323ed742010-05-06 08:58:33 +00004026
4027 // These break the otherwise-useful invariant below. Fortunately,
4028 // we don't really need to recurse into them, because any internal
4029 // expressions should have been analyzed already when they were
4030 // built into statements.
4031 if (isa<StmtExpr>(E)) return;
4032
4033 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004034 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00004035
4036 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00004037 CC = E->getExprLoc();
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004038 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
4039 bool IsLogicalOperator = BO && BO->isLogicalOp();
4040 for (Stmt::child_range I = E->children(); I; ++I) {
4041 Expr *ChildExpr = cast<Expr>(*I);
4042 if (IsLogicalOperator &&
4043 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
4044 // Ignore checking string literals that are in logical operators.
4045 continue;
4046 AnalyzeImplicitConversions(S, ChildExpr, CC);
4047 }
John McCall323ed742010-05-06 08:58:33 +00004048}
4049
4050} // end anonymous namespace
4051
4052/// Diagnoses "dangerous" implicit conversions within the given
4053/// expression (which is a full expression). Implements -Wconversion
4054/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00004055///
4056/// \param CC the "context" location of the implicit conversion, i.e.
4057/// the most location of the syntactic entity requiring the implicit
4058/// conversion
4059void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00004060 // Don't diagnose in unevaluated contexts.
4061 if (ExprEvalContexts.back().Context == Sema::Unevaluated)
4062 return;
4063
4064 // Don't diagnose for value- or type-dependent expressions.
4065 if (E->isTypeDependent() || E->isValueDependent())
4066 return;
4067
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004068 // Check for array bounds violations in cases where the check isn't triggered
4069 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
4070 // ArraySubscriptExpr is on the RHS of a variable initialization.
4071 CheckArrayAccess(E);
4072
John McCallb4eb64d2010-10-08 02:01:28 +00004073 // This is not the right CC for (e.g.) a variable initialization.
4074 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00004075}
4076
John McCall15d7d122010-11-11 03:21:53 +00004077void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
4078 FieldDecl *BitField,
4079 Expr *Init) {
4080 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
4081}
4082
Mike Stumpf8c49212010-01-21 03:59:47 +00004083/// CheckParmsForFunctionDef - Check that the parameters of the given
4084/// function are appropriate for the definition of a function. This
4085/// takes care of any checks that cannot be performed on the
4086/// declaration itself, e.g., that the types of each of the function
4087/// parameters are complete.
Douglas Gregor82aa7132010-11-01 18:37:59 +00004088bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
4089 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00004090 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00004091 for (; P != PEnd; ++P) {
4092 ParmVarDecl *Param = *P;
4093
Mike Stumpf8c49212010-01-21 03:59:47 +00004094 // C99 6.7.5.3p4: the parameters in a parameter type list in a
4095 // function declarator that is part of a function definition of
4096 // that function shall not have incomplete type.
4097 //
4098 // This is also C++ [dcl.fct]p6.
4099 if (!Param->isInvalidDecl() &&
4100 RequireCompleteType(Param->getLocation(), Param->getType(),
4101 diag::err_typecheck_decl_incomplete_type)) {
4102 Param->setInvalidDecl();
4103 HasInvalidParm = true;
4104 }
4105
4106 // C99 6.9.1p5: If the declarator includes a parameter type list, the
4107 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00004108 if (CheckParameterNames &&
4109 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00004110 !Param->isImplicit() &&
4111 !getLangOptions().CPlusPlus)
4112 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00004113
4114 // C99 6.7.5.3p12:
4115 // If the function declarator is not part of a definition of that
4116 // function, parameters may have incomplete type and may use the [*]
4117 // notation in their sequences of declarator specifiers to specify
4118 // variable length array types.
4119 QualType PType = Param->getOriginalType();
4120 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
4121 if (AT->getSizeModifier() == ArrayType::Star) {
4122 // FIXME: This diagnosic should point the the '[*]' if source-location
4123 // information is added for it.
4124 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
4125 }
4126 }
Mike Stumpf8c49212010-01-21 03:59:47 +00004127 }
4128
4129 return HasInvalidParm;
4130}
John McCallb7f4ffe2010-08-12 21:44:57 +00004131
4132/// CheckCastAlign - Implements -Wcast-align, which warns when a
4133/// pointer cast increases the alignment requirements.
4134void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
4135 // This is actually a lot of work to potentially be doing on every
4136 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00004137 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
4138 TRange.getBegin())
David Blaikied6471f72011-09-25 23:23:43 +00004139 == DiagnosticsEngine::Ignored)
John McCallb7f4ffe2010-08-12 21:44:57 +00004140 return;
4141
4142 // Ignore dependent types.
4143 if (T->isDependentType() || Op->getType()->isDependentType())
4144 return;
4145
4146 // Require that the destination be a pointer type.
4147 const PointerType *DestPtr = T->getAs<PointerType>();
4148 if (!DestPtr) return;
4149
4150 // If the destination has alignment 1, we're done.
4151 QualType DestPointee = DestPtr->getPointeeType();
4152 if (DestPointee->isIncompleteType()) return;
4153 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
4154 if (DestAlign.isOne()) return;
4155
4156 // Require that the source be a pointer type.
4157 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
4158 if (!SrcPtr) return;
4159 QualType SrcPointee = SrcPtr->getPointeeType();
4160
4161 // Whitelist casts from cv void*. We already implicitly
4162 // whitelisted casts to cv void*, since they have alignment 1.
4163 // Also whitelist casts involving incomplete types, which implicitly
4164 // includes 'void'.
4165 if (SrcPointee->isIncompleteType()) return;
4166
4167 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
4168 if (SrcAlign >= DestAlign) return;
4169
4170 Diag(TRange.getBegin(), diag::warn_cast_align)
4171 << Op->getType() << T
4172 << static_cast<unsigned>(SrcAlign.getQuantity())
4173 << static_cast<unsigned>(DestAlign.getQuantity())
4174 << TRange << Op->getSourceRange();
4175}
4176
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004177static const Type* getElementType(const Expr *BaseExpr) {
4178 const Type* EltType = BaseExpr->getType().getTypePtr();
4179 if (EltType->isAnyPointerType())
4180 return EltType->getPointeeType().getTypePtr();
4181 else if (EltType->isArrayType())
4182 return EltType->getBaseElementTypeUnsafe();
4183 return EltType;
4184}
4185
Chandler Carruthc2684342011-08-05 09:10:50 +00004186/// \brief Check whether this array fits the idiom of a size-one tail padded
4187/// array member of a struct.
4188///
4189/// We avoid emitting out-of-bounds access warnings for such arrays as they are
4190/// commonly used to emulate flexible arrays in C89 code.
4191static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
4192 const NamedDecl *ND) {
4193 if (Size != 1 || !ND) return false;
4194
4195 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
4196 if (!FD) return false;
4197
4198 // Don't consider sizes resulting from macro expansions or template argument
4199 // substitution to form C89 tail-padded arrays.
4200 ConstantArrayTypeLoc TL =
4201 cast<ConstantArrayTypeLoc>(FD->getTypeSourceInfo()->getTypeLoc());
4202 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(TL.getSizeExpr());
4203 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
4204 return false;
4205
4206 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gay381711c2011-11-29 22:43:53 +00004207 if (!RD) return false;
4208 if (RD->isUnion()) return false;
4209 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
4210 if (!CRD->isStandardLayout()) return false;
4211 }
Chandler Carruthc2684342011-08-05 09:10:50 +00004212
Benjamin Kramer22d4fed2011-08-06 03:04:42 +00004213 // See if this is the last field decl in the record.
4214 const Decl *D = FD;
4215 while ((D = D->getNextDeclInContext()))
4216 if (isa<FieldDecl>(D))
4217 return false;
4218 return true;
Chandler Carruthc2684342011-08-05 09:10:50 +00004219}
4220
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004221void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004222 const ArraySubscriptExpr *ASE,
Richard Smith25b009a2011-12-16 19:31:14 +00004223 bool AllowOnePastEnd, bool IndexNegated) {
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004224 IndexExpr = IndexExpr->IgnoreParenCasts();
4225 if (IndexExpr->isValueDependent())
4226 return;
4227
Matt Beaumont-Gay8ef8f432011-12-12 22:35:02 +00004228 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004229 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth34064582011-02-17 20:55:08 +00004230 const ConstantArrayType *ArrayTy =
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004231 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00004232 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00004233 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00004234
Chandler Carruth34064582011-02-17 20:55:08 +00004235 llvm::APSInt index;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004236 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00004237 return;
Richard Smith25b009a2011-12-16 19:31:14 +00004238 if (IndexNegated)
4239 index = -index;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00004240
Chandler Carruthba447122011-08-05 08:07:29 +00004241 const NamedDecl *ND = NULL;
Chandler Carruthba447122011-08-05 08:07:29 +00004242 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
4243 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruthc2684342011-08-05 09:10:50 +00004244 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruthba447122011-08-05 08:07:29 +00004245 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruthba447122011-08-05 08:07:29 +00004246
Ted Kremenek9e060ca2011-02-23 23:06:04 +00004247 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00004248 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00004249 if (!size.isStrictlyPositive())
4250 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004251
4252 const Type* BaseType = getElementType(BaseExpr);
Nico Weberde5998f2011-09-17 22:59:41 +00004253 if (BaseType != EffectiveType) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004254 // Make sure we're comparing apples to apples when comparing index to size
4255 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
4256 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhraind10f4bc2011-08-10 19:47:25 +00004257 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhrain18f16972011-08-10 18:49:28 +00004258 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004259 if (ptrarith_typesize != array_typesize) {
4260 // There's a cast to a different size type involved
4261 uint64_t ratio = array_typesize / ptrarith_typesize;
4262 // TODO: Be smarter about handling cases where array_typesize is not a
4263 // multiple of ptrarith_typesize
4264 if (ptrarith_typesize * ratio == array_typesize)
4265 size *= llvm::APInt(size.getBitWidth(), ratio);
4266 }
4267 }
4268
Chandler Carruth34064582011-02-17 20:55:08 +00004269 if (size.getBitWidth() > index.getBitWidth())
4270 index = index.sext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00004271 else if (size.getBitWidth() < index.getBitWidth())
4272 size = size.sext(index.getBitWidth());
4273
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004274 // For array subscripting the index must be less than size, but for pointer
4275 // arithmetic also allow the index (offset) to be equal to size since
4276 // computing the next address after the end of the array is legal and
4277 // commonly done e.g. in C++ iterators and range-based for loops.
4278 if (AllowOnePastEnd ? index.sle(size) : index.slt(size))
Chandler Carruthba447122011-08-05 08:07:29 +00004279 return;
4280
4281 // Also don't warn for arrays of size 1 which are members of some
4282 // structure. These are often used to approximate flexible arrays in C89
4283 // code.
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004284 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00004285 return;
Chandler Carruth34064582011-02-17 20:55:08 +00004286
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004287 // Suppress the warning if the subscript expression (as identified by the
4288 // ']' location) and the index expression are both from macro expansions
4289 // within a system header.
4290 if (ASE) {
4291 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
4292 ASE->getRBracketLoc());
4293 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
4294 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
4295 IndexExpr->getLocStart());
4296 if (SourceMgr.isFromSameFile(RBracketLoc, IndexLoc))
4297 return;
4298 }
4299 }
4300
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004301 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004302 if (ASE)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004303 DiagID = diag::warn_array_index_exceeds_bounds;
4304
4305 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
4306 PDiag(DiagID) << index.toString(10, true)
4307 << size.toString(10, true)
4308 << (unsigned)size.getLimitedValue(~0U)
4309 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00004310 } else {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004311 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004312 if (!ASE) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004313 DiagID = diag::warn_ptr_arith_precedes_bounds;
4314 if (index.isNegative()) index = -index;
4315 }
4316
4317 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
4318 PDiag(DiagID) << index.toString(10, true)
4319 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00004320 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00004321
Matt Beaumont-Gaycfbc5b52011-11-29 19:27:11 +00004322 if (!ND) {
4323 // Try harder to find a NamedDecl to point at in the note.
4324 while (const ArraySubscriptExpr *ASE =
4325 dyn_cast<ArraySubscriptExpr>(BaseExpr))
4326 BaseExpr = ASE->getBase()->IgnoreParenCasts();
4327 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
4328 ND = dyn_cast<NamedDecl>(DRE->getDecl());
4329 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
4330 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
4331 }
4332
Chandler Carruth35001ca2011-02-17 21:10:52 +00004333 if (ND)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004334 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
4335 PDiag(diag::note_array_index_out_of_bounds)
4336 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00004337}
4338
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004339void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004340 int AllowOnePastEnd = 0;
4341 while (expr) {
4342 expr = expr->IgnoreParenImpCasts();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004343 switch (expr->getStmtClass()) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004344 case Stmt::ArraySubscriptExprClass: {
4345 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004346 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004347 AllowOnePastEnd > 0);
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004348 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004349 }
4350 case Stmt::UnaryOperatorClass: {
4351 // Only unwrap the * and & unary operators
4352 const UnaryOperator *UO = cast<UnaryOperator>(expr);
4353 expr = UO->getSubExpr();
4354 switch (UO->getOpcode()) {
4355 case UO_AddrOf:
4356 AllowOnePastEnd++;
4357 break;
4358 case UO_Deref:
4359 AllowOnePastEnd--;
4360 break;
4361 default:
4362 return;
4363 }
4364 break;
4365 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004366 case Stmt::ConditionalOperatorClass: {
4367 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
4368 if (const Expr *lhs = cond->getLHS())
4369 CheckArrayAccess(lhs);
4370 if (const Expr *rhs = cond->getRHS())
4371 CheckArrayAccess(rhs);
4372 return;
4373 }
4374 default:
4375 return;
4376 }
Peter Collingbournef111d932011-04-15 00:35:48 +00004377 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004378}
John McCallf85e1932011-06-15 23:02:42 +00004379
4380//===--- CHECK: Objective-C retain cycles ----------------------------------//
4381
4382namespace {
4383 struct RetainCycleOwner {
4384 RetainCycleOwner() : Variable(0), Indirect(false) {}
4385 VarDecl *Variable;
4386 SourceRange Range;
4387 SourceLocation Loc;
4388 bool Indirect;
4389
4390 void setLocsFrom(Expr *e) {
4391 Loc = e->getExprLoc();
4392 Range = e->getSourceRange();
4393 }
4394 };
4395}
4396
4397/// Consider whether capturing the given variable can possibly lead to
4398/// a retain cycle.
4399static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
4400 // In ARC, it's captured strongly iff the variable has __strong
4401 // lifetime. In MRR, it's captured strongly if the variable is
4402 // __block and has an appropriate type.
4403 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
4404 return false;
4405
4406 owner.Variable = var;
4407 owner.setLocsFrom(ref);
4408 return true;
4409}
4410
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00004411static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCallf85e1932011-06-15 23:02:42 +00004412 while (true) {
4413 e = e->IgnoreParens();
4414 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
4415 switch (cast->getCastKind()) {
4416 case CK_BitCast:
4417 case CK_LValueBitCast:
4418 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00004419 case CK_ARCReclaimReturnedObject:
John McCallf85e1932011-06-15 23:02:42 +00004420 e = cast->getSubExpr();
4421 continue;
4422
John McCallf85e1932011-06-15 23:02:42 +00004423 default:
4424 return false;
4425 }
4426 }
4427
4428 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
4429 ObjCIvarDecl *ivar = ref->getDecl();
4430 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
4431 return false;
4432
4433 // Try to find a retain cycle in the base.
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00004434 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCallf85e1932011-06-15 23:02:42 +00004435 return false;
4436
4437 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
4438 owner.Indirect = true;
4439 return true;
4440 }
4441
4442 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
4443 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
4444 if (!var) return false;
4445 return considerVariable(var, ref, owner);
4446 }
4447
4448 if (BlockDeclRefExpr *ref = dyn_cast<BlockDeclRefExpr>(e)) {
4449 owner.Variable = ref->getDecl();
4450 owner.setLocsFrom(ref);
4451 return true;
4452 }
4453
4454 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
4455 if (member->isArrow()) return false;
4456
4457 // Don't count this as an indirect ownership.
4458 e = member->getBase();
4459 continue;
4460 }
4461
John McCall4b9c2d22011-11-06 09:01:30 +00004462 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
4463 // Only pay attention to pseudo-objects on property references.
4464 ObjCPropertyRefExpr *pre
4465 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
4466 ->IgnoreParens());
4467 if (!pre) return false;
4468 if (pre->isImplicitProperty()) return false;
4469 ObjCPropertyDecl *property = pre->getExplicitProperty();
4470 if (!property->isRetaining() &&
4471 !(property->getPropertyIvarDecl() &&
4472 property->getPropertyIvarDecl()->getType()
4473 .getObjCLifetime() == Qualifiers::OCL_Strong))
4474 return false;
4475
4476 owner.Indirect = true;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00004477 if (pre->isSuperReceiver()) {
4478 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
4479 if (!owner.Variable)
4480 return false;
4481 owner.Loc = pre->getLocation();
4482 owner.Range = pre->getSourceRange();
4483 return true;
4484 }
John McCall4b9c2d22011-11-06 09:01:30 +00004485 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
4486 ->getSourceExpr());
4487 continue;
4488 }
4489
John McCallf85e1932011-06-15 23:02:42 +00004490 // Array ivars?
4491
4492 return false;
4493 }
4494}
4495
4496namespace {
4497 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
4498 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
4499 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
4500 Variable(variable), Capturer(0) {}
4501
4502 VarDecl *Variable;
4503 Expr *Capturer;
4504
4505 void VisitDeclRefExpr(DeclRefExpr *ref) {
4506 if (ref->getDecl() == Variable && !Capturer)
4507 Capturer = ref;
4508 }
4509
4510 void VisitBlockDeclRefExpr(BlockDeclRefExpr *ref) {
4511 if (ref->getDecl() == Variable && !Capturer)
4512 Capturer = ref;
4513 }
4514
4515 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
4516 if (Capturer) return;
4517 Visit(ref->getBase());
4518 if (Capturer && ref->isFreeIvar())
4519 Capturer = ref;
4520 }
4521
4522 void VisitBlockExpr(BlockExpr *block) {
4523 // Look inside nested blocks
4524 if (block->getBlockDecl()->capturesVariable(Variable))
4525 Visit(block->getBlockDecl()->getBody());
4526 }
4527 };
4528}
4529
4530/// Check whether the given argument is a block which captures a
4531/// variable.
4532static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
4533 assert(owner.Variable && owner.Loc.isValid());
4534
4535 e = e->IgnoreParenCasts();
4536 BlockExpr *block = dyn_cast<BlockExpr>(e);
4537 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
4538 return 0;
4539
4540 FindCaptureVisitor visitor(S.Context, owner.Variable);
4541 visitor.Visit(block->getBlockDecl()->getBody());
4542 return visitor.Capturer;
4543}
4544
4545static void diagnoseRetainCycle(Sema &S, Expr *capturer,
4546 RetainCycleOwner &owner) {
4547 assert(capturer);
4548 assert(owner.Variable && owner.Loc.isValid());
4549
4550 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
4551 << owner.Variable << capturer->getSourceRange();
4552 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
4553 << owner.Indirect << owner.Range;
4554}
4555
4556/// Check for a keyword selector that starts with the word 'add' or
4557/// 'set'.
4558static bool isSetterLikeSelector(Selector sel) {
4559 if (sel.isUnarySelector()) return false;
4560
Chris Lattner5f9e2722011-07-23 10:55:15 +00004561 StringRef str = sel.getNameForSlot(0);
John McCallf85e1932011-06-15 23:02:42 +00004562 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00004563 if (str.startswith("set"))
John McCallf85e1932011-06-15 23:02:42 +00004564 str = str.substr(3);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00004565 else if (str.startswith("add")) {
4566 // Specially whitelist 'addOperationWithBlock:'.
4567 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
4568 return false;
4569 str = str.substr(3);
4570 }
John McCallf85e1932011-06-15 23:02:42 +00004571 else
4572 return false;
4573
4574 if (str.empty()) return true;
4575 return !islower(str.front());
4576}
4577
4578/// Check a message send to see if it's likely to cause a retain cycle.
4579void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
4580 // Only check instance methods whose selector looks like a setter.
4581 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
4582 return;
4583
4584 // Try to find a variable that the receiver is strongly owned by.
4585 RetainCycleOwner owner;
4586 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00004587 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCallf85e1932011-06-15 23:02:42 +00004588 return;
4589 } else {
4590 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
4591 owner.Variable = getCurMethodDecl()->getSelfDecl();
4592 owner.Loc = msg->getSuperLoc();
4593 owner.Range = msg->getSuperLoc();
4594 }
4595
4596 // Check whether the receiver is captured by any of the arguments.
4597 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
4598 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
4599 return diagnoseRetainCycle(*this, capturer, owner);
4600}
4601
4602/// Check a property assign to see if it's likely to cause a retain cycle.
4603void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
4604 RetainCycleOwner owner;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00004605 if (!findRetainCycleOwner(*this, receiver, owner))
John McCallf85e1932011-06-15 23:02:42 +00004606 return;
4607
4608 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
4609 diagnoseRetainCycle(*this, capturer, owner);
4610}
4611
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004612bool Sema::checkUnsafeAssigns(SourceLocation Loc,
John McCallf85e1932011-06-15 23:02:42 +00004613 QualType LHS, Expr *RHS) {
4614 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
4615 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004616 return false;
4617 // strip off any implicit cast added to get to the one arc-specific
4618 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00004619 if (cast->getCastKind() == CK_ARCConsumeObject) {
John McCallf85e1932011-06-15 23:02:42 +00004620 Diag(Loc, diag::warn_arc_retained_assign)
4621 << (LT == Qualifiers::OCL_ExplicitNone)
4622 << RHS->getSourceRange();
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004623 return true;
4624 }
4625 RHS = cast->getSubExpr();
4626 }
4627 return false;
John McCallf85e1932011-06-15 23:02:42 +00004628}
4629
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004630void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
4631 Expr *LHS, Expr *RHS) {
4632 QualType LHSType = LHS->getType();
4633 if (checkUnsafeAssigns(Loc, LHSType, RHS))
4634 return;
4635 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
4636 // FIXME. Check for other life times.
4637 if (LT != Qualifiers::OCL_None)
4638 return;
4639
John McCall3c3b7f92011-10-25 17:37:35 +00004640 if (ObjCPropertyRefExpr *PRE
4641 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens())) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004642 if (PRE->isImplicitProperty())
4643 return;
4644 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
4645 if (!PD)
4646 return;
4647
4648 unsigned Attributes = PD->getPropertyAttributes();
4649 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign)
4650 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00004651 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004652 Diag(Loc, diag::warn_arc_retained_property_assign)
4653 << RHS->getSourceRange();
4654 return;
4655 }
4656 RHS = cast->getSubExpr();
4657 }
4658 }
4659}