blob: be326880d587e319ff86bf5500e9eff523c4e494 [file] [log] [blame]
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-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 Lattnerb87b1b32007-08-10 20:18:51 +00007//
8//===----------------------------------------------------------------------===//
9//
Mike Stump11289f42009-09-09 15:08:12 +000010// This file implements extra semantic analysis beyond what is enforced
Chris Lattnerb87b1b32007-08-10 20:18:51 +000011// by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
John McCall29ad95b2011-08-27 01:09:30 +000015#include "clang/Sema/Initialization.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000016#include "clang/Sema/Sema.h"
John McCall83024632010-08-25 22:03:47 +000017#include "clang/Sema/SemaInternal.h"
Eli Friedmandf14b3a2011-10-11 02:20:01 +000018#include "clang/Sema/Initialization.h"
John McCallaab3e412010-08-25 08:40:02 +000019#include "clang/Sema/ScopeInfo.h"
Ted Kremenek02087932010-07-16 02:11:22 +000020#include "clang/Analysis/Analyses/FormatString.h"
Chris Lattnerb87b1b32007-08-10 20:18:51 +000021#include "clang/AST/ASTContext.h"
Ken Dyck40775002010-01-11 17:06:35 +000022#include "clang/AST/CharUnits.h"
John McCall28a0cf72010-08-25 07:42:41 +000023#include "clang/AST/DeclCXX.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000024#include "clang/AST/DeclObjC.h"
Ted Kremenekc81614d2007-08-20 16:18:38 +000025#include "clang/AST/ExprCXX.h"
Ted Kremenek34f664d2008-06-16 18:00:42 +000026#include "clang/AST/ExprObjC.h"
John McCall31168b02011-06-15 23:02:42 +000027#include "clang/AST/EvaluatedExprVisitor.h"
Mike Stump0c2ec772010-01-21 03:59:47 +000028#include "clang/AST/DeclObjC.h"
29#include "clang/AST/StmtCXX.h"
30#include "clang/AST/StmtObjC.h"
Chris Lattnerb87b1b32007-08-10 20:18:51 +000031#include "clang/Lex/Preprocessor.h"
Mike Stump0c2ec772010-01-21 03:59:47 +000032#include "llvm/ADT/BitVector.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000033#include "llvm/ADT/SmallString.h"
Mike Stump0c2ec772010-01-21 03:59:47 +000034#include "llvm/ADT/STLExtras.h"
Tom Careb7042702010-06-09 04:11:11 +000035#include "llvm/Support/raw_ostream.h"
Eric Christopher8d0c6212010-04-17 02:26:23 +000036#include "clang/Basic/TargetBuiltins.h"
Nate Begeman4904e322010-06-08 02:47:44 +000037#include "clang/Basic/TargetInfo.h"
Fariborz Jahanian56603ef2010-09-07 19:38:13 +000038#include "clang/Basic/ConvertUTF.h"
Zhongxing Xu050379b2009-05-20 01:55:10 +000039#include <limits>
Chris Lattnerb87b1b32007-08-10 20:18:51 +000040using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000041using namespace sema;
Chris Lattnerb87b1b32007-08-10 20:18:51 +000042
Chris Lattnera26fb342009-02-18 17:49:48 +000043SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
44 unsigned ByteNo) const {
Chris Lattnere925d612010-11-17 07:37:15 +000045 return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
46 PP.getLangOptions(), PP.getTargetInfo());
Chris Lattnera26fb342009-02-18 17:49:48 +000047}
48
John McCallbebede42011-02-26 05:39:39 +000049/// Checks that a call expression's argument count is the desired number.
50/// This is useful when doing custom type-checking. Returns true on error.
51static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
52 unsigned argCount = call->getNumArgs();
53 if (argCount == desiredArgCount) return false;
54
55 if (argCount < desiredArgCount)
56 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
57 << 0 /*function call*/ << desiredArgCount << argCount
58 << call->getSourceRange();
59
60 // Highlight all the excess arguments.
61 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
62 call->getArg(argCount - 1)->getLocEnd());
63
64 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
65 << 0 /*function call*/ << desiredArgCount << argCount
66 << call->getArg(1)->getSourceRange();
67}
68
Julien Lerouge5a6b6982011-09-09 22:41:49 +000069/// CheckBuiltinAnnotationString - Checks that string argument to the builtin
70/// annotation is a non wide string literal.
71static bool CheckBuiltinAnnotationString(Sema &S, Expr *Arg) {
72 Arg = Arg->IgnoreParenCasts();
73 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
74 if (!Literal || !Literal->isAscii()) {
75 S.Diag(Arg->getLocStart(), diag::err_builtin_annotation_not_string_constant)
76 << Arg->getSourceRange();
77 return true;
78 }
79 return false;
80}
81
John McCalldadc5752010-08-24 06:29:42 +000082ExprResult
Anders Carlssonbc4c1072009-08-16 01:56:34 +000083Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
John McCalldadc5752010-08-24 06:29:42 +000084 ExprResult TheCallResult(Owned(TheCall));
Douglas Gregorae2fbad2008-11-17 20:34:05 +000085
Chris Lattner3be167f2010-10-01 23:23:24 +000086 // Find out if any arguments are required to be integer constant expressions.
87 unsigned ICEArguments = 0;
88 ASTContext::GetBuiltinTypeError Error;
89 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
90 if (Error != ASTContext::GE_None)
91 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
92
93 // If any arguments are required to be ICE's, check and diagnose.
94 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
95 // Skip arguments not required to be ICE's.
96 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
97
98 llvm::APSInt Result;
99 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
100 return true;
101 ICEArguments &= ~(1 << ArgNo);
102 }
103
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000104 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000105 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000106 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000107 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000108 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000109 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000110 break;
Ted Kremeneka174c522008-07-09 17:58:53 +0000111 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000112 case Builtin::BI__builtin_va_start:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000113 if (SemaBuiltinVAStart(TheCall))
114 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000115 break;
Chris Lattner2da14fb2007-12-20 00:26:33 +0000116 case Builtin::BI__builtin_isgreater:
117 case Builtin::BI__builtin_isgreaterequal:
118 case Builtin::BI__builtin_isless:
119 case Builtin::BI__builtin_islessequal:
120 case Builtin::BI__builtin_islessgreater:
121 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000122 if (SemaBuiltinUnorderedCompare(TheCall))
123 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000124 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000125 case Builtin::BI__builtin_fpclassify:
126 if (SemaBuiltinFPClassification(TheCall, 6))
127 return ExprError();
128 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000129 case Builtin::BI__builtin_isfinite:
130 case Builtin::BI__builtin_isinf:
131 case Builtin::BI__builtin_isinf_sign:
132 case Builtin::BI__builtin_isnan:
133 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000134 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000135 return ExprError();
136 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000137 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000138 return SemaBuiltinShuffleVector(TheCall);
139 // TheCall will be freed by the smart pointer here, but that's fine, since
140 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000141 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000142 if (SemaBuiltinPrefetch(TheCall))
143 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000144 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000145 case Builtin::BI__builtin_object_size:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000146 if (SemaBuiltinObjectSize(TheCall))
147 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000148 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000149 case Builtin::BI__builtin_longjmp:
150 if (SemaBuiltinLongjmp(TheCall))
151 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000152 break;
John McCallbebede42011-02-26 05:39:39 +0000153
154 case Builtin::BI__builtin_classify_type:
155 if (checkArgCount(*this, TheCall, 1)) return true;
156 TheCall->setType(Context.IntTy);
157 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000158 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000159 if (checkArgCount(*this, TheCall, 1)) return true;
160 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000161 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000162 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000163 case Builtin::BI__sync_fetch_and_add_1:
164 case Builtin::BI__sync_fetch_and_add_2:
165 case Builtin::BI__sync_fetch_and_add_4:
166 case Builtin::BI__sync_fetch_and_add_8:
167 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000168 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000169 case Builtin::BI__sync_fetch_and_sub_1:
170 case Builtin::BI__sync_fetch_and_sub_2:
171 case Builtin::BI__sync_fetch_and_sub_4:
172 case Builtin::BI__sync_fetch_and_sub_8:
173 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000174 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000175 case Builtin::BI__sync_fetch_and_or_1:
176 case Builtin::BI__sync_fetch_and_or_2:
177 case Builtin::BI__sync_fetch_and_or_4:
178 case Builtin::BI__sync_fetch_and_or_8:
179 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000180 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000181 case Builtin::BI__sync_fetch_and_and_1:
182 case Builtin::BI__sync_fetch_and_and_2:
183 case Builtin::BI__sync_fetch_and_and_4:
184 case Builtin::BI__sync_fetch_and_and_8:
185 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000186 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000187 case Builtin::BI__sync_fetch_and_xor_1:
188 case Builtin::BI__sync_fetch_and_xor_2:
189 case Builtin::BI__sync_fetch_and_xor_4:
190 case Builtin::BI__sync_fetch_and_xor_8:
191 case Builtin::BI__sync_fetch_and_xor_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000192 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000193 case Builtin::BI__sync_add_and_fetch_1:
194 case Builtin::BI__sync_add_and_fetch_2:
195 case Builtin::BI__sync_add_and_fetch_4:
196 case Builtin::BI__sync_add_and_fetch_8:
197 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000198 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000199 case Builtin::BI__sync_sub_and_fetch_1:
200 case Builtin::BI__sync_sub_and_fetch_2:
201 case Builtin::BI__sync_sub_and_fetch_4:
202 case Builtin::BI__sync_sub_and_fetch_8:
203 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000204 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000205 case Builtin::BI__sync_and_and_fetch_1:
206 case Builtin::BI__sync_and_and_fetch_2:
207 case Builtin::BI__sync_and_and_fetch_4:
208 case Builtin::BI__sync_and_and_fetch_8:
209 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000210 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000211 case Builtin::BI__sync_or_and_fetch_1:
212 case Builtin::BI__sync_or_and_fetch_2:
213 case Builtin::BI__sync_or_and_fetch_4:
214 case Builtin::BI__sync_or_and_fetch_8:
215 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000216 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000217 case Builtin::BI__sync_xor_and_fetch_1:
218 case Builtin::BI__sync_xor_and_fetch_2:
219 case Builtin::BI__sync_xor_and_fetch_4:
220 case Builtin::BI__sync_xor_and_fetch_8:
221 case Builtin::BI__sync_xor_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000222 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000223 case Builtin::BI__sync_val_compare_and_swap_1:
224 case Builtin::BI__sync_val_compare_and_swap_2:
225 case Builtin::BI__sync_val_compare_and_swap_4:
226 case Builtin::BI__sync_val_compare_and_swap_8:
227 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000228 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000229 case Builtin::BI__sync_bool_compare_and_swap_1:
230 case Builtin::BI__sync_bool_compare_and_swap_2:
231 case Builtin::BI__sync_bool_compare_and_swap_4:
232 case Builtin::BI__sync_bool_compare_and_swap_8:
233 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000234 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +0000235 case Builtin::BI__sync_lock_test_and_set_1:
236 case Builtin::BI__sync_lock_test_and_set_2:
237 case Builtin::BI__sync_lock_test_and_set_4:
238 case Builtin::BI__sync_lock_test_and_set_8:
239 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000240 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +0000241 case Builtin::BI__sync_lock_release_1:
242 case Builtin::BI__sync_lock_release_2:
243 case Builtin::BI__sync_lock_release_4:
244 case Builtin::BI__sync_lock_release_8:
245 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000246 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000247 case Builtin::BI__sync_swap_1:
248 case Builtin::BI__sync_swap_2:
249 case Builtin::BI__sync_swap_4:
250 case Builtin::BI__sync_swap_8:
251 case Builtin::BI__sync_swap_16:
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000252 return SemaBuiltinAtomicOverloaded(move(TheCallResult));
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000253 case Builtin::BI__atomic_load:
254 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Load);
255 case Builtin::BI__atomic_store:
256 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Store);
David Chisnallfa35df62012-01-16 17:27:18 +0000257 case Builtin::BI__atomic_init:
258 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Init);
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000259 case Builtin::BI__atomic_exchange:
260 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Xchg);
261 case Builtin::BI__atomic_compare_exchange_strong:
262 return SemaAtomicOpsOverloaded(move(TheCallResult),
263 AtomicExpr::CmpXchgStrong);
264 case Builtin::BI__atomic_compare_exchange_weak:
265 return SemaAtomicOpsOverloaded(move(TheCallResult),
266 AtomicExpr::CmpXchgWeak);
267 case Builtin::BI__atomic_fetch_add:
268 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Add);
269 case Builtin::BI__atomic_fetch_sub:
270 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Sub);
271 case Builtin::BI__atomic_fetch_and:
272 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::And);
273 case Builtin::BI__atomic_fetch_or:
274 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Or);
275 case Builtin::BI__atomic_fetch_xor:
276 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Xor);
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000277 case Builtin::BI__builtin_annotation:
278 if (CheckBuiltinAnnotationString(*this, TheCall->getArg(1)))
279 return ExprError();
280 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000281 }
282
283 // Since the target specific builtins for each arch overlap, only check those
284 // of the arch we are compiling for.
285 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000286 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +0000287 case llvm::Triple::arm:
288 case llvm::Triple::thumb:
289 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
290 return ExprError();
291 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000292 default:
293 break;
294 }
295 }
296
297 return move(TheCallResult);
298}
299
Nate Begeman91e1fea2010-06-14 05:21:25 +0000300// Get the valid immediate range for the specified NEON type code.
301static unsigned RFT(unsigned t, bool shift = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +0000302 NeonTypeFlags Type(t);
303 int IsQuad = Type.isQuad();
304 switch (Type.getEltType()) {
305 case NeonTypeFlags::Int8:
306 case NeonTypeFlags::Poly8:
307 return shift ? 7 : (8 << IsQuad) - 1;
308 case NeonTypeFlags::Int16:
309 case NeonTypeFlags::Poly16:
310 return shift ? 15 : (4 << IsQuad) - 1;
311 case NeonTypeFlags::Int32:
312 return shift ? 31 : (2 << IsQuad) - 1;
313 case NeonTypeFlags::Int64:
314 return shift ? 63 : (1 << IsQuad) - 1;
315 case NeonTypeFlags::Float16:
316 assert(!shift && "cannot shift float types!");
317 return (4 << IsQuad) - 1;
318 case NeonTypeFlags::Float32:
319 assert(!shift && "cannot shift float types!");
320 return (2 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000321 }
David Blaikie8a40f702012-01-17 06:56:22 +0000322 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +0000323}
324
Bob Wilsone4d77232011-11-08 05:04:11 +0000325/// getNeonEltType - Return the QualType corresponding to the elements of
326/// the vector type specified by the NeonTypeFlags. This is used to check
327/// the pointer arguments for Neon load/store intrinsics.
328static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context) {
329 switch (Flags.getEltType()) {
330 case NeonTypeFlags::Int8:
331 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
332 case NeonTypeFlags::Int16:
333 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
334 case NeonTypeFlags::Int32:
335 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
336 case NeonTypeFlags::Int64:
337 return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy;
338 case NeonTypeFlags::Poly8:
339 return Context.SignedCharTy;
340 case NeonTypeFlags::Poly16:
341 return Context.ShortTy;
342 case NeonTypeFlags::Float16:
343 return Context.UnsignedShortTy;
344 case NeonTypeFlags::Float32:
345 return Context.FloatTy;
346 }
David Blaikie8a40f702012-01-17 06:56:22 +0000347 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +0000348}
349
Nate Begeman4904e322010-06-08 02:47:44 +0000350bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +0000351 llvm::APSInt Result;
352
Nate Begemand773fe62010-06-13 04:47:52 +0000353 unsigned mask = 0;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000354 unsigned TV = 0;
Bob Wilson89d14242011-11-16 21:32:23 +0000355 int PtrArgNum = -1;
Bob Wilsone4d77232011-11-08 05:04:11 +0000356 bool HasConstPtr = false;
Nate Begeman55483092010-06-09 01:10:23 +0000357 switch (BuiltinID) {
Nate Begeman35f4c1c2010-06-17 04:17:01 +0000358#define GET_NEON_OVERLOAD_CHECK
359#include "clang/Basic/arm_neon.inc"
360#undef GET_NEON_OVERLOAD_CHECK
Nate Begeman55483092010-06-09 01:10:23 +0000361 }
362
Nate Begemand773fe62010-06-13 04:47:52 +0000363 // For NEON intrinsics which are overloaded on vector element type, validate
364 // the immediate which specifies which variant to emit.
Bob Wilsone4d77232011-11-08 05:04:11 +0000365 unsigned ImmArg = TheCall->getNumArgs()-1;
Nate Begemand773fe62010-06-13 04:47:52 +0000366 if (mask) {
Bob Wilsone4d77232011-11-08 05:04:11 +0000367 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
Nate Begemand773fe62010-06-13 04:47:52 +0000368 return true;
369
Bob Wilson98bc98c2011-11-08 01:16:11 +0000370 TV = Result.getLimitedValue(64);
371 if ((TV > 63) || (mask & (1 << TV)) == 0)
Nate Begemand773fe62010-06-13 04:47:52 +0000372 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Bob Wilsone4d77232011-11-08 05:04:11 +0000373 << TheCall->getArg(ImmArg)->getSourceRange();
374 }
375
Bob Wilson89d14242011-11-16 21:32:23 +0000376 if (PtrArgNum >= 0) {
Bob Wilsone4d77232011-11-08 05:04:11 +0000377 // Check that pointer arguments have the specified type.
Bob Wilson89d14242011-11-16 21:32:23 +0000378 Expr *Arg = TheCall->getArg(PtrArgNum);
379 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
380 Arg = ICE->getSubExpr();
381 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
382 QualType RHSTy = RHS.get()->getType();
383 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context);
384 if (HasConstPtr)
385 EltTy = EltTy.withConst();
386 QualType LHSTy = Context.getPointerType(EltTy);
387 AssignConvertType ConvTy;
388 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
389 if (RHS.isInvalid())
390 return true;
391 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
392 RHS.get(), AA_Assigning))
393 return true;
Nate Begemand773fe62010-06-13 04:47:52 +0000394 }
Nate Begeman55483092010-06-09 01:10:23 +0000395
Nate Begemand773fe62010-06-13 04:47:52 +0000396 // For NEON intrinsics which take an immediate value as part of the
397 // instruction, range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +0000398 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +0000399 switch (BuiltinID) {
400 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +0000401 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
402 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +0000403 case ARM::BI__builtin_arm_vcvtr_f:
404 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Nate Begeman35f4c1c2010-06-17 04:17:01 +0000405#define GET_NEON_IMMEDIATE_CHECK
406#include "clang/Basic/arm_neon.inc"
407#undef GET_NEON_IMMEDIATE_CHECK
Nate Begemand773fe62010-06-13 04:47:52 +0000408 };
409
Nate Begeman91e1fea2010-06-14 05:21:25 +0000410 // Check that the immediate argument is actually a constant.
Nate Begemand773fe62010-06-13 04:47:52 +0000411 if (SemaBuiltinConstantArg(TheCall, i, Result))
412 return true;
413
Nate Begeman91e1fea2010-06-14 05:21:25 +0000414 // Range check against the upper/lower values for this isntruction.
Nate Begemand773fe62010-06-13 04:47:52 +0000415 unsigned Val = Result.getZExtValue();
Nate Begeman91e1fea2010-06-14 05:21:25 +0000416 if (Val < l || Val > (u + l))
Nate Begemand773fe62010-06-13 04:47:52 +0000417 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramere8394df2010-08-11 14:47:12 +0000418 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begemand773fe62010-06-13 04:47:52 +0000419
Nate Begemanf568b072010-08-03 21:32:34 +0000420 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman4904e322010-06-08 02:47:44 +0000421 return false;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000422}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000423
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000424/// CheckFunctionCall - Check a direct function call for various correctness
425/// and safety properties not strictly enforced by the C type system.
426bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
427 // Get the IdentifierInfo* for the called function.
428 IdentifierInfo *FnInfo = FDecl->getIdentifier();
429
430 // None of the checks below are needed for functions that don't have
431 // simple names (e.g., C++ conversion functions).
432 if (!FnInfo)
433 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000434
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000435 // FIXME: This mechanism should be abstracted to be less fragile and
436 // more efficient. For example, just map function ids to custom
437 // handlers.
438
Ted Kremenekb8176da2010-09-09 04:33:05 +0000439 // Printf and scanf checking.
440 for (specific_attr_iterator<FormatAttr>
441 i = FDecl->specific_attr_begin<FormatAttr>(),
442 e = FDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000443 CheckFormatArguments(*i, TheCall);
Chris Lattnerb87b1b32007-08-10 20:18:51 +0000444 }
Mike Stump11289f42009-09-09 15:08:12 +0000445
Ted Kremenekb8176da2010-09-09 04:33:05 +0000446 for (specific_attr_iterator<NonNullAttr>
447 i = FDecl->specific_attr_begin<NonNullAttr>(),
448 e = FDecl->specific_attr_end<NonNullAttr>(); i != e; ++i) {
Nick Lewyckyd4693212011-03-25 01:44:32 +0000449 CheckNonNullArguments(*i, TheCall->getArgs(),
450 TheCall->getCallee()->getLocStart());
Ted Kremenekb8176da2010-09-09 04:33:05 +0000451 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000452
Anna Zaks22122702012-01-17 00:37:07 +0000453 unsigned CMId = FDecl->getMemoryFunctionKind();
454 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +0000455 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +0000456
Anna Zaks201d4892012-01-13 21:52:01 +0000457 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +0000458 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +0000459 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +0000460 else if (CMId == Builtin::BIstrncat)
461 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +0000462 else
Anna Zaks22122702012-01-17 00:37:07 +0000463 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +0000464
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000465 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +0000466}
467
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000468bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
469 Expr **Args, unsigned NumArgs) {
470 for (specific_attr_iterator<FormatAttr>
471 i = Method->specific_attr_begin<FormatAttr>(),
472 e = Method->specific_attr_end<FormatAttr>(); i != e ; ++i) {
473
474 CheckFormatArguments(*i, Args, NumArgs, false, lbrac,
475 Method->getSourceRange());
476 }
477
478 // diagnose nonnull arguments.
479 for (specific_attr_iterator<NonNullAttr>
480 i = Method->specific_attr_begin<NonNullAttr>(),
481 e = Method->specific_attr_end<NonNullAttr>(); i != e; ++i) {
482 CheckNonNullArguments(*i, Args, lbrac);
483 }
484
485 return false;
486}
487
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000488bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000489 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
490 if (!V)
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000491 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000492
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000493 QualType Ty = V->getType();
494 if (!Ty->isBlockPointerType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000495 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000496
Jean-Daniel Dupas3b8dfa02012-01-25 00:55:11 +0000497 // format string checking.
498 for (specific_attr_iterator<FormatAttr>
499 i = NDecl->specific_attr_begin<FormatAttr>(),
500 e = NDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) {
501 CheckFormatArguments(*i, TheCall);
502 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000503
504 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000505}
506
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000507ExprResult
508Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, AtomicExpr::AtomicOp Op) {
509 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
510 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000511
512 // All these operations take one of the following four forms:
513 // T __atomic_load(_Atomic(T)*, int) (loads)
514 // T* __atomic_add(_Atomic(T*)*, ptrdiff_t, int) (pointer add/sub)
515 // int __atomic_compare_exchange_strong(_Atomic(T)*, T*, T, int, int)
516 // (cmpxchg)
517 // T __atomic_exchange(_Atomic(T)*, T, int) (everything else)
518 // where T is an appropriate type, and the int paremeterss are for orderings.
519 unsigned NumVals = 1;
520 unsigned NumOrders = 1;
521 if (Op == AtomicExpr::Load) {
522 NumVals = 0;
523 } else if (Op == AtomicExpr::CmpXchgWeak || Op == AtomicExpr::CmpXchgStrong) {
524 NumVals = 2;
525 NumOrders = 2;
526 }
David Chisnallfa35df62012-01-16 17:27:18 +0000527 if (Op == AtomicExpr::Init)
528 NumOrders = 0;
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000529
530 if (TheCall->getNumArgs() < NumVals+NumOrders+1) {
531 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
532 << 0 << NumVals+NumOrders+1 << TheCall->getNumArgs()
533 << TheCall->getCallee()->getSourceRange();
534 return ExprError();
535 } else if (TheCall->getNumArgs() > NumVals+NumOrders+1) {
536 Diag(TheCall->getArg(NumVals+NumOrders+1)->getLocStart(),
537 diag::err_typecheck_call_too_many_args)
538 << 0 << NumVals+NumOrders+1 << TheCall->getNumArgs()
539 << TheCall->getCallee()->getSourceRange();
540 return ExprError();
541 }
542
543 // Inspect the first argument of the atomic operation. This should always be
544 // a pointer to an _Atomic type.
Eli Friedman8d3e43f2011-10-14 22:48:56 +0000545 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000546 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
547 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
548 if (!pointerType) {
549 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
550 << Ptr->getType() << Ptr->getSourceRange();
551 return ExprError();
552 }
553
554 QualType AtomTy = pointerType->getPointeeType();
555 if (!AtomTy->isAtomicType()) {
556 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
557 << Ptr->getType() << Ptr->getSourceRange();
558 return ExprError();
559 }
560 QualType ValType = AtomTy->getAs<AtomicType>()->getValueType();
561
562 if ((Op == AtomicExpr::Add || Op == AtomicExpr::Sub) &&
563 !ValType->isIntegerType() && !ValType->isPointerType()) {
564 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
565 << Ptr->getType() << Ptr->getSourceRange();
566 return ExprError();
567 }
568
569 if (!ValType->isIntegerType() &&
570 (Op == AtomicExpr::And || Op == AtomicExpr::Or || Op == AtomicExpr::Xor)){
571 Diag(DRE->getLocStart(), diag::err_atomic_op_logical_needs_atomic_int)
572 << Ptr->getType() << Ptr->getSourceRange();
573 return ExprError();
574 }
575
576 switch (ValType.getObjCLifetime()) {
577 case Qualifiers::OCL_None:
578 case Qualifiers::OCL_ExplicitNone:
579 // okay
580 break;
581
582 case Qualifiers::OCL_Weak:
583 case Qualifiers::OCL_Strong:
584 case Qualifiers::OCL_Autoreleasing:
585 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
586 << ValType << Ptr->getSourceRange();
587 return ExprError();
588 }
589
590 QualType ResultType = ValType;
David Chisnallfa35df62012-01-16 17:27:18 +0000591 if (Op == AtomicExpr::Store || Op == AtomicExpr::Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000592 ResultType = Context.VoidTy;
593 else if (Op == AtomicExpr::CmpXchgWeak || Op == AtomicExpr::CmpXchgStrong)
594 ResultType = Context.BoolTy;
595
596 // The first argument --- the pointer --- has a fixed type; we
597 // deduce the types of the rest of the arguments accordingly. Walk
598 // the remaining arguments, converting them to the deduced value type.
599 for (unsigned i = 1; i != NumVals+NumOrders+1; ++i) {
600 ExprResult Arg = TheCall->getArg(i);
601 QualType Ty;
602 if (i < NumVals+1) {
603 // The second argument to a cmpxchg is a pointer to the data which will
604 // be exchanged. The second argument to a pointer add/subtract is the
605 // amount to add/subtract, which must be a ptrdiff_t. The third
606 // argument to a cmpxchg and the second argument in all other cases
607 // is the type of the value.
608 if (i == 1 && (Op == AtomicExpr::CmpXchgWeak ||
609 Op == AtomicExpr::CmpXchgStrong))
610 Ty = Context.getPointerType(ValType.getUnqualifiedType());
611 else if (!ValType->isIntegerType() &&
612 (Op == AtomicExpr::Add || Op == AtomicExpr::Sub))
613 Ty = Context.getPointerDiffType();
614 else
615 Ty = ValType;
616 } else {
617 // The order(s) are always converted to int.
618 Ty = Context.IntTy;
619 }
620 InitializedEntity Entity =
621 InitializedEntity::InitializeParameter(Context, Ty, false);
622 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
623 if (Arg.isInvalid())
624 return true;
625 TheCall->setArg(i, Arg.get());
626 }
627
Eli Friedman8d3e43f2011-10-14 22:48:56 +0000628 SmallVector<Expr*, 5> SubExprs;
629 SubExprs.push_back(Ptr);
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000630 if (Op == AtomicExpr::Load) {
Eli Friedman8d3e43f2011-10-14 22:48:56 +0000631 SubExprs.push_back(TheCall->getArg(1)); // Order
David Chisnallfa35df62012-01-16 17:27:18 +0000632 } else if (Op == AtomicExpr::Init) {
633 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000634 } else if (Op != AtomicExpr::CmpXchgWeak && Op != AtomicExpr::CmpXchgStrong) {
Eli Friedman8d3e43f2011-10-14 22:48:56 +0000635 SubExprs.push_back(TheCall->getArg(2)); // Order
636 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000637 } else {
Eli Friedman8d3e43f2011-10-14 22:48:56 +0000638 SubExprs.push_back(TheCall->getArg(3)); // Order
639 SubExprs.push_back(TheCall->getArg(1)); // Val1
640 SubExprs.push_back(TheCall->getArg(2)); // Val2
641 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000642 }
Eli Friedman8d3e43f2011-10-14 22:48:56 +0000643
644 return Owned(new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
645 SubExprs.data(), SubExprs.size(),
646 ResultType, Op,
647 TheCall->getRParenLoc()));
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000648}
649
650
John McCall29ad95b2011-08-27 01:09:30 +0000651/// checkBuiltinArgument - Given a call to a builtin function, perform
652/// normal type-checking on the given argument, updating the call in
653/// place. This is useful when a builtin function requires custom
654/// type-checking for some of its arguments but not necessarily all of
655/// them.
656///
657/// Returns true on error.
658static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
659 FunctionDecl *Fn = E->getDirectCallee();
660 assert(Fn && "builtin call without direct callee!");
661
662 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
663 InitializedEntity Entity =
664 InitializedEntity::InitializeParameter(S.Context, Param);
665
666 ExprResult Arg = E->getArg(0);
667 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
668 if (Arg.isInvalid())
669 return true;
670
671 E->setArg(ArgIndex, Arg.take());
672 return false;
673}
674
Chris Lattnerdc046542009-05-08 06:58:22 +0000675/// SemaBuiltinAtomicOverloaded - We have a call to a function like
676/// __sync_fetch_and_add, which is an overloaded function based on the pointer
677/// type of its first argument. The main ActOnCallExpr routines have already
678/// promoted the types of arguments because all of these calls are prototyped as
679/// void(...).
680///
681/// This function goes through and does final semantic checking for these
682/// builtins,
John McCalldadc5752010-08-24 06:29:42 +0000683ExprResult
684Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000685 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +0000686 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
687 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
688
689 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000690 if (TheCall->getNumArgs() < 1) {
691 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
692 << 0 << 1 << TheCall->getNumArgs()
693 << TheCall->getCallee()->getSourceRange();
694 return ExprError();
695 }
Mike Stump11289f42009-09-09 15:08:12 +0000696
Chris Lattnerdc046542009-05-08 06:58:22 +0000697 // Inspect the first argument of the atomic builtin. This should always be
698 // a pointer type, whose element is an integral scalar or pointer type.
699 // Because it is a pointer type, we don't have to worry about any implicit
700 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000701 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +0000702 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +0000703 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
704 if (FirstArgResult.isInvalid())
705 return ExprError();
706 FirstArg = FirstArgResult.take();
707 TheCall->setArg(0, FirstArg);
708
John McCall31168b02011-06-15 23:02:42 +0000709 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
710 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000711 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
712 << FirstArg->getType() << FirstArg->getSourceRange();
713 return ExprError();
714 }
Mike Stump11289f42009-09-09 15:08:12 +0000715
John McCall31168b02011-06-15 23:02:42 +0000716 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +0000717 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000718 !ValType->isBlockPointerType()) {
719 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
720 << FirstArg->getType() << FirstArg->getSourceRange();
721 return ExprError();
722 }
Chris Lattnerdc046542009-05-08 06:58:22 +0000723
John McCall31168b02011-06-15 23:02:42 +0000724 switch (ValType.getObjCLifetime()) {
725 case Qualifiers::OCL_None:
726 case Qualifiers::OCL_ExplicitNone:
727 // okay
728 break;
729
730 case Qualifiers::OCL_Weak:
731 case Qualifiers::OCL_Strong:
732 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +0000733 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +0000734 << ValType << FirstArg->getSourceRange();
735 return ExprError();
736 }
737
John McCallb50451a2011-10-05 07:41:44 +0000738 // Strip any qualifiers off ValType.
739 ValType = ValType.getUnqualifiedType();
740
Chandler Carruth3973af72010-07-18 20:54:12 +0000741 // The majority of builtins return a value, but a few have special return
742 // types, so allow them to override appropriately below.
743 QualType ResultType = ValType;
744
Chris Lattnerdc046542009-05-08 06:58:22 +0000745 // We need to figure out which concrete builtin this maps onto. For example,
746 // __sync_fetch_and_add with a 2 byte object turns into
747 // __sync_fetch_and_add_2.
748#define BUILTIN_ROW(x) \
749 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
750 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +0000751
Chris Lattnerdc046542009-05-08 06:58:22 +0000752 static const unsigned BuiltinIndices[][5] = {
753 BUILTIN_ROW(__sync_fetch_and_add),
754 BUILTIN_ROW(__sync_fetch_and_sub),
755 BUILTIN_ROW(__sync_fetch_and_or),
756 BUILTIN_ROW(__sync_fetch_and_and),
757 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump11289f42009-09-09 15:08:12 +0000758
Chris Lattnerdc046542009-05-08 06:58:22 +0000759 BUILTIN_ROW(__sync_add_and_fetch),
760 BUILTIN_ROW(__sync_sub_and_fetch),
761 BUILTIN_ROW(__sync_and_and_fetch),
762 BUILTIN_ROW(__sync_or_and_fetch),
763 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +0000764
Chris Lattnerdc046542009-05-08 06:58:22 +0000765 BUILTIN_ROW(__sync_val_compare_and_swap),
766 BUILTIN_ROW(__sync_bool_compare_and_swap),
767 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000768 BUILTIN_ROW(__sync_lock_release),
769 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +0000770 };
Mike Stump11289f42009-09-09 15:08:12 +0000771#undef BUILTIN_ROW
772
Chris Lattnerdc046542009-05-08 06:58:22 +0000773 // Determine the index of the size.
774 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +0000775 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +0000776 case 1: SizeIndex = 0; break;
777 case 2: SizeIndex = 1; break;
778 case 4: SizeIndex = 2; break;
779 case 8: SizeIndex = 3; break;
780 case 16: SizeIndex = 4; break;
781 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000782 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
783 << FirstArg->getType() << FirstArg->getSourceRange();
784 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +0000785 }
Mike Stump11289f42009-09-09 15:08:12 +0000786
Chris Lattnerdc046542009-05-08 06:58:22 +0000787 // Each of these builtins has one pointer argument, followed by some number of
788 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
789 // that we ignore. Find out which row of BuiltinIndices to read from as well
790 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +0000791 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +0000792 unsigned BuiltinIndex, NumFixed = 1;
793 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +0000794 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +0000795 case Builtin::BI__sync_fetch_and_add:
796 case Builtin::BI__sync_fetch_and_add_1:
797 case Builtin::BI__sync_fetch_and_add_2:
798 case Builtin::BI__sync_fetch_and_add_4:
799 case Builtin::BI__sync_fetch_and_add_8:
800 case Builtin::BI__sync_fetch_and_add_16:
801 BuiltinIndex = 0;
802 break;
803
804 case Builtin::BI__sync_fetch_and_sub:
805 case Builtin::BI__sync_fetch_and_sub_1:
806 case Builtin::BI__sync_fetch_and_sub_2:
807 case Builtin::BI__sync_fetch_and_sub_4:
808 case Builtin::BI__sync_fetch_and_sub_8:
809 case Builtin::BI__sync_fetch_and_sub_16:
810 BuiltinIndex = 1;
811 break;
812
813 case Builtin::BI__sync_fetch_and_or:
814 case Builtin::BI__sync_fetch_and_or_1:
815 case Builtin::BI__sync_fetch_and_or_2:
816 case Builtin::BI__sync_fetch_and_or_4:
817 case Builtin::BI__sync_fetch_and_or_8:
818 case Builtin::BI__sync_fetch_and_or_16:
819 BuiltinIndex = 2;
820 break;
821
822 case Builtin::BI__sync_fetch_and_and:
823 case Builtin::BI__sync_fetch_and_and_1:
824 case Builtin::BI__sync_fetch_and_and_2:
825 case Builtin::BI__sync_fetch_and_and_4:
826 case Builtin::BI__sync_fetch_and_and_8:
827 case Builtin::BI__sync_fetch_and_and_16:
828 BuiltinIndex = 3;
829 break;
Mike Stump11289f42009-09-09 15:08:12 +0000830
Douglas Gregor73722482011-11-28 16:30:08 +0000831 case Builtin::BI__sync_fetch_and_xor:
832 case Builtin::BI__sync_fetch_and_xor_1:
833 case Builtin::BI__sync_fetch_and_xor_2:
834 case Builtin::BI__sync_fetch_and_xor_4:
835 case Builtin::BI__sync_fetch_and_xor_8:
836 case Builtin::BI__sync_fetch_and_xor_16:
837 BuiltinIndex = 4;
838 break;
839
840 case Builtin::BI__sync_add_and_fetch:
841 case Builtin::BI__sync_add_and_fetch_1:
842 case Builtin::BI__sync_add_and_fetch_2:
843 case Builtin::BI__sync_add_and_fetch_4:
844 case Builtin::BI__sync_add_and_fetch_8:
845 case Builtin::BI__sync_add_and_fetch_16:
846 BuiltinIndex = 5;
847 break;
848
849 case Builtin::BI__sync_sub_and_fetch:
850 case Builtin::BI__sync_sub_and_fetch_1:
851 case Builtin::BI__sync_sub_and_fetch_2:
852 case Builtin::BI__sync_sub_and_fetch_4:
853 case Builtin::BI__sync_sub_and_fetch_8:
854 case Builtin::BI__sync_sub_and_fetch_16:
855 BuiltinIndex = 6;
856 break;
857
858 case Builtin::BI__sync_and_and_fetch:
859 case Builtin::BI__sync_and_and_fetch_1:
860 case Builtin::BI__sync_and_and_fetch_2:
861 case Builtin::BI__sync_and_and_fetch_4:
862 case Builtin::BI__sync_and_and_fetch_8:
863 case Builtin::BI__sync_and_and_fetch_16:
864 BuiltinIndex = 7;
865 break;
866
867 case Builtin::BI__sync_or_and_fetch:
868 case Builtin::BI__sync_or_and_fetch_1:
869 case Builtin::BI__sync_or_and_fetch_2:
870 case Builtin::BI__sync_or_and_fetch_4:
871 case Builtin::BI__sync_or_and_fetch_8:
872 case Builtin::BI__sync_or_and_fetch_16:
873 BuiltinIndex = 8;
874 break;
875
876 case Builtin::BI__sync_xor_and_fetch:
877 case Builtin::BI__sync_xor_and_fetch_1:
878 case Builtin::BI__sync_xor_and_fetch_2:
879 case Builtin::BI__sync_xor_and_fetch_4:
880 case Builtin::BI__sync_xor_and_fetch_8:
881 case Builtin::BI__sync_xor_and_fetch_16:
882 BuiltinIndex = 9;
883 break;
Mike Stump11289f42009-09-09 15:08:12 +0000884
Chris Lattnerdc046542009-05-08 06:58:22 +0000885 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000886 case Builtin::BI__sync_val_compare_and_swap_1:
887 case Builtin::BI__sync_val_compare_and_swap_2:
888 case Builtin::BI__sync_val_compare_and_swap_4:
889 case Builtin::BI__sync_val_compare_and_swap_8:
890 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +0000891 BuiltinIndex = 10;
Chris Lattnerdc046542009-05-08 06:58:22 +0000892 NumFixed = 2;
893 break;
Douglas Gregor73722482011-11-28 16:30:08 +0000894
Chris Lattnerdc046542009-05-08 06:58:22 +0000895 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000896 case Builtin::BI__sync_bool_compare_and_swap_1:
897 case Builtin::BI__sync_bool_compare_and_swap_2:
898 case Builtin::BI__sync_bool_compare_and_swap_4:
899 case Builtin::BI__sync_bool_compare_and_swap_8:
900 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +0000901 BuiltinIndex = 11;
Chris Lattnerdc046542009-05-08 06:58:22 +0000902 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +0000903 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +0000904 break;
Douglas Gregor73722482011-11-28 16:30:08 +0000905
906 case Builtin::BI__sync_lock_test_and_set:
907 case Builtin::BI__sync_lock_test_and_set_1:
908 case Builtin::BI__sync_lock_test_and_set_2:
909 case Builtin::BI__sync_lock_test_and_set_4:
910 case Builtin::BI__sync_lock_test_and_set_8:
911 case Builtin::BI__sync_lock_test_and_set_16:
912 BuiltinIndex = 12;
913 break;
914
Chris Lattnerdc046542009-05-08 06:58:22 +0000915 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +0000916 case Builtin::BI__sync_lock_release_1:
917 case Builtin::BI__sync_lock_release_2:
918 case Builtin::BI__sync_lock_release_4:
919 case Builtin::BI__sync_lock_release_8:
920 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +0000921 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +0000922 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +0000923 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +0000924 break;
Douglas Gregor73722482011-11-28 16:30:08 +0000925
926 case Builtin::BI__sync_swap:
927 case Builtin::BI__sync_swap_1:
928 case Builtin::BI__sync_swap_2:
929 case Builtin::BI__sync_swap_4:
930 case Builtin::BI__sync_swap_8:
931 case Builtin::BI__sync_swap_16:
932 BuiltinIndex = 14;
933 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000934 }
Mike Stump11289f42009-09-09 15:08:12 +0000935
Chris Lattnerdc046542009-05-08 06:58:22 +0000936 // Now that we know how many fixed arguments we expect, first check that we
937 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000938 if (TheCall->getNumArgs() < 1+NumFixed) {
939 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
940 << 0 << 1+NumFixed << TheCall->getNumArgs()
941 << TheCall->getCallee()->getSourceRange();
942 return ExprError();
943 }
Mike Stump11289f42009-09-09 15:08:12 +0000944
Chris Lattner5b9241b2009-05-08 15:36:58 +0000945 // Get the decl for the concrete builtin from this, we can tell what the
946 // concrete integer type we should convert to is.
947 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
948 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
949 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
Mike Stump11289f42009-09-09 15:08:12 +0000950 FunctionDecl *NewBuiltinDecl =
Chris Lattner5b9241b2009-05-08 15:36:58 +0000951 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
952 TUScope, false, DRE->getLocStart()));
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000953
John McCallcf142162010-08-07 06:22:56 +0000954 // The first argument --- the pointer --- has a fixed type; we
955 // deduce the types of the rest of the arguments accordingly. Walk
956 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +0000957 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +0000958 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +0000959
Chris Lattnerdc046542009-05-08 06:58:22 +0000960 // GCC does an implicit conversion to the pointer or integer ValType. This
961 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +0000962 // Initialize the argument.
963 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
964 ValType, /*consume*/ false);
965 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +0000966 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000967 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +0000968
Chris Lattnerdc046542009-05-08 06:58:22 +0000969 // Okay, we have something that *can* be converted to the right type. Check
970 // to see if there is a potentially weird extension going on here. This can
971 // happen when you do an atomic operation on something like an char* and
972 // pass in 42. The 42 gets converted to char. This is even more strange
973 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +0000974 // FIXME: Do this check.
John McCallb50451a2011-10-05 07:41:44 +0000975 TheCall->setArg(i+1, Arg.take());
Chris Lattnerdc046542009-05-08 06:58:22 +0000976 }
Mike Stump11289f42009-09-09 15:08:12 +0000977
Douglas Gregor6b3bcf22011-09-09 16:51:10 +0000978 ASTContext& Context = this->getASTContext();
979
980 // Create a new DeclRefExpr to refer to the new decl.
981 DeclRefExpr* NewDRE = DeclRefExpr::Create(
982 Context,
983 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +0000984 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +0000985 NewBuiltinDecl,
986 DRE->getLocation(),
987 NewBuiltinDecl->getType(),
988 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +0000989
Chris Lattnerdc046542009-05-08 06:58:22 +0000990 // Set the callee in the CallExpr.
991 // FIXME: This leaks the original parens and implicit casts.
Douglas Gregor6b3bcf22011-09-09 16:51:10 +0000992 ExprResult PromotedCall = UsualUnaryConversions(NewDRE);
John Wiegley01296292011-04-08 18:41:53 +0000993 if (PromotedCall.isInvalid())
994 return ExprError();
995 TheCall->setCallee(PromotedCall.take());
Mike Stump11289f42009-09-09 15:08:12 +0000996
Chandler Carruthbc8cab12010-07-18 07:23:17 +0000997 // Change the result type of the call to match the original value type. This
998 // is arbitrary, but the codegen for these builtins ins design to handle it
999 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00001000 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001001
1002 return move(TheCallResult);
Chris Lattnerdc046542009-05-08 06:58:22 +00001003}
1004
Chris Lattner6436fb62009-02-18 06:01:06 +00001005/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00001006/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00001007/// Note: It might also make sense to do the UTF-16 conversion here (would
1008/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00001009bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00001010 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00001011 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1012
Douglas Gregorfb65e592011-07-27 05:40:30 +00001013 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00001014 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1015 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00001016 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00001017 }
Mike Stump11289f42009-09-09 15:08:12 +00001018
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001019 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001020 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001021 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001022 SmallVector<UTF16, 128> ToBuf(NumBytes);
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001023 const UTF8 *FromPtr = (UTF8 *)String.data();
1024 UTF16 *ToPtr = &ToBuf[0];
1025
1026 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1027 &ToPtr, ToPtr + NumBytes,
1028 strictConversion);
1029 // Check for conversion failure.
1030 if (Result != conversionOK)
1031 Diag(Arg->getLocStart(),
1032 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1033 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00001034 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001035}
1036
Chris Lattnere202e6a2007-12-20 00:05:45 +00001037/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1038/// Emit an error and return true on failure, return false on success.
Chris Lattner08464942007-12-28 05:29:59 +00001039bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1040 Expr *Fn = TheCall->getCallee();
1041 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00001042 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001043 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001044 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1045 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00001046 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001047 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00001048 return true;
1049 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00001050
1051 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00001052 return Diag(TheCall->getLocEnd(),
1053 diag::err_typecheck_call_too_few_args_at_least)
1054 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00001055 }
1056
John McCall29ad95b2011-08-27 01:09:30 +00001057 // Type-check the first argument normally.
1058 if (checkBuiltinArgument(*this, TheCall, 0))
1059 return true;
1060
Chris Lattnere202e6a2007-12-20 00:05:45 +00001061 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00001062 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00001063 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00001064 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00001065 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00001066 else if (FunctionDecl *FD = getCurFunctionDecl())
1067 isVariadic = FD->isVariadic();
1068 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00001069 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00001070
Chris Lattnere202e6a2007-12-20 00:05:45 +00001071 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00001072 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1073 return true;
1074 }
Mike Stump11289f42009-09-09 15:08:12 +00001075
Chris Lattner43be2e62007-12-19 23:59:04 +00001076 // Verify that the second argument to the builtin is the last argument of the
1077 // current function or method.
1078 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00001079 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00001080
Anders Carlsson6a8350b2008-02-11 04:20:54 +00001081 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1082 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00001083 // FIXME: This isn't correct for methods (results in bogus warning).
1084 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00001085 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00001086 if (CurBlock)
1087 LastArg = *(CurBlock->TheDecl->param_end()-1);
1088 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +00001089 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00001090 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00001091 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00001092 SecondArgIsLastNamedArgument = PV == LastArg;
1093 }
1094 }
Mike Stump11289f42009-09-09 15:08:12 +00001095
Chris Lattner43be2e62007-12-19 23:59:04 +00001096 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001097 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +00001098 diag::warn_second_parameter_of_va_start_not_last_named_argument);
1099 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00001100}
Chris Lattner43be2e62007-12-19 23:59:04 +00001101
Chris Lattner2da14fb2007-12-20 00:26:33 +00001102/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1103/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00001104bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1105 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00001106 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00001107 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00001108 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00001109 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001110 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001111 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00001112 << SourceRange(TheCall->getArg(2)->getLocStart(),
1113 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00001114
John Wiegley01296292011-04-08 18:41:53 +00001115 ExprResult OrigArg0 = TheCall->getArg(0);
1116 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00001117
Chris Lattner2da14fb2007-12-20 00:26:33 +00001118 // Do standard promotions between the two arguments, returning their common
1119 // type.
Chris Lattner08464942007-12-28 05:29:59 +00001120 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00001121 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1122 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00001123
1124 // Make sure any conversions are pushed back into the call; this is
1125 // type safe since unordered compare builtins are declared as "_Bool
1126 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00001127 TheCall->setArg(0, OrigArg0.get());
1128 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00001129
John Wiegley01296292011-04-08 18:41:53 +00001130 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00001131 return false;
1132
Chris Lattner2da14fb2007-12-20 00:26:33 +00001133 // If the common type isn't a real floating type, then the arguments were
1134 // invalid for this operation.
1135 if (!Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00001136 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001137 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00001138 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1139 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00001140
Chris Lattner2da14fb2007-12-20 00:26:33 +00001141 return false;
1142}
1143
Benjamin Kramer634fc102010-02-15 22:42:31 +00001144/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1145/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00001146/// to check everything. We expect the last argument to be a floating point
1147/// value.
1148bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1149 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00001150 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00001151 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00001152 if (TheCall->getNumArgs() > NumArgs)
1153 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001154 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001155 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00001156 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001157 (*(TheCall->arg_end()-1))->getLocEnd());
1158
Benjamin Kramer64aae502010-02-16 10:07:31 +00001159 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00001160
Eli Friedman7e4faac2009-08-31 20:06:00 +00001161 if (OrigArg->isTypeDependent())
1162 return false;
1163
Chris Lattner68784ef2010-05-06 05:50:07 +00001164 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00001165 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00001166 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001167 diag::err_typecheck_call_invalid_unary_fp)
1168 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001169
Chris Lattner68784ef2010-05-06 05:50:07 +00001170 // If this is an implicit conversion from float -> double, remove it.
1171 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1172 Expr *CastArg = Cast->getSubExpr();
1173 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1174 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1175 "promotion from float to double is the only expected cast here");
1176 Cast->setSubExpr(0);
Chris Lattner68784ef2010-05-06 05:50:07 +00001177 TheCall->setArg(NumArgs-1, CastArg);
1178 OrigArg = CastArg;
1179 }
1180 }
1181
Eli Friedman7e4faac2009-08-31 20:06:00 +00001182 return false;
1183}
1184
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001185/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1186// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00001187ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00001188 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001189 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00001190 diag::err_typecheck_call_too_few_args_at_least)
Nate Begemana0110022010-06-08 00:16:34 +00001191 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherabf1e182010-04-16 04:48:22 +00001192 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001193
Nate Begemana0110022010-06-08 00:16:34 +00001194 // Determine which of the following types of shufflevector we're checking:
1195 // 1) unary, vector mask: (lhs, mask)
1196 // 2) binary, vector mask: (lhs, rhs, mask)
1197 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1198 QualType resType = TheCall->getArg(0)->getType();
1199 unsigned numElements = 0;
1200
Douglas Gregorc25f7662009-05-19 22:10:17 +00001201 if (!TheCall->getArg(0)->isTypeDependent() &&
1202 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00001203 QualType LHSType = TheCall->getArg(0)->getType();
1204 QualType RHSType = TheCall->getArg(1)->getType();
1205
1206 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00001207 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump11289f42009-09-09 15:08:12 +00001208 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorc25f7662009-05-19 22:10:17 +00001209 TheCall->getArg(1)->getLocEnd());
1210 return ExprError();
1211 }
Nate Begemana0110022010-06-08 00:16:34 +00001212
1213 numElements = LHSType->getAs<VectorType>()->getNumElements();
1214 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00001215
Nate Begemana0110022010-06-08 00:16:34 +00001216 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1217 // with mask. If so, verify that RHS is an integer vector type with the
1218 // same number of elts as lhs.
1219 if (TheCall->getNumArgs() == 2) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00001220 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00001221 RHSType->getAs<VectorType>()->getNumElements() != numElements)
1222 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
1223 << SourceRange(TheCall->getArg(1)->getLocStart(),
1224 TheCall->getArg(1)->getLocEnd());
1225 numResElements = numElements;
1226 }
1227 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00001228 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump11289f42009-09-09 15:08:12 +00001229 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorc25f7662009-05-19 22:10:17 +00001230 TheCall->getArg(1)->getLocEnd());
1231 return ExprError();
Nate Begemana0110022010-06-08 00:16:34 +00001232 } else if (numElements != numResElements) {
1233 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00001234 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001235 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00001236 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001237 }
1238
1239 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00001240 if (TheCall->getArg(i)->isTypeDependent() ||
1241 TheCall->getArg(i)->isValueDependent())
1242 continue;
1243
Nate Begemana0110022010-06-08 00:16:34 +00001244 llvm::APSInt Result(32);
1245 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1246 return ExprError(Diag(TheCall->getLocStart(),
1247 diag::err_shufflevector_nonconstant_argument)
1248 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001249
Chris Lattner7ab824e2008-08-10 02:05:13 +00001250 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001251 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001252 diag::err_shufflevector_argument_too_large)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001253 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001254 }
1255
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001256 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001257
Chris Lattner7ab824e2008-08-10 02:05:13 +00001258 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001259 exprs.push_back(TheCall->getArg(i));
1260 TheCall->setArg(i, 0);
1261 }
1262
Nate Begemanf485fb52009-08-12 02:10:25 +00001263 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
Nate Begemana0110022010-06-08 00:16:34 +00001264 exprs.size(), resType,
Ted Kremenek5a201952009-02-07 01:47:29 +00001265 TheCall->getCallee()->getLocStart(),
1266 TheCall->getRParenLoc()));
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001267}
Chris Lattner43be2e62007-12-19 23:59:04 +00001268
Daniel Dunbarb7257262008-07-21 22:59:13 +00001269/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1270// This is declared to take (const void*, ...) and can take two
1271// optional constant int args.
1272bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00001273 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001274
Chris Lattner3b054132008-11-19 05:08:23 +00001275 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001276 return Diag(TheCall->getLocEnd(),
1277 diag::err_typecheck_call_too_many_args_at_most)
1278 << 0 /*function call*/ << 3 << NumArgs
1279 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001280
1281 // Argument 0 is checked for us and the remaining arguments must be
1282 // constant integers.
Chris Lattner3b054132008-11-19 05:08:23 +00001283 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbarb7257262008-07-21 22:59:13 +00001284 Expr *Arg = TheCall->getArg(i);
Eric Christopher8d0c6212010-04-17 02:26:23 +00001285
Eli Friedman5efba262009-12-04 00:30:06 +00001286 llvm::APSInt Result;
Eric Christopher8d0c6212010-04-17 02:26:23 +00001287 if (SemaBuiltinConstantArg(TheCall, i, Result))
1288 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001289
Daniel Dunbarb7257262008-07-21 22:59:13 +00001290 // FIXME: gcc issues a warning and rewrites these to 0. These
1291 // seems especially odd for the third argument since the default
1292 // is 3.
Chris Lattner3b054132008-11-19 05:08:23 +00001293 if (i == 1) {
Eli Friedman5efba262009-12-04 00:30:06 +00001294 if (Result.getLimitedValue() > 1)
Chris Lattner3b054132008-11-19 05:08:23 +00001295 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattnerd545ad12009-09-23 06:06:36 +00001296 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001297 } else {
Eli Friedman5efba262009-12-04 00:30:06 +00001298 if (Result.getLimitedValue() > 3)
Chris Lattner3b054132008-11-19 05:08:23 +00001299 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattnerd545ad12009-09-23 06:06:36 +00001300 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001301 }
1302 }
1303
Chris Lattner3b054132008-11-19 05:08:23 +00001304 return false;
Daniel Dunbarb7257262008-07-21 22:59:13 +00001305}
1306
Eric Christopher8d0c6212010-04-17 02:26:23 +00001307/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1308/// TheCall is a constant expression.
1309bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1310 llvm::APSInt &Result) {
1311 Expr *Arg = TheCall->getArg(ArgNum);
1312 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1313 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1314
1315 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1316
1317 if (!Arg->isIntegerConstantExpr(Result, Context))
1318 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00001319 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00001320
Chris Lattnerd545ad12009-09-23 06:06:36 +00001321 return false;
1322}
1323
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00001324/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1325/// int type). This simply type checks that type is one of the defined
1326/// constants (0-3).
Chris Lattner57540c52011-04-15 05:22:18 +00001327// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00001328bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00001329 llvm::APSInt Result;
1330
1331 // Check constant-ness first.
1332 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1333 return true;
1334
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00001335 Expr *Arg = TheCall->getArg(1);
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00001336 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattner3b054132008-11-19 05:08:23 +00001337 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1338 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00001339 }
1340
1341 return false;
1342}
1343
Eli Friedmanc97d0142009-05-03 06:04:26 +00001344/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmaneed8ad22009-05-03 04:46:36 +00001345/// This checks that val is a constant 1.
1346bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1347 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00001348 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00001349
Eric Christopher8d0c6212010-04-17 02:26:23 +00001350 // TODO: This is less than ideal. Overload this to take a value.
1351 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1352 return true;
1353
1354 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00001355 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1356 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1357
1358 return false;
1359}
1360
Ted Kremeneka8890832011-02-24 23:03:04 +00001361// Handle i > 1 ? "x" : "y", recursively.
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001362bool Sema::SemaCheckStringLiteral(const Expr *E, Expr **Args,
1363 unsigned NumArgs, bool HasVAListArg,
Ted Kremenek02087932010-07-16 02:11:22 +00001364 unsigned format_idx, unsigned firstDataArg,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00001365 FormatStringType Type, bool inFunctionCall) {
Ted Kremenek808829352010-09-09 03:51:39 +00001366 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00001367 if (E->isTypeDependent() || E->isValueDependent())
1368 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001369
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00001370 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00001371
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001372 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00001373 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001374 case Stmt::ConditionalOperatorClass: {
John McCallc07a0c72011-02-17 10:25:35 +00001375 const AbstractConditionalOperator *C = cast<AbstractConditionalOperator>(E);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001376 return SemaCheckStringLiteral(C->getTrueExpr(), Args, NumArgs, HasVAListArg,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00001377 format_idx, firstDataArg, Type,
Richard Trieu03cf7b72011-10-28 00:41:25 +00001378 inFunctionCall)
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00001379 && SemaCheckStringLiteral(C->getFalseExpr(), Args, NumArgs, HasVAListArg,
1380 format_idx, firstDataArg, Type,
1381 inFunctionCall);
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001382 }
1383
Ted Kremenekdde2ade2012-02-10 19:13:51 +00001384 case Stmt::GNUNullExprClass:
Ted Kremenek1520dae2010-09-09 03:51:42 +00001385 case Stmt::IntegerLiteralClass:
1386 // Technically -Wformat-nonliteral does not warn about this case.
1387 // The behavior of printf and friends in this case is implementation
1388 // dependent. Ideally if the format string cannot be null then
1389 // it should have a 'nonnull' attribute in the function prototype.
1390 return true;
1391
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001392 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00001393 E = cast<ImplicitCastExpr>(E)->getSubExpr();
1394 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001395 }
1396
John McCallc07a0c72011-02-17 10:25:35 +00001397 case Stmt::OpaqueValueExprClass:
1398 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
1399 E = src;
1400 goto tryAgain;
1401 }
1402 return false;
1403
Ted Kremeneka8890832011-02-24 23:03:04 +00001404 case Stmt::PredefinedExprClass:
1405 // While __func__, etc., are technically not string literals, they
1406 // cannot contain format specifiers and thus are not a security
1407 // liability.
1408 return true;
1409
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001410 case Stmt::DeclRefExprClass: {
1411 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00001412
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001413 // As an exception, do not flag errors for variables binding to
1414 // const string literals.
1415 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1416 bool isConstant = false;
1417 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001418
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001419 if (const ArrayType *AT = Context.getAsArrayType(T)) {
1420 isConstant = AT->getElementType().isConstant(Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00001421 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001422 isConstant = T.isConstant(Context) &&
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001423 PT->getPointeeType().isConstant(Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00001424 } else if (T->isObjCObjectPointerType()) {
1425 // In ObjC, there is usually no "const ObjectPointer" type,
1426 // so don't check if the pointee type is constant.
1427 isConstant = T.isConstant(Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001428 }
Mike Stump11289f42009-09-09 15:08:12 +00001429
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001430 if (isConstant) {
Sebastian Redl5ca79842010-02-01 20:16:42 +00001431 if (const Expr *Init = VD->getAnyInitializer())
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001432 return SemaCheckStringLiteral(Init, Args, NumArgs,
Ted Kremenek02087932010-07-16 02:11:22 +00001433 HasVAListArg, format_idx, firstDataArg,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00001434 Type, /*inFunctionCall*/false);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001435 }
Mike Stump11289f42009-09-09 15:08:12 +00001436
Anders Carlssonb012ca92009-06-28 19:55:58 +00001437 // For vprintf* functions (i.e., HasVAListArg==true), we add a
1438 // special check to see if the format string is a function parameter
1439 // of the function calling the printf function. If the function
1440 // has an attribute indicating it is a printf-like function, then we
1441 // should suppress warnings concerning non-literals being used in a call
1442 // to a vprintf function. For example:
1443 //
1444 // void
1445 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
1446 // va_list ap;
1447 // va_start(ap, fmt);
1448 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
1449 // ...
1450 //
1451 //
1452 // FIXME: We don't have full attribute support yet, so just check to see
1453 // if the argument is a DeclRefExpr that references a parameter. We'll
1454 // add proper support for checking the attribute later.
1455 if (HasVAListArg)
1456 if (isa<ParmVarDecl>(VD))
1457 return true;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001458 }
Mike Stump11289f42009-09-09 15:08:12 +00001459
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001460 return false;
1461 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001462
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00001463 case Stmt::CallExprClass:
1464 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00001465 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00001466 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
1467 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
1468 unsigned ArgIndex = FA->getFormatIdx();
1469 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
1470 if (MD->isInstance())
1471 --ArgIndex;
1472 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00001473
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00001474 return SemaCheckStringLiteral(Arg, Args, NumArgs, HasVAListArg,
1475 format_idx, firstDataArg, Type,
1476 inFunctionCall);
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00001477 }
1478 }
Mike Stump11289f42009-09-09 15:08:12 +00001479
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00001480 return false;
1481 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001482 case Stmt::ObjCStringLiteralClass:
1483 case Stmt::StringLiteralClass: {
1484 const StringLiteral *StrE = NULL;
Mike Stump11289f42009-09-09 15:08:12 +00001485
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001486 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001487 StrE = ObjCFExpr->getString();
1488 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001489 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00001490
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001491 if (StrE) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001492 CheckFormatString(StrE, E, Args, NumArgs, HasVAListArg, format_idx,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00001493 firstDataArg, Type, inFunctionCall);
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001494 return true;
1495 }
Mike Stump11289f42009-09-09 15:08:12 +00001496
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001497 return false;
1498 }
Mike Stump11289f42009-09-09 15:08:12 +00001499
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001500 default:
1501 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001502 }
1503}
1504
Fariborz Jahaniancd1a88d2009-05-21 18:48:51 +00001505void
Mike Stump11289f42009-09-09 15:08:12 +00001506Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewyckyd4693212011-03-25 01:44:32 +00001507 const Expr * const *ExprArgs,
1508 SourceLocation CallSiteLoc) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001509 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1510 e = NonNull->args_end();
Fariborz Jahaniancd1a88d2009-05-21 18:48:51 +00001511 i != e; ++i) {
Nick Lewyckyd4693212011-03-25 01:44:32 +00001512 const Expr *ArgExpr = ExprArgs[*i];
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001513 if (ArgExpr->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00001514 Expr::NPC_ValueDependentIsNotNull))
Nick Lewyckyd4693212011-03-25 01:44:32 +00001515 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniancd1a88d2009-05-21 18:48:51 +00001516 }
1517}
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001518
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00001519Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
1520 return llvm::StringSwitch<FormatStringType>(Format->getType())
1521 .Case("scanf", FST_Scanf)
1522 .Cases("printf", "printf0", FST_Printf)
1523 .Cases("NSString", "CFString", FST_NSString)
1524 .Case("strftime", FST_Strftime)
1525 .Case("strfmon", FST_Strfmon)
1526 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
1527 .Default(FST_Unknown);
1528}
1529
Ted Kremenek02087932010-07-16 02:11:22 +00001530/// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar
1531/// functions) for correct use of format strings.
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001532void Sema::CheckFormatArguments(const FormatAttr *Format, CallExpr *TheCall) {
1533 bool IsCXXMember = false;
Sebastian Redl6eedcc12009-11-17 18:02:24 +00001534 // The way the format attribute works in GCC, the implicit this argument
1535 // of member functions is counted. However, it doesn't appear in our own
1536 // lists, so decrement format_idx in that case.
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00001537 IsCXXMember = isa<CXXMemberCallExpr>(TheCall);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001538 CheckFormatArguments(Format, TheCall->getArgs(), TheCall->getNumArgs(),
1539 IsCXXMember, TheCall->getRParenLoc(),
1540 TheCall->getCallee()->getSourceRange());
1541}
1542
1543void Sema::CheckFormatArguments(const FormatAttr *Format, Expr **Args,
1544 unsigned NumArgs, bool IsCXXMember,
1545 SourceLocation Loc, SourceRange Range) {
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00001546 bool HasVAListArg = Format->getFirstArg() == 0;
1547 unsigned format_idx = Format->getFormatIdx() - 1;
1548 unsigned firstDataArg = HasVAListArg ? 0 : Format->getFirstArg() - 1;
1549 if (IsCXXMember) {
1550 if (format_idx == 0)
1551 return;
1552 --format_idx;
1553 if(firstDataArg != 0)
1554 --firstDataArg;
Sebastian Redl6eedcc12009-11-17 18:02:24 +00001555 }
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00001556 CheckFormatArguments(Args, NumArgs, HasVAListArg, format_idx,
1557 firstDataArg, GetFormatStringType(Format), Loc, Range);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001558}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00001559
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00001560void Sema::CheckFormatArguments(Expr **Args, unsigned NumArgs,
1561 bool HasVAListArg, unsigned format_idx,
1562 unsigned firstDataArg, FormatStringType Type,
1563 SourceLocation Loc, SourceRange Range) {
Ted Kremenek02087932010-07-16 02:11:22 +00001564 // CHECK: printf/scanf-like function is called with no format string.
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001565 if (format_idx >= NumArgs) {
1566 Diag(Loc, diag::warn_missing_format_string) << Range;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00001567 return;
1568 }
Mike Stump11289f42009-09-09 15:08:12 +00001569
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001570 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00001571
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001572 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00001573 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00001574 // Dynamically generated format strings are difficult to
1575 // automatically vet at compile time. Requiring that format strings
1576 // are string literals: (1) permits the checking of format strings by
1577 // the compiler and thereby (2) can practically remove the source of
1578 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00001579
Mike Stump11289f42009-09-09 15:08:12 +00001580 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00001581 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00001582 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00001583 // the same format string checking logic for both ObjC and C strings.
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001584 if (SemaCheckStringLiteral(OrigFormatExpr, Args, NumArgs, HasVAListArg,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00001585 format_idx, firstDataArg, Type))
Chris Lattnere009a882009-04-29 04:49:34 +00001586 return; // Literal format string found, check done!
Ted Kremenek34f664d2008-06-16 18:00:42 +00001587
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00001588 // Strftime is particular as it always uses a single 'time' argument,
1589 // so it is safe to pass a non-literal string.
1590 if (Type == FST_Strftime)
1591 return;
1592
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00001593 // Do not emit diag when the string param is a macro expansion and the
1594 // format is either NSString or CFString. This is a hack to prevent
1595 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
1596 // which are usually used in place of NS and CF string literals.
1597 if (Type == FST_NSString && Args[format_idx]->getLocStart().isMacroID())
1598 return;
1599
Chris Lattnercc5d1c22009-04-29 04:59:47 +00001600 // If there are no arguments specified, warn with -Wformat-security, otherwise
1601 // warn only with -Wformat-nonliteral.
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001602 if (NumArgs == format_idx+1)
1603 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00001604 diag::warn_format_nonliteral_noargs)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00001605 << OrigFormatExpr->getSourceRange();
1606 else
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001607 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00001608 diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00001609 << OrigFormatExpr->getSourceRange();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001610}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00001611
Ted Kremenekab278de2010-01-28 23:39:18 +00001612namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00001613class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1614protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00001615 Sema &S;
1616 const StringLiteral *FExpr;
1617 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00001618 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00001619 const unsigned NumDataArgs;
1620 const bool IsObjCLiteral;
1621 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00001622 const bool HasVAListArg;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001623 const Expr * const *Args;
1624 const unsigned NumArgs;
Ted Kremenek5739de72010-01-29 01:06:55 +00001625 unsigned FormatIdx;
Ted Kremenek4a49d982010-02-26 19:18:41 +00001626 llvm::BitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00001627 bool usesPositionalArgs;
1628 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00001629 bool inFunctionCall;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001630public:
Ted Kremenek02087932010-07-16 02:11:22 +00001631 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00001632 const Expr *origFormatExpr, unsigned firstDataArg,
Ted Kremenekab278de2010-01-28 23:39:18 +00001633 unsigned numDataArgs, bool isObjCLiteral,
Ted Kremenek5739de72010-01-29 01:06:55 +00001634 const char *beg, bool hasVAListArg,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001635 Expr **args, unsigned numArgs,
1636 unsigned formatIdx, bool inFunctionCall)
Ted Kremenekab278de2010-01-28 23:39:18 +00001637 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Ted Kremenek4d745dd2010-03-25 03:59:12 +00001638 FirstDataArg(firstDataArg),
Ted Kremenek4a49d982010-02-26 19:18:41 +00001639 NumDataArgs(numDataArgs),
Ted Kremenek5739de72010-01-29 01:06:55 +00001640 IsObjCLiteral(isObjCLiteral), Beg(beg),
1641 HasVAListArg(hasVAListArg),
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001642 Args(args), NumArgs(numArgs), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00001643 usesPositionalArgs(false), atFirstArg(true),
1644 inFunctionCall(inFunctionCall) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00001645 CoveredArgs.resize(numDataArgs);
1646 CoveredArgs.reset();
1647 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001648
Ted Kremenek019d2242010-01-29 01:50:07 +00001649 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001650
Ted Kremenek02087932010-07-16 02:11:22 +00001651 void HandleIncompleteSpecifier(const char *startSpecifier,
1652 unsigned specifierLen);
1653
Ted Kremenekd1668192010-02-27 01:41:03 +00001654 virtual void HandleInvalidPosition(const char *startSpecifier,
1655 unsigned specifierLen,
Ted Kremenek02087932010-07-16 02:11:22 +00001656 analyze_format_string::PositionContext p);
Ted Kremenekd1668192010-02-27 01:41:03 +00001657
1658 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1659
Ted Kremenekab278de2010-01-28 23:39:18 +00001660 void HandleNullChar(const char *nullCharacter);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001661
Richard Trieu03cf7b72011-10-28 00:41:25 +00001662 template <typename Range>
1663 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
1664 const Expr *ArgumentExpr,
1665 PartialDiagnostic PDiag,
1666 SourceLocation StringLoc,
1667 bool IsStringLocation, Range StringRange,
1668 FixItHint Fixit = FixItHint());
1669
Ted Kremenek02087932010-07-16 02:11:22 +00001670protected:
Ted Kremenekce815422010-07-19 21:25:57 +00001671 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
1672 const char *startSpec,
1673 unsigned specifierLen,
1674 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00001675
1676 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
1677 const char *startSpec,
1678 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00001679
Ted Kremenek8d9842d2010-01-29 20:55:36 +00001680 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00001681 CharSourceRange getSpecifierRange(const char *startSpecifier,
1682 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00001683 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001684
Ted Kremenek5739de72010-01-29 01:06:55 +00001685 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00001686
1687 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
1688 const analyze_format_string::ConversionSpecifier &CS,
1689 const char *startSpecifier, unsigned specifierLen,
1690 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00001691
1692 template <typename Range>
1693 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
1694 bool IsStringLocation, Range StringRange,
1695 FixItHint Fixit = FixItHint());
1696
1697 void CheckPositionalAndNonpositionalArgs(
1698 const analyze_format_string::FormatSpecifier *FS);
Ted Kremenekab278de2010-01-28 23:39:18 +00001699};
1700}
1701
Ted Kremenek02087932010-07-16 02:11:22 +00001702SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00001703 return OrigFormatExpr->getSourceRange();
1704}
1705
Ted Kremenek02087932010-07-16 02:11:22 +00001706CharSourceRange CheckFormatHandler::
1707getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00001708 SourceLocation Start = getLocationOfByte(startSpecifier);
1709 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
1710
1711 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001712 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00001713
1714 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00001715}
1716
Ted Kremenek02087932010-07-16 02:11:22 +00001717SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001718 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00001719}
1720
Ted Kremenek02087932010-07-16 02:11:22 +00001721void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
1722 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00001723 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
1724 getLocationOfByte(startSpecifier),
1725 /*IsStringLocation*/true,
1726 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00001727}
1728
Ted Kremenekd1668192010-02-27 01:41:03 +00001729void
Ted Kremenek02087932010-07-16 02:11:22 +00001730CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
1731 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00001732 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
1733 << (unsigned) p,
1734 getLocationOfByte(startPos), /*IsStringLocation*/true,
1735 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00001736}
1737
Ted Kremenek02087932010-07-16 02:11:22 +00001738void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00001739 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00001740 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
1741 getLocationOfByte(startPos),
1742 /*IsStringLocation*/true,
1743 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00001744}
1745
Ted Kremenek02087932010-07-16 02:11:22 +00001746void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00001747 if (!IsObjCLiteral) {
1748 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00001749 EmitFormatDiagnostic(
1750 S.PDiag(diag::warn_printf_format_string_contains_null_char),
1751 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
1752 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00001753 }
Ted Kremenek02087932010-07-16 02:11:22 +00001754}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001755
Ted Kremenek02087932010-07-16 02:11:22 +00001756const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001757 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00001758}
1759
1760void CheckFormatHandler::DoneProcessing() {
1761 // Does the number of data arguments exceed the number of
1762 // format conversions in the format string?
1763 if (!HasVAListArg) {
1764 // Find any arguments that weren't covered.
1765 CoveredArgs.flip();
1766 signed notCoveredArg = CoveredArgs.find_first();
1767 if (notCoveredArg >= 0) {
1768 assert((unsigned)notCoveredArg < NumDataArgs);
Richard Trieu03cf7b72011-10-28 00:41:25 +00001769 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
1770 getDataArg((unsigned) notCoveredArg)->getLocStart(),
1771 /*IsStringLocation*/false, getFormatStringRange());
Ted Kremenek02087932010-07-16 02:11:22 +00001772 }
1773 }
1774}
1775
Ted Kremenekce815422010-07-19 21:25:57 +00001776bool
1777CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
1778 SourceLocation Loc,
1779 const char *startSpec,
1780 unsigned specifierLen,
1781 const char *csStart,
1782 unsigned csLen) {
1783
1784 bool keepGoing = true;
1785 if (argIndex < NumDataArgs) {
1786 // Consider the argument coverered, even though the specifier doesn't
1787 // make sense.
1788 CoveredArgs.set(argIndex);
1789 }
1790 else {
1791 // If argIndex exceeds the number of data arguments we
1792 // don't issue a warning because that is just a cascade of warnings (and
1793 // they may have intended '%%' anyway). We don't want to continue processing
1794 // the format string after this point, however, as we will like just get
1795 // gibberish when trying to match arguments.
1796 keepGoing = false;
1797 }
1798
Richard Trieu03cf7b72011-10-28 00:41:25 +00001799 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
1800 << StringRef(csStart, csLen),
1801 Loc, /*IsStringLocation*/true,
1802 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekce815422010-07-19 21:25:57 +00001803
1804 return keepGoing;
1805}
1806
Richard Trieu03cf7b72011-10-28 00:41:25 +00001807void
1808CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
1809 const char *startSpec,
1810 unsigned specifierLen) {
1811 EmitFormatDiagnostic(
1812 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
1813 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
1814}
1815
Ted Kremenek6adb7e32010-07-26 19:45:42 +00001816bool
1817CheckFormatHandler::CheckNumArgs(
1818 const analyze_format_string::FormatSpecifier &FS,
1819 const analyze_format_string::ConversionSpecifier &CS,
1820 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
1821
1822 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00001823 PartialDiagnostic PDiag = FS.usesPositionalArg()
1824 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
1825 << (argIndex+1) << NumDataArgs)
1826 : S.PDiag(diag::warn_printf_insufficient_data_args);
1827 EmitFormatDiagnostic(
1828 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
1829 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek6adb7e32010-07-26 19:45:42 +00001830 return false;
1831 }
1832 return true;
1833}
1834
Richard Trieu03cf7b72011-10-28 00:41:25 +00001835template<typename Range>
1836void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
1837 SourceLocation Loc,
1838 bool IsStringLocation,
1839 Range StringRange,
1840 FixItHint FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001841 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00001842 Loc, IsStringLocation, StringRange, FixIt);
1843}
1844
1845/// \brief If the format string is not within the funcion call, emit a note
1846/// so that the function call and string are in diagnostic messages.
1847///
1848/// \param inFunctionCall if true, the format string is within the function
1849/// call and only one diagnostic message will be produced. Otherwise, an
1850/// extra note will be emitted pointing to location of the format string.
1851///
1852/// \param ArgumentExpr the expression that is passed as the format string
1853/// argument in the function call. Used for getting locations when two
1854/// diagnostics are emitted.
1855///
1856/// \param PDiag the callee should already have provided any strings for the
1857/// diagnostic message. This function only adds locations and fixits
1858/// to diagnostics.
1859///
1860/// \param Loc primary location for diagnostic. If two diagnostics are
1861/// required, one will be at Loc and a new SourceLocation will be created for
1862/// the other one.
1863///
1864/// \param IsStringLocation if true, Loc points to the format string should be
1865/// used for the note. Otherwise, Loc points to the argument list and will
1866/// be used with PDiag.
1867///
1868/// \param StringRange some or all of the string to highlight. This is
1869/// templated so it can accept either a CharSourceRange or a SourceRange.
1870///
1871/// \param Fixit optional fix it hint for the format string.
1872template<typename Range>
1873void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
1874 const Expr *ArgumentExpr,
1875 PartialDiagnostic PDiag,
1876 SourceLocation Loc,
1877 bool IsStringLocation,
1878 Range StringRange,
1879 FixItHint FixIt) {
1880 if (InFunctionCall)
1881 S.Diag(Loc, PDiag) << StringRange << FixIt;
1882 else {
1883 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
1884 << ArgumentExpr->getSourceRange();
1885 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
1886 diag::note_format_string_defined)
1887 << StringRange << FixIt;
1888 }
1889}
1890
Ted Kremenek02087932010-07-16 02:11:22 +00001891//===--- CHECK: Printf format string checking ------------------------------===//
1892
1893namespace {
1894class CheckPrintfHandler : public CheckFormatHandler {
1895public:
1896 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
1897 const Expr *origFormatExpr, unsigned firstDataArg,
1898 unsigned numDataArgs, bool isObjCLiteral,
1899 const char *beg, bool hasVAListArg,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001900 Expr **Args, unsigned NumArgs,
1901 unsigned formatIdx, bool inFunctionCall)
Ted Kremenek02087932010-07-16 02:11:22 +00001902 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1903 numDataArgs, isObjCLiteral, beg, hasVAListArg,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001904 Args, NumArgs, formatIdx, inFunctionCall) {}
Ted Kremenek02087932010-07-16 02:11:22 +00001905
1906
1907 bool HandleInvalidPrintfConversionSpecifier(
1908 const analyze_printf::PrintfSpecifier &FS,
1909 const char *startSpecifier,
1910 unsigned specifierLen);
1911
1912 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
1913 const char *startSpecifier,
1914 unsigned specifierLen);
1915
1916 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
1917 const char *startSpecifier, unsigned specifierLen);
1918 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
1919 const analyze_printf::OptionalAmount &Amt,
1920 unsigned type,
1921 const char *startSpecifier, unsigned specifierLen);
1922 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
1923 const analyze_printf::OptionalFlag &flag,
1924 const char *startSpecifier, unsigned specifierLen);
1925 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
1926 const analyze_printf::OptionalFlag &ignoredFlag,
1927 const analyze_printf::OptionalFlag &flag,
1928 const char *startSpecifier, unsigned specifierLen);
1929};
1930}
1931
1932bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
1933 const analyze_printf::PrintfSpecifier &FS,
1934 const char *startSpecifier,
1935 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00001936 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00001937 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00001938
Ted Kremenekce815422010-07-19 21:25:57 +00001939 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1940 getLocationOfByte(CS.getStart()),
1941 startSpecifier, specifierLen,
1942 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00001943}
1944
Ted Kremenek02087932010-07-16 02:11:22 +00001945bool CheckPrintfHandler::HandleAmount(
1946 const analyze_format_string::OptionalAmount &Amt,
1947 unsigned k, const char *startSpecifier,
1948 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00001949
1950 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00001951 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00001952 unsigned argIndex = Amt.getArgIndex();
1953 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00001954 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
1955 << k,
1956 getLocationOfByte(Amt.getStart()),
1957 /*IsStringLocation*/true,
1958 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00001959 // Don't do any more checking. We will just emit
1960 // spurious errors.
1961 return false;
1962 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001963
Ted Kremenek5739de72010-01-29 01:06:55 +00001964 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00001965 // Although not in conformance with C99, we also allow the argument to be
1966 // an 'unsigned int' as that is a reasonably safe case. GCC also
1967 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00001968 CoveredArgs.set(argIndex);
1969 const Expr *Arg = getDataArg(argIndex);
Ted Kremenek5739de72010-01-29 01:06:55 +00001970 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001971
1972 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
1973 assert(ATR.isValid());
1974
1975 if (!ATR.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00001976 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborg772e9272011-12-07 10:33:11 +00001977 << k << ATR.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00001978 << T << Arg->getSourceRange(),
1979 getLocationOfByte(Amt.getStart()),
1980 /*IsStringLocation*/true,
1981 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00001982 // Don't do any more checking. We will just emit
1983 // spurious errors.
1984 return false;
1985 }
1986 }
1987 }
1988 return true;
1989}
Ted Kremenek5739de72010-01-29 01:06:55 +00001990
Tom Careb49ec692010-06-17 19:00:27 +00001991void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00001992 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00001993 const analyze_printf::OptionalAmount &Amt,
1994 unsigned type,
1995 const char *startSpecifier,
1996 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00001997 const analyze_printf::PrintfConversionSpecifier &CS =
1998 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00001999
Richard Trieu03cf7b72011-10-28 00:41:25 +00002000 FixItHint fixit =
2001 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2002 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2003 Amt.getConstantLength()))
2004 : FixItHint();
2005
2006 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2007 << type << CS.toString(),
2008 getLocationOfByte(Amt.getStart()),
2009 /*IsStringLocation*/true,
2010 getSpecifierRange(startSpecifier, specifierLen),
2011 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00002012}
2013
Ted Kremenek02087932010-07-16 02:11:22 +00002014void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002015 const analyze_printf::OptionalFlag &flag,
2016 const char *startSpecifier,
2017 unsigned specifierLen) {
2018 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002019 const analyze_printf::PrintfConversionSpecifier &CS =
2020 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00002021 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2022 << flag.toString() << CS.toString(),
2023 getLocationOfByte(flag.getPosition()),
2024 /*IsStringLocation*/true,
2025 getSpecifierRange(startSpecifier, specifierLen),
2026 FixItHint::CreateRemoval(
2027 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00002028}
2029
2030void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00002031 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002032 const analyze_printf::OptionalFlag &ignoredFlag,
2033 const analyze_printf::OptionalFlag &flag,
2034 const char *startSpecifier,
2035 unsigned specifierLen) {
2036 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002037 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2038 << ignoredFlag.toString() << flag.toString(),
2039 getLocationOfByte(ignoredFlag.getPosition()),
2040 /*IsStringLocation*/true,
2041 getSpecifierRange(startSpecifier, specifierLen),
2042 FixItHint::CreateRemoval(
2043 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00002044}
2045
Ted Kremenekab278de2010-01-28 23:39:18 +00002046bool
Ted Kremenek02087932010-07-16 02:11:22 +00002047CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00002048 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00002049 const char *startSpecifier,
2050 unsigned specifierLen) {
2051
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002052 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00002053 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002054 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00002055
Ted Kremenek6cd69422010-07-19 22:01:06 +00002056 if (FS.consumesDataArgument()) {
2057 if (atFirstArg) {
2058 atFirstArg = false;
2059 usesPositionalArgs = FS.usesPositionalArg();
2060 }
2061 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002062 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2063 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00002064 return false;
2065 }
Ted Kremenek5739de72010-01-29 01:06:55 +00002066 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002067
Ted Kremenekd1668192010-02-27 01:41:03 +00002068 // First check if the field width, precision, and conversion specifier
2069 // have matching data arguments.
2070 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2071 startSpecifier, specifierLen)) {
2072 return false;
2073 }
2074
2075 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2076 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00002077 return false;
2078 }
2079
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002080 if (!CS.consumesDataArgument()) {
2081 // FIXME: Technically specifying a precision or field width here
2082 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00002083 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002084 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002085
Ted Kremenek4a49d982010-02-26 19:18:41 +00002086 // Consume the argument.
2087 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00002088 if (argIndex < NumDataArgs) {
2089 // The check to see if the argIndex is valid will come later.
2090 // We set the bit here because we may exit early from this
2091 // function if we encounter some other error.
2092 CoveredArgs.set(argIndex);
2093 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00002094
2095 // Check for using an Objective-C specific conversion specifier
2096 // in a non-ObjC literal.
2097 if (!IsObjCLiteral && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00002098 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
2099 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00002100 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002101
Tom Careb49ec692010-06-17 19:00:27 +00002102 // Check for invalid use of field width
2103 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00002104 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00002105 startSpecifier, specifierLen);
2106 }
2107
2108 // Check for invalid use of precision
2109 if (!FS.hasValidPrecision()) {
2110 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
2111 startSpecifier, specifierLen);
2112 }
2113
2114 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00002115 if (!FS.hasValidThousandsGroupingPrefix())
2116 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00002117 if (!FS.hasValidLeadingZeros())
2118 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
2119 if (!FS.hasValidPlusPrefix())
2120 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00002121 if (!FS.hasValidSpacePrefix())
2122 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00002123 if (!FS.hasValidAlternativeForm())
2124 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
2125 if (!FS.hasValidLeftJustified())
2126 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
2127
2128 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00002129 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
2130 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
2131 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00002132 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
2133 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
2134 startSpecifier, specifierLen);
2135
2136 // Check the length modifier is valid with the given conversion specifier.
2137 const LengthModifier &LM = FS.getLengthModifier();
2138 if (!FS.hasValidLengthModifier())
Richard Trieu03cf7b72011-10-28 00:41:25 +00002139 EmitFormatDiagnostic(S.PDiag(diag::warn_format_nonsensical_length)
2140 << LM.toString() << CS.toString(),
2141 getLocationOfByte(LM.getStart()),
2142 /*IsStringLocation*/true,
2143 getSpecifierRange(startSpecifier, specifierLen),
2144 FixItHint::CreateRemoval(
2145 getSpecifierRange(LM.getStart(),
2146 LM.getLength())));
Tom Careb49ec692010-06-17 19:00:27 +00002147
2148 // Are we using '%n'?
Ted Kremenek516ef222010-07-20 20:04:10 +00002149 if (CS.getKind() == ConversionSpecifier::nArg) {
Tom Careb49ec692010-06-17 19:00:27 +00002150 // Issue a warning about this being a possible security issue.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002151 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_write_back),
2152 getLocationOfByte(CS.getStart()),
2153 /*IsStringLocation*/true,
2154 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekd5fd0fa2010-01-29 01:35:25 +00002155 // Continue checking the other format specifiers.
2156 return true;
2157 }
Ted Kremenekd31b2632010-02-11 09:27:41 +00002158
Ted Kremenek9fcd8302010-01-29 01:43:31 +00002159 // The remaining checks depend on the data arguments.
2160 if (HasVAListArg)
2161 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002162
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002163 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00002164 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002165
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00002166 // Now type check the data expression that matches the
2167 // format specifier.
2168 const Expr *Ex = getDataArg(argIndex);
Nico Weber496cdc22012-01-31 01:43:25 +00002169 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context,
2170 IsObjCLiteral);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00002171 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
2172 // Check if we didn't match because of an implicit cast from a 'char'
2173 // or 'short' to an 'int'. This is done because printf is a varargs
2174 // function.
2175 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
Ted Kremenek12a37de2010-10-21 04:00:58 +00002176 if (ICE->getType() == S.Context.IntTy) {
2177 // All further checking is done on the subexpression.
2178 Ex = ICE->getSubExpr();
2179 if (ATR.matchesType(S.Context, Ex->getType()))
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00002180 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00002181 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00002182
2183 // We may be able to offer a FixItHint if it is a supported type.
2184 PrintfSpecifier fixedFS = FS;
Hans Wennborgf99d04f2011-10-18 08:10:06 +00002185 bool success = fixedFS.fixType(Ex->getType(), S.getLangOptions());
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00002186
2187 if (success) {
2188 // Get the fix string from the fixed format specifier
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002189 SmallString<128> buf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00002190 llvm::raw_svector_ostream os(buf);
2191 fixedFS.toString(os);
2192
Richard Trieu03cf7b72011-10-28 00:41:25 +00002193 EmitFormatDiagnostic(
2194 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg772e9272011-12-07 10:33:11 +00002195 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
Richard Trieu03cf7b72011-10-28 00:41:25 +00002196 << Ex->getSourceRange(),
2197 getLocationOfByte(CS.getStart()),
2198 /*IsStringLocation*/true,
2199 getSpecifierRange(startSpecifier, specifierLen),
2200 FixItHint::CreateReplacement(
2201 getSpecifierRange(startSpecifier, specifierLen),
2202 os.str()));
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00002203 }
2204 else {
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00002205 EmitFormatDiagnostic(
2206 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2207 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
2208 << getSpecifierRange(startSpecifier, specifierLen)
2209 << Ex->getSourceRange(),
2210 getLocationOfByte(CS.getStart()),
2211 true,
2212 getSpecifierRange(startSpecifier, specifierLen));
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00002213 }
2214 }
2215
Ted Kremenekab278de2010-01-28 23:39:18 +00002216 return true;
2217}
2218
Ted Kremenek02087932010-07-16 02:11:22 +00002219//===--- CHECK: Scanf format string checking ------------------------------===//
2220
2221namespace {
2222class CheckScanfHandler : public CheckFormatHandler {
2223public:
2224 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
2225 const Expr *origFormatExpr, unsigned firstDataArg,
2226 unsigned numDataArgs, bool isObjCLiteral,
2227 const char *beg, bool hasVAListArg,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002228 Expr **Args, unsigned NumArgs,
2229 unsigned formatIdx, bool inFunctionCall)
Ted Kremenek02087932010-07-16 02:11:22 +00002230 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2231 numDataArgs, isObjCLiteral, beg, hasVAListArg,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002232 Args, NumArgs, formatIdx, inFunctionCall) {}
Ted Kremenek02087932010-07-16 02:11:22 +00002233
2234 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
2235 const char *startSpecifier,
2236 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00002237
2238 bool HandleInvalidScanfConversionSpecifier(
2239 const analyze_scanf::ScanfSpecifier &FS,
2240 const char *startSpecifier,
2241 unsigned specifierLen);
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00002242
2243 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek02087932010-07-16 02:11:22 +00002244};
Ted Kremenek019d2242010-01-29 01:50:07 +00002245}
Ted Kremenekab278de2010-01-28 23:39:18 +00002246
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00002247void CheckScanfHandler::HandleIncompleteScanList(const char *start,
2248 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002249 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
2250 getLocationOfByte(end), /*IsStringLocation*/true,
2251 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00002252}
2253
Ted Kremenekce815422010-07-19 21:25:57 +00002254bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
2255 const analyze_scanf::ScanfSpecifier &FS,
2256 const char *startSpecifier,
2257 unsigned specifierLen) {
2258
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002259 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00002260 FS.getConversionSpecifier();
2261
2262 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2263 getLocationOfByte(CS.getStart()),
2264 startSpecifier, specifierLen,
2265 CS.getStart(), CS.getLength());
2266}
2267
Ted Kremenek02087932010-07-16 02:11:22 +00002268bool CheckScanfHandler::HandleScanfSpecifier(
2269 const analyze_scanf::ScanfSpecifier &FS,
2270 const char *startSpecifier,
2271 unsigned specifierLen) {
2272
2273 using namespace analyze_scanf;
2274 using namespace analyze_format_string;
2275
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002276 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00002277
Ted Kremenek6cd69422010-07-19 22:01:06 +00002278 // Handle case where '%' and '*' don't consume an argument. These shouldn't
2279 // be used to decide if we are using positional arguments consistently.
2280 if (FS.consumesDataArgument()) {
2281 if (atFirstArg) {
2282 atFirstArg = false;
2283 usesPositionalArgs = FS.usesPositionalArg();
2284 }
2285 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002286 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2287 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00002288 return false;
2289 }
Ted Kremenek02087932010-07-16 02:11:22 +00002290 }
2291
2292 // Check if the field with is non-zero.
2293 const OptionalAmount &Amt = FS.getFieldWidth();
2294 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
2295 if (Amt.getConstantAmount() == 0) {
2296 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
2297 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00002298 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
2299 getLocationOfByte(Amt.getStart()),
2300 /*IsStringLocation*/true, R,
2301 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00002302 }
2303 }
2304
2305 if (!FS.consumesDataArgument()) {
2306 // FIXME: Technically specifying a precision or field width here
2307 // makes no sense. Worth issuing a warning at some point.
2308 return true;
2309 }
2310
2311 // Consume the argument.
2312 unsigned argIndex = FS.getArgIndex();
2313 if (argIndex < NumDataArgs) {
2314 // The check to see if the argIndex is valid will come later.
2315 // We set the bit here because we may exit early from this
2316 // function if we encounter some other error.
2317 CoveredArgs.set(argIndex);
2318 }
2319
Ted Kremenek4407ea42010-07-20 20:04:47 +00002320 // Check the length modifier is valid with the given conversion specifier.
2321 const LengthModifier &LM = FS.getLengthModifier();
2322 if (!FS.hasValidLengthModifier()) {
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00002323 const CharSourceRange &R = getSpecifierRange(LM.getStart(), LM.getLength());
2324 EmitFormatDiagnostic(S.PDiag(diag::warn_format_nonsensical_length)
2325 << LM.toString() << CS.toString()
2326 << getSpecifierRange(startSpecifier, specifierLen),
2327 getLocationOfByte(LM.getStart()),
2328 /*IsStringLocation*/true, R,
2329 FixItHint::CreateRemoval(R));
Ted Kremenek4407ea42010-07-20 20:04:47 +00002330 }
2331
Ted Kremenek02087932010-07-16 02:11:22 +00002332 // The remaining checks depend on the data arguments.
2333 if (HasVAListArg)
2334 return true;
2335
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002336 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00002337 return false;
Ted Kremenek02087932010-07-16 02:11:22 +00002338
Hans Wennborgb1a5e092011-12-10 13:20:11 +00002339 // Check that the argument type matches the format specifier.
2340 const Expr *Ex = getDataArg(argIndex);
2341 const analyze_scanf::ScanfArgTypeResult &ATR = FS.getArgType(S.Context);
2342 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
2343 ScanfSpecifier fixedFS = FS;
2344 bool success = fixedFS.fixType(Ex->getType(), S.getLangOptions());
2345
2346 if (success) {
2347 // Get the fix string from the fixed format specifier.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002348 SmallString<128> buf;
Hans Wennborgb1a5e092011-12-10 13:20:11 +00002349 llvm::raw_svector_ostream os(buf);
2350 fixedFS.toString(os);
2351
2352 EmitFormatDiagnostic(
2353 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2354 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
2355 << Ex->getSourceRange(),
2356 getLocationOfByte(CS.getStart()),
2357 /*IsStringLocation*/true,
2358 getSpecifierRange(startSpecifier, specifierLen),
2359 FixItHint::CreateReplacement(
2360 getSpecifierRange(startSpecifier, specifierLen),
2361 os.str()));
2362 } else {
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00002363 EmitFormatDiagnostic(
2364 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborgb1a5e092011-12-10 13:20:11 +00002365 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00002366 << Ex->getSourceRange(),
2367 getLocationOfByte(CS.getStart()),
2368 /*IsStringLocation*/true,
2369 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00002370 }
2371 }
2372
Ted Kremenek02087932010-07-16 02:11:22 +00002373 return true;
2374}
2375
2376void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenekfb45d352010-02-10 02:16:30 +00002377 const Expr *OrigFormatExpr,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002378 Expr **Args, unsigned NumArgs,
2379 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002380 unsigned firstDataArg, FormatStringType Type,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002381 bool inFunctionCall) {
Ted Kremenek02087932010-07-16 02:11:22 +00002382
Ted Kremenekab278de2010-01-28 23:39:18 +00002383 // CHECK: is the format string a wide literal?
Douglas Gregorfb65e592011-07-27 05:40:30 +00002384 if (!FExpr->isAscii()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002385 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002386 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00002387 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
2388 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00002389 return;
2390 }
Ted Kremenek02087932010-07-16 02:11:22 +00002391
Ted Kremenekab278de2010-01-28 23:39:18 +00002392 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002393 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00002394 const char *Str = StrRef.data();
2395 unsigned StrLen = StrRef.size();
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002396 const unsigned numDataArgs = NumArgs - firstDataArg;
Ted Kremenek02087932010-07-16 02:11:22 +00002397
Ted Kremenekab278de2010-01-28 23:39:18 +00002398 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00002399 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002400 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002401 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00002402 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
2403 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00002404 return;
2405 }
Ted Kremenek02087932010-07-16 02:11:22 +00002406
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002407 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek02087932010-07-16 02:11:22 +00002408 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Ted Kremenek6e302b22011-09-29 05:52:16 +00002409 numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr),
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002410 Str, HasVAListArg, Args, NumArgs, format_idx,
Richard Trieu03cf7b72011-10-28 00:41:25 +00002411 inFunctionCall);
Ted Kremenek02087932010-07-16 02:11:22 +00002412
Hans Wennborg23926bd2011-12-15 10:25:47 +00002413 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
2414 getLangOptions()))
Ted Kremenek02087932010-07-16 02:11:22 +00002415 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002416 } else if (Type == FST_Scanf) {
Ted Kremenek02087932010-07-16 02:11:22 +00002417 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Ted Kremenek6e302b22011-09-29 05:52:16 +00002418 numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr),
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002419 Str, HasVAListArg, Args, NumArgs, format_idx,
Richard Trieu03cf7b72011-10-28 00:41:25 +00002420 inFunctionCall);
Ted Kremenek02087932010-07-16 02:11:22 +00002421
Hans Wennborg23926bd2011-12-15 10:25:47 +00002422 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
2423 getLangOptions()))
Ted Kremenek02087932010-07-16 02:11:22 +00002424 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002425 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00002426}
2427
Chandler Carruth53caa4d2011-04-27 07:05:31 +00002428//===--- CHECK: Standard memory functions ---------------------------------===//
2429
Douglas Gregora74926b2011-05-03 20:05:22 +00002430/// \brief Determine whether the given type is a dynamic class type (e.g.,
2431/// whether it has a vtable).
2432static bool isDynamicClassType(QualType T) {
2433 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
2434 if (CXXRecordDecl *Definition = Record->getDefinition())
2435 if (Definition->isDynamicClass())
2436 return true;
2437
2438 return false;
2439}
2440
Chandler Carruth889ed862011-06-21 23:04:20 +00002441/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00002442/// otherwise returns NULL.
2443static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Weberc5e73862011-06-14 16:14:58 +00002444 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00002445 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2446 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
2447 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00002448
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00002449 return 0;
2450}
2451
Chandler Carruth889ed862011-06-21 23:04:20 +00002452/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00002453static QualType getSizeOfArgType(const Expr* E) {
2454 if (const UnaryExprOrTypeTraitExpr *SizeOf =
2455 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2456 if (SizeOf->getKind() == clang::UETT_SizeOf)
2457 return SizeOf->getTypeOfArgument();
2458
2459 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00002460}
2461
Chandler Carruth53caa4d2011-04-27 07:05:31 +00002462/// \brief Check for dangerous or invalid arguments to memset().
2463///
Chandler Carruthac687262011-06-03 06:23:57 +00002464/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00002465/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
2466/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00002467///
2468/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00002469void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00002470 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00002471 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00002472 assert(BId != 0);
2473
Ted Kremenekb5fabb22011-04-28 01:38:02 +00002474 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00002475 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00002476 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00002477 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00002478 return;
2479
Anna Zaks22122702012-01-17 00:37:07 +00002480 unsigned LastArg = (BId == Builtin::BImemset ||
2481 BId == Builtin::BIstrndup ? 1 : 2);
2482 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00002483 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00002484
2485 // We have special checking when the length is a sizeof expression.
2486 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
2487 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
2488 llvm::FoldingSetNodeID SizeOfArgID;
2489
Douglas Gregor3bb2a812011-05-03 20:37:33 +00002490 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
2491 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00002492 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00002493
Douglas Gregor3bb2a812011-05-03 20:37:33 +00002494 QualType DestTy = Dest->getType();
2495 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
2496 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00002497
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00002498 // Never warn about void type pointers. This can be used to suppress
2499 // false positives.
2500 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00002501 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00002502
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00002503 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
2504 // actually comparing the expressions for equality. Because computing the
2505 // expression IDs can be expensive, we only do this if the diagnostic is
2506 // enabled.
2507 if (SizeOfArg &&
2508 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
2509 SizeOfArg->getExprLoc())) {
2510 // We only compute IDs for expressions if the warning is enabled, and
2511 // cache the sizeof arg's ID.
2512 if (SizeOfArgID == llvm::FoldingSetNodeID())
2513 SizeOfArg->Profile(SizeOfArgID, Context, true);
2514 llvm::FoldingSetNodeID DestID;
2515 Dest->Profile(DestID, Context, true);
2516 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00002517 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
2518 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00002519 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
2520 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
2521 if (UnaryOp->getOpcode() == UO_AddrOf)
2522 ActionIdx = 1; // If its an address-of operator, just remove it.
2523 if (Context.getTypeSize(PointeeTy) == Context.getCharWidth())
2524 ActionIdx = 2; // If the pointee's size is sizeof(char),
2525 // suggest an explicit length.
Anna Zaks201d4892012-01-13 21:52:01 +00002526 unsigned DestSrcSelect =
Anna Zaks22122702012-01-17 00:37:07 +00002527 (BId == Builtin::BIstrndup ? 1 : ArgIdx);
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00002528 DiagRuntimeBehavior(SizeOfArg->getExprLoc(), Dest,
2529 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Nico Weber39bfed82011-10-13 22:30:23 +00002530 << FnName << DestSrcSelect << ActionIdx
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00002531 << Dest->getSourceRange()
2532 << SizeOfArg->getSourceRange());
2533 break;
2534 }
2535 }
2536
2537 // Also check for cases where the sizeof argument is the exact same
2538 // type as the memory argument, and where it points to a user-defined
2539 // record type.
2540 if (SizeOfArgTy != QualType()) {
2541 if (PointeeTy->isRecordType() &&
2542 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
2543 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
2544 PDiag(diag::warn_sizeof_pointer_type_memaccess)
2545 << FnName << SizeOfArgTy << ArgIdx
2546 << PointeeTy << Dest->getSourceRange()
2547 << LenExpr->getSourceRange());
2548 break;
2549 }
Nico Weberc5e73862011-06-14 16:14:58 +00002550 }
2551
Douglas Gregor3bb2a812011-05-03 20:37:33 +00002552 // Always complain about dynamic classes.
Anna Zaks22122702012-01-17 00:37:07 +00002553 if (isDynamicClassType(PointeeTy)) {
2554
2555 unsigned OperationType = 0;
2556 // "overwritten" if we're warning about the destination for any call
2557 // but memcmp; otherwise a verb appropriate to the call.
2558 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
2559 if (BId == Builtin::BImemcpy)
2560 OperationType = 1;
2561 else if(BId == Builtin::BImemmove)
2562 OperationType = 2;
2563 else if (BId == Builtin::BImemcmp)
2564 OperationType = 3;
2565 }
2566
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00002567 DiagRuntimeBehavior(
2568 Dest->getExprLoc(), Dest,
2569 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks22122702012-01-17 00:37:07 +00002570 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Anna Zaks201d4892012-01-13 21:52:01 +00002571 << FnName << PointeeTy
Anna Zaks22122702012-01-17 00:37:07 +00002572 << OperationType
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00002573 << Call->getCallee()->getSourceRange());
Anna Zaks22122702012-01-17 00:37:07 +00002574 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
2575 BId != Builtin::BImemset)
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00002576 DiagRuntimeBehavior(
2577 Dest->getExprLoc(), Dest,
2578 PDiag(diag::warn_arc_object_memaccess)
2579 << ArgIdx << FnName << PointeeTy
2580 << Call->getCallee()->getSourceRange());
John McCall31168b02011-06-15 23:02:42 +00002581 else
Douglas Gregor3bb2a812011-05-03 20:37:33 +00002582 continue;
John McCall31168b02011-06-15 23:02:42 +00002583
2584 DiagRuntimeBehavior(
2585 Dest->getExprLoc(), Dest,
Chandler Carruthac687262011-06-03 06:23:57 +00002586 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor3bb2a812011-05-03 20:37:33 +00002587 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
2588 break;
2589 }
Chandler Carruth53caa4d2011-04-27 07:05:31 +00002590 }
2591}
2592
Ted Kremenek6865f772011-08-18 20:55:45 +00002593// A little helper routine: ignore addition and subtraction of integer literals.
2594// This intentionally does not ignore all integer constant expressions because
2595// we don't want to remove sizeof().
2596static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
2597 Ex = Ex->IgnoreParenCasts();
2598
2599 for (;;) {
2600 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
2601 if (!BO || !BO->isAdditiveOp())
2602 break;
2603
2604 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
2605 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
2606
2607 if (isa<IntegerLiteral>(RHS))
2608 Ex = LHS;
2609 else if (isa<IntegerLiteral>(LHS))
2610 Ex = RHS;
2611 else
2612 break;
2613 }
2614
2615 return Ex;
2616}
2617
2618// Warn if the user has made the 'size' argument to strlcpy or strlcat
2619// be the size of the source, instead of the destination.
2620void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
2621 IdentifierInfo *FnName) {
2622
2623 // Don't crash if the user has the wrong number of arguments
2624 if (Call->getNumArgs() != 3)
2625 return;
2626
2627 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
2628 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
2629 const Expr *CompareWithSrc = NULL;
2630
2631 // Look for 'strlcpy(dst, x, sizeof(x))'
2632 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
2633 CompareWithSrc = Ex;
2634 else {
2635 // Look for 'strlcpy(dst, x, strlen(x))'
2636 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Richard Smithd62306a2011-11-10 06:34:14 +00002637 if (SizeCall->isBuiltinCall() == Builtin::BIstrlen
Ted Kremenek6865f772011-08-18 20:55:45 +00002638 && SizeCall->getNumArgs() == 1)
2639 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
2640 }
2641 }
2642
2643 if (!CompareWithSrc)
2644 return;
2645
2646 // Determine if the argument to sizeof/strlen is equal to the source
2647 // argument. In principle there's all kinds of things you could do
2648 // here, for instance creating an == expression and evaluating it with
2649 // EvaluateAsBooleanCondition, but this uses a more direct technique:
2650 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
2651 if (!SrcArgDRE)
2652 return;
2653
2654 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
2655 if (!CompareWithSrcDRE ||
2656 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
2657 return;
2658
2659 const Expr *OriginalSizeArg = Call->getArg(2);
2660 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
2661 << OriginalSizeArg->getSourceRange() << FnName;
2662
2663 // Output a FIXIT hint if the destination is an array (rather than a
2664 // pointer to an array). This could be enhanced to handle some
2665 // pointers if we know the actual size, like if DstArg is 'array+2'
2666 // we could say 'sizeof(array)-2'.
2667 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Ted Kremenek18db5d42011-08-18 22:48:41 +00002668 QualType DstArgTy = DstArg->getType();
Ted Kremenek6865f772011-08-18 20:55:45 +00002669
Ted Kremenek18db5d42011-08-18 22:48:41 +00002670 // Only handle constant-sized or VLAs, but not flexible members.
2671 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(DstArgTy)) {
2672 // Only issue the FIXIT for arrays of size > 1.
2673 if (CAT->getSize().getSExtValue() <= 1)
2674 return;
2675 } else if (!DstArgTy->isVariableArrayType()) {
2676 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00002677 }
Ted Kremenek18db5d42011-08-18 22:48:41 +00002678
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002679 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00002680 llvm::raw_svector_ostream OS(sizeString);
2681 OS << "sizeof(";
Douglas Gregor75acd922011-09-27 23:30:47 +00002682 DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00002683 OS << ")";
2684
2685 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
2686 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
2687 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00002688}
2689
Anna Zaks314cd092012-02-01 19:08:57 +00002690/// Check if two expressions refer to the same declaration.
2691static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
2692 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
2693 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
2694 return D1->getDecl() == D2->getDecl();
2695 return false;
2696}
2697
2698static const Expr *getStrlenExprArg(const Expr *E) {
2699 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
2700 const FunctionDecl *FD = CE->getDirectCallee();
2701 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
2702 return 0;
2703 return CE->getArg(0)->IgnoreParenCasts();
2704 }
2705 return 0;
2706}
2707
2708// Warn on anti-patterns as the 'size' argument to strncat.
2709// The correct size argument should look like following:
2710// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
2711void Sema::CheckStrncatArguments(const CallExpr *CE,
2712 IdentifierInfo *FnName) {
2713 // Don't crash if the user has the wrong number of arguments.
2714 if (CE->getNumArgs() < 3)
2715 return;
2716 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
2717 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
2718 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
2719
2720 // Identify common expressions, which are wrongly used as the size argument
2721 // to strncat and may lead to buffer overflows.
2722 unsigned PatternType = 0;
2723 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
2724 // - sizeof(dst)
2725 if (referToTheSameDecl(SizeOfArg, DstArg))
2726 PatternType = 1;
2727 // - sizeof(src)
2728 else if (referToTheSameDecl(SizeOfArg, SrcArg))
2729 PatternType = 2;
2730 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
2731 if (BE->getOpcode() == BO_Sub) {
2732 const Expr *L = BE->getLHS()->IgnoreParenCasts();
2733 const Expr *R = BE->getRHS()->IgnoreParenCasts();
2734 // - sizeof(dst) - strlen(dst)
2735 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
2736 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
2737 PatternType = 1;
2738 // - sizeof(src) - (anything)
2739 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
2740 PatternType = 2;
2741 }
2742 }
2743
2744 if (PatternType == 0)
2745 return;
2746
Anna Zaks5069aa32012-02-03 01:27:37 +00002747 // Generate the diagnostic.
2748 SourceLocation SL = LenArg->getLocStart();
2749 SourceRange SR = LenArg->getSourceRange();
2750 SourceManager &SM = PP.getSourceManager();
2751
2752 // If the function is defined as a builtin macro, do not show macro expansion.
2753 if (SM.isMacroArgExpansion(SL)) {
2754 SL = SM.getSpellingLoc(SL);
2755 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
2756 SM.getSpellingLoc(SR.getEnd()));
2757 }
2758
Anna Zaks314cd092012-02-01 19:08:57 +00002759 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00002760 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00002761 else
Anna Zaks5069aa32012-02-03 01:27:37 +00002762 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00002763
2764 // Output a FIXIT hint if the destination is an array (rather than a
2765 // pointer to an array). This could be enhanced to handle some
2766 // pointers if we know the actual size, like if DstArg is 'array+2'
2767 // we could say 'sizeof(array)-2'.
2768 QualType DstArgTy = DstArg->getType();
2769
2770 // Only handle constant-sized or VLAs, but not flexible members.
2771 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(DstArgTy)) {
2772 // Only issue the FIXIT for arrays of size > 1.
2773 if (CAT->getSize().getSExtValue() <= 1)
2774 return;
2775 } else if (!DstArgTy->isVariableArrayType()) {
2776 return;
2777 }
2778
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002779 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00002780 llvm::raw_svector_ostream OS(sizeString);
2781 OS << "sizeof(";
2782 DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
2783 OS << ") - ";
2784 OS << "strlen(";
2785 DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
2786 OS << ") - 1";
2787
Anna Zaks5069aa32012-02-03 01:27:37 +00002788 Diag(SL, diag::note_strncat_wrong_size)
2789 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00002790}
2791
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002792//===--- CHECK: Return Address of Stack Variable --------------------------===//
2793
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002794static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars);
2795static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002796
2797/// CheckReturnStackAddr - Check if a return statement returns the address
2798/// of a stack variable.
2799void
2800Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
2801 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00002802
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002803 Expr *stackE = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002804 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002805
2806 // Perform checking for returned stack addresses, local blocks,
2807 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00002808 if (lhsType->isPointerType() ||
2809 (!getLangOptions().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002810 stackE = EvalAddr(RetValExp, refVars);
Mike Stump12b8ce12009-08-04 21:02:39 +00002811 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002812 stackE = EvalVal(RetValExp, refVars);
2813 }
2814
2815 if (stackE == 0)
2816 return; // Nothing suspicious was found.
2817
2818 SourceLocation diagLoc;
2819 SourceRange diagRange;
2820 if (refVars.empty()) {
2821 diagLoc = stackE->getLocStart();
2822 diagRange = stackE->getSourceRange();
2823 } else {
2824 // We followed through a reference variable. 'stackE' contains the
2825 // problematic expression but we will warn at the return statement pointing
2826 // at the reference variable. We will later display the "trail" of
2827 // reference variables using notes.
2828 diagLoc = refVars[0]->getLocStart();
2829 diagRange = refVars[0]->getSourceRange();
2830 }
2831
2832 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
2833 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
2834 : diag::warn_ret_stack_addr)
2835 << DR->getDecl()->getDeclName() << diagRange;
2836 } else if (isa<BlockExpr>(stackE)) { // local block.
2837 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
2838 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
2839 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
2840 } else { // local temporary.
2841 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
2842 : diag::warn_ret_local_temp_addr)
2843 << diagRange;
2844 }
2845
2846 // Display the "trail" of reference variables that we followed until we
2847 // found the problematic expression using notes.
2848 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
2849 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
2850 // If this var binds to another reference var, show the range of the next
2851 // var, otherwise the var binds to the problematic expression, in which case
2852 // show the range of the expression.
2853 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
2854 : stackE->getSourceRange();
2855 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
2856 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002857 }
2858}
2859
2860/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
2861/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002862/// to a location on the stack, a local block, an address of a label, or a
2863/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002864/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002865/// encounter a subexpression that (1) clearly does not lead to one of the
2866/// above problematic expressions (2) is something we cannot determine leads to
2867/// a problematic expression based on such local checking.
2868///
2869/// Both EvalAddr and EvalVal follow through reference variables to evaluate
2870/// the expression that they point to. Such variables are added to the
2871/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002872///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00002873/// EvalAddr processes expressions that are pointers that are used as
2874/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002875/// At the base case of the recursion is a check for the above problematic
2876/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002877///
2878/// This implementation handles:
2879///
2880/// * pointer-to-pointer casts
2881/// * implicit conversions from array references to pointers
2882/// * taking the address of fields
2883/// * arbitrary interplay between "&" and "*" operators
2884/// * pointer arithmetic from an address of a stack variable
2885/// * taking the address of an array element where the array is on the stack
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002886static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002887 if (E->isTypeDependent())
2888 return NULL;
2889
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002890 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00002891 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002892 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002893 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00002894 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00002895
Peter Collingbourne91147592011-04-15 00:35:48 +00002896 E = E->IgnoreParens();
2897
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002898 // Our "symbolic interpreter" is just a dispatch off the currently
2899 // viewed AST node. We then recursively traverse the AST by calling
2900 // EvalAddr and EvalVal appropriately.
2901 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002902 case Stmt::DeclRefExprClass: {
2903 DeclRefExpr *DR = cast<DeclRefExpr>(E);
2904
2905 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
2906 // If this is a reference variable, follow through to the expression that
2907 // it points to.
2908 if (V->hasLocalStorage() &&
2909 V->getType()->isReferenceType() && V->hasInit()) {
2910 // Add the reference variable to the "trail".
2911 refVars.push_back(DR);
2912 return EvalAddr(V->getInit(), refVars);
2913 }
2914
2915 return NULL;
2916 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002917
Chris Lattner934edb22007-12-28 05:31:15 +00002918 case Stmt::UnaryOperatorClass: {
2919 // The only unary operator that make sense to handle here
2920 // is AddrOf. All others don't make sense as pointers.
2921 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002922
John McCalle3027922010-08-25 11:45:40 +00002923 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002924 return EvalVal(U->getSubExpr(), refVars);
Chris Lattner934edb22007-12-28 05:31:15 +00002925 else
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002926 return NULL;
2927 }
Mike Stump11289f42009-09-09 15:08:12 +00002928
Chris Lattner934edb22007-12-28 05:31:15 +00002929 case Stmt::BinaryOperatorClass: {
2930 // Handle pointer arithmetic. All other binary operators are not valid
2931 // in this context.
2932 BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00002933 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00002934
John McCalle3027922010-08-25 11:45:40 +00002935 if (op != BO_Add && op != BO_Sub)
Chris Lattner934edb22007-12-28 05:31:15 +00002936 return NULL;
Mike Stump11289f42009-09-09 15:08:12 +00002937
Chris Lattner934edb22007-12-28 05:31:15 +00002938 Expr *Base = B->getLHS();
2939
2940 // Determine which argument is the real pointer base. It could be
2941 // the RHS argument instead of the LHS.
2942 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00002943
Chris Lattner934edb22007-12-28 05:31:15 +00002944 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002945 return EvalAddr(Base, refVars);
Chris Lattner934edb22007-12-28 05:31:15 +00002946 }
Steve Naroff2752a172008-09-10 19:17:48 +00002947
Chris Lattner934edb22007-12-28 05:31:15 +00002948 // For conditional operators we need to see if either the LHS or RHS are
2949 // valid DeclRefExpr*s. If one of them is valid, we return it.
2950 case Stmt::ConditionalOperatorClass: {
2951 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002952
Chris Lattner934edb22007-12-28 05:31:15 +00002953 // Handle the GNU extension for missing LHS.
Douglas Gregor270b2ef2010-10-21 16:21:08 +00002954 if (Expr *lhsExpr = C->getLHS()) {
2955 // In C++, we can have a throw-expression, which has 'void' type.
2956 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002957 if (Expr* LHS = EvalAddr(lhsExpr, refVars))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00002958 return LHS;
2959 }
Chris Lattner934edb22007-12-28 05:31:15 +00002960
Douglas Gregor270b2ef2010-10-21 16:21:08 +00002961 // In C++, we can have a throw-expression, which has 'void' type.
2962 if (C->getRHS()->getType()->isVoidType())
2963 return NULL;
2964
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002965 return EvalAddr(C->getRHS(), refVars);
Chris Lattner934edb22007-12-28 05:31:15 +00002966 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002967
2968 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00002969 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002970 return E; // local block.
2971 return NULL;
2972
2973 case Stmt::AddrLabelExprClass:
2974 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00002975
John McCall28fc7092011-11-10 05:35:25 +00002976 case Stmt::ExprWithCleanupsClass:
2977 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars);
2978
Ted Kremenekc3b4c522008-08-07 00:49:01 +00002979 // For casts, we need to handle conversions from arrays to
2980 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00002981 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00002982 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00002983 case Stmt::CXXFunctionalCastExprClass:
2984 case Stmt::ObjCBridgedCastExprClass: {
Argyrios Kyrtzidis3bab3d22008-08-18 23:01:59 +00002985 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenekc3b4c522008-08-07 00:49:01 +00002986 QualType T = SubExpr->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002987
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002988 if (SubExpr->getType()->isPointerType() ||
2989 SubExpr->getType()->isBlockPointerType() ||
2990 SubExpr->getType()->isObjCQualifiedIdType())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002991 return EvalAddr(SubExpr, refVars);
Ted Kremenekc3b4c522008-08-07 00:49:01 +00002992 else if (T->isArrayType())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002993 return EvalVal(SubExpr, refVars);
Chris Lattner934edb22007-12-28 05:31:15 +00002994 else
Ted Kremenekc3b4c522008-08-07 00:49:01 +00002995 return 0;
Chris Lattner934edb22007-12-28 05:31:15 +00002996 }
Mike Stump11289f42009-09-09 15:08:12 +00002997
Chris Lattner934edb22007-12-28 05:31:15 +00002998 // C++ casts. For dynamic casts, static casts, and const casts, we
2999 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregore200adc2008-10-27 19:41:14 +00003000 // through the cast. In the case the dynamic cast doesn't fail (and
3001 // return NULL), we take the conservative route and report cases
Chris Lattner934edb22007-12-28 05:31:15 +00003002 // where we return the address of a stack variable. For Reinterpre
Douglas Gregore200adc2008-10-27 19:41:14 +00003003 // FIXME: The comment about is wrong; we're not always converting
3004 // from pointer to pointer. I'm guessing that this code should also
Mike Stump11289f42009-09-09 15:08:12 +00003005 // handle references to objects.
3006 case Stmt::CXXStaticCastExprClass:
3007 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00003008 case Stmt::CXXConstCastExprClass:
3009 case Stmt::CXXReinterpretCastExprClass: {
3010 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003011 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00003012 return EvalAddr(S, refVars);
Chris Lattner934edb22007-12-28 05:31:15 +00003013 else
3014 return NULL;
Chris Lattner934edb22007-12-28 05:31:15 +00003015 }
Mike Stump11289f42009-09-09 15:08:12 +00003016
Douglas Gregorfe314812011-06-21 17:03:29 +00003017 case Stmt::MaterializeTemporaryExprClass:
3018 if (Expr *Result = EvalAddr(
3019 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
3020 refVars))
3021 return Result;
3022
3023 return E;
3024
Chris Lattner934edb22007-12-28 05:31:15 +00003025 // Everything else: we simply don't reason about them.
3026 default:
3027 return NULL;
3028 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00003029}
Mike Stump11289f42009-09-09 15:08:12 +00003030
Ted Kremenekcff94fa2007-08-17 16:46:58 +00003031
3032/// EvalVal - This function is complements EvalAddr in the mutual recursion.
3033/// See the comments for EvalAddr for more details.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003034static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
Ted Kremenekb7861562010-08-04 20:01:07 +00003035do {
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00003036 // We should only be called for evaluating non-pointer expressions, or
3037 // expressions with a pointer type that are not used as references but instead
3038 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00003039
Ted Kremenekcff94fa2007-08-17 16:46:58 +00003040 // Our "symbolic interpreter" is just a dispatch off the currently
3041 // viewed AST node. We then recursively traverse the AST by calling
3042 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00003043
3044 E = E->IgnoreParens();
Ted Kremenekcff94fa2007-08-17 16:46:58 +00003045 switch (E->getStmtClass()) {
Ted Kremenekb7861562010-08-04 20:01:07 +00003046 case Stmt::ImplicitCastExprClass: {
3047 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall2536c6d2010-08-25 10:28:54 +00003048 if (IE->getValueKind() == VK_LValue) {
Ted Kremenekb7861562010-08-04 20:01:07 +00003049 E = IE->getSubExpr();
3050 continue;
3051 }
3052 return NULL;
3053 }
3054
John McCall28fc7092011-11-10 05:35:25 +00003055 case Stmt::ExprWithCleanupsClass:
3056 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars);
3057
Douglas Gregor4bd90e52009-10-23 18:54:35 +00003058 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00003059 // When we hit a DeclRefExpr we are looking at code that refers to a
3060 // variable's name. If it's not a reference variable we check if it has
3061 // local storage within the function, and if so, return the expression.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00003062 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00003063
Ted Kremenekcff94fa2007-08-17 16:46:58 +00003064 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00003065 if (V->hasLocalStorage()) {
3066 if (!V->getType()->isReferenceType())
3067 return DR;
3068
3069 // Reference variable, follow through to the expression that
3070 // it points to.
3071 if (V->hasInit()) {
3072 // Add the reference variable to the "trail".
3073 refVars.push_back(DR);
3074 return EvalVal(V->getInit(), refVars);
3075 }
3076 }
Mike Stump11289f42009-09-09 15:08:12 +00003077
Ted Kremenekcff94fa2007-08-17 16:46:58 +00003078 return NULL;
3079 }
Mike Stump11289f42009-09-09 15:08:12 +00003080
Ted Kremenekcff94fa2007-08-17 16:46:58 +00003081 case Stmt::UnaryOperatorClass: {
3082 // The only unary operator that make sense to handle here
3083 // is Deref. All others don't resolve to a "name." This includes
3084 // handling all sorts of rvalues passed to a unary operator.
3085 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00003086
John McCalle3027922010-08-25 11:45:40 +00003087 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00003088 return EvalAddr(U->getSubExpr(), refVars);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00003089
3090 return NULL;
3091 }
Mike Stump11289f42009-09-09 15:08:12 +00003092
Ted Kremenekcff94fa2007-08-17 16:46:58 +00003093 case Stmt::ArraySubscriptExprClass: {
3094 // Array subscripts are potential references to data on the stack. We
3095 // retrieve the DeclRefExpr* for the array variable if it indeed
3096 // has local storage.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00003097 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00003098 }
Mike Stump11289f42009-09-09 15:08:12 +00003099
Ted Kremenekcff94fa2007-08-17 16:46:58 +00003100 case Stmt::ConditionalOperatorClass: {
3101 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00003102 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00003103 ConditionalOperator *C = cast<ConditionalOperator>(E);
3104
Anders Carlsson801c5c72007-11-30 19:04:31 +00003105 // Handle the GNU extension for missing LHS.
3106 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00003107 if (Expr *LHS = EvalVal(lhsExpr, refVars))
Anders Carlsson801c5c72007-11-30 19:04:31 +00003108 return LHS;
3109
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00003110 return EvalVal(C->getRHS(), refVars);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00003111 }
Mike Stump11289f42009-09-09 15:08:12 +00003112
Ted Kremenekcff94fa2007-08-17 16:46:58 +00003113 // Accesses to members are potential references to data on the stack.
Douglas Gregorf405d7e2009-08-31 23:41:50 +00003114 case Stmt::MemberExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00003115 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00003116
Ted Kremenekcff94fa2007-08-17 16:46:58 +00003117 // Check for indirect access. We only want direct field accesses.
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00003118 if (M->isArrow())
Ted Kremenekcff94fa2007-08-17 16:46:58 +00003119 return NULL;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00003120
3121 // Check whether the member type is itself a reference, in which case
3122 // we're not going to refer to the member, but to what the member refers to.
3123 if (M->getMemberDecl()->getType()->isReferenceType())
3124 return NULL;
3125
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00003126 return EvalVal(M->getBase(), refVars);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00003127 }
Mike Stump11289f42009-09-09 15:08:12 +00003128
Douglas Gregorfe314812011-06-21 17:03:29 +00003129 case Stmt::MaterializeTemporaryExprClass:
3130 if (Expr *Result = EvalVal(
3131 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
3132 refVars))
3133 return Result;
3134
3135 return E;
3136
Ted Kremenekcff94fa2007-08-17 16:46:58 +00003137 default:
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00003138 // Check that we don't return or take the address of a reference to a
3139 // temporary. This is only useful in C++.
3140 if (!E->isTypeDependent() && E->isRValue())
3141 return E;
3142
3143 // Everything else: we simply don't reason about them.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00003144 return NULL;
3145 }
Ted Kremenekb7861562010-08-04 20:01:07 +00003146} while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00003147}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00003148
3149//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
3150
3151/// Check for comparisons of floating point operands using != and ==.
3152/// Issue a warning if these are no self-comparisons, as they are not likely
3153/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00003154void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Ted Kremenek43fb8b02007-11-25 00:58:00 +00003155 bool EmitWarning = true;
Mike Stump11289f42009-09-09 15:08:12 +00003156
Richard Trieu82402a02011-09-15 21:56:47 +00003157 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
3158 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00003159
3160 // Special case: check for x == x (which is OK).
3161 // Do not emit warnings for such cases.
3162 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
3163 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
3164 if (DRL->getDecl() == DRR->getDecl())
3165 EmitWarning = false;
Mike Stump11289f42009-09-09 15:08:12 +00003166
3167
Ted Kremenekeda40e22007-11-29 00:59:04 +00003168 // Special case: check for comparisons against literals that can be exactly
3169 // represented by APFloat. In such cases, do not emit a warning. This
3170 // is a heuristic: often comparison against such literals are used to
3171 // detect if a value in a variable has not changed. This clearly can
3172 // lead to false negatives.
3173 if (EmitWarning) {
3174 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
3175 if (FLL->isExact())
3176 EmitWarning = false;
Mike Stump12b8ce12009-08-04 21:02:39 +00003177 } else
Ted Kremenekeda40e22007-11-29 00:59:04 +00003178 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
3179 if (FLR->isExact())
3180 EmitWarning = false;
3181 }
3182 }
Mike Stump11289f42009-09-09 15:08:12 +00003183
Ted Kremenek43fb8b02007-11-25 00:58:00 +00003184 // Check for comparisons with builtin types.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003185 if (EmitWarning)
Ted Kremenek43fb8b02007-11-25 00:58:00 +00003186 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Richard Smithd62306a2011-11-10 06:34:14 +00003187 if (CL->isBuiltinCall())
Ted Kremenek43fb8b02007-11-25 00:58:00 +00003188 EmitWarning = false;
Mike Stump11289f42009-09-09 15:08:12 +00003189
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003190 if (EmitWarning)
Ted Kremenek43fb8b02007-11-25 00:58:00 +00003191 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Richard Smithd62306a2011-11-10 06:34:14 +00003192 if (CR->isBuiltinCall())
Ted Kremenek43fb8b02007-11-25 00:58:00 +00003193 EmitWarning = false;
Mike Stump11289f42009-09-09 15:08:12 +00003194
Ted Kremenek43fb8b02007-11-25 00:58:00 +00003195 // Emit the diagnostic.
3196 if (EmitWarning)
Richard Trieu82402a02011-09-15 21:56:47 +00003197 Diag(Loc, diag::warn_floatingpoint_eq)
3198 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00003199}
John McCallca01b222010-01-04 23:21:16 +00003200
John McCall70aa5392010-01-06 05:24:50 +00003201//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
3202//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00003203
John McCall70aa5392010-01-06 05:24:50 +00003204namespace {
John McCallca01b222010-01-04 23:21:16 +00003205
John McCall70aa5392010-01-06 05:24:50 +00003206/// Structure recording the 'active' range of an integer-valued
3207/// expression.
3208struct IntRange {
3209 /// The number of bits active in the int.
3210 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00003211
John McCall70aa5392010-01-06 05:24:50 +00003212 /// True if the int is known not to have negative values.
3213 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00003214
John McCall70aa5392010-01-06 05:24:50 +00003215 IntRange(unsigned Width, bool NonNegative)
3216 : Width(Width), NonNegative(NonNegative)
3217 {}
John McCallca01b222010-01-04 23:21:16 +00003218
John McCall817d4af2010-11-10 23:38:19 +00003219 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00003220 static IntRange forBoolType() {
3221 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00003222 }
3223
John McCall817d4af2010-11-10 23:38:19 +00003224 /// Returns the range of an opaque value of the given integral type.
3225 static IntRange forValueOfType(ASTContext &C, QualType T) {
3226 return forValueOfCanonicalType(C,
3227 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00003228 }
3229
John McCall817d4af2010-11-10 23:38:19 +00003230 /// Returns the range of an opaque value of a canonical integral type.
3231 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00003232 assert(T->isCanonicalUnqualified());
3233
3234 if (const VectorType *VT = dyn_cast<VectorType>(T))
3235 T = VT->getElementType().getTypePtr();
3236 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
3237 T = CT->getElementType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00003238
John McCall18a2c2c2010-11-09 22:22:12 +00003239 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00003240 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
3241 EnumDecl *Enum = ET->getDecl();
John McCallf937c022011-10-07 06:10:15 +00003242 if (!Enum->isCompleteDefinition())
John McCall18a2c2c2010-11-09 22:22:12 +00003243 return IntRange(C.getIntWidth(QualType(T, 0)), false);
3244
John McCallcc7e5bf2010-05-06 08:58:33 +00003245 unsigned NumPositive = Enum->getNumPositiveBits();
3246 unsigned NumNegative = Enum->getNumNegativeBits();
3247
3248 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
3249 }
John McCall70aa5392010-01-06 05:24:50 +00003250
3251 const BuiltinType *BT = cast<BuiltinType>(T);
3252 assert(BT->isInteger());
3253
3254 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
3255 }
3256
John McCall817d4af2010-11-10 23:38:19 +00003257 /// Returns the "target" range of a canonical integral type, i.e.
3258 /// the range of values expressible in the type.
3259 ///
3260 /// This matches forValueOfCanonicalType except that enums have the
3261 /// full range of their type, not the range of their enumerators.
3262 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
3263 assert(T->isCanonicalUnqualified());
3264
3265 if (const VectorType *VT = dyn_cast<VectorType>(T))
3266 T = VT->getElementType().getTypePtr();
3267 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
3268 T = CT->getElementType().getTypePtr();
3269 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00003270 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00003271
3272 const BuiltinType *BT = cast<BuiltinType>(T);
3273 assert(BT->isInteger());
3274
3275 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
3276 }
3277
3278 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00003279 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00003280 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00003281 L.NonNegative && R.NonNegative);
3282 }
3283
John McCall817d4af2010-11-10 23:38:19 +00003284 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00003285 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00003286 return IntRange(std::min(L.Width, R.Width),
3287 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00003288 }
3289};
3290
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00003291static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
3292 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00003293 if (value.isSigned() && value.isNegative())
3294 return IntRange(value.getMinSignedBits(), false);
3295
3296 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00003297 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00003298
3299 // isNonNegative() just checks the sign bit without considering
3300 // signedness.
3301 return IntRange(value.getActiveBits(), true);
3302}
3303
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00003304static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
3305 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00003306 if (result.isInt())
3307 return GetValueRange(C, result.getInt(), MaxWidth);
3308
3309 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00003310 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
3311 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
3312 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
3313 R = IntRange::join(R, El);
3314 }
John McCall70aa5392010-01-06 05:24:50 +00003315 return R;
3316 }
3317
3318 if (result.isComplexInt()) {
3319 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
3320 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
3321 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00003322 }
3323
3324 // This can happen with lossless casts to intptr_t of "based" lvalues.
3325 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00003326 // FIXME: The only reason we need to pass the type in here is to get
3327 // the sign right on this one case. It would be nice if APValue
3328 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00003329 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00003330 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00003331}
John McCall70aa5392010-01-06 05:24:50 +00003332
3333/// Pseudo-evaluate the given integer expression, estimating the
3334/// range of values it might take.
3335///
3336/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00003337static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00003338 E = E->IgnoreParens();
3339
3340 // Try a full evaluation first.
3341 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00003342 if (E->EvaluateAsRValue(result, C))
John McCall74430522010-01-06 22:57:21 +00003343 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00003344
3345 // I think we only want to look through implicit casts here; if the
3346 // user has an explicit widening cast, we should treat the value as
3347 // being of the new, wider type.
3348 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00003349 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00003350 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
3351
John McCall817d4af2010-11-10 23:38:19 +00003352 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
John McCall70aa5392010-01-06 05:24:50 +00003353
John McCalle3027922010-08-25 11:45:40 +00003354 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall2ce81ad2010-01-06 22:07:33 +00003355
John McCall70aa5392010-01-06 05:24:50 +00003356 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00003357 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00003358 return OutputTypeRange;
3359
3360 IntRange SubRange
3361 = GetExprRange(C, CE->getSubExpr(),
3362 std::min(MaxWidth, OutputTypeRange.Width));
3363
3364 // Bail out if the subexpr's range is as wide as the cast type.
3365 if (SubRange.Width >= OutputTypeRange.Width)
3366 return OutputTypeRange;
3367
3368 // Otherwise, we take the smaller width, and we're non-negative if
3369 // either the output type or the subexpr is.
3370 return IntRange(SubRange.Width,
3371 SubRange.NonNegative || OutputTypeRange.NonNegative);
3372 }
3373
3374 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3375 // If we can fold the condition, just take that operand.
3376 bool CondResult;
3377 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
3378 return GetExprRange(C, CondResult ? CO->getTrueExpr()
3379 : CO->getFalseExpr(),
3380 MaxWidth);
3381
3382 // Otherwise, conservatively merge.
3383 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
3384 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
3385 return IntRange::join(L, R);
3386 }
3387
3388 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3389 switch (BO->getOpcode()) {
3390
3391 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00003392 case BO_LAnd:
3393 case BO_LOr:
3394 case BO_LT:
3395 case BO_GT:
3396 case BO_LE:
3397 case BO_GE:
3398 case BO_EQ:
3399 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00003400 return IntRange::forBoolType();
3401
John McCallc3688382011-07-13 06:35:24 +00003402 // The type of the assignments is the type of the LHS, so the RHS
3403 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00003404 case BO_MulAssign:
3405 case BO_DivAssign:
3406 case BO_RemAssign:
3407 case BO_AddAssign:
3408 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00003409 case BO_XorAssign:
3410 case BO_OrAssign:
3411 // TODO: bitfields?
John McCall817d4af2010-11-10 23:38:19 +00003412 return IntRange::forValueOfType(C, E->getType());
John McCallff96ccd2010-02-23 19:22:29 +00003413
John McCallc3688382011-07-13 06:35:24 +00003414 // Simple assignments just pass through the RHS, which will have
3415 // been coerced to the LHS type.
3416 case BO_Assign:
3417 // TODO: bitfields?
3418 return GetExprRange(C, BO->getRHS(), MaxWidth);
3419
John McCall70aa5392010-01-06 05:24:50 +00003420 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00003421 case BO_PtrMemD:
3422 case BO_PtrMemI:
John McCall817d4af2010-11-10 23:38:19 +00003423 return IntRange::forValueOfType(C, E->getType());
John McCall70aa5392010-01-06 05:24:50 +00003424
John McCall2ce81ad2010-01-06 22:07:33 +00003425 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00003426 case BO_And:
3427 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00003428 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
3429 GetExprRange(C, BO->getRHS(), MaxWidth));
3430
John McCall70aa5392010-01-06 05:24:50 +00003431 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00003432 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00003433 // ...except that we want to treat '1 << (blah)' as logically
3434 // positive. It's an important idiom.
3435 if (IntegerLiteral *I
3436 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
3437 if (I->getValue() == 1) {
John McCall817d4af2010-11-10 23:38:19 +00003438 IntRange R = IntRange::forValueOfType(C, E->getType());
John McCall1bff9932010-04-07 01:14:35 +00003439 return IntRange(R.Width, /*NonNegative*/ true);
3440 }
3441 }
3442 // fallthrough
3443
John McCalle3027922010-08-25 11:45:40 +00003444 case BO_ShlAssign:
John McCall817d4af2010-11-10 23:38:19 +00003445 return IntRange::forValueOfType(C, E->getType());
John McCall70aa5392010-01-06 05:24:50 +00003446
John McCall2ce81ad2010-01-06 22:07:33 +00003447 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00003448 case BO_Shr:
3449 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00003450 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3451
3452 // If the shift amount is a positive constant, drop the width by
3453 // that much.
3454 llvm::APSInt shift;
3455 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
3456 shift.isNonNegative()) {
3457 unsigned zext = shift.getZExtValue();
3458 if (zext >= L.Width)
3459 L.Width = (L.NonNegative ? 0 : 1);
3460 else
3461 L.Width -= zext;
3462 }
3463
3464 return L;
3465 }
3466
3467 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00003468 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00003469 return GetExprRange(C, BO->getRHS(), MaxWidth);
3470
John McCall2ce81ad2010-01-06 22:07:33 +00003471 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00003472 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00003473 if (BO->getLHS()->getType()->isPointerType())
John McCall817d4af2010-11-10 23:38:19 +00003474 return IntRange::forValueOfType(C, E->getType());
John McCall51431812011-07-14 22:39:48 +00003475 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003476
John McCall51431812011-07-14 22:39:48 +00003477 // The width of a division result is mostly determined by the size
3478 // of the LHS.
3479 case BO_Div: {
3480 // Don't 'pre-truncate' the operands.
3481 unsigned opWidth = C.getIntWidth(E->getType());
3482 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3483
3484 // If the divisor is constant, use that.
3485 llvm::APSInt divisor;
3486 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
3487 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
3488 if (log2 >= L.Width)
3489 L.Width = (L.NonNegative ? 0 : 1);
3490 else
3491 L.Width = std::min(L.Width - log2, MaxWidth);
3492 return L;
3493 }
3494
3495 // Otherwise, just use the LHS's width.
3496 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3497 return IntRange(L.Width, L.NonNegative && R.NonNegative);
3498 }
3499
3500 // The result of a remainder can't be larger than the result of
3501 // either side.
3502 case BO_Rem: {
3503 // Don't 'pre-truncate' the operands.
3504 unsigned opWidth = C.getIntWidth(E->getType());
3505 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3506 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3507
3508 IntRange meet = IntRange::meet(L, R);
3509 meet.Width = std::min(meet.Width, MaxWidth);
3510 return meet;
3511 }
3512
3513 // The default behavior is okay for these.
3514 case BO_Mul:
3515 case BO_Add:
3516 case BO_Xor:
3517 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00003518 break;
3519 }
3520
John McCall51431812011-07-14 22:39:48 +00003521 // The default case is to treat the operation as if it were closed
3522 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00003523 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3524 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
3525 return IntRange::join(L, R);
3526 }
3527
3528 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
3529 switch (UO->getOpcode()) {
3530 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00003531 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00003532 return IntRange::forBoolType();
3533
3534 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00003535 case UO_Deref:
3536 case UO_AddrOf: // should be impossible
John McCall817d4af2010-11-10 23:38:19 +00003537 return IntRange::forValueOfType(C, E->getType());
John McCall70aa5392010-01-06 05:24:50 +00003538
3539 default:
3540 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
3541 }
3542 }
Douglas Gregor882211c2010-04-28 22:16:22 +00003543
3544 if (dyn_cast<OffsetOfExpr>(E)) {
John McCall817d4af2010-11-10 23:38:19 +00003545 IntRange::forValueOfType(C, E->getType());
Douglas Gregor882211c2010-04-28 22:16:22 +00003546 }
John McCall70aa5392010-01-06 05:24:50 +00003547
Richard Smithcaf33902011-10-10 18:28:20 +00003548 if (FieldDecl *BitField = E->getBitField())
3549 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00003550 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00003551
John McCall817d4af2010-11-10 23:38:19 +00003552 return IntRange::forValueOfType(C, E->getType());
John McCall70aa5392010-01-06 05:24:50 +00003553}
John McCall263a48b2010-01-04 23:31:57 +00003554
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00003555static IntRange GetExprRange(ASTContext &C, Expr *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00003556 return GetExprRange(C, E, C.getIntWidth(E->getType()));
3557}
3558
John McCall263a48b2010-01-04 23:31:57 +00003559/// Checks whether the given value, which currently has the given
3560/// source semantics, has the same value when coerced through the
3561/// target semantics.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00003562static bool IsSameFloatAfterCast(const llvm::APFloat &value,
3563 const llvm::fltSemantics &Src,
3564 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00003565 llvm::APFloat truncated = value;
3566
3567 bool ignored;
3568 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
3569 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
3570
3571 return truncated.bitwiseIsEqual(value);
3572}
3573
3574/// Checks whether the given value, which currently has the given
3575/// source semantics, has the same value when coerced through the
3576/// target semantics.
3577///
3578/// The value might be a vector of floats (or a complex number).
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00003579static bool IsSameFloatAfterCast(const APValue &value,
3580 const llvm::fltSemantics &Src,
3581 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00003582 if (value.isFloat())
3583 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
3584
3585 if (value.isVector()) {
3586 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
3587 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
3588 return false;
3589 return true;
3590 }
3591
3592 assert(value.isComplexFloat());
3593 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
3594 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
3595}
3596
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00003597static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00003598
Ted Kremenek6274be42010-09-23 21:43:44 +00003599static bool IsZero(Sema &S, Expr *E) {
3600 // Suppress cases where we are comparing against an enum constant.
3601 if (const DeclRefExpr *DR =
3602 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
3603 if (isa<EnumConstantDecl>(DR->getDecl()))
3604 return false;
3605
3606 // Suppress cases where the '0' value is expanded from a macro.
3607 if (E->getLocStart().isMacroID())
3608 return false;
3609
John McCallcc7e5bf2010-05-06 08:58:33 +00003610 llvm::APSInt Value;
3611 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
3612}
3613
John McCall2551c1b2010-10-06 00:25:24 +00003614static bool HasEnumType(Expr *E) {
3615 // Strip off implicit integral promotions.
3616 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00003617 if (ICE->getCastKind() != CK_IntegralCast &&
3618 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00003619 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00003620 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00003621 }
3622
3623 return E->getType()->isEnumeralType();
3624}
3625
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00003626static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00003627 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00003628 if (E->isValueDependent())
3629 return;
3630
John McCalle3027922010-08-25 11:45:40 +00003631 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00003632 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00003633 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00003634 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00003635 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00003636 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00003637 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00003638 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00003639 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00003640 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00003641 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00003642 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00003643 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00003644 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00003645 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00003646 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
3647 }
3648}
3649
3650/// Analyze the operands of the given comparison. Implements the
3651/// fallback case from AnalyzeComparison.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00003652static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00003653 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
3654 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00003655}
John McCall263a48b2010-01-04 23:31:57 +00003656
John McCallca01b222010-01-04 23:21:16 +00003657/// \brief Implements -Wsign-compare.
3658///
Richard Trieu82402a02011-09-15 21:56:47 +00003659/// \param E the binary operator to check for warnings
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00003660static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00003661 // The type the comparison is being performed in.
3662 QualType T = E->getLHS()->getType();
3663 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
3664 && "comparison with mismatched types");
John McCallca01b222010-01-04 23:21:16 +00003665
John McCallcc7e5bf2010-05-06 08:58:33 +00003666 // We don't do anything special if this isn't an unsigned integral
3667 // comparison: we're only interested in integral comparisons, and
3668 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00003669 //
3670 // We also don't care about value-dependent expressions or expressions
3671 // whose result is a constant.
3672 if (!T->hasUnsignedIntegerRepresentation()
3673 || E->isValueDependent() || E->isIntegerConstantExpr(S.Context))
John McCallcc7e5bf2010-05-06 08:58:33 +00003674 return AnalyzeImpConvsInComparison(S, E);
John McCall70aa5392010-01-06 05:24:50 +00003675
Richard Trieu82402a02011-09-15 21:56:47 +00003676 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
3677 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
John McCallca01b222010-01-04 23:21:16 +00003678
John McCallcc7e5bf2010-05-06 08:58:33 +00003679 // Check to see if one of the (unmodified) operands is of different
3680 // signedness.
3681 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00003682 if (LHS->getType()->hasSignedIntegerRepresentation()) {
3683 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00003684 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00003685 signedOperand = LHS;
3686 unsignedOperand = RHS;
3687 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
3688 signedOperand = RHS;
3689 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00003690 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00003691 CheckTrivialUnsignedComparison(S, E);
3692 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00003693 }
3694
John McCallcc7e5bf2010-05-06 08:58:33 +00003695 // Otherwise, calculate the effective range of the signed operand.
3696 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00003697
John McCallcc7e5bf2010-05-06 08:58:33 +00003698 // Go ahead and analyze implicit conversions in the operands. Note
3699 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00003700 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
3701 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00003702
John McCallcc7e5bf2010-05-06 08:58:33 +00003703 // If the signed range is non-negative, -Wsign-compare won't fire,
3704 // but we should still check for comparisons which are always true
3705 // or false.
3706 if (signedRange.NonNegative)
3707 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00003708
3709 // For (in)equality comparisons, if the unsigned operand is a
3710 // constant which cannot collide with a overflowed signed operand,
3711 // then reinterpreting the signed operand as unsigned will not
3712 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00003713 if (E->isEqualityOp()) {
3714 unsigned comparisonWidth = S.Context.getIntWidth(T);
3715 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00003716
John McCallcc7e5bf2010-05-06 08:58:33 +00003717 // We should never be unable to prove that the unsigned operand is
3718 // non-negative.
3719 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
3720
3721 if (unsignedRange.Width < comparisonWidth)
3722 return;
3723 }
3724
3725 S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison)
Richard Trieu82402a02011-09-15 21:56:47 +00003726 << LHS->getType() << RHS->getType()
3727 << LHS->getSourceRange() << RHS->getSourceRange();
John McCallca01b222010-01-04 23:21:16 +00003728}
3729
John McCall1f425642010-11-11 03:21:53 +00003730/// Analyzes an attempt to assign the given value to a bitfield.
3731///
3732/// Returns true if there was something fishy about the attempt.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00003733static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
3734 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00003735 assert(Bitfield->isBitField());
3736 if (Bitfield->isInvalidDecl())
3737 return false;
3738
John McCalldeebbcf2010-11-11 05:33:51 +00003739 // White-list bool bitfields.
3740 if (Bitfield->getType()->isBooleanType())
3741 return false;
3742
Douglas Gregor789adec2011-02-04 13:09:01 +00003743 // Ignore value- or type-dependent expressions.
3744 if (Bitfield->getBitWidth()->isValueDependent() ||
3745 Bitfield->getBitWidth()->isTypeDependent() ||
3746 Init->isValueDependent() ||
3747 Init->isTypeDependent())
3748 return false;
3749
John McCall1f425642010-11-11 03:21:53 +00003750 Expr *OriginalInit = Init->IgnoreParenImpCasts();
3751
Richard Smith5fab0c92011-12-28 19:48:30 +00003752 llvm::APSInt Value;
3753 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00003754 return false;
3755
John McCall1f425642010-11-11 03:21:53 +00003756 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00003757 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00003758
3759 if (OriginalWidth <= FieldWidth)
3760 return false;
3761
Eli Friedmanc267a322012-01-26 23:11:39 +00003762 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00003763 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00003764 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00003765
Eli Friedmanc267a322012-01-26 23:11:39 +00003766 // Check whether the stored value is equal to the original value.
3767 TruncatedValue = TruncatedValue.extend(OriginalWidth);
John McCall1f425642010-11-11 03:21:53 +00003768 if (Value == TruncatedValue)
3769 return false;
3770
Eli Friedmanc267a322012-01-26 23:11:39 +00003771 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00003772 // therefore don't strictly fit into a signed bitfield of width 1.
3773 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00003774 return false;
3775
John McCall1f425642010-11-11 03:21:53 +00003776 std::string PrettyValue = Value.toString(10);
3777 std::string PrettyTrunc = TruncatedValue.toString(10);
3778
3779 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
3780 << PrettyValue << PrettyTrunc << OriginalInit->getType()
3781 << Init->getSourceRange();
3782
3783 return true;
3784}
3785
John McCalld2a53122010-11-09 23:24:47 +00003786/// Analyze the given simple or compound assignment for warning-worthy
3787/// operations.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00003788static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00003789 // Just recurse on the LHS.
3790 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
3791
3792 // We want to recurse on the RHS as normal unless we're assigning to
3793 // a bitfield.
3794 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
John McCall1f425642010-11-11 03:21:53 +00003795 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
3796 E->getOperatorLoc())) {
3797 // Recurse, ignoring any implicit conversions on the RHS.
3798 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
3799 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00003800 }
3801 }
3802
3803 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
3804}
3805
John McCall263a48b2010-01-04 23:31:57 +00003806/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00003807static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00003808 SourceLocation CContext, unsigned diag,
3809 bool pruneControlFlow = false) {
3810 if (pruneControlFlow) {
3811 S.DiagRuntimeBehavior(E->getExprLoc(), E,
3812 S.PDiag(diag)
3813 << SourceType << T << E->getSourceRange()
3814 << SourceRange(CContext));
3815 return;
3816 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00003817 S.Diag(E->getExprLoc(), diag)
3818 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
3819}
3820
Chandler Carruth7f3654f2011-04-05 06:47:57 +00003821/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00003822static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00003823 SourceLocation CContext, unsigned diag,
3824 bool pruneControlFlow = false) {
3825 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00003826}
3827
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00003828/// Diagnose an implicit cast from a literal expression. Does not warn when the
3829/// cast wouldn't lose information.
Chandler Carruth016ef402011-04-10 08:36:24 +00003830void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
3831 SourceLocation CContext) {
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00003832 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruth016ef402011-04-10 08:36:24 +00003833 bool isExact = false;
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00003834 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00003835 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
3836 T->hasUnsignedIntegerRepresentation());
3837 if (Value.convertToInteger(IntegerValue,
Chandler Carruth016ef402011-04-10 08:36:24 +00003838 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00003839 == llvm::APFloat::opOK && isExact)
Chandler Carruth016ef402011-04-10 08:36:24 +00003840 return;
3841
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00003842 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
3843 << FL->getType() << T << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruth016ef402011-04-10 08:36:24 +00003844}
3845
John McCall18a2c2c2010-11-09 22:22:12 +00003846std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
3847 if (!Range.Width) return "0";
3848
3849 llvm::APSInt ValueInRange = Value;
3850 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00003851 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00003852 return ValueInRange.toString(10);
3853}
3854
John McCallcc7e5bf2010-05-06 08:58:33 +00003855void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00003856 SourceLocation CC, bool *ICContext = 0) {
John McCallcc7e5bf2010-05-06 08:58:33 +00003857 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00003858
John McCallcc7e5bf2010-05-06 08:58:33 +00003859 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
3860 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
3861 if (Source == Target) return;
3862 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00003863
Chandler Carruthc22845a2011-07-26 05:40:03 +00003864 // If the conversion context location is invalid don't complain. We also
3865 // don't want to emit a warning if the issue occurs from the expansion of
3866 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
3867 // delay this check as long as possible. Once we detect we are in that
3868 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00003869 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00003870 return;
3871
Richard Trieu021baa32011-09-23 20:10:00 +00003872 // Diagnose implicit casts to bool.
3873 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
3874 if (isa<StringLiteral>(E))
3875 // Warn on string literal to bool. Checks for string literals in logical
3876 // expressions, for instances, assert(0 && "error here"), is prevented
3877 // by a check in AnalyzeImplicitConversions().
3878 return DiagnoseImpCast(S, E, T, CC,
3879 diag::warn_impcast_string_literal_to_bool);
Lang Hamesdf5c1212011-12-05 20:49:50 +00003880 if (Source->isFunctionType()) {
3881 // Warn on function to bool. Checks free functions and static member
3882 // functions. Weakly imported functions are excluded from the check,
3883 // since it's common to test their value to check whether the linker
3884 // found a definition for them.
3885 ValueDecl *D = 0;
3886 if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
3887 D = R->getDecl();
3888 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
3889 D = M->getMemberDecl();
3890 }
3891
3892 if (D && !D->isWeak()) {
Richard Trieu5f623222011-12-06 04:48:01 +00003893 if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
3894 S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
3895 << F << E->getSourceRange() << SourceRange(CC);
David Blaikie10eb4b62011-12-09 21:42:37 +00003896 S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
3897 << FixItHint::CreateInsertion(E->getExprLoc(), "&");
3898 QualType ReturnType;
3899 UnresolvedSet<4> NonTemplateOverloads;
3900 S.isExprCallable(*E, ReturnType, NonTemplateOverloads);
3901 if (!ReturnType.isNull()
3902 && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
3903 S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
3904 << FixItHint::CreateInsertion(
3905 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu5f623222011-12-06 04:48:01 +00003906 return;
3907 }
Lang Hamesdf5c1212011-12-05 20:49:50 +00003908 }
3909 }
David Blaikie7833b7d2011-09-29 04:06:47 +00003910 return; // Other casts to bool are not checked.
Richard Trieu021baa32011-09-23 20:10:00 +00003911 }
John McCall263a48b2010-01-04 23:31:57 +00003912
3913 // Strip vector types.
3914 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00003915 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00003916 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00003917 return;
John McCallacf0ee52010-10-08 02:01:28 +00003918 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00003919 }
Chris Lattneree7286f2011-06-14 04:51:15 +00003920
3921 // If the vector cast is cast between two vectors of the same size, it is
3922 // a bitcast, not a conversion.
3923 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
3924 return;
John McCall263a48b2010-01-04 23:31:57 +00003925
3926 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
3927 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
3928 }
3929
3930 // Strip complex types.
3931 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00003932 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00003933 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00003934 return;
3935
John McCallacf0ee52010-10-08 02:01:28 +00003936 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00003937 }
John McCall263a48b2010-01-04 23:31:57 +00003938
3939 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
3940 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
3941 }
3942
3943 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
3944 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
3945
3946 // If the source is floating point...
3947 if (SourceBT && SourceBT->isFloatingPoint()) {
3948 // ...and the target is floating point...
3949 if (TargetBT && TargetBT->isFloatingPoint()) {
3950 // ...then warn if we're dropping FP rank.
3951
3952 // Builtin FP kinds are ordered by increasing FP rank.
3953 if (SourceBT->getKind() > TargetBT->getKind()) {
3954 // Don't warn about float constants that are precisely
3955 // representable in the target type.
3956 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00003957 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00003958 // Value might be a float, a float vector, or a float complex.
3959 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00003960 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
3961 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00003962 return;
3963 }
3964
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00003965 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00003966 return;
3967
John McCallacf0ee52010-10-08 02:01:28 +00003968 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall263a48b2010-01-04 23:31:57 +00003969 }
3970 return;
3971 }
3972
Ted Kremenek4c0826c2011-03-10 20:03:42 +00003973 // If the target is integral, always warn.
Chandler Carruth22c7a792011-02-17 11:05:49 +00003974 if ((TargetBT && TargetBT->isInteger())) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00003975 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00003976 return;
3977
Chandler Carruth22c7a792011-02-17 11:05:49 +00003978 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00003979 // We also want to warn on, e.g., "int i = -1.234"
3980 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
3981 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
3982 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
3983
Chandler Carruth016ef402011-04-10 08:36:24 +00003984 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
3985 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00003986 } else {
3987 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
3988 }
3989 }
John McCall263a48b2010-01-04 23:31:57 +00003990
3991 return;
3992 }
3993
John McCall70aa5392010-01-06 05:24:50 +00003994 if (!Source->isIntegerType() || !Target->isIntegerType())
John McCall263a48b2010-01-04 23:31:57 +00003995 return;
3996
Richard Trieubeaf3452011-05-29 19:59:02 +00003997 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
3998 == Expr::NPCK_GNUNull) && Target->isIntegerType()) {
3999 S.Diag(E->getExprLoc(), diag::warn_impcast_null_pointer_to_integer)
4000 << E->getSourceRange() << clang::SourceRange(CC);
4001 return;
4002 }
4003
John McCallcc7e5bf2010-05-06 08:58:33 +00004004 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00004005 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00004006
4007 if (SourceRange.Width > TargetRange.Width) {
John McCall18a2c2c2010-11-09 22:22:12 +00004008 // If the source is a constant, use a default-on diagnostic.
4009 // TODO: this should happen for bitfield stores, too.
4010 llvm::APSInt Value(32);
4011 if (E->isIntegerConstantExpr(Value, S.Context)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00004012 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00004013 return;
4014
John McCall18a2c2c2010-11-09 22:22:12 +00004015 std::string PrettySourceValue = Value.toString(10);
4016 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
4017
Ted Kremenek33ba9952011-10-22 02:37:33 +00004018 S.DiagRuntimeBehavior(E->getExprLoc(), E,
4019 S.PDiag(diag::warn_impcast_integer_precision_constant)
4020 << PrettySourceValue << PrettyTargetValue
4021 << E->getType() << T << E->getSourceRange()
4022 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00004023 return;
4024 }
4025
Chris Lattneree7286f2011-06-14 04:51:15 +00004026 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00004027 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00004028 return;
4029
John McCall70aa5392010-01-06 05:24:50 +00004030 if (SourceRange.Width == 64 && TargetRange.Width == 32)
Anna Zaks314cd092012-02-01 19:08:57 +00004031 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
4032 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00004033 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00004034 }
4035
4036 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
4037 (!TargetRange.NonNegative && SourceRange.NonNegative &&
4038 SourceRange.Width == TargetRange.Width)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00004039
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00004040 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00004041 return;
4042
John McCallcc7e5bf2010-05-06 08:58:33 +00004043 unsigned DiagID = diag::warn_impcast_integer_sign;
4044
4045 // Traditionally, gcc has warned about this under -Wsign-compare.
4046 // We also want to warn about it in -Wconversion.
4047 // So if -Wconversion is off, use a completely identical diagnostic
4048 // in the sign-compare group.
4049 // The conditional-checking code will
4050 if (ICContext) {
4051 DiagID = diag::warn_impcast_integer_sign_conditional;
4052 *ICContext = true;
4053 }
4054
John McCallacf0ee52010-10-08 02:01:28 +00004055 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00004056 }
4057
Douglas Gregora78f1932011-02-22 02:45:07 +00004058 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00004059 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
4060 // type, to give us better diagnostics.
4061 QualType SourceType = E->getType();
4062 if (!S.getLangOptions().CPlusPlus) {
4063 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
4064 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
4065 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
4066 SourceType = S.Context.getTypeDeclType(Enum);
4067 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
4068 }
4069 }
4070
Douglas Gregora78f1932011-02-22 02:45:07 +00004071 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
4072 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
4073 if ((SourceEnum->getDecl()->getIdentifier() ||
Richard Smithdda56e42011-04-15 14:24:37 +00004074 SourceEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Douglas Gregora78f1932011-02-22 02:45:07 +00004075 (TargetEnum->getDecl()->getIdentifier() ||
Richard Smithdda56e42011-04-15 14:24:37 +00004076 TargetEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00004077 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00004078 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00004079 return;
4080
Douglas Gregor364f7db2011-03-12 00:14:31 +00004081 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00004082 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00004083 }
Douglas Gregora78f1932011-02-22 02:45:07 +00004084
John McCall263a48b2010-01-04 23:31:57 +00004085 return;
4086}
4087
John McCallcc7e5bf2010-05-06 08:58:33 +00004088void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T);
4089
4090void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00004091 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00004092 E = E->IgnoreParenImpCasts();
4093
4094 if (isa<ConditionalOperator>(E))
4095 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T);
4096
John McCallacf0ee52010-10-08 02:01:28 +00004097 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00004098 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00004099 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00004100 return;
4101}
4102
4103void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) {
John McCallacf0ee52010-10-08 02:01:28 +00004104 SourceLocation CC = E->getQuestionLoc();
4105
4106 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00004107
4108 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00004109 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
4110 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00004111
4112 // If -Wconversion would have warned about either of the candidates
4113 // for a signedness conversion to the context type...
4114 if (!Suspicious) return;
4115
4116 // ...but it's currently ignored...
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00004117 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
4118 CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00004119 return;
4120
John McCallcc7e5bf2010-05-06 08:58:33 +00004121 // ...then check whether it would have warned about either of the
4122 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00004123 if (E->getType() == T) return;
4124
4125 Suspicious = false;
4126 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
4127 E->getType(), CC, &Suspicious);
4128 if (!Suspicious)
4129 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00004130 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00004131}
4132
4133/// AnalyzeImplicitConversions - Find and report any interesting
4134/// implicit conversions in the given expression. There are a couple
4135/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00004136void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00004137 QualType T = OrigE->getType();
4138 Expr *E = OrigE->IgnoreParenImpCasts();
4139
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00004140 if (E->isTypeDependent() || E->isValueDependent())
4141 return;
4142
John McCallcc7e5bf2010-05-06 08:58:33 +00004143 // For conditional operators, we analyze the arguments as if they
4144 // were being fed directly into the output.
4145 if (isa<ConditionalOperator>(E)) {
4146 ConditionalOperator *CO = cast<ConditionalOperator>(E);
4147 CheckConditionalOperator(S, CO, T);
4148 return;
4149 }
4150
4151 // Go ahead and check any implicit conversions we might have skipped.
4152 // The non-canonical typecheck is just an optimization;
4153 // CheckImplicitConversion will filter out dead implicit conversions.
4154 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00004155 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00004156
4157 // Now continue drilling into this expression.
4158
4159 // Skip past explicit casts.
4160 if (isa<ExplicitCastExpr>(E)) {
4161 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00004162 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00004163 }
4164
John McCalld2a53122010-11-09 23:24:47 +00004165 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4166 // Do a somewhat different check with comparison operators.
4167 if (BO->isComparisonOp())
4168 return AnalyzeComparison(S, BO);
4169
Eli Friedman66b63952012-01-26 23:34:06 +00004170 // And with simple assignments.
4171 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00004172 return AnalyzeAssignment(S, BO);
4173 }
John McCallcc7e5bf2010-05-06 08:58:33 +00004174
4175 // These break the otherwise-useful invariant below. Fortunately,
4176 // we don't really need to recurse into them, because any internal
4177 // expressions should have been analyzed already when they were
4178 // built into statements.
4179 if (isa<StmtExpr>(E)) return;
4180
4181 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00004182 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00004183
4184 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00004185 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00004186 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
4187 bool IsLogicalOperator = BO && BO->isLogicalOp();
4188 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor73456262012-02-09 10:18:50 +00004189 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00004190 if (!ChildExpr)
4191 continue;
4192
Richard Trieu021baa32011-09-23 20:10:00 +00004193 if (IsLogicalOperator &&
4194 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
4195 // Ignore checking string literals that are in logical operators.
4196 continue;
4197 AnalyzeImplicitConversions(S, ChildExpr, CC);
4198 }
John McCallcc7e5bf2010-05-06 08:58:33 +00004199}
4200
4201} // end anonymous namespace
4202
4203/// Diagnoses "dangerous" implicit conversions within the given
4204/// expression (which is a full expression). Implements -Wconversion
4205/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00004206///
4207/// \param CC the "context" location of the implicit conversion, i.e.
4208/// the most location of the syntactic entity requiring the implicit
4209/// conversion
4210void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00004211 // Don't diagnose in unevaluated contexts.
4212 if (ExprEvalContexts.back().Context == Sema::Unevaluated)
4213 return;
4214
4215 // Don't diagnose for value- or type-dependent expressions.
4216 if (E->isTypeDependent() || E->isValueDependent())
4217 return;
4218
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00004219 // Check for array bounds violations in cases where the check isn't triggered
4220 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
4221 // ArraySubscriptExpr is on the RHS of a variable initialization.
4222 CheckArrayAccess(E);
4223
John McCallacf0ee52010-10-08 02:01:28 +00004224 // This is not the right CC for (e.g.) a variable initialization.
4225 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00004226}
4227
John McCall1f425642010-11-11 03:21:53 +00004228void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
4229 FieldDecl *BitField,
4230 Expr *Init) {
4231 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
4232}
4233
Mike Stump0c2ec772010-01-21 03:59:47 +00004234/// CheckParmsForFunctionDef - Check that the parameters of the given
4235/// function are appropriate for the definition of a function. This
4236/// takes care of any checks that cannot be performed on the
4237/// declaration itself, e.g., that the types of each of the function
4238/// parameters are complete.
Douglas Gregorb524d902010-11-01 18:37:59 +00004239bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
4240 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00004241 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00004242 for (; P != PEnd; ++P) {
4243 ParmVarDecl *Param = *P;
4244
Mike Stump0c2ec772010-01-21 03:59:47 +00004245 // C99 6.7.5.3p4: the parameters in a parameter type list in a
4246 // function declarator that is part of a function definition of
4247 // that function shall not have incomplete type.
4248 //
4249 // This is also C++ [dcl.fct]p6.
4250 if (!Param->isInvalidDecl() &&
4251 RequireCompleteType(Param->getLocation(), Param->getType(),
4252 diag::err_typecheck_decl_incomplete_type)) {
4253 Param->setInvalidDecl();
4254 HasInvalidParm = true;
4255 }
4256
4257 // C99 6.9.1p5: If the declarator includes a parameter type list, the
4258 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00004259 if (CheckParameterNames &&
4260 Param->getIdentifier() == 0 &&
Mike Stump0c2ec772010-01-21 03:59:47 +00004261 !Param->isImplicit() &&
4262 !getLangOptions().CPlusPlus)
4263 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00004264
4265 // C99 6.7.5.3p12:
4266 // If the function declarator is not part of a definition of that
4267 // function, parameters may have incomplete type and may use the [*]
4268 // notation in their sequences of declarator specifiers to specify
4269 // variable length array types.
4270 QualType PType = Param->getOriginalType();
4271 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
4272 if (AT->getSizeModifier() == ArrayType::Star) {
4273 // FIXME: This diagnosic should point the the '[*]' if source-location
4274 // information is added for it.
4275 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
4276 }
4277 }
Mike Stump0c2ec772010-01-21 03:59:47 +00004278 }
4279
4280 return HasInvalidParm;
4281}
John McCall2b5c1b22010-08-12 21:44:57 +00004282
4283/// CheckCastAlign - Implements -Wcast-align, which warns when a
4284/// pointer cast increases the alignment requirements.
4285void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
4286 // This is actually a lot of work to potentially be doing on every
4287 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00004288 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
4289 TRange.getBegin())
David Blaikie9c902b52011-09-25 23:23:43 +00004290 == DiagnosticsEngine::Ignored)
John McCall2b5c1b22010-08-12 21:44:57 +00004291 return;
4292
4293 // Ignore dependent types.
4294 if (T->isDependentType() || Op->getType()->isDependentType())
4295 return;
4296
4297 // Require that the destination be a pointer type.
4298 const PointerType *DestPtr = T->getAs<PointerType>();
4299 if (!DestPtr) return;
4300
4301 // If the destination has alignment 1, we're done.
4302 QualType DestPointee = DestPtr->getPointeeType();
4303 if (DestPointee->isIncompleteType()) return;
4304 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
4305 if (DestAlign.isOne()) return;
4306
4307 // Require that the source be a pointer type.
4308 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
4309 if (!SrcPtr) return;
4310 QualType SrcPointee = SrcPtr->getPointeeType();
4311
4312 // Whitelist casts from cv void*. We already implicitly
4313 // whitelisted casts to cv void*, since they have alignment 1.
4314 // Also whitelist casts involving incomplete types, which implicitly
4315 // includes 'void'.
4316 if (SrcPointee->isIncompleteType()) return;
4317
4318 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
4319 if (SrcAlign >= DestAlign) return;
4320
4321 Diag(TRange.getBegin(), diag::warn_cast_align)
4322 << Op->getType() << T
4323 << static_cast<unsigned>(SrcAlign.getQuantity())
4324 << static_cast<unsigned>(DestAlign.getQuantity())
4325 << TRange << Op->getSourceRange();
4326}
4327
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00004328static const Type* getElementType(const Expr *BaseExpr) {
4329 const Type* EltType = BaseExpr->getType().getTypePtr();
4330 if (EltType->isAnyPointerType())
4331 return EltType->getPointeeType().getTypePtr();
4332 else if (EltType->isArrayType())
4333 return EltType->getBaseElementTypeUnsafe();
4334 return EltType;
4335}
4336
Chandler Carruth28389f02011-08-05 09:10:50 +00004337/// \brief Check whether this array fits the idiom of a size-one tail padded
4338/// array member of a struct.
4339///
4340/// We avoid emitting out-of-bounds access warnings for such arrays as they are
4341/// commonly used to emulate flexible arrays in C89 code.
4342static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
4343 const NamedDecl *ND) {
4344 if (Size != 1 || !ND) return false;
4345
4346 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
4347 if (!FD) return false;
4348
4349 // Don't consider sizes resulting from macro expansions or template argument
4350 // substitution to form C89 tail-padded arrays.
4351 ConstantArrayTypeLoc TL =
4352 cast<ConstantArrayTypeLoc>(FD->getTypeSourceInfo()->getTypeLoc());
4353 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(TL.getSizeExpr());
4354 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
4355 return false;
4356
4357 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00004358 if (!RD) return false;
4359 if (RD->isUnion()) return false;
4360 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
4361 if (!CRD->isStandardLayout()) return false;
4362 }
Chandler Carruth28389f02011-08-05 09:10:50 +00004363
Benjamin Kramer8c543672011-08-06 03:04:42 +00004364 // See if this is the last field decl in the record.
4365 const Decl *D = FD;
4366 while ((D = D->getNextDeclInContext()))
4367 if (isa<FieldDecl>(D))
4368 return false;
4369 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00004370}
4371
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00004372void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00004373 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00004374 bool AllowOnePastEnd, bool IndexNegated) {
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00004375 IndexExpr = IndexExpr->IgnoreParenCasts();
4376 if (IndexExpr->isValueDependent())
4377 return;
4378
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00004379 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00004380 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00004381 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00004382 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00004383 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00004384 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00004385
Chandler Carruth2a666fc2011-02-17 20:55:08 +00004386 llvm::APSInt index;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00004387 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremenek64699be2011-02-16 01:57:07 +00004388 return;
Richard Smith13f67182011-12-16 19:31:14 +00004389 if (IndexNegated)
4390 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00004391
Chandler Carruth126b1552011-08-05 08:07:29 +00004392 const NamedDecl *ND = NULL;
Chandler Carruth126b1552011-08-05 08:07:29 +00004393 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
4394 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00004395 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00004396 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00004397
Ted Kremeneke4b316c2011-02-23 23:06:04 +00004398 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00004399 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00004400 if (!size.isStrictlyPositive())
4401 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00004402
4403 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00004404 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00004405 // Make sure we're comparing apples to apples when comparing index to size
4406 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
4407 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00004408 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00004409 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00004410 if (ptrarith_typesize != array_typesize) {
4411 // There's a cast to a different size type involved
4412 uint64_t ratio = array_typesize / ptrarith_typesize;
4413 // TODO: Be smarter about handling cases where array_typesize is not a
4414 // multiple of ptrarith_typesize
4415 if (ptrarith_typesize * ratio == array_typesize)
4416 size *= llvm::APInt(size.getBitWidth(), ratio);
4417 }
4418 }
4419
Chandler Carruth2a666fc2011-02-17 20:55:08 +00004420 if (size.getBitWidth() > index.getBitWidth())
4421 index = index.sext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00004422 else if (size.getBitWidth() < index.getBitWidth())
4423 size = size.sext(index.getBitWidth());
4424
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00004425 // For array subscripting the index must be less than size, but for pointer
4426 // arithmetic also allow the index (offset) to be equal to size since
4427 // computing the next address after the end of the array is legal and
4428 // commonly done e.g. in C++ iterators and range-based for loops.
4429 if (AllowOnePastEnd ? index.sle(size) : index.slt(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00004430 return;
4431
4432 // Also don't warn for arrays of size 1 which are members of some
4433 // structure. These are often used to approximate flexible arrays in C89
4434 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00004435 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00004436 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00004437
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00004438 // Suppress the warning if the subscript expression (as identified by the
4439 // ']' location) and the index expression are both from macro expansions
4440 // within a system header.
4441 if (ASE) {
4442 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
4443 ASE->getRBracketLoc());
4444 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
4445 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
4446 IndexExpr->getLocStart());
4447 if (SourceMgr.isFromSameFile(RBracketLoc, IndexLoc))
4448 return;
4449 }
4450 }
4451
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00004452 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00004453 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00004454 DiagID = diag::warn_array_index_exceeds_bounds;
4455
4456 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
4457 PDiag(DiagID) << index.toString(10, true)
4458 << size.toString(10, true)
4459 << (unsigned)size.getLimitedValue(~0U)
4460 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00004461 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00004462 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00004463 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00004464 DiagID = diag::warn_ptr_arith_precedes_bounds;
4465 if (index.isNegative()) index = -index;
4466 }
4467
4468 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
4469 PDiag(DiagID) << index.toString(10, true)
4470 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00004471 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00004472
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00004473 if (!ND) {
4474 // Try harder to find a NamedDecl to point at in the note.
4475 while (const ArraySubscriptExpr *ASE =
4476 dyn_cast<ArraySubscriptExpr>(BaseExpr))
4477 BaseExpr = ASE->getBase()->IgnoreParenCasts();
4478 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
4479 ND = dyn_cast<NamedDecl>(DRE->getDecl());
4480 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
4481 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
4482 }
4483
Chandler Carruth1af88f12011-02-17 21:10:52 +00004484 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00004485 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
4486 PDiag(diag::note_array_index_out_of_bounds)
4487 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00004488}
4489
Ted Kremenekdf26df72011-03-01 18:41:00 +00004490void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00004491 int AllowOnePastEnd = 0;
4492 while (expr) {
4493 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00004494 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00004495 case Stmt::ArraySubscriptExprClass: {
4496 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00004497 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00004498 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00004499 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00004500 }
4501 case Stmt::UnaryOperatorClass: {
4502 // Only unwrap the * and & unary operators
4503 const UnaryOperator *UO = cast<UnaryOperator>(expr);
4504 expr = UO->getSubExpr();
4505 switch (UO->getOpcode()) {
4506 case UO_AddrOf:
4507 AllowOnePastEnd++;
4508 break;
4509 case UO_Deref:
4510 AllowOnePastEnd--;
4511 break;
4512 default:
4513 return;
4514 }
4515 break;
4516 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00004517 case Stmt::ConditionalOperatorClass: {
4518 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
4519 if (const Expr *lhs = cond->getLHS())
4520 CheckArrayAccess(lhs);
4521 if (const Expr *rhs = cond->getRHS())
4522 CheckArrayAccess(rhs);
4523 return;
4524 }
4525 default:
4526 return;
4527 }
Peter Collingbourne91147592011-04-15 00:35:48 +00004528 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00004529}
John McCall31168b02011-06-15 23:02:42 +00004530
4531//===--- CHECK: Objective-C retain cycles ----------------------------------//
4532
4533namespace {
4534 struct RetainCycleOwner {
4535 RetainCycleOwner() : Variable(0), Indirect(false) {}
4536 VarDecl *Variable;
4537 SourceRange Range;
4538 SourceLocation Loc;
4539 bool Indirect;
4540
4541 void setLocsFrom(Expr *e) {
4542 Loc = e->getExprLoc();
4543 Range = e->getSourceRange();
4544 }
4545 };
4546}
4547
4548/// Consider whether capturing the given variable can possibly lead to
4549/// a retain cycle.
4550static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
4551 // In ARC, it's captured strongly iff the variable has __strong
4552 // lifetime. In MRR, it's captured strongly if the variable is
4553 // __block and has an appropriate type.
4554 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
4555 return false;
4556
4557 owner.Variable = var;
4558 owner.setLocsFrom(ref);
4559 return true;
4560}
4561
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00004562static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00004563 while (true) {
4564 e = e->IgnoreParens();
4565 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
4566 switch (cast->getCastKind()) {
4567 case CK_BitCast:
4568 case CK_LValueBitCast:
4569 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00004570 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00004571 e = cast->getSubExpr();
4572 continue;
4573
John McCall31168b02011-06-15 23:02:42 +00004574 default:
4575 return false;
4576 }
4577 }
4578
4579 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
4580 ObjCIvarDecl *ivar = ref->getDecl();
4581 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
4582 return false;
4583
4584 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00004585 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00004586 return false;
4587
4588 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
4589 owner.Indirect = true;
4590 return true;
4591 }
4592
4593 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
4594 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
4595 if (!var) return false;
4596 return considerVariable(var, ref, owner);
4597 }
4598
4599 if (BlockDeclRefExpr *ref = dyn_cast<BlockDeclRefExpr>(e)) {
4600 owner.Variable = ref->getDecl();
4601 owner.setLocsFrom(ref);
4602 return true;
4603 }
4604
4605 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
4606 if (member->isArrow()) return false;
4607
4608 // Don't count this as an indirect ownership.
4609 e = member->getBase();
4610 continue;
4611 }
4612
John McCallfe96e0b2011-11-06 09:01:30 +00004613 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
4614 // Only pay attention to pseudo-objects on property references.
4615 ObjCPropertyRefExpr *pre
4616 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
4617 ->IgnoreParens());
4618 if (!pre) return false;
4619 if (pre->isImplicitProperty()) return false;
4620 ObjCPropertyDecl *property = pre->getExplicitProperty();
4621 if (!property->isRetaining() &&
4622 !(property->getPropertyIvarDecl() &&
4623 property->getPropertyIvarDecl()->getType()
4624 .getObjCLifetime() == Qualifiers::OCL_Strong))
4625 return false;
4626
4627 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00004628 if (pre->isSuperReceiver()) {
4629 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
4630 if (!owner.Variable)
4631 return false;
4632 owner.Loc = pre->getLocation();
4633 owner.Range = pre->getSourceRange();
4634 return true;
4635 }
John McCallfe96e0b2011-11-06 09:01:30 +00004636 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
4637 ->getSourceExpr());
4638 continue;
4639 }
4640
John McCall31168b02011-06-15 23:02:42 +00004641 // Array ivars?
4642
4643 return false;
4644 }
4645}
4646
4647namespace {
4648 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
4649 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
4650 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
4651 Variable(variable), Capturer(0) {}
4652
4653 VarDecl *Variable;
4654 Expr *Capturer;
4655
4656 void VisitDeclRefExpr(DeclRefExpr *ref) {
4657 if (ref->getDecl() == Variable && !Capturer)
4658 Capturer = ref;
4659 }
4660
4661 void VisitBlockDeclRefExpr(BlockDeclRefExpr *ref) {
4662 if (ref->getDecl() == Variable && !Capturer)
4663 Capturer = ref;
4664 }
4665
4666 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
4667 if (Capturer) return;
4668 Visit(ref->getBase());
4669 if (Capturer && ref->isFreeIvar())
4670 Capturer = ref;
4671 }
4672
4673 void VisitBlockExpr(BlockExpr *block) {
4674 // Look inside nested blocks
4675 if (block->getBlockDecl()->capturesVariable(Variable))
4676 Visit(block->getBlockDecl()->getBody());
4677 }
4678 };
4679}
4680
4681/// Check whether the given argument is a block which captures a
4682/// variable.
4683static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
4684 assert(owner.Variable && owner.Loc.isValid());
4685
4686 e = e->IgnoreParenCasts();
4687 BlockExpr *block = dyn_cast<BlockExpr>(e);
4688 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
4689 return 0;
4690
4691 FindCaptureVisitor visitor(S.Context, owner.Variable);
4692 visitor.Visit(block->getBlockDecl()->getBody());
4693 return visitor.Capturer;
4694}
4695
4696static void diagnoseRetainCycle(Sema &S, Expr *capturer,
4697 RetainCycleOwner &owner) {
4698 assert(capturer);
4699 assert(owner.Variable && owner.Loc.isValid());
4700
4701 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
4702 << owner.Variable << capturer->getSourceRange();
4703 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
4704 << owner.Indirect << owner.Range;
4705}
4706
4707/// Check for a keyword selector that starts with the word 'add' or
4708/// 'set'.
4709static bool isSetterLikeSelector(Selector sel) {
4710 if (sel.isUnarySelector()) return false;
4711
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004712 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00004713 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00004714 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00004715 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00004716 else if (str.startswith("add")) {
4717 // Specially whitelist 'addOperationWithBlock:'.
4718 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
4719 return false;
4720 str = str.substr(3);
4721 }
John McCall31168b02011-06-15 23:02:42 +00004722 else
4723 return false;
4724
4725 if (str.empty()) return true;
4726 return !islower(str.front());
4727}
4728
4729/// Check a message send to see if it's likely to cause a retain cycle.
4730void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
4731 // Only check instance methods whose selector looks like a setter.
4732 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
4733 return;
4734
4735 // Try to find a variable that the receiver is strongly owned by.
4736 RetainCycleOwner owner;
4737 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00004738 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00004739 return;
4740 } else {
4741 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
4742 owner.Variable = getCurMethodDecl()->getSelfDecl();
4743 owner.Loc = msg->getSuperLoc();
4744 owner.Range = msg->getSuperLoc();
4745 }
4746
4747 // Check whether the receiver is captured by any of the arguments.
4748 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
4749 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
4750 return diagnoseRetainCycle(*this, capturer, owner);
4751}
4752
4753/// Check a property assign to see if it's likely to cause a retain cycle.
4754void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
4755 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00004756 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00004757 return;
4758
4759 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
4760 diagnoseRetainCycle(*this, capturer, owner);
4761}
4762
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00004763bool Sema::checkUnsafeAssigns(SourceLocation Loc,
John McCall31168b02011-06-15 23:02:42 +00004764 QualType LHS, Expr *RHS) {
4765 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
4766 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00004767 return false;
4768 // strip off any implicit cast added to get to the one arc-specific
4769 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00004770 if (cast->getCastKind() == CK_ARCConsumeObject) {
John McCall31168b02011-06-15 23:02:42 +00004771 Diag(Loc, diag::warn_arc_retained_assign)
4772 << (LT == Qualifiers::OCL_ExplicitNone)
4773 << RHS->getSourceRange();
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00004774 return true;
4775 }
4776 RHS = cast->getSubExpr();
4777 }
4778 return false;
John McCall31168b02011-06-15 23:02:42 +00004779}
4780
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00004781void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
4782 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00004783 QualType LHSType;
4784 // PropertyRef on LHS type need be directly obtained from
4785 // its declaration as it has a PsuedoType.
4786 ObjCPropertyRefExpr *PRE
4787 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
4788 if (PRE && !PRE->isImplicitProperty()) {
4789 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
4790 if (PD)
4791 LHSType = PD->getType();
4792 }
4793
4794 if (LHSType.isNull())
4795 LHSType = LHS->getType();
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00004796 if (checkUnsafeAssigns(Loc, LHSType, RHS))
4797 return;
4798 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
4799 // FIXME. Check for other life times.
4800 if (LT != Qualifiers::OCL_None)
4801 return;
4802
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00004803 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00004804 if (PRE->isImplicitProperty())
4805 return;
4806 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
4807 if (!PD)
4808 return;
4809
4810 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00004811 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
4812 // when 'assign' attribute was not explicitly specified
4813 // by user, ignore it and rely on property type itself
4814 // for lifetime info.
4815 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
4816 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
4817 LHSType->isObjCRetainableType())
4818 return;
4819
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00004820 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00004821 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00004822 Diag(Loc, diag::warn_arc_retained_property_assign)
4823 << RHS->getSourceRange();
4824 return;
4825 }
4826 RHS = cast->getSubExpr();
4827 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00004828 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00004829 }
4830}