blob: 092bf5b5970ae47029ef189ab75b84e47315aac2 [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"
33#include "llvm/ADT/STLExtras.h"
Tom Careb7042702010-06-09 04:11:11 +000034#include "llvm/Support/raw_ostream.h"
Eric Christopher8d0c6212010-04-17 02:26:23 +000035#include "clang/Basic/TargetBuiltins.h"
Nate Begeman4904e322010-06-08 02:47:44 +000036#include "clang/Basic/TargetInfo.h"
Fariborz Jahanian56603ef2010-09-07 19:38:13 +000037#include "clang/Basic/ConvertUTF.h"
Zhongxing Xu050379b2009-05-20 01:55:10 +000038#include <limits>
Chris Lattnerb87b1b32007-08-10 20:18:51 +000039using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000040using namespace sema;
Chris Lattnerb87b1b32007-08-10 20:18:51 +000041
Chris Lattnera26fb342009-02-18 17:49:48 +000042SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
43 unsigned ByteNo) const {
Chris Lattnere925d612010-11-17 07:37:15 +000044 return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
45 PP.getLangOptions(), PP.getTargetInfo());
Chris Lattnera26fb342009-02-18 17:49:48 +000046}
47
John McCallbebede42011-02-26 05:39:39 +000048/// Checks that a call expression's argument count is the desired number.
49/// This is useful when doing custom type-checking. Returns true on error.
50static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
51 unsigned argCount = call->getNumArgs();
52 if (argCount == desiredArgCount) return false;
53
54 if (argCount < desiredArgCount)
55 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
56 << 0 /*function call*/ << desiredArgCount << argCount
57 << call->getSourceRange();
58
59 // Highlight all the excess arguments.
60 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
61 call->getArg(argCount - 1)->getLocEnd());
62
63 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
64 << 0 /*function call*/ << desiredArgCount << argCount
65 << call->getArg(1)->getSourceRange();
66}
67
Julien Lerouge5a6b6982011-09-09 22:41:49 +000068/// CheckBuiltinAnnotationString - Checks that string argument to the builtin
69/// annotation is a non wide string literal.
70static bool CheckBuiltinAnnotationString(Sema &S, Expr *Arg) {
71 Arg = Arg->IgnoreParenCasts();
72 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
73 if (!Literal || !Literal->isAscii()) {
74 S.Diag(Arg->getLocStart(), diag::err_builtin_annotation_not_string_constant)
75 << Arg->getSourceRange();
76 return true;
77 }
78 return false;
79}
80
John McCalldadc5752010-08-24 06:29:42 +000081ExprResult
Anders Carlssonbc4c1072009-08-16 01:56:34 +000082Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
John McCalldadc5752010-08-24 06:29:42 +000083 ExprResult TheCallResult(Owned(TheCall));
Douglas Gregorae2fbad2008-11-17 20:34:05 +000084
Chris Lattner3be167f2010-10-01 23:23:24 +000085 // Find out if any arguments are required to be integer constant expressions.
86 unsigned ICEArguments = 0;
87 ASTContext::GetBuiltinTypeError Error;
88 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
89 if (Error != ASTContext::GE_None)
90 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
91
92 // If any arguments are required to be ICE's, check and diagnose.
93 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
94 // Skip arguments not required to be ICE's.
95 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
96
97 llvm::APSInt Result;
98 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
99 return true;
100 ICEArguments &= ~(1 << ArgNo);
101 }
102
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000103 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000104 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000105 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000106 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000107 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000108 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000109 break;
Ted Kremeneka174c522008-07-09 17:58:53 +0000110 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000111 case Builtin::BI__builtin_va_start:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000112 if (SemaBuiltinVAStart(TheCall))
113 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000114 break;
Chris Lattner2da14fb2007-12-20 00:26:33 +0000115 case Builtin::BI__builtin_isgreater:
116 case Builtin::BI__builtin_isgreaterequal:
117 case Builtin::BI__builtin_isless:
118 case Builtin::BI__builtin_islessequal:
119 case Builtin::BI__builtin_islessgreater:
120 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000121 if (SemaBuiltinUnorderedCompare(TheCall))
122 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000123 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000124 case Builtin::BI__builtin_fpclassify:
125 if (SemaBuiltinFPClassification(TheCall, 6))
126 return ExprError();
127 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000128 case Builtin::BI__builtin_isfinite:
129 case Builtin::BI__builtin_isinf:
130 case Builtin::BI__builtin_isinf_sign:
131 case Builtin::BI__builtin_isnan:
132 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000133 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000134 return ExprError();
135 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000136 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000137 return SemaBuiltinShuffleVector(TheCall);
138 // TheCall will be freed by the smart pointer here, but that's fine, since
139 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000140 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000141 if (SemaBuiltinPrefetch(TheCall))
142 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000143 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000144 case Builtin::BI__builtin_object_size:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000145 if (SemaBuiltinObjectSize(TheCall))
146 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000147 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000148 case Builtin::BI__builtin_longjmp:
149 if (SemaBuiltinLongjmp(TheCall))
150 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000151 break;
John McCallbebede42011-02-26 05:39:39 +0000152
153 case Builtin::BI__builtin_classify_type:
154 if (checkArgCount(*this, TheCall, 1)) return true;
155 TheCall->setType(Context.IntTy);
156 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000157 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000158 if (checkArgCount(*this, TheCall, 1)) return true;
159 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000160 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000161 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000162 case Builtin::BI__sync_fetch_and_add_1:
163 case Builtin::BI__sync_fetch_and_add_2:
164 case Builtin::BI__sync_fetch_and_add_4:
165 case Builtin::BI__sync_fetch_and_add_8:
166 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000167 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000168 case Builtin::BI__sync_fetch_and_sub_1:
169 case Builtin::BI__sync_fetch_and_sub_2:
170 case Builtin::BI__sync_fetch_and_sub_4:
171 case Builtin::BI__sync_fetch_and_sub_8:
172 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000173 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000174 case Builtin::BI__sync_fetch_and_or_1:
175 case Builtin::BI__sync_fetch_and_or_2:
176 case Builtin::BI__sync_fetch_and_or_4:
177 case Builtin::BI__sync_fetch_and_or_8:
178 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000179 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000180 case Builtin::BI__sync_fetch_and_and_1:
181 case Builtin::BI__sync_fetch_and_and_2:
182 case Builtin::BI__sync_fetch_and_and_4:
183 case Builtin::BI__sync_fetch_and_and_8:
184 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000185 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000186 case Builtin::BI__sync_fetch_and_xor_1:
187 case Builtin::BI__sync_fetch_and_xor_2:
188 case Builtin::BI__sync_fetch_and_xor_4:
189 case Builtin::BI__sync_fetch_and_xor_8:
190 case Builtin::BI__sync_fetch_and_xor_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000191 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000192 case Builtin::BI__sync_add_and_fetch_1:
193 case Builtin::BI__sync_add_and_fetch_2:
194 case Builtin::BI__sync_add_and_fetch_4:
195 case Builtin::BI__sync_add_and_fetch_8:
196 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000197 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000198 case Builtin::BI__sync_sub_and_fetch_1:
199 case Builtin::BI__sync_sub_and_fetch_2:
200 case Builtin::BI__sync_sub_and_fetch_4:
201 case Builtin::BI__sync_sub_and_fetch_8:
202 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000203 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000204 case Builtin::BI__sync_and_and_fetch_1:
205 case Builtin::BI__sync_and_and_fetch_2:
206 case Builtin::BI__sync_and_and_fetch_4:
207 case Builtin::BI__sync_and_and_fetch_8:
208 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000209 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000210 case Builtin::BI__sync_or_and_fetch_1:
211 case Builtin::BI__sync_or_and_fetch_2:
212 case Builtin::BI__sync_or_and_fetch_4:
213 case Builtin::BI__sync_or_and_fetch_8:
214 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000215 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000216 case Builtin::BI__sync_xor_and_fetch_1:
217 case Builtin::BI__sync_xor_and_fetch_2:
218 case Builtin::BI__sync_xor_and_fetch_4:
219 case Builtin::BI__sync_xor_and_fetch_8:
220 case Builtin::BI__sync_xor_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000221 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000222 case Builtin::BI__sync_val_compare_and_swap_1:
223 case Builtin::BI__sync_val_compare_and_swap_2:
224 case Builtin::BI__sync_val_compare_and_swap_4:
225 case Builtin::BI__sync_val_compare_and_swap_8:
226 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000227 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000228 case Builtin::BI__sync_bool_compare_and_swap_1:
229 case Builtin::BI__sync_bool_compare_and_swap_2:
230 case Builtin::BI__sync_bool_compare_and_swap_4:
231 case Builtin::BI__sync_bool_compare_and_swap_8:
232 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000233 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +0000234 case Builtin::BI__sync_lock_test_and_set_1:
235 case Builtin::BI__sync_lock_test_and_set_2:
236 case Builtin::BI__sync_lock_test_and_set_4:
237 case Builtin::BI__sync_lock_test_and_set_8:
238 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000239 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +0000240 case Builtin::BI__sync_lock_release_1:
241 case Builtin::BI__sync_lock_release_2:
242 case Builtin::BI__sync_lock_release_4:
243 case Builtin::BI__sync_lock_release_8:
244 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000245 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000246 case Builtin::BI__sync_swap_1:
247 case Builtin::BI__sync_swap_2:
248 case Builtin::BI__sync_swap_4:
249 case Builtin::BI__sync_swap_8:
250 case Builtin::BI__sync_swap_16:
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000251 return SemaBuiltinAtomicOverloaded(move(TheCallResult));
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000252 case Builtin::BI__atomic_load:
253 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Load);
254 case Builtin::BI__atomic_store:
255 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Store);
David Chisnallfa35df62012-01-16 17:27:18 +0000256 case Builtin::BI__atomic_init:
257 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Init);
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000258 case Builtin::BI__atomic_exchange:
259 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Xchg);
260 case Builtin::BI__atomic_compare_exchange_strong:
261 return SemaAtomicOpsOverloaded(move(TheCallResult),
262 AtomicExpr::CmpXchgStrong);
263 case Builtin::BI__atomic_compare_exchange_weak:
264 return SemaAtomicOpsOverloaded(move(TheCallResult),
265 AtomicExpr::CmpXchgWeak);
266 case Builtin::BI__atomic_fetch_add:
267 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Add);
268 case Builtin::BI__atomic_fetch_sub:
269 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Sub);
270 case Builtin::BI__atomic_fetch_and:
271 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::And);
272 case Builtin::BI__atomic_fetch_or:
273 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Or);
274 case Builtin::BI__atomic_fetch_xor:
275 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Xor);
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000276 case Builtin::BI__builtin_annotation:
277 if (CheckBuiltinAnnotationString(*this, TheCall->getArg(1)))
278 return ExprError();
279 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000280 }
281
282 // Since the target specific builtins for each arch overlap, only check those
283 // of the arch we are compiling for.
284 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000285 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +0000286 case llvm::Triple::arm:
287 case llvm::Triple::thumb:
288 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
289 return ExprError();
290 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000291 default:
292 break;
293 }
294 }
295
296 return move(TheCallResult);
297}
298
Nate Begeman91e1fea2010-06-14 05:21:25 +0000299// Get the valid immediate range for the specified NEON type code.
300static unsigned RFT(unsigned t, bool shift = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +0000301 NeonTypeFlags Type(t);
302 int IsQuad = Type.isQuad();
303 switch (Type.getEltType()) {
304 case NeonTypeFlags::Int8:
305 case NeonTypeFlags::Poly8:
306 return shift ? 7 : (8 << IsQuad) - 1;
307 case NeonTypeFlags::Int16:
308 case NeonTypeFlags::Poly16:
309 return shift ? 15 : (4 << IsQuad) - 1;
310 case NeonTypeFlags::Int32:
311 return shift ? 31 : (2 << IsQuad) - 1;
312 case NeonTypeFlags::Int64:
313 return shift ? 63 : (1 << IsQuad) - 1;
314 case NeonTypeFlags::Float16:
315 assert(!shift && "cannot shift float types!");
316 return (4 << IsQuad) - 1;
317 case NeonTypeFlags::Float32:
318 assert(!shift && "cannot shift float types!");
319 return (2 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000320 }
David Blaikie8a40f702012-01-17 06:56:22 +0000321 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +0000322}
323
Bob Wilsone4d77232011-11-08 05:04:11 +0000324/// getNeonEltType - Return the QualType corresponding to the elements of
325/// the vector type specified by the NeonTypeFlags. This is used to check
326/// the pointer arguments for Neon load/store intrinsics.
327static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context) {
328 switch (Flags.getEltType()) {
329 case NeonTypeFlags::Int8:
330 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
331 case NeonTypeFlags::Int16:
332 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
333 case NeonTypeFlags::Int32:
334 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
335 case NeonTypeFlags::Int64:
336 return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy;
337 case NeonTypeFlags::Poly8:
338 return Context.SignedCharTy;
339 case NeonTypeFlags::Poly16:
340 return Context.ShortTy;
341 case NeonTypeFlags::Float16:
342 return Context.UnsignedShortTy;
343 case NeonTypeFlags::Float32:
344 return Context.FloatTy;
345 }
David Blaikie8a40f702012-01-17 06:56:22 +0000346 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +0000347}
348
Nate Begeman4904e322010-06-08 02:47:44 +0000349bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +0000350 llvm::APSInt Result;
351
Nate Begemand773fe62010-06-13 04:47:52 +0000352 unsigned mask = 0;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000353 unsigned TV = 0;
Bob Wilson89d14242011-11-16 21:32:23 +0000354 int PtrArgNum = -1;
Bob Wilsone4d77232011-11-08 05:04:11 +0000355 bool HasConstPtr = false;
Nate Begeman55483092010-06-09 01:10:23 +0000356 switch (BuiltinID) {
Nate Begeman35f4c1c2010-06-17 04:17:01 +0000357#define GET_NEON_OVERLOAD_CHECK
358#include "clang/Basic/arm_neon.inc"
359#undef GET_NEON_OVERLOAD_CHECK
Nate Begeman55483092010-06-09 01:10:23 +0000360 }
361
Nate Begemand773fe62010-06-13 04:47:52 +0000362 // For NEON intrinsics which are overloaded on vector element type, validate
363 // the immediate which specifies which variant to emit.
Bob Wilsone4d77232011-11-08 05:04:11 +0000364 unsigned ImmArg = TheCall->getNumArgs()-1;
Nate Begemand773fe62010-06-13 04:47:52 +0000365 if (mask) {
Bob Wilsone4d77232011-11-08 05:04:11 +0000366 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
Nate Begemand773fe62010-06-13 04:47:52 +0000367 return true;
368
Bob Wilson98bc98c2011-11-08 01:16:11 +0000369 TV = Result.getLimitedValue(64);
370 if ((TV > 63) || (mask & (1 << TV)) == 0)
Nate Begemand773fe62010-06-13 04:47:52 +0000371 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Bob Wilsone4d77232011-11-08 05:04:11 +0000372 << TheCall->getArg(ImmArg)->getSourceRange();
373 }
374
Bob Wilson89d14242011-11-16 21:32:23 +0000375 if (PtrArgNum >= 0) {
Bob Wilsone4d77232011-11-08 05:04:11 +0000376 // Check that pointer arguments have the specified type.
Bob Wilson89d14242011-11-16 21:32:23 +0000377 Expr *Arg = TheCall->getArg(PtrArgNum);
378 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
379 Arg = ICE->getSubExpr();
380 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
381 QualType RHSTy = RHS.get()->getType();
382 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context);
383 if (HasConstPtr)
384 EltTy = EltTy.withConst();
385 QualType LHSTy = Context.getPointerType(EltTy);
386 AssignConvertType ConvTy;
387 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
388 if (RHS.isInvalid())
389 return true;
390 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
391 RHS.get(), AA_Assigning))
392 return true;
Nate Begemand773fe62010-06-13 04:47:52 +0000393 }
Nate Begeman55483092010-06-09 01:10:23 +0000394
Nate Begemand773fe62010-06-13 04:47:52 +0000395 // For NEON intrinsics which take an immediate value as part of the
396 // instruction, range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +0000397 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +0000398 switch (BuiltinID) {
399 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +0000400 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
401 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +0000402 case ARM::BI__builtin_arm_vcvtr_f:
403 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Nate Begeman35f4c1c2010-06-17 04:17:01 +0000404#define GET_NEON_IMMEDIATE_CHECK
405#include "clang/Basic/arm_neon.inc"
406#undef GET_NEON_IMMEDIATE_CHECK
Nate Begemand773fe62010-06-13 04:47:52 +0000407 };
408
Nate Begeman91e1fea2010-06-14 05:21:25 +0000409 // Check that the immediate argument is actually a constant.
Nate Begemand773fe62010-06-13 04:47:52 +0000410 if (SemaBuiltinConstantArg(TheCall, i, Result))
411 return true;
412
Nate Begeman91e1fea2010-06-14 05:21:25 +0000413 // Range check against the upper/lower values for this isntruction.
Nate Begemand773fe62010-06-13 04:47:52 +0000414 unsigned Val = Result.getZExtValue();
Nate Begeman91e1fea2010-06-14 05:21:25 +0000415 if (Val < l || Val > (u + l))
Nate Begemand773fe62010-06-13 04:47:52 +0000416 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramere8394df2010-08-11 14:47:12 +0000417 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begemand773fe62010-06-13 04:47:52 +0000418
Nate Begemanf568b072010-08-03 21:32:34 +0000419 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman4904e322010-06-08 02:47:44 +0000420 return false;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000421}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000422
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000423/// CheckFunctionCall - Check a direct function call for various correctness
424/// and safety properties not strictly enforced by the C type system.
425bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
426 // Get the IdentifierInfo* for the called function.
427 IdentifierInfo *FnInfo = FDecl->getIdentifier();
428
429 // None of the checks below are needed for functions that don't have
430 // simple names (e.g., C++ conversion functions).
431 if (!FnInfo)
432 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000433
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000434 // FIXME: This mechanism should be abstracted to be less fragile and
435 // more efficient. For example, just map function ids to custom
436 // handlers.
437
Ted Kremenekb8176da2010-09-09 04:33:05 +0000438 // Printf and scanf checking.
439 for (specific_attr_iterator<FormatAttr>
440 i = FDecl->specific_attr_begin<FormatAttr>(),
441 e = FDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000442 CheckFormatArguments(*i, TheCall);
Chris Lattnerb87b1b32007-08-10 20:18:51 +0000443 }
Mike Stump11289f42009-09-09 15:08:12 +0000444
Ted Kremenekb8176da2010-09-09 04:33:05 +0000445 for (specific_attr_iterator<NonNullAttr>
446 i = FDecl->specific_attr_begin<NonNullAttr>(),
447 e = FDecl->specific_attr_end<NonNullAttr>(); i != e; ++i) {
Nick Lewyckyd4693212011-03-25 01:44:32 +0000448 CheckNonNullArguments(*i, TheCall->getArgs(),
449 TheCall->getCallee()->getLocStart());
Ted Kremenekb8176da2010-09-09 04:33:05 +0000450 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000451
Anna Zaks22122702012-01-17 00:37:07 +0000452 unsigned CMId = FDecl->getMemoryFunctionKind();
453 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +0000454 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +0000455
Anna Zaks201d4892012-01-13 21:52:01 +0000456 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +0000457 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +0000458 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +0000459 else
Anna Zaks22122702012-01-17 00:37:07 +0000460 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +0000461
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000462 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +0000463}
464
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000465bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
466 Expr **Args, unsigned NumArgs) {
467 for (specific_attr_iterator<FormatAttr>
468 i = Method->specific_attr_begin<FormatAttr>(),
469 e = Method->specific_attr_end<FormatAttr>(); i != e ; ++i) {
470
471 CheckFormatArguments(*i, Args, NumArgs, false, lbrac,
472 Method->getSourceRange());
473 }
474
475 // diagnose nonnull arguments.
476 for (specific_attr_iterator<NonNullAttr>
477 i = Method->specific_attr_begin<NonNullAttr>(),
478 e = Method->specific_attr_end<NonNullAttr>(); i != e; ++i) {
479 CheckNonNullArguments(*i, Args, lbrac);
480 }
481
482 return false;
483}
484
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000485bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000486 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
487 if (!V)
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000488 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000489
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000490 QualType Ty = V->getType();
491 if (!Ty->isBlockPointerType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000492 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000493
Jean-Daniel Dupas3b8dfa02012-01-25 00:55:11 +0000494 // format string checking.
495 for (specific_attr_iterator<FormatAttr>
496 i = NDecl->specific_attr_begin<FormatAttr>(),
497 e = NDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) {
498 CheckFormatArguments(*i, TheCall);
499 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000500
501 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000502}
503
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000504ExprResult
505Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, AtomicExpr::AtomicOp Op) {
506 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
507 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000508
509 // All these operations take one of the following four forms:
510 // T __atomic_load(_Atomic(T)*, int) (loads)
511 // T* __atomic_add(_Atomic(T*)*, ptrdiff_t, int) (pointer add/sub)
512 // int __atomic_compare_exchange_strong(_Atomic(T)*, T*, T, int, int)
513 // (cmpxchg)
514 // T __atomic_exchange(_Atomic(T)*, T, int) (everything else)
515 // where T is an appropriate type, and the int paremeterss are for orderings.
516 unsigned NumVals = 1;
517 unsigned NumOrders = 1;
518 if (Op == AtomicExpr::Load) {
519 NumVals = 0;
520 } else if (Op == AtomicExpr::CmpXchgWeak || Op == AtomicExpr::CmpXchgStrong) {
521 NumVals = 2;
522 NumOrders = 2;
523 }
David Chisnallfa35df62012-01-16 17:27:18 +0000524 if (Op == AtomicExpr::Init)
525 NumOrders = 0;
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000526
527 if (TheCall->getNumArgs() < NumVals+NumOrders+1) {
528 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
529 << 0 << NumVals+NumOrders+1 << TheCall->getNumArgs()
530 << TheCall->getCallee()->getSourceRange();
531 return ExprError();
532 } else if (TheCall->getNumArgs() > NumVals+NumOrders+1) {
533 Diag(TheCall->getArg(NumVals+NumOrders+1)->getLocStart(),
534 diag::err_typecheck_call_too_many_args)
535 << 0 << NumVals+NumOrders+1 << TheCall->getNumArgs()
536 << TheCall->getCallee()->getSourceRange();
537 return ExprError();
538 }
539
540 // Inspect the first argument of the atomic operation. This should always be
541 // a pointer to an _Atomic type.
Eli Friedman8d3e43f2011-10-14 22:48:56 +0000542 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000543 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
544 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
545 if (!pointerType) {
546 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
547 << Ptr->getType() << Ptr->getSourceRange();
548 return ExprError();
549 }
550
551 QualType AtomTy = pointerType->getPointeeType();
552 if (!AtomTy->isAtomicType()) {
553 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
554 << Ptr->getType() << Ptr->getSourceRange();
555 return ExprError();
556 }
557 QualType ValType = AtomTy->getAs<AtomicType>()->getValueType();
558
559 if ((Op == AtomicExpr::Add || Op == AtomicExpr::Sub) &&
560 !ValType->isIntegerType() && !ValType->isPointerType()) {
561 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
562 << Ptr->getType() << Ptr->getSourceRange();
563 return ExprError();
564 }
565
566 if (!ValType->isIntegerType() &&
567 (Op == AtomicExpr::And || Op == AtomicExpr::Or || Op == AtomicExpr::Xor)){
568 Diag(DRE->getLocStart(), diag::err_atomic_op_logical_needs_atomic_int)
569 << Ptr->getType() << Ptr->getSourceRange();
570 return ExprError();
571 }
572
573 switch (ValType.getObjCLifetime()) {
574 case Qualifiers::OCL_None:
575 case Qualifiers::OCL_ExplicitNone:
576 // okay
577 break;
578
579 case Qualifiers::OCL_Weak:
580 case Qualifiers::OCL_Strong:
581 case Qualifiers::OCL_Autoreleasing:
582 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
583 << ValType << Ptr->getSourceRange();
584 return ExprError();
585 }
586
587 QualType ResultType = ValType;
David Chisnallfa35df62012-01-16 17:27:18 +0000588 if (Op == AtomicExpr::Store || Op == AtomicExpr::Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000589 ResultType = Context.VoidTy;
590 else if (Op == AtomicExpr::CmpXchgWeak || Op == AtomicExpr::CmpXchgStrong)
591 ResultType = Context.BoolTy;
592
593 // The first argument --- the pointer --- has a fixed type; we
594 // deduce the types of the rest of the arguments accordingly. Walk
595 // the remaining arguments, converting them to the deduced value type.
596 for (unsigned i = 1; i != NumVals+NumOrders+1; ++i) {
597 ExprResult Arg = TheCall->getArg(i);
598 QualType Ty;
599 if (i < NumVals+1) {
600 // The second argument to a cmpxchg is a pointer to the data which will
601 // be exchanged. The second argument to a pointer add/subtract is the
602 // amount to add/subtract, which must be a ptrdiff_t. The third
603 // argument to a cmpxchg and the second argument in all other cases
604 // is the type of the value.
605 if (i == 1 && (Op == AtomicExpr::CmpXchgWeak ||
606 Op == AtomicExpr::CmpXchgStrong))
607 Ty = Context.getPointerType(ValType.getUnqualifiedType());
608 else if (!ValType->isIntegerType() &&
609 (Op == AtomicExpr::Add || Op == AtomicExpr::Sub))
610 Ty = Context.getPointerDiffType();
611 else
612 Ty = ValType;
613 } else {
614 // The order(s) are always converted to int.
615 Ty = Context.IntTy;
616 }
617 InitializedEntity Entity =
618 InitializedEntity::InitializeParameter(Context, Ty, false);
619 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
620 if (Arg.isInvalid())
621 return true;
622 TheCall->setArg(i, Arg.get());
623 }
624
Eli Friedman8d3e43f2011-10-14 22:48:56 +0000625 SmallVector<Expr*, 5> SubExprs;
626 SubExprs.push_back(Ptr);
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000627 if (Op == AtomicExpr::Load) {
Eli Friedman8d3e43f2011-10-14 22:48:56 +0000628 SubExprs.push_back(TheCall->getArg(1)); // Order
David Chisnallfa35df62012-01-16 17:27:18 +0000629 } else if (Op == AtomicExpr::Init) {
630 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000631 } else if (Op != AtomicExpr::CmpXchgWeak && Op != AtomicExpr::CmpXchgStrong) {
Eli Friedman8d3e43f2011-10-14 22:48:56 +0000632 SubExprs.push_back(TheCall->getArg(2)); // Order
633 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000634 } else {
Eli Friedman8d3e43f2011-10-14 22:48:56 +0000635 SubExprs.push_back(TheCall->getArg(3)); // Order
636 SubExprs.push_back(TheCall->getArg(1)); // Val1
637 SubExprs.push_back(TheCall->getArg(2)); // Val2
638 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000639 }
Eli Friedman8d3e43f2011-10-14 22:48:56 +0000640
641 return Owned(new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
642 SubExprs.data(), SubExprs.size(),
643 ResultType, Op,
644 TheCall->getRParenLoc()));
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000645}
646
647
John McCall29ad95b2011-08-27 01:09:30 +0000648/// checkBuiltinArgument - Given a call to a builtin function, perform
649/// normal type-checking on the given argument, updating the call in
650/// place. This is useful when a builtin function requires custom
651/// type-checking for some of its arguments but not necessarily all of
652/// them.
653///
654/// Returns true on error.
655static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
656 FunctionDecl *Fn = E->getDirectCallee();
657 assert(Fn && "builtin call without direct callee!");
658
659 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
660 InitializedEntity Entity =
661 InitializedEntity::InitializeParameter(S.Context, Param);
662
663 ExprResult Arg = E->getArg(0);
664 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
665 if (Arg.isInvalid())
666 return true;
667
668 E->setArg(ArgIndex, Arg.take());
669 return false;
670}
671
Chris Lattnerdc046542009-05-08 06:58:22 +0000672/// SemaBuiltinAtomicOverloaded - We have a call to a function like
673/// __sync_fetch_and_add, which is an overloaded function based on the pointer
674/// type of its first argument. The main ActOnCallExpr routines have already
675/// promoted the types of arguments because all of these calls are prototyped as
676/// void(...).
677///
678/// This function goes through and does final semantic checking for these
679/// builtins,
John McCalldadc5752010-08-24 06:29:42 +0000680ExprResult
681Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000682 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +0000683 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
684 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
685
686 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000687 if (TheCall->getNumArgs() < 1) {
688 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
689 << 0 << 1 << TheCall->getNumArgs()
690 << TheCall->getCallee()->getSourceRange();
691 return ExprError();
692 }
Mike Stump11289f42009-09-09 15:08:12 +0000693
Chris Lattnerdc046542009-05-08 06:58:22 +0000694 // Inspect the first argument of the atomic builtin. This should always be
695 // a pointer type, whose element is an integral scalar or pointer type.
696 // Because it is a pointer type, we don't have to worry about any implicit
697 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000698 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +0000699 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +0000700 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
701 if (FirstArgResult.isInvalid())
702 return ExprError();
703 FirstArg = FirstArgResult.take();
704 TheCall->setArg(0, FirstArg);
705
John McCall31168b02011-06-15 23:02:42 +0000706 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
707 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000708 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
709 << FirstArg->getType() << FirstArg->getSourceRange();
710 return ExprError();
711 }
Mike Stump11289f42009-09-09 15:08:12 +0000712
John McCall31168b02011-06-15 23:02:42 +0000713 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +0000714 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000715 !ValType->isBlockPointerType()) {
716 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
717 << FirstArg->getType() << FirstArg->getSourceRange();
718 return ExprError();
719 }
Chris Lattnerdc046542009-05-08 06:58:22 +0000720
John McCall31168b02011-06-15 23:02:42 +0000721 switch (ValType.getObjCLifetime()) {
722 case Qualifiers::OCL_None:
723 case Qualifiers::OCL_ExplicitNone:
724 // okay
725 break;
726
727 case Qualifiers::OCL_Weak:
728 case Qualifiers::OCL_Strong:
729 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +0000730 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +0000731 << ValType << FirstArg->getSourceRange();
732 return ExprError();
733 }
734
John McCallb50451a2011-10-05 07:41:44 +0000735 // Strip any qualifiers off ValType.
736 ValType = ValType.getUnqualifiedType();
737
Chandler Carruth3973af72010-07-18 20:54:12 +0000738 // The majority of builtins return a value, but a few have special return
739 // types, so allow them to override appropriately below.
740 QualType ResultType = ValType;
741
Chris Lattnerdc046542009-05-08 06:58:22 +0000742 // We need to figure out which concrete builtin this maps onto. For example,
743 // __sync_fetch_and_add with a 2 byte object turns into
744 // __sync_fetch_and_add_2.
745#define BUILTIN_ROW(x) \
746 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
747 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +0000748
Chris Lattnerdc046542009-05-08 06:58:22 +0000749 static const unsigned BuiltinIndices[][5] = {
750 BUILTIN_ROW(__sync_fetch_and_add),
751 BUILTIN_ROW(__sync_fetch_and_sub),
752 BUILTIN_ROW(__sync_fetch_and_or),
753 BUILTIN_ROW(__sync_fetch_and_and),
754 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump11289f42009-09-09 15:08:12 +0000755
Chris Lattnerdc046542009-05-08 06:58:22 +0000756 BUILTIN_ROW(__sync_add_and_fetch),
757 BUILTIN_ROW(__sync_sub_and_fetch),
758 BUILTIN_ROW(__sync_and_and_fetch),
759 BUILTIN_ROW(__sync_or_and_fetch),
760 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +0000761
Chris Lattnerdc046542009-05-08 06:58:22 +0000762 BUILTIN_ROW(__sync_val_compare_and_swap),
763 BUILTIN_ROW(__sync_bool_compare_and_swap),
764 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000765 BUILTIN_ROW(__sync_lock_release),
766 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +0000767 };
Mike Stump11289f42009-09-09 15:08:12 +0000768#undef BUILTIN_ROW
769
Chris Lattnerdc046542009-05-08 06:58:22 +0000770 // Determine the index of the size.
771 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +0000772 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +0000773 case 1: SizeIndex = 0; break;
774 case 2: SizeIndex = 1; break;
775 case 4: SizeIndex = 2; break;
776 case 8: SizeIndex = 3; break;
777 case 16: SizeIndex = 4; break;
778 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000779 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
780 << FirstArg->getType() << FirstArg->getSourceRange();
781 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +0000782 }
Mike Stump11289f42009-09-09 15:08:12 +0000783
Chris Lattnerdc046542009-05-08 06:58:22 +0000784 // Each of these builtins has one pointer argument, followed by some number of
785 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
786 // that we ignore. Find out which row of BuiltinIndices to read from as well
787 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +0000788 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +0000789 unsigned BuiltinIndex, NumFixed = 1;
790 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +0000791 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +0000792 case Builtin::BI__sync_fetch_and_add:
793 case Builtin::BI__sync_fetch_and_add_1:
794 case Builtin::BI__sync_fetch_and_add_2:
795 case Builtin::BI__sync_fetch_and_add_4:
796 case Builtin::BI__sync_fetch_and_add_8:
797 case Builtin::BI__sync_fetch_and_add_16:
798 BuiltinIndex = 0;
799 break;
800
801 case Builtin::BI__sync_fetch_and_sub:
802 case Builtin::BI__sync_fetch_and_sub_1:
803 case Builtin::BI__sync_fetch_and_sub_2:
804 case Builtin::BI__sync_fetch_and_sub_4:
805 case Builtin::BI__sync_fetch_and_sub_8:
806 case Builtin::BI__sync_fetch_and_sub_16:
807 BuiltinIndex = 1;
808 break;
809
810 case Builtin::BI__sync_fetch_and_or:
811 case Builtin::BI__sync_fetch_and_or_1:
812 case Builtin::BI__sync_fetch_and_or_2:
813 case Builtin::BI__sync_fetch_and_or_4:
814 case Builtin::BI__sync_fetch_and_or_8:
815 case Builtin::BI__sync_fetch_and_or_16:
816 BuiltinIndex = 2;
817 break;
818
819 case Builtin::BI__sync_fetch_and_and:
820 case Builtin::BI__sync_fetch_and_and_1:
821 case Builtin::BI__sync_fetch_and_and_2:
822 case Builtin::BI__sync_fetch_and_and_4:
823 case Builtin::BI__sync_fetch_and_and_8:
824 case Builtin::BI__sync_fetch_and_and_16:
825 BuiltinIndex = 3;
826 break;
Mike Stump11289f42009-09-09 15:08:12 +0000827
Douglas Gregor73722482011-11-28 16:30:08 +0000828 case Builtin::BI__sync_fetch_and_xor:
829 case Builtin::BI__sync_fetch_and_xor_1:
830 case Builtin::BI__sync_fetch_and_xor_2:
831 case Builtin::BI__sync_fetch_and_xor_4:
832 case Builtin::BI__sync_fetch_and_xor_8:
833 case Builtin::BI__sync_fetch_and_xor_16:
834 BuiltinIndex = 4;
835 break;
836
837 case Builtin::BI__sync_add_and_fetch:
838 case Builtin::BI__sync_add_and_fetch_1:
839 case Builtin::BI__sync_add_and_fetch_2:
840 case Builtin::BI__sync_add_and_fetch_4:
841 case Builtin::BI__sync_add_and_fetch_8:
842 case Builtin::BI__sync_add_and_fetch_16:
843 BuiltinIndex = 5;
844 break;
845
846 case Builtin::BI__sync_sub_and_fetch:
847 case Builtin::BI__sync_sub_and_fetch_1:
848 case Builtin::BI__sync_sub_and_fetch_2:
849 case Builtin::BI__sync_sub_and_fetch_4:
850 case Builtin::BI__sync_sub_and_fetch_8:
851 case Builtin::BI__sync_sub_and_fetch_16:
852 BuiltinIndex = 6;
853 break;
854
855 case Builtin::BI__sync_and_and_fetch:
856 case Builtin::BI__sync_and_and_fetch_1:
857 case Builtin::BI__sync_and_and_fetch_2:
858 case Builtin::BI__sync_and_and_fetch_4:
859 case Builtin::BI__sync_and_and_fetch_8:
860 case Builtin::BI__sync_and_and_fetch_16:
861 BuiltinIndex = 7;
862 break;
863
864 case Builtin::BI__sync_or_and_fetch:
865 case Builtin::BI__sync_or_and_fetch_1:
866 case Builtin::BI__sync_or_and_fetch_2:
867 case Builtin::BI__sync_or_and_fetch_4:
868 case Builtin::BI__sync_or_and_fetch_8:
869 case Builtin::BI__sync_or_and_fetch_16:
870 BuiltinIndex = 8;
871 break;
872
873 case Builtin::BI__sync_xor_and_fetch:
874 case Builtin::BI__sync_xor_and_fetch_1:
875 case Builtin::BI__sync_xor_and_fetch_2:
876 case Builtin::BI__sync_xor_and_fetch_4:
877 case Builtin::BI__sync_xor_and_fetch_8:
878 case Builtin::BI__sync_xor_and_fetch_16:
879 BuiltinIndex = 9;
880 break;
Mike Stump11289f42009-09-09 15:08:12 +0000881
Chris Lattnerdc046542009-05-08 06:58:22 +0000882 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000883 case Builtin::BI__sync_val_compare_and_swap_1:
884 case Builtin::BI__sync_val_compare_and_swap_2:
885 case Builtin::BI__sync_val_compare_and_swap_4:
886 case Builtin::BI__sync_val_compare_and_swap_8:
887 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +0000888 BuiltinIndex = 10;
Chris Lattnerdc046542009-05-08 06:58:22 +0000889 NumFixed = 2;
890 break;
Douglas Gregor73722482011-11-28 16:30:08 +0000891
Chris Lattnerdc046542009-05-08 06:58:22 +0000892 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000893 case Builtin::BI__sync_bool_compare_and_swap_1:
894 case Builtin::BI__sync_bool_compare_and_swap_2:
895 case Builtin::BI__sync_bool_compare_and_swap_4:
896 case Builtin::BI__sync_bool_compare_and_swap_8:
897 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +0000898 BuiltinIndex = 11;
Chris Lattnerdc046542009-05-08 06:58:22 +0000899 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +0000900 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +0000901 break;
Douglas Gregor73722482011-11-28 16:30:08 +0000902
903 case Builtin::BI__sync_lock_test_and_set:
904 case Builtin::BI__sync_lock_test_and_set_1:
905 case Builtin::BI__sync_lock_test_and_set_2:
906 case Builtin::BI__sync_lock_test_and_set_4:
907 case Builtin::BI__sync_lock_test_and_set_8:
908 case Builtin::BI__sync_lock_test_and_set_16:
909 BuiltinIndex = 12;
910 break;
911
Chris Lattnerdc046542009-05-08 06:58:22 +0000912 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +0000913 case Builtin::BI__sync_lock_release_1:
914 case Builtin::BI__sync_lock_release_2:
915 case Builtin::BI__sync_lock_release_4:
916 case Builtin::BI__sync_lock_release_8:
917 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +0000918 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +0000919 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +0000920 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +0000921 break;
Douglas Gregor73722482011-11-28 16:30:08 +0000922
923 case Builtin::BI__sync_swap:
924 case Builtin::BI__sync_swap_1:
925 case Builtin::BI__sync_swap_2:
926 case Builtin::BI__sync_swap_4:
927 case Builtin::BI__sync_swap_8:
928 case Builtin::BI__sync_swap_16:
929 BuiltinIndex = 14;
930 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000931 }
Mike Stump11289f42009-09-09 15:08:12 +0000932
Chris Lattnerdc046542009-05-08 06:58:22 +0000933 // Now that we know how many fixed arguments we expect, first check that we
934 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000935 if (TheCall->getNumArgs() < 1+NumFixed) {
936 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
937 << 0 << 1+NumFixed << TheCall->getNumArgs()
938 << TheCall->getCallee()->getSourceRange();
939 return ExprError();
940 }
Mike Stump11289f42009-09-09 15:08:12 +0000941
Chris Lattner5b9241b2009-05-08 15:36:58 +0000942 // Get the decl for the concrete builtin from this, we can tell what the
943 // concrete integer type we should convert to is.
944 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
945 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
946 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
Mike Stump11289f42009-09-09 15:08:12 +0000947 FunctionDecl *NewBuiltinDecl =
Chris Lattner5b9241b2009-05-08 15:36:58 +0000948 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
949 TUScope, false, DRE->getLocStart()));
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000950
John McCallcf142162010-08-07 06:22:56 +0000951 // The first argument --- the pointer --- has a fixed type; we
952 // deduce the types of the rest of the arguments accordingly. Walk
953 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +0000954 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +0000955 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +0000956
Chris Lattnerdc046542009-05-08 06:58:22 +0000957 // GCC does an implicit conversion to the pointer or integer ValType. This
958 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +0000959 // Initialize the argument.
960 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
961 ValType, /*consume*/ false);
962 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +0000963 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000964 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +0000965
Chris Lattnerdc046542009-05-08 06:58:22 +0000966 // Okay, we have something that *can* be converted to the right type. Check
967 // to see if there is a potentially weird extension going on here. This can
968 // happen when you do an atomic operation on something like an char* and
969 // pass in 42. The 42 gets converted to char. This is even more strange
970 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +0000971 // FIXME: Do this check.
John McCallb50451a2011-10-05 07:41:44 +0000972 TheCall->setArg(i+1, Arg.take());
Chris Lattnerdc046542009-05-08 06:58:22 +0000973 }
Mike Stump11289f42009-09-09 15:08:12 +0000974
Douglas Gregor6b3bcf22011-09-09 16:51:10 +0000975 ASTContext& Context = this->getASTContext();
976
977 // Create a new DeclRefExpr to refer to the new decl.
978 DeclRefExpr* NewDRE = DeclRefExpr::Create(
979 Context,
980 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +0000981 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +0000982 NewBuiltinDecl,
983 DRE->getLocation(),
984 NewBuiltinDecl->getType(),
985 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +0000986
Chris Lattnerdc046542009-05-08 06:58:22 +0000987 // Set the callee in the CallExpr.
988 // FIXME: This leaks the original parens and implicit casts.
Douglas Gregor6b3bcf22011-09-09 16:51:10 +0000989 ExprResult PromotedCall = UsualUnaryConversions(NewDRE);
John Wiegley01296292011-04-08 18:41:53 +0000990 if (PromotedCall.isInvalid())
991 return ExprError();
992 TheCall->setCallee(PromotedCall.take());
Mike Stump11289f42009-09-09 15:08:12 +0000993
Chandler Carruthbc8cab12010-07-18 07:23:17 +0000994 // Change the result type of the call to match the original value type. This
995 // is arbitrary, but the codegen for these builtins ins design to handle it
996 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +0000997 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000998
999 return move(TheCallResult);
Chris Lattnerdc046542009-05-08 06:58:22 +00001000}
1001
Chris Lattner6436fb62009-02-18 06:01:06 +00001002/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00001003/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00001004/// Note: It might also make sense to do the UTF-16 conversion here (would
1005/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00001006bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00001007 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00001008 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1009
Douglas Gregorfb65e592011-07-27 05:40:30 +00001010 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00001011 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1012 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00001013 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00001014 }
Mike Stump11289f42009-09-09 15:08:12 +00001015
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001016 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001017 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001018 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001019 SmallVector<UTF16, 128> ToBuf(NumBytes);
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001020 const UTF8 *FromPtr = (UTF8 *)String.data();
1021 UTF16 *ToPtr = &ToBuf[0];
1022
1023 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1024 &ToPtr, ToPtr + NumBytes,
1025 strictConversion);
1026 // Check for conversion failure.
1027 if (Result != conversionOK)
1028 Diag(Arg->getLocStart(),
1029 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1030 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00001031 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001032}
1033
Chris Lattnere202e6a2007-12-20 00:05:45 +00001034/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1035/// Emit an error and return true on failure, return false on success.
Chris Lattner08464942007-12-28 05:29:59 +00001036bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1037 Expr *Fn = TheCall->getCallee();
1038 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00001039 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001040 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001041 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1042 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00001043 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001044 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00001045 return true;
1046 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00001047
1048 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00001049 return Diag(TheCall->getLocEnd(),
1050 diag::err_typecheck_call_too_few_args_at_least)
1051 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00001052 }
1053
John McCall29ad95b2011-08-27 01:09:30 +00001054 // Type-check the first argument normally.
1055 if (checkBuiltinArgument(*this, TheCall, 0))
1056 return true;
1057
Chris Lattnere202e6a2007-12-20 00:05:45 +00001058 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00001059 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00001060 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00001061 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00001062 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00001063 else if (FunctionDecl *FD = getCurFunctionDecl())
1064 isVariadic = FD->isVariadic();
1065 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00001066 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00001067
Chris Lattnere202e6a2007-12-20 00:05:45 +00001068 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00001069 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1070 return true;
1071 }
Mike Stump11289f42009-09-09 15:08:12 +00001072
Chris Lattner43be2e62007-12-19 23:59:04 +00001073 // Verify that the second argument to the builtin is the last argument of the
1074 // current function or method.
1075 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00001076 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00001077
Anders Carlsson6a8350b2008-02-11 04:20:54 +00001078 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1079 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00001080 // FIXME: This isn't correct for methods (results in bogus warning).
1081 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00001082 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00001083 if (CurBlock)
1084 LastArg = *(CurBlock->TheDecl->param_end()-1);
1085 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +00001086 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00001087 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00001088 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00001089 SecondArgIsLastNamedArgument = PV == LastArg;
1090 }
1091 }
Mike Stump11289f42009-09-09 15:08:12 +00001092
Chris Lattner43be2e62007-12-19 23:59:04 +00001093 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001094 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +00001095 diag::warn_second_parameter_of_va_start_not_last_named_argument);
1096 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00001097}
Chris Lattner43be2e62007-12-19 23:59:04 +00001098
Chris Lattner2da14fb2007-12-20 00:26:33 +00001099/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1100/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00001101bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1102 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00001103 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00001104 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00001105 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00001106 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001107 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001108 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00001109 << SourceRange(TheCall->getArg(2)->getLocStart(),
1110 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00001111
John Wiegley01296292011-04-08 18:41:53 +00001112 ExprResult OrigArg0 = TheCall->getArg(0);
1113 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00001114
Chris Lattner2da14fb2007-12-20 00:26:33 +00001115 // Do standard promotions between the two arguments, returning their common
1116 // type.
Chris Lattner08464942007-12-28 05:29:59 +00001117 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00001118 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1119 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00001120
1121 // Make sure any conversions are pushed back into the call; this is
1122 // type safe since unordered compare builtins are declared as "_Bool
1123 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00001124 TheCall->setArg(0, OrigArg0.get());
1125 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00001126
John Wiegley01296292011-04-08 18:41:53 +00001127 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00001128 return false;
1129
Chris Lattner2da14fb2007-12-20 00:26:33 +00001130 // If the common type isn't a real floating type, then the arguments were
1131 // invalid for this operation.
1132 if (!Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00001133 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001134 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00001135 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1136 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00001137
Chris Lattner2da14fb2007-12-20 00:26:33 +00001138 return false;
1139}
1140
Benjamin Kramer634fc102010-02-15 22:42:31 +00001141/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1142/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00001143/// to check everything. We expect the last argument to be a floating point
1144/// value.
1145bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1146 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00001147 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00001148 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00001149 if (TheCall->getNumArgs() > NumArgs)
1150 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001151 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001152 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00001153 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001154 (*(TheCall->arg_end()-1))->getLocEnd());
1155
Benjamin Kramer64aae502010-02-16 10:07:31 +00001156 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00001157
Eli Friedman7e4faac2009-08-31 20:06:00 +00001158 if (OrigArg->isTypeDependent())
1159 return false;
1160
Chris Lattner68784ef2010-05-06 05:50:07 +00001161 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00001162 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00001163 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001164 diag::err_typecheck_call_invalid_unary_fp)
1165 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001166
Chris Lattner68784ef2010-05-06 05:50:07 +00001167 // If this is an implicit conversion from float -> double, remove it.
1168 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1169 Expr *CastArg = Cast->getSubExpr();
1170 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1171 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1172 "promotion from float to double is the only expected cast here");
1173 Cast->setSubExpr(0);
Chris Lattner68784ef2010-05-06 05:50:07 +00001174 TheCall->setArg(NumArgs-1, CastArg);
1175 OrigArg = CastArg;
1176 }
1177 }
1178
Eli Friedman7e4faac2009-08-31 20:06:00 +00001179 return false;
1180}
1181
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001182/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1183// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00001184ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00001185 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001186 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00001187 diag::err_typecheck_call_too_few_args_at_least)
Nate Begemana0110022010-06-08 00:16:34 +00001188 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherabf1e182010-04-16 04:48:22 +00001189 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001190
Nate Begemana0110022010-06-08 00:16:34 +00001191 // Determine which of the following types of shufflevector we're checking:
1192 // 1) unary, vector mask: (lhs, mask)
1193 // 2) binary, vector mask: (lhs, rhs, mask)
1194 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1195 QualType resType = TheCall->getArg(0)->getType();
1196 unsigned numElements = 0;
1197
Douglas Gregorc25f7662009-05-19 22:10:17 +00001198 if (!TheCall->getArg(0)->isTypeDependent() &&
1199 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00001200 QualType LHSType = TheCall->getArg(0)->getType();
1201 QualType RHSType = TheCall->getArg(1)->getType();
1202
1203 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00001204 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump11289f42009-09-09 15:08:12 +00001205 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorc25f7662009-05-19 22:10:17 +00001206 TheCall->getArg(1)->getLocEnd());
1207 return ExprError();
1208 }
Nate Begemana0110022010-06-08 00:16:34 +00001209
1210 numElements = LHSType->getAs<VectorType>()->getNumElements();
1211 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00001212
Nate Begemana0110022010-06-08 00:16:34 +00001213 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1214 // with mask. If so, verify that RHS is an integer vector type with the
1215 // same number of elts as lhs.
1216 if (TheCall->getNumArgs() == 2) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00001217 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00001218 RHSType->getAs<VectorType>()->getNumElements() != numElements)
1219 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
1220 << SourceRange(TheCall->getArg(1)->getLocStart(),
1221 TheCall->getArg(1)->getLocEnd());
1222 numResElements = numElements;
1223 }
1224 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00001225 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump11289f42009-09-09 15:08:12 +00001226 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorc25f7662009-05-19 22:10:17 +00001227 TheCall->getArg(1)->getLocEnd());
1228 return ExprError();
Nate Begemana0110022010-06-08 00:16:34 +00001229 } else if (numElements != numResElements) {
1230 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00001231 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001232 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00001233 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001234 }
1235
1236 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00001237 if (TheCall->getArg(i)->isTypeDependent() ||
1238 TheCall->getArg(i)->isValueDependent())
1239 continue;
1240
Nate Begemana0110022010-06-08 00:16:34 +00001241 llvm::APSInt Result(32);
1242 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1243 return ExprError(Diag(TheCall->getLocStart(),
1244 diag::err_shufflevector_nonconstant_argument)
1245 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001246
Chris Lattner7ab824e2008-08-10 02:05:13 +00001247 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001248 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001249 diag::err_shufflevector_argument_too_large)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001250 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001251 }
1252
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001253 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001254
Chris Lattner7ab824e2008-08-10 02:05:13 +00001255 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001256 exprs.push_back(TheCall->getArg(i));
1257 TheCall->setArg(i, 0);
1258 }
1259
Nate Begemanf485fb52009-08-12 02:10:25 +00001260 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
Nate Begemana0110022010-06-08 00:16:34 +00001261 exprs.size(), resType,
Ted Kremenek5a201952009-02-07 01:47:29 +00001262 TheCall->getCallee()->getLocStart(),
1263 TheCall->getRParenLoc()));
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001264}
Chris Lattner43be2e62007-12-19 23:59:04 +00001265
Daniel Dunbarb7257262008-07-21 22:59:13 +00001266/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1267// This is declared to take (const void*, ...) and can take two
1268// optional constant int args.
1269bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00001270 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001271
Chris Lattner3b054132008-11-19 05:08:23 +00001272 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001273 return Diag(TheCall->getLocEnd(),
1274 diag::err_typecheck_call_too_many_args_at_most)
1275 << 0 /*function call*/ << 3 << NumArgs
1276 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001277
1278 // Argument 0 is checked for us and the remaining arguments must be
1279 // constant integers.
Chris Lattner3b054132008-11-19 05:08:23 +00001280 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbarb7257262008-07-21 22:59:13 +00001281 Expr *Arg = TheCall->getArg(i);
Eric Christopher8d0c6212010-04-17 02:26:23 +00001282
Eli Friedman5efba262009-12-04 00:30:06 +00001283 llvm::APSInt Result;
Eric Christopher8d0c6212010-04-17 02:26:23 +00001284 if (SemaBuiltinConstantArg(TheCall, i, Result))
1285 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001286
Daniel Dunbarb7257262008-07-21 22:59:13 +00001287 // FIXME: gcc issues a warning and rewrites these to 0. These
1288 // seems especially odd for the third argument since the default
1289 // is 3.
Chris Lattner3b054132008-11-19 05:08:23 +00001290 if (i == 1) {
Eli Friedman5efba262009-12-04 00:30:06 +00001291 if (Result.getLimitedValue() > 1)
Chris Lattner3b054132008-11-19 05:08:23 +00001292 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattnerd545ad12009-09-23 06:06:36 +00001293 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001294 } else {
Eli Friedman5efba262009-12-04 00:30:06 +00001295 if (Result.getLimitedValue() > 3)
Chris Lattner3b054132008-11-19 05:08:23 +00001296 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattnerd545ad12009-09-23 06:06:36 +00001297 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001298 }
1299 }
1300
Chris Lattner3b054132008-11-19 05:08:23 +00001301 return false;
Daniel Dunbarb7257262008-07-21 22:59:13 +00001302}
1303
Eric Christopher8d0c6212010-04-17 02:26:23 +00001304/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1305/// TheCall is a constant expression.
1306bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1307 llvm::APSInt &Result) {
1308 Expr *Arg = TheCall->getArg(ArgNum);
1309 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1310 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1311
1312 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1313
1314 if (!Arg->isIntegerConstantExpr(Result, Context))
1315 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00001316 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00001317
Chris Lattnerd545ad12009-09-23 06:06:36 +00001318 return false;
1319}
1320
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00001321/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1322/// int type). This simply type checks that type is one of the defined
1323/// constants (0-3).
Chris Lattner57540c52011-04-15 05:22:18 +00001324// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00001325bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00001326 llvm::APSInt Result;
1327
1328 // Check constant-ness first.
1329 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1330 return true;
1331
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00001332 Expr *Arg = TheCall->getArg(1);
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00001333 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattner3b054132008-11-19 05:08:23 +00001334 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1335 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00001336 }
1337
1338 return false;
1339}
1340
Eli Friedmanc97d0142009-05-03 06:04:26 +00001341/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmaneed8ad22009-05-03 04:46:36 +00001342/// This checks that val is a constant 1.
1343bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1344 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00001345 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00001346
Eric Christopher8d0c6212010-04-17 02:26:23 +00001347 // TODO: This is less than ideal. Overload this to take a value.
1348 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1349 return true;
1350
1351 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00001352 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1353 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1354
1355 return false;
1356}
1357
Ted Kremeneka8890832011-02-24 23:03:04 +00001358// Handle i > 1 ? "x" : "y", recursively.
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001359bool Sema::SemaCheckStringLiteral(const Expr *E, Expr **Args,
1360 unsigned NumArgs, bool HasVAListArg,
Ted Kremenek02087932010-07-16 02:11:22 +00001361 unsigned format_idx, unsigned firstDataArg,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00001362 FormatStringType Type, bool inFunctionCall) {
Ted Kremenek808829352010-09-09 03:51:39 +00001363 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00001364 if (E->isTypeDependent() || E->isValueDependent())
1365 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001366
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00001367 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00001368
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001369 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00001370 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001371 case Stmt::ConditionalOperatorClass: {
John McCallc07a0c72011-02-17 10:25:35 +00001372 const AbstractConditionalOperator *C = cast<AbstractConditionalOperator>(E);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001373 return SemaCheckStringLiteral(C->getTrueExpr(), Args, NumArgs, HasVAListArg,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00001374 format_idx, firstDataArg, Type,
Richard Trieu03cf7b72011-10-28 00:41:25 +00001375 inFunctionCall)
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00001376 && SemaCheckStringLiteral(C->getFalseExpr(), Args, NumArgs, HasVAListArg,
1377 format_idx, firstDataArg, Type,
1378 inFunctionCall);
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001379 }
1380
Ted Kremenek1520dae2010-09-09 03:51:42 +00001381 case Stmt::IntegerLiteralClass:
1382 // Technically -Wformat-nonliteral does not warn about this case.
1383 // The behavior of printf and friends in this case is implementation
1384 // dependent. Ideally if the format string cannot be null then
1385 // it should have a 'nonnull' attribute in the function prototype.
1386 return true;
1387
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001388 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00001389 E = cast<ImplicitCastExpr>(E)->getSubExpr();
1390 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001391 }
1392
John McCallc07a0c72011-02-17 10:25:35 +00001393 case Stmt::OpaqueValueExprClass:
1394 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
1395 E = src;
1396 goto tryAgain;
1397 }
1398 return false;
1399
Ted Kremeneka8890832011-02-24 23:03:04 +00001400 case Stmt::PredefinedExprClass:
1401 // While __func__, etc., are technically not string literals, they
1402 // cannot contain format specifiers and thus are not a security
1403 // liability.
1404 return true;
1405
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001406 case Stmt::DeclRefExprClass: {
1407 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00001408
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001409 // As an exception, do not flag errors for variables binding to
1410 // const string literals.
1411 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1412 bool isConstant = false;
1413 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001414
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001415 if (const ArrayType *AT = Context.getAsArrayType(T)) {
1416 isConstant = AT->getElementType().isConstant(Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00001417 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001418 isConstant = T.isConstant(Context) &&
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001419 PT->getPointeeType().isConstant(Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00001420 } else if (T->isObjCObjectPointerType()) {
1421 // In ObjC, there is usually no "const ObjectPointer" type,
1422 // so don't check if the pointee type is constant.
1423 isConstant = T.isConstant(Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001424 }
Mike Stump11289f42009-09-09 15:08:12 +00001425
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001426 if (isConstant) {
Sebastian Redl5ca79842010-02-01 20:16:42 +00001427 if (const Expr *Init = VD->getAnyInitializer())
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001428 return SemaCheckStringLiteral(Init, Args, NumArgs,
Ted Kremenek02087932010-07-16 02:11:22 +00001429 HasVAListArg, format_idx, firstDataArg,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00001430 Type, /*inFunctionCall*/false);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001431 }
Mike Stump11289f42009-09-09 15:08:12 +00001432
Anders Carlssonb012ca92009-06-28 19:55:58 +00001433 // For vprintf* functions (i.e., HasVAListArg==true), we add a
1434 // special check to see if the format string is a function parameter
1435 // of the function calling the printf function. If the function
1436 // has an attribute indicating it is a printf-like function, then we
1437 // should suppress warnings concerning non-literals being used in a call
1438 // to a vprintf function. For example:
1439 //
1440 // void
1441 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
1442 // va_list ap;
1443 // va_start(ap, fmt);
1444 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
1445 // ...
1446 //
1447 //
1448 // FIXME: We don't have full attribute support yet, so just check to see
1449 // if the argument is a DeclRefExpr that references a parameter. We'll
1450 // add proper support for checking the attribute later.
1451 if (HasVAListArg)
1452 if (isa<ParmVarDecl>(VD))
1453 return true;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001454 }
Mike Stump11289f42009-09-09 15:08:12 +00001455
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001456 return false;
1457 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001458
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00001459 case Stmt::CallExprClass: {
1460 const CallExpr *CE = cast<CallExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00001461 if (const ImplicitCastExpr *ICE
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00001462 = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
1463 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
1464 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001465 if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00001466 unsigned ArgIndex = FA->getFormatIdx();
1467 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00001468
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001469 return SemaCheckStringLiteral(Arg, Args, NumArgs, HasVAListArg,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00001470 format_idx, firstDataArg, Type,
Richard Trieu03cf7b72011-10-28 00:41:25 +00001471 inFunctionCall);
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00001472 }
1473 }
1474 }
1475 }
Mike Stump11289f42009-09-09 15:08:12 +00001476
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00001477 return false;
1478 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001479 case Stmt::ObjCStringLiteralClass:
1480 case Stmt::StringLiteralClass: {
1481 const StringLiteral *StrE = NULL;
Mike Stump11289f42009-09-09 15:08:12 +00001482
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001483 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001484 StrE = ObjCFExpr->getString();
1485 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001486 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00001487
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001488 if (StrE) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001489 CheckFormatString(StrE, E, Args, NumArgs, HasVAListArg, format_idx,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00001490 firstDataArg, Type, inFunctionCall);
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001491 return true;
1492 }
Mike Stump11289f42009-09-09 15:08:12 +00001493
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001494 return false;
1495 }
Mike Stump11289f42009-09-09 15:08:12 +00001496
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001497 default:
1498 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001499 }
1500}
1501
Fariborz Jahaniancd1a88d2009-05-21 18:48:51 +00001502void
Mike Stump11289f42009-09-09 15:08:12 +00001503Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewyckyd4693212011-03-25 01:44:32 +00001504 const Expr * const *ExprArgs,
1505 SourceLocation CallSiteLoc) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001506 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1507 e = NonNull->args_end();
Fariborz Jahaniancd1a88d2009-05-21 18:48:51 +00001508 i != e; ++i) {
Nick Lewyckyd4693212011-03-25 01:44:32 +00001509 const Expr *ArgExpr = ExprArgs[*i];
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001510 if (ArgExpr->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00001511 Expr::NPC_ValueDependentIsNotNull))
Nick Lewyckyd4693212011-03-25 01:44:32 +00001512 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniancd1a88d2009-05-21 18:48:51 +00001513 }
1514}
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001515
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00001516Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
1517 return llvm::StringSwitch<FormatStringType>(Format->getType())
1518 .Case("scanf", FST_Scanf)
1519 .Cases("printf", "printf0", FST_Printf)
1520 .Cases("NSString", "CFString", FST_NSString)
1521 .Case("strftime", FST_Strftime)
1522 .Case("strfmon", FST_Strfmon)
1523 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
1524 .Default(FST_Unknown);
1525}
1526
Ted Kremenek02087932010-07-16 02:11:22 +00001527/// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar
1528/// functions) for correct use of format strings.
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001529void Sema::CheckFormatArguments(const FormatAttr *Format, CallExpr *TheCall) {
1530 bool IsCXXMember = false;
Sebastian Redl6eedcc12009-11-17 18:02:24 +00001531 // The way the format attribute works in GCC, the implicit this argument
1532 // of member functions is counted. However, it doesn't appear in our own
1533 // lists, so decrement format_idx in that case.
1534 if (isa<CXXMemberCallExpr>(TheCall)) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001535 const CXXMethodDecl *method_decl =
1536 dyn_cast<CXXMethodDecl>(TheCall->getCalleeDecl());
1537 IsCXXMember = method_decl && method_decl->isInstance();
1538 }
1539 CheckFormatArguments(Format, TheCall->getArgs(), TheCall->getNumArgs(),
1540 IsCXXMember, TheCall->getRParenLoc(),
1541 TheCall->getCallee()->getSourceRange());
1542}
1543
1544void Sema::CheckFormatArguments(const FormatAttr *Format, Expr **Args,
1545 unsigned NumArgs, bool IsCXXMember,
1546 SourceLocation Loc, SourceRange Range) {
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00001547 bool HasVAListArg = Format->getFirstArg() == 0;
1548 unsigned format_idx = Format->getFormatIdx() - 1;
1549 unsigned firstDataArg = HasVAListArg ? 0 : Format->getFirstArg() - 1;
1550 if (IsCXXMember) {
1551 if (format_idx == 0)
1552 return;
1553 --format_idx;
1554 if(firstDataArg != 0)
1555 --firstDataArg;
Sebastian Redl6eedcc12009-11-17 18:02:24 +00001556 }
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00001557 CheckFormatArguments(Args, NumArgs, HasVAListArg, format_idx,
1558 firstDataArg, GetFormatStringType(Format), Loc, Range);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001559}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00001560
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00001561void Sema::CheckFormatArguments(Expr **Args, unsigned NumArgs,
1562 bool HasVAListArg, unsigned format_idx,
1563 unsigned firstDataArg, FormatStringType Type,
1564 SourceLocation Loc, SourceRange Range) {
Ted Kremenek02087932010-07-16 02:11:22 +00001565 // CHECK: printf/scanf-like function is called with no format string.
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001566 if (format_idx >= NumArgs) {
1567 Diag(Loc, diag::warn_missing_format_string) << Range;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00001568 return;
1569 }
Mike Stump11289f42009-09-09 15:08:12 +00001570
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001571 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00001572
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001573 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00001574 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00001575 // Dynamically generated format strings are difficult to
1576 // automatically vet at compile time. Requiring that format strings
1577 // are string literals: (1) permits the checking of format strings by
1578 // the compiler and thereby (2) can practically remove the source of
1579 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00001580
Mike Stump11289f42009-09-09 15:08:12 +00001581 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00001582 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00001583 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00001584 // the same format string checking logic for both ObjC and C strings.
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001585 if (SemaCheckStringLiteral(OrigFormatExpr, Args, NumArgs, HasVAListArg,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00001586 format_idx, firstDataArg, Type))
Chris Lattnere009a882009-04-29 04:49:34 +00001587 return; // Literal format string found, check done!
Ted Kremenek34f664d2008-06-16 18:00:42 +00001588
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00001589 // Do not emit diag when the string param is a macro expansion and the
1590 // format is either NSString or CFString. This is a hack to prevent
1591 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
1592 // which are usually used in place of NS and CF string literals.
1593 if (Type == FST_NSString && Args[format_idx]->getLocStart().isMacroID())
1594 return;
1595
Chris Lattnercc5d1c22009-04-29 04:59:47 +00001596 // If there are no arguments specified, warn with -Wformat-security, otherwise
1597 // warn only with -Wformat-nonliteral.
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001598 if (NumArgs == format_idx+1)
1599 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00001600 diag::warn_format_nonliteral_noargs)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00001601 << OrigFormatExpr->getSourceRange();
1602 else
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001603 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00001604 diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00001605 << OrigFormatExpr->getSourceRange();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001606}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00001607
Ted Kremenekab278de2010-01-28 23:39:18 +00001608namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00001609class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1610protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00001611 Sema &S;
1612 const StringLiteral *FExpr;
1613 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00001614 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00001615 const unsigned NumDataArgs;
1616 const bool IsObjCLiteral;
1617 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00001618 const bool HasVAListArg;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001619 const Expr * const *Args;
1620 const unsigned NumArgs;
Ted Kremenek5739de72010-01-29 01:06:55 +00001621 unsigned FormatIdx;
Ted Kremenek4a49d982010-02-26 19:18:41 +00001622 llvm::BitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00001623 bool usesPositionalArgs;
1624 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00001625 bool inFunctionCall;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001626public:
Ted Kremenek02087932010-07-16 02:11:22 +00001627 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00001628 const Expr *origFormatExpr, unsigned firstDataArg,
Ted Kremenekab278de2010-01-28 23:39:18 +00001629 unsigned numDataArgs, bool isObjCLiteral,
Ted Kremenek5739de72010-01-29 01:06:55 +00001630 const char *beg, bool hasVAListArg,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001631 Expr **args, unsigned numArgs,
1632 unsigned formatIdx, bool inFunctionCall)
Ted Kremenekab278de2010-01-28 23:39:18 +00001633 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Ted Kremenek4d745dd2010-03-25 03:59:12 +00001634 FirstDataArg(firstDataArg),
Ted Kremenek4a49d982010-02-26 19:18:41 +00001635 NumDataArgs(numDataArgs),
Ted Kremenek5739de72010-01-29 01:06:55 +00001636 IsObjCLiteral(isObjCLiteral), Beg(beg),
1637 HasVAListArg(hasVAListArg),
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001638 Args(args), NumArgs(numArgs), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00001639 usesPositionalArgs(false), atFirstArg(true),
1640 inFunctionCall(inFunctionCall) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00001641 CoveredArgs.resize(numDataArgs);
1642 CoveredArgs.reset();
1643 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001644
Ted Kremenek019d2242010-01-29 01:50:07 +00001645 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001646
Ted Kremenek02087932010-07-16 02:11:22 +00001647 void HandleIncompleteSpecifier(const char *startSpecifier,
1648 unsigned specifierLen);
1649
Ted Kremenekd1668192010-02-27 01:41:03 +00001650 virtual void HandleInvalidPosition(const char *startSpecifier,
1651 unsigned specifierLen,
Ted Kremenek02087932010-07-16 02:11:22 +00001652 analyze_format_string::PositionContext p);
Ted Kremenekd1668192010-02-27 01:41:03 +00001653
1654 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1655
Ted Kremenekab278de2010-01-28 23:39:18 +00001656 void HandleNullChar(const char *nullCharacter);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001657
Richard Trieu03cf7b72011-10-28 00:41:25 +00001658 template <typename Range>
1659 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
1660 const Expr *ArgumentExpr,
1661 PartialDiagnostic PDiag,
1662 SourceLocation StringLoc,
1663 bool IsStringLocation, Range StringRange,
1664 FixItHint Fixit = FixItHint());
1665
Ted Kremenek02087932010-07-16 02:11:22 +00001666protected:
Ted Kremenekce815422010-07-19 21:25:57 +00001667 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
1668 const char *startSpec,
1669 unsigned specifierLen,
1670 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00001671
1672 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
1673 const char *startSpec,
1674 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00001675
Ted Kremenek8d9842d2010-01-29 20:55:36 +00001676 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00001677 CharSourceRange getSpecifierRange(const char *startSpecifier,
1678 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00001679 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001680
Ted Kremenek5739de72010-01-29 01:06:55 +00001681 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00001682
1683 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
1684 const analyze_format_string::ConversionSpecifier &CS,
1685 const char *startSpecifier, unsigned specifierLen,
1686 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00001687
1688 template <typename Range>
1689 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
1690 bool IsStringLocation, Range StringRange,
1691 FixItHint Fixit = FixItHint());
1692
1693 void CheckPositionalAndNonpositionalArgs(
1694 const analyze_format_string::FormatSpecifier *FS);
Ted Kremenekab278de2010-01-28 23:39:18 +00001695};
1696}
1697
Ted Kremenek02087932010-07-16 02:11:22 +00001698SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00001699 return OrigFormatExpr->getSourceRange();
1700}
1701
Ted Kremenek02087932010-07-16 02:11:22 +00001702CharSourceRange CheckFormatHandler::
1703getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00001704 SourceLocation Start = getLocationOfByte(startSpecifier);
1705 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
1706
1707 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001708 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00001709
1710 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00001711}
1712
Ted Kremenek02087932010-07-16 02:11:22 +00001713SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001714 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00001715}
1716
Ted Kremenek02087932010-07-16 02:11:22 +00001717void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
1718 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00001719 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
1720 getLocationOfByte(startSpecifier),
1721 /*IsStringLocation*/true,
1722 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00001723}
1724
Ted Kremenekd1668192010-02-27 01:41:03 +00001725void
Ted Kremenek02087932010-07-16 02:11:22 +00001726CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
1727 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00001728 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
1729 << (unsigned) p,
1730 getLocationOfByte(startPos), /*IsStringLocation*/true,
1731 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00001732}
1733
Ted Kremenek02087932010-07-16 02:11:22 +00001734void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00001735 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00001736 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
1737 getLocationOfByte(startPos),
1738 /*IsStringLocation*/true,
1739 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00001740}
1741
Ted Kremenek02087932010-07-16 02:11:22 +00001742void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00001743 if (!IsObjCLiteral) {
1744 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00001745 EmitFormatDiagnostic(
1746 S.PDiag(diag::warn_printf_format_string_contains_null_char),
1747 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
1748 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00001749 }
Ted Kremenek02087932010-07-16 02:11:22 +00001750}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001751
Ted Kremenek02087932010-07-16 02:11:22 +00001752const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001753 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00001754}
1755
1756void CheckFormatHandler::DoneProcessing() {
1757 // Does the number of data arguments exceed the number of
1758 // format conversions in the format string?
1759 if (!HasVAListArg) {
1760 // Find any arguments that weren't covered.
1761 CoveredArgs.flip();
1762 signed notCoveredArg = CoveredArgs.find_first();
1763 if (notCoveredArg >= 0) {
1764 assert((unsigned)notCoveredArg < NumDataArgs);
Richard Trieu03cf7b72011-10-28 00:41:25 +00001765 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
1766 getDataArg((unsigned) notCoveredArg)->getLocStart(),
1767 /*IsStringLocation*/false, getFormatStringRange());
Ted Kremenek02087932010-07-16 02:11:22 +00001768 }
1769 }
1770}
1771
Ted Kremenekce815422010-07-19 21:25:57 +00001772bool
1773CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
1774 SourceLocation Loc,
1775 const char *startSpec,
1776 unsigned specifierLen,
1777 const char *csStart,
1778 unsigned csLen) {
1779
1780 bool keepGoing = true;
1781 if (argIndex < NumDataArgs) {
1782 // Consider the argument coverered, even though the specifier doesn't
1783 // make sense.
1784 CoveredArgs.set(argIndex);
1785 }
1786 else {
1787 // If argIndex exceeds the number of data arguments we
1788 // don't issue a warning because that is just a cascade of warnings (and
1789 // they may have intended '%%' anyway). We don't want to continue processing
1790 // the format string after this point, however, as we will like just get
1791 // gibberish when trying to match arguments.
1792 keepGoing = false;
1793 }
1794
Richard Trieu03cf7b72011-10-28 00:41:25 +00001795 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
1796 << StringRef(csStart, csLen),
1797 Loc, /*IsStringLocation*/true,
1798 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekce815422010-07-19 21:25:57 +00001799
1800 return keepGoing;
1801}
1802
Richard Trieu03cf7b72011-10-28 00:41:25 +00001803void
1804CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
1805 const char *startSpec,
1806 unsigned specifierLen) {
1807 EmitFormatDiagnostic(
1808 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
1809 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
1810}
1811
Ted Kremenek6adb7e32010-07-26 19:45:42 +00001812bool
1813CheckFormatHandler::CheckNumArgs(
1814 const analyze_format_string::FormatSpecifier &FS,
1815 const analyze_format_string::ConversionSpecifier &CS,
1816 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
1817
1818 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00001819 PartialDiagnostic PDiag = FS.usesPositionalArg()
1820 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
1821 << (argIndex+1) << NumDataArgs)
1822 : S.PDiag(diag::warn_printf_insufficient_data_args);
1823 EmitFormatDiagnostic(
1824 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
1825 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek6adb7e32010-07-26 19:45:42 +00001826 return false;
1827 }
1828 return true;
1829}
1830
Richard Trieu03cf7b72011-10-28 00:41:25 +00001831template<typename Range>
1832void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
1833 SourceLocation Loc,
1834 bool IsStringLocation,
1835 Range StringRange,
1836 FixItHint FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001837 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00001838 Loc, IsStringLocation, StringRange, FixIt);
1839}
1840
1841/// \brief If the format string is not within the funcion call, emit a note
1842/// so that the function call and string are in diagnostic messages.
1843///
1844/// \param inFunctionCall if true, the format string is within the function
1845/// call and only one diagnostic message will be produced. Otherwise, an
1846/// extra note will be emitted pointing to location of the format string.
1847///
1848/// \param ArgumentExpr the expression that is passed as the format string
1849/// argument in the function call. Used for getting locations when two
1850/// diagnostics are emitted.
1851///
1852/// \param PDiag the callee should already have provided any strings for the
1853/// diagnostic message. This function only adds locations and fixits
1854/// to diagnostics.
1855///
1856/// \param Loc primary location for diagnostic. If two diagnostics are
1857/// required, one will be at Loc and a new SourceLocation will be created for
1858/// the other one.
1859///
1860/// \param IsStringLocation if true, Loc points to the format string should be
1861/// used for the note. Otherwise, Loc points to the argument list and will
1862/// be used with PDiag.
1863///
1864/// \param StringRange some or all of the string to highlight. This is
1865/// templated so it can accept either a CharSourceRange or a SourceRange.
1866///
1867/// \param Fixit optional fix it hint for the format string.
1868template<typename Range>
1869void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
1870 const Expr *ArgumentExpr,
1871 PartialDiagnostic PDiag,
1872 SourceLocation Loc,
1873 bool IsStringLocation,
1874 Range StringRange,
1875 FixItHint FixIt) {
1876 if (InFunctionCall)
1877 S.Diag(Loc, PDiag) << StringRange << FixIt;
1878 else {
1879 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
1880 << ArgumentExpr->getSourceRange();
1881 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
1882 diag::note_format_string_defined)
1883 << StringRange << FixIt;
1884 }
1885}
1886
Ted Kremenek02087932010-07-16 02:11:22 +00001887//===--- CHECK: Printf format string checking ------------------------------===//
1888
1889namespace {
1890class CheckPrintfHandler : public CheckFormatHandler {
1891public:
1892 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
1893 const Expr *origFormatExpr, unsigned firstDataArg,
1894 unsigned numDataArgs, bool isObjCLiteral,
1895 const char *beg, bool hasVAListArg,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001896 Expr **Args, unsigned NumArgs,
1897 unsigned formatIdx, bool inFunctionCall)
Ted Kremenek02087932010-07-16 02:11:22 +00001898 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1899 numDataArgs, isObjCLiteral, beg, hasVAListArg,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001900 Args, NumArgs, formatIdx, inFunctionCall) {}
Ted Kremenek02087932010-07-16 02:11:22 +00001901
1902
1903 bool HandleInvalidPrintfConversionSpecifier(
1904 const analyze_printf::PrintfSpecifier &FS,
1905 const char *startSpecifier,
1906 unsigned specifierLen);
1907
1908 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
1909 const char *startSpecifier,
1910 unsigned specifierLen);
1911
1912 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
1913 const char *startSpecifier, unsigned specifierLen);
1914 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
1915 const analyze_printf::OptionalAmount &Amt,
1916 unsigned type,
1917 const char *startSpecifier, unsigned specifierLen);
1918 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
1919 const analyze_printf::OptionalFlag &flag,
1920 const char *startSpecifier, unsigned specifierLen);
1921 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
1922 const analyze_printf::OptionalFlag &ignoredFlag,
1923 const analyze_printf::OptionalFlag &flag,
1924 const char *startSpecifier, unsigned specifierLen);
1925};
1926}
1927
1928bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
1929 const analyze_printf::PrintfSpecifier &FS,
1930 const char *startSpecifier,
1931 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00001932 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00001933 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00001934
Ted Kremenekce815422010-07-19 21:25:57 +00001935 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1936 getLocationOfByte(CS.getStart()),
1937 startSpecifier, specifierLen,
1938 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00001939}
1940
Ted Kremenek02087932010-07-16 02:11:22 +00001941bool CheckPrintfHandler::HandleAmount(
1942 const analyze_format_string::OptionalAmount &Amt,
1943 unsigned k, const char *startSpecifier,
1944 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00001945
1946 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00001947 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00001948 unsigned argIndex = Amt.getArgIndex();
1949 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00001950 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
1951 << k,
1952 getLocationOfByte(Amt.getStart()),
1953 /*IsStringLocation*/true,
1954 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00001955 // Don't do any more checking. We will just emit
1956 // spurious errors.
1957 return false;
1958 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001959
Ted Kremenek5739de72010-01-29 01:06:55 +00001960 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00001961 // Although not in conformance with C99, we also allow the argument to be
1962 // an 'unsigned int' as that is a reasonably safe case. GCC also
1963 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00001964 CoveredArgs.set(argIndex);
1965 const Expr *Arg = getDataArg(argIndex);
Ted Kremenek5739de72010-01-29 01:06:55 +00001966 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001967
1968 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
1969 assert(ATR.isValid());
1970
1971 if (!ATR.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00001972 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborg772e9272011-12-07 10:33:11 +00001973 << k << ATR.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00001974 << T << Arg->getSourceRange(),
1975 getLocationOfByte(Amt.getStart()),
1976 /*IsStringLocation*/true,
1977 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00001978 // Don't do any more checking. We will just emit
1979 // spurious errors.
1980 return false;
1981 }
1982 }
1983 }
1984 return true;
1985}
Ted Kremenek5739de72010-01-29 01:06:55 +00001986
Tom Careb49ec692010-06-17 19:00:27 +00001987void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00001988 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00001989 const analyze_printf::OptionalAmount &Amt,
1990 unsigned type,
1991 const char *startSpecifier,
1992 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00001993 const analyze_printf::PrintfConversionSpecifier &CS =
1994 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00001995
Richard Trieu03cf7b72011-10-28 00:41:25 +00001996 FixItHint fixit =
1997 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
1998 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
1999 Amt.getConstantLength()))
2000 : FixItHint();
2001
2002 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2003 << type << CS.toString(),
2004 getLocationOfByte(Amt.getStart()),
2005 /*IsStringLocation*/true,
2006 getSpecifierRange(startSpecifier, specifierLen),
2007 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00002008}
2009
Ted Kremenek02087932010-07-16 02:11:22 +00002010void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002011 const analyze_printf::OptionalFlag &flag,
2012 const char *startSpecifier,
2013 unsigned specifierLen) {
2014 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002015 const analyze_printf::PrintfConversionSpecifier &CS =
2016 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00002017 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2018 << flag.toString() << CS.toString(),
2019 getLocationOfByte(flag.getPosition()),
2020 /*IsStringLocation*/true,
2021 getSpecifierRange(startSpecifier, specifierLen),
2022 FixItHint::CreateRemoval(
2023 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00002024}
2025
2026void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00002027 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002028 const analyze_printf::OptionalFlag &ignoredFlag,
2029 const analyze_printf::OptionalFlag &flag,
2030 const char *startSpecifier,
2031 unsigned specifierLen) {
2032 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002033 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2034 << ignoredFlag.toString() << flag.toString(),
2035 getLocationOfByte(ignoredFlag.getPosition()),
2036 /*IsStringLocation*/true,
2037 getSpecifierRange(startSpecifier, specifierLen),
2038 FixItHint::CreateRemoval(
2039 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00002040}
2041
Ted Kremenekab278de2010-01-28 23:39:18 +00002042bool
Ted Kremenek02087932010-07-16 02:11:22 +00002043CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00002044 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00002045 const char *startSpecifier,
2046 unsigned specifierLen) {
2047
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002048 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00002049 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002050 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00002051
Ted Kremenek6cd69422010-07-19 22:01:06 +00002052 if (FS.consumesDataArgument()) {
2053 if (atFirstArg) {
2054 atFirstArg = false;
2055 usesPositionalArgs = FS.usesPositionalArg();
2056 }
2057 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002058 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2059 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00002060 return false;
2061 }
Ted Kremenek5739de72010-01-29 01:06:55 +00002062 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002063
Ted Kremenekd1668192010-02-27 01:41:03 +00002064 // First check if the field width, precision, and conversion specifier
2065 // have matching data arguments.
2066 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2067 startSpecifier, specifierLen)) {
2068 return false;
2069 }
2070
2071 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2072 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00002073 return false;
2074 }
2075
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002076 if (!CS.consumesDataArgument()) {
2077 // FIXME: Technically specifying a precision or field width here
2078 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00002079 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002080 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002081
Ted Kremenek4a49d982010-02-26 19:18:41 +00002082 // Consume the argument.
2083 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00002084 if (argIndex < NumDataArgs) {
2085 // The check to see if the argIndex is valid will come later.
2086 // We set the bit here because we may exit early from this
2087 // function if we encounter some other error.
2088 CoveredArgs.set(argIndex);
2089 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00002090
2091 // Check for using an Objective-C specific conversion specifier
2092 // in a non-ObjC literal.
2093 if (!IsObjCLiteral && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00002094 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
2095 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00002096 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002097
Tom Careb49ec692010-06-17 19:00:27 +00002098 // Check for invalid use of field width
2099 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00002100 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00002101 startSpecifier, specifierLen);
2102 }
2103
2104 // Check for invalid use of precision
2105 if (!FS.hasValidPrecision()) {
2106 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
2107 startSpecifier, specifierLen);
2108 }
2109
2110 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00002111 if (!FS.hasValidThousandsGroupingPrefix())
2112 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00002113 if (!FS.hasValidLeadingZeros())
2114 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
2115 if (!FS.hasValidPlusPrefix())
2116 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00002117 if (!FS.hasValidSpacePrefix())
2118 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00002119 if (!FS.hasValidAlternativeForm())
2120 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
2121 if (!FS.hasValidLeftJustified())
2122 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
2123
2124 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00002125 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
2126 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
2127 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00002128 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
2129 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
2130 startSpecifier, specifierLen);
2131
2132 // Check the length modifier is valid with the given conversion specifier.
2133 const LengthModifier &LM = FS.getLengthModifier();
2134 if (!FS.hasValidLengthModifier())
Richard Trieu03cf7b72011-10-28 00:41:25 +00002135 EmitFormatDiagnostic(S.PDiag(diag::warn_format_nonsensical_length)
2136 << LM.toString() << CS.toString(),
2137 getLocationOfByte(LM.getStart()),
2138 /*IsStringLocation*/true,
2139 getSpecifierRange(startSpecifier, specifierLen),
2140 FixItHint::CreateRemoval(
2141 getSpecifierRange(LM.getStart(),
2142 LM.getLength())));
Tom Careb49ec692010-06-17 19:00:27 +00002143
2144 // Are we using '%n'?
Ted Kremenek516ef222010-07-20 20:04:10 +00002145 if (CS.getKind() == ConversionSpecifier::nArg) {
Tom Careb49ec692010-06-17 19:00:27 +00002146 // Issue a warning about this being a possible security issue.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002147 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_write_back),
2148 getLocationOfByte(CS.getStart()),
2149 /*IsStringLocation*/true,
2150 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekd5fd0fa2010-01-29 01:35:25 +00002151 // Continue checking the other format specifiers.
2152 return true;
2153 }
Ted Kremenekd31b2632010-02-11 09:27:41 +00002154
Ted Kremenek9fcd8302010-01-29 01:43:31 +00002155 // The remaining checks depend on the data arguments.
2156 if (HasVAListArg)
2157 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002158
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002159 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00002160 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002161
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00002162 // Now type check the data expression that matches the
2163 // format specifier.
2164 const Expr *Ex = getDataArg(argIndex);
Nico Weber496cdc22012-01-31 01:43:25 +00002165 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context,
2166 IsObjCLiteral);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00002167 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
2168 // Check if we didn't match because of an implicit cast from a 'char'
2169 // or 'short' to an 'int'. This is done because printf is a varargs
2170 // function.
2171 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
Ted Kremenek12a37de2010-10-21 04:00:58 +00002172 if (ICE->getType() == S.Context.IntTy) {
2173 // All further checking is done on the subexpression.
2174 Ex = ICE->getSubExpr();
2175 if (ATR.matchesType(S.Context, Ex->getType()))
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00002176 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00002177 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00002178
2179 // We may be able to offer a FixItHint if it is a supported type.
2180 PrintfSpecifier fixedFS = FS;
Hans Wennborgf99d04f2011-10-18 08:10:06 +00002181 bool success = fixedFS.fixType(Ex->getType(), S.getLangOptions());
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00002182
2183 if (success) {
2184 // Get the fix string from the fixed format specifier
2185 llvm::SmallString<128> buf;
2186 llvm::raw_svector_ostream os(buf);
2187 fixedFS.toString(os);
2188
Richard Trieu03cf7b72011-10-28 00:41:25 +00002189 EmitFormatDiagnostic(
2190 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg772e9272011-12-07 10:33:11 +00002191 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
Richard Trieu03cf7b72011-10-28 00:41:25 +00002192 << Ex->getSourceRange(),
2193 getLocationOfByte(CS.getStart()),
2194 /*IsStringLocation*/true,
2195 getSpecifierRange(startSpecifier, specifierLen),
2196 FixItHint::CreateReplacement(
2197 getSpecifierRange(startSpecifier, specifierLen),
2198 os.str()));
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00002199 }
2200 else {
2201 S.Diag(getLocationOfByte(CS.getStart()),
2202 diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg772e9272011-12-07 10:33:11 +00002203 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00002204 << getSpecifierRange(startSpecifier, specifierLen)
2205 << Ex->getSourceRange();
2206 }
2207 }
2208
Ted Kremenekab278de2010-01-28 23:39:18 +00002209 return true;
2210}
2211
Ted Kremenek02087932010-07-16 02:11:22 +00002212//===--- CHECK: Scanf format string checking ------------------------------===//
2213
2214namespace {
2215class CheckScanfHandler : public CheckFormatHandler {
2216public:
2217 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
2218 const Expr *origFormatExpr, unsigned firstDataArg,
2219 unsigned numDataArgs, bool isObjCLiteral,
2220 const char *beg, bool hasVAListArg,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002221 Expr **Args, unsigned NumArgs,
2222 unsigned formatIdx, bool inFunctionCall)
Ted Kremenek02087932010-07-16 02:11:22 +00002223 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2224 numDataArgs, isObjCLiteral, beg, hasVAListArg,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002225 Args, NumArgs, formatIdx, inFunctionCall) {}
Ted Kremenek02087932010-07-16 02:11:22 +00002226
2227 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
2228 const char *startSpecifier,
2229 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00002230
2231 bool HandleInvalidScanfConversionSpecifier(
2232 const analyze_scanf::ScanfSpecifier &FS,
2233 const char *startSpecifier,
2234 unsigned specifierLen);
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00002235
2236 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek02087932010-07-16 02:11:22 +00002237};
Ted Kremenek019d2242010-01-29 01:50:07 +00002238}
Ted Kremenekab278de2010-01-28 23:39:18 +00002239
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00002240void CheckScanfHandler::HandleIncompleteScanList(const char *start,
2241 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002242 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
2243 getLocationOfByte(end), /*IsStringLocation*/true,
2244 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00002245}
2246
Ted Kremenekce815422010-07-19 21:25:57 +00002247bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
2248 const analyze_scanf::ScanfSpecifier &FS,
2249 const char *startSpecifier,
2250 unsigned specifierLen) {
2251
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002252 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00002253 FS.getConversionSpecifier();
2254
2255 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2256 getLocationOfByte(CS.getStart()),
2257 startSpecifier, specifierLen,
2258 CS.getStart(), CS.getLength());
2259}
2260
Ted Kremenek02087932010-07-16 02:11:22 +00002261bool CheckScanfHandler::HandleScanfSpecifier(
2262 const analyze_scanf::ScanfSpecifier &FS,
2263 const char *startSpecifier,
2264 unsigned specifierLen) {
2265
2266 using namespace analyze_scanf;
2267 using namespace analyze_format_string;
2268
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002269 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00002270
Ted Kremenek6cd69422010-07-19 22:01:06 +00002271 // Handle case where '%' and '*' don't consume an argument. These shouldn't
2272 // be used to decide if we are using positional arguments consistently.
2273 if (FS.consumesDataArgument()) {
2274 if (atFirstArg) {
2275 atFirstArg = false;
2276 usesPositionalArgs = FS.usesPositionalArg();
2277 }
2278 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002279 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2280 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00002281 return false;
2282 }
Ted Kremenek02087932010-07-16 02:11:22 +00002283 }
2284
2285 // Check if the field with is non-zero.
2286 const OptionalAmount &Amt = FS.getFieldWidth();
2287 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
2288 if (Amt.getConstantAmount() == 0) {
2289 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
2290 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00002291 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
2292 getLocationOfByte(Amt.getStart()),
2293 /*IsStringLocation*/true, R,
2294 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00002295 }
2296 }
2297
2298 if (!FS.consumesDataArgument()) {
2299 // FIXME: Technically specifying a precision or field width here
2300 // makes no sense. Worth issuing a warning at some point.
2301 return true;
2302 }
2303
2304 // Consume the argument.
2305 unsigned argIndex = FS.getArgIndex();
2306 if (argIndex < NumDataArgs) {
2307 // The check to see if the argIndex is valid will come later.
2308 // We set the bit here because we may exit early from this
2309 // function if we encounter some other error.
2310 CoveredArgs.set(argIndex);
2311 }
2312
Ted Kremenek4407ea42010-07-20 20:04:47 +00002313 // Check the length modifier is valid with the given conversion specifier.
2314 const LengthModifier &LM = FS.getLengthModifier();
2315 if (!FS.hasValidLengthModifier()) {
2316 S.Diag(getLocationOfByte(LM.getStart()),
2317 diag::warn_format_nonsensical_length)
2318 << LM.toString() << CS.toString()
2319 << getSpecifierRange(startSpecifier, specifierLen)
2320 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
2321 LM.getLength()));
2322 }
2323
Ted Kremenek02087932010-07-16 02:11:22 +00002324 // The remaining checks depend on the data arguments.
2325 if (HasVAListArg)
2326 return true;
2327
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002328 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00002329 return false;
Ted Kremenek02087932010-07-16 02:11:22 +00002330
Hans Wennborgb1a5e092011-12-10 13:20:11 +00002331 // Check that the argument type matches the format specifier.
2332 const Expr *Ex = getDataArg(argIndex);
2333 const analyze_scanf::ScanfArgTypeResult &ATR = FS.getArgType(S.Context);
2334 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
2335 ScanfSpecifier fixedFS = FS;
2336 bool success = fixedFS.fixType(Ex->getType(), S.getLangOptions());
2337
2338 if (success) {
2339 // Get the fix string from the fixed format specifier.
2340 llvm::SmallString<128> buf;
2341 llvm::raw_svector_ostream os(buf);
2342 fixedFS.toString(os);
2343
2344 EmitFormatDiagnostic(
2345 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2346 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
2347 << Ex->getSourceRange(),
2348 getLocationOfByte(CS.getStart()),
2349 /*IsStringLocation*/true,
2350 getSpecifierRange(startSpecifier, specifierLen),
2351 FixItHint::CreateReplacement(
2352 getSpecifierRange(startSpecifier, specifierLen),
2353 os.str()));
2354 } else {
2355 S.Diag(getLocationOfByte(CS.getStart()),
2356 diag::warn_printf_conversion_argument_type_mismatch)
2357 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
2358 << getSpecifierRange(startSpecifier, specifierLen)
2359 << Ex->getSourceRange();
2360 }
2361 }
2362
Ted Kremenek02087932010-07-16 02:11:22 +00002363 return true;
2364}
2365
2366void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenekfb45d352010-02-10 02:16:30 +00002367 const Expr *OrigFormatExpr,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002368 Expr **Args, unsigned NumArgs,
2369 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002370 unsigned firstDataArg, FormatStringType Type,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002371 bool inFunctionCall) {
Ted Kremenek02087932010-07-16 02:11:22 +00002372
Ted Kremenekab278de2010-01-28 23:39:18 +00002373 // CHECK: is the format string a wide literal?
Douglas Gregorfb65e592011-07-27 05:40:30 +00002374 if (!FExpr->isAscii()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002375 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002376 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00002377 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
2378 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00002379 return;
2380 }
Ted Kremenek02087932010-07-16 02:11:22 +00002381
Ted Kremenekab278de2010-01-28 23:39:18 +00002382 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002383 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00002384 const char *Str = StrRef.data();
2385 unsigned StrLen = StrRef.size();
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002386 const unsigned numDataArgs = NumArgs - firstDataArg;
Ted Kremenek02087932010-07-16 02:11:22 +00002387
Ted Kremenekab278de2010-01-28 23:39:18 +00002388 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00002389 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002390 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002391 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00002392 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
2393 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00002394 return;
2395 }
Ted Kremenek02087932010-07-16 02:11:22 +00002396
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002397 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek02087932010-07-16 02:11:22 +00002398 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Ted Kremenek6e302b22011-09-29 05:52:16 +00002399 numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr),
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002400 Str, HasVAListArg, Args, NumArgs, format_idx,
Richard Trieu03cf7b72011-10-28 00:41:25 +00002401 inFunctionCall);
Ted Kremenek02087932010-07-16 02:11:22 +00002402
Hans Wennborg23926bd2011-12-15 10:25:47 +00002403 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
2404 getLangOptions()))
Ted Kremenek02087932010-07-16 02:11:22 +00002405 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002406 } else if (Type == FST_Scanf) {
Ted Kremenek02087932010-07-16 02:11:22 +00002407 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Ted Kremenek6e302b22011-09-29 05:52:16 +00002408 numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr),
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002409 Str, HasVAListArg, Args, NumArgs, format_idx,
Richard Trieu03cf7b72011-10-28 00:41:25 +00002410 inFunctionCall);
Ted Kremenek02087932010-07-16 02:11:22 +00002411
Hans Wennborg23926bd2011-12-15 10:25:47 +00002412 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
2413 getLangOptions()))
Ted Kremenek02087932010-07-16 02:11:22 +00002414 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002415 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00002416}
2417
Chandler Carruth53caa4d2011-04-27 07:05:31 +00002418//===--- CHECK: Standard memory functions ---------------------------------===//
2419
Douglas Gregora74926b2011-05-03 20:05:22 +00002420/// \brief Determine whether the given type is a dynamic class type (e.g.,
2421/// whether it has a vtable).
2422static bool isDynamicClassType(QualType T) {
2423 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
2424 if (CXXRecordDecl *Definition = Record->getDefinition())
2425 if (Definition->isDynamicClass())
2426 return true;
2427
2428 return false;
2429}
2430
Chandler Carruth889ed862011-06-21 23:04:20 +00002431/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00002432/// otherwise returns NULL.
2433static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Weberc5e73862011-06-14 16:14:58 +00002434 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00002435 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2436 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
2437 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00002438
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00002439 return 0;
2440}
2441
Chandler Carruth889ed862011-06-21 23:04:20 +00002442/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00002443static QualType getSizeOfArgType(const Expr* E) {
2444 if (const UnaryExprOrTypeTraitExpr *SizeOf =
2445 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2446 if (SizeOf->getKind() == clang::UETT_SizeOf)
2447 return SizeOf->getTypeOfArgument();
2448
2449 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00002450}
2451
Chandler Carruth53caa4d2011-04-27 07:05:31 +00002452/// \brief Check for dangerous or invalid arguments to memset().
2453///
Chandler Carruthac687262011-06-03 06:23:57 +00002454/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00002455/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
2456/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00002457///
2458/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00002459void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00002460 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00002461 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00002462 assert(BId != 0);
2463
Ted Kremenekb5fabb22011-04-28 01:38:02 +00002464 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00002465 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00002466 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00002467 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00002468 return;
2469
Anna Zaks22122702012-01-17 00:37:07 +00002470 unsigned LastArg = (BId == Builtin::BImemset ||
2471 BId == Builtin::BIstrndup ? 1 : 2);
2472 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00002473 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00002474
2475 // We have special checking when the length is a sizeof expression.
2476 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
2477 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
2478 llvm::FoldingSetNodeID SizeOfArgID;
2479
Douglas Gregor3bb2a812011-05-03 20:37:33 +00002480 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
2481 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00002482 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00002483
Douglas Gregor3bb2a812011-05-03 20:37:33 +00002484 QualType DestTy = Dest->getType();
2485 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
2486 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00002487
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00002488 // Never warn about void type pointers. This can be used to suppress
2489 // false positives.
2490 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00002491 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00002492
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00002493 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
2494 // actually comparing the expressions for equality. Because computing the
2495 // expression IDs can be expensive, we only do this if the diagnostic is
2496 // enabled.
2497 if (SizeOfArg &&
2498 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
2499 SizeOfArg->getExprLoc())) {
2500 // We only compute IDs for expressions if the warning is enabled, and
2501 // cache the sizeof arg's ID.
2502 if (SizeOfArgID == llvm::FoldingSetNodeID())
2503 SizeOfArg->Profile(SizeOfArgID, Context, true);
2504 llvm::FoldingSetNodeID DestID;
2505 Dest->Profile(DestID, Context, true);
2506 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00002507 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
2508 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00002509 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
2510 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
2511 if (UnaryOp->getOpcode() == UO_AddrOf)
2512 ActionIdx = 1; // If its an address-of operator, just remove it.
2513 if (Context.getTypeSize(PointeeTy) == Context.getCharWidth())
2514 ActionIdx = 2; // If the pointee's size is sizeof(char),
2515 // suggest an explicit length.
Anna Zaks201d4892012-01-13 21:52:01 +00002516 unsigned DestSrcSelect =
Anna Zaks22122702012-01-17 00:37:07 +00002517 (BId == Builtin::BIstrndup ? 1 : ArgIdx);
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00002518 DiagRuntimeBehavior(SizeOfArg->getExprLoc(), Dest,
2519 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Nico Weber39bfed82011-10-13 22:30:23 +00002520 << FnName << DestSrcSelect << ActionIdx
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00002521 << Dest->getSourceRange()
2522 << SizeOfArg->getSourceRange());
2523 break;
2524 }
2525 }
2526
2527 // Also check for cases where the sizeof argument is the exact same
2528 // type as the memory argument, and where it points to a user-defined
2529 // record type.
2530 if (SizeOfArgTy != QualType()) {
2531 if (PointeeTy->isRecordType() &&
2532 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
2533 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
2534 PDiag(diag::warn_sizeof_pointer_type_memaccess)
2535 << FnName << SizeOfArgTy << ArgIdx
2536 << PointeeTy << Dest->getSourceRange()
2537 << LenExpr->getSourceRange());
2538 break;
2539 }
Nico Weberc5e73862011-06-14 16:14:58 +00002540 }
2541
Douglas Gregor3bb2a812011-05-03 20:37:33 +00002542 // Always complain about dynamic classes.
Anna Zaks22122702012-01-17 00:37:07 +00002543 if (isDynamicClassType(PointeeTy)) {
2544
2545 unsigned OperationType = 0;
2546 // "overwritten" if we're warning about the destination for any call
2547 // but memcmp; otherwise a verb appropriate to the call.
2548 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
2549 if (BId == Builtin::BImemcpy)
2550 OperationType = 1;
2551 else if(BId == Builtin::BImemmove)
2552 OperationType = 2;
2553 else if (BId == Builtin::BImemcmp)
2554 OperationType = 3;
2555 }
2556
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00002557 DiagRuntimeBehavior(
2558 Dest->getExprLoc(), Dest,
2559 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks22122702012-01-17 00:37:07 +00002560 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Anna Zaks201d4892012-01-13 21:52:01 +00002561 << FnName << PointeeTy
Anna Zaks22122702012-01-17 00:37:07 +00002562 << OperationType
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00002563 << Call->getCallee()->getSourceRange());
Anna Zaks22122702012-01-17 00:37:07 +00002564 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
2565 BId != Builtin::BImemset)
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00002566 DiagRuntimeBehavior(
2567 Dest->getExprLoc(), Dest,
2568 PDiag(diag::warn_arc_object_memaccess)
2569 << ArgIdx << FnName << PointeeTy
2570 << Call->getCallee()->getSourceRange());
John McCall31168b02011-06-15 23:02:42 +00002571 else
Douglas Gregor3bb2a812011-05-03 20:37:33 +00002572 continue;
John McCall31168b02011-06-15 23:02:42 +00002573
2574 DiagRuntimeBehavior(
2575 Dest->getExprLoc(), Dest,
Chandler Carruthac687262011-06-03 06:23:57 +00002576 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor3bb2a812011-05-03 20:37:33 +00002577 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
2578 break;
2579 }
Chandler Carruth53caa4d2011-04-27 07:05:31 +00002580 }
2581}
2582
Ted Kremenek6865f772011-08-18 20:55:45 +00002583// A little helper routine: ignore addition and subtraction of integer literals.
2584// This intentionally does not ignore all integer constant expressions because
2585// we don't want to remove sizeof().
2586static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
2587 Ex = Ex->IgnoreParenCasts();
2588
2589 for (;;) {
2590 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
2591 if (!BO || !BO->isAdditiveOp())
2592 break;
2593
2594 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
2595 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
2596
2597 if (isa<IntegerLiteral>(RHS))
2598 Ex = LHS;
2599 else if (isa<IntegerLiteral>(LHS))
2600 Ex = RHS;
2601 else
2602 break;
2603 }
2604
2605 return Ex;
2606}
2607
2608// Warn if the user has made the 'size' argument to strlcpy or strlcat
2609// be the size of the source, instead of the destination.
2610void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
2611 IdentifierInfo *FnName) {
2612
2613 // Don't crash if the user has the wrong number of arguments
2614 if (Call->getNumArgs() != 3)
2615 return;
2616
2617 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
2618 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
2619 const Expr *CompareWithSrc = NULL;
2620
2621 // Look for 'strlcpy(dst, x, sizeof(x))'
2622 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
2623 CompareWithSrc = Ex;
2624 else {
2625 // Look for 'strlcpy(dst, x, strlen(x))'
2626 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Richard Smithd62306a2011-11-10 06:34:14 +00002627 if (SizeCall->isBuiltinCall() == Builtin::BIstrlen
Ted Kremenek6865f772011-08-18 20:55:45 +00002628 && SizeCall->getNumArgs() == 1)
2629 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
2630 }
2631 }
2632
2633 if (!CompareWithSrc)
2634 return;
2635
2636 // Determine if the argument to sizeof/strlen is equal to the source
2637 // argument. In principle there's all kinds of things you could do
2638 // here, for instance creating an == expression and evaluating it with
2639 // EvaluateAsBooleanCondition, but this uses a more direct technique:
2640 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
2641 if (!SrcArgDRE)
2642 return;
2643
2644 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
2645 if (!CompareWithSrcDRE ||
2646 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
2647 return;
2648
2649 const Expr *OriginalSizeArg = Call->getArg(2);
2650 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
2651 << OriginalSizeArg->getSourceRange() << FnName;
2652
2653 // Output a FIXIT hint if the destination is an array (rather than a
2654 // pointer to an array). This could be enhanced to handle some
2655 // pointers if we know the actual size, like if DstArg is 'array+2'
2656 // we could say 'sizeof(array)-2'.
2657 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Ted Kremenek18db5d42011-08-18 22:48:41 +00002658 QualType DstArgTy = DstArg->getType();
Ted Kremenek6865f772011-08-18 20:55:45 +00002659
Ted Kremenek18db5d42011-08-18 22:48:41 +00002660 // Only handle constant-sized or VLAs, but not flexible members.
2661 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(DstArgTy)) {
2662 // Only issue the FIXIT for arrays of size > 1.
2663 if (CAT->getSize().getSExtValue() <= 1)
2664 return;
2665 } else if (!DstArgTy->isVariableArrayType()) {
2666 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00002667 }
Ted Kremenek18db5d42011-08-18 22:48:41 +00002668
2669 llvm::SmallString<128> sizeString;
2670 llvm::raw_svector_ostream OS(sizeString);
2671 OS << "sizeof(";
Douglas Gregor75acd922011-09-27 23:30:47 +00002672 DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00002673 OS << ")";
2674
2675 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
2676 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
2677 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00002678}
2679
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002680//===--- CHECK: Return Address of Stack Variable --------------------------===//
2681
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002682static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars);
2683static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002684
2685/// CheckReturnStackAddr - Check if a return statement returns the address
2686/// of a stack variable.
2687void
2688Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
2689 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00002690
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002691 Expr *stackE = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002692 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002693
2694 // Perform checking for returned stack addresses, local blocks,
2695 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00002696 if (lhsType->isPointerType() ||
2697 (!getLangOptions().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002698 stackE = EvalAddr(RetValExp, refVars);
Mike Stump12b8ce12009-08-04 21:02:39 +00002699 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002700 stackE = EvalVal(RetValExp, refVars);
2701 }
2702
2703 if (stackE == 0)
2704 return; // Nothing suspicious was found.
2705
2706 SourceLocation diagLoc;
2707 SourceRange diagRange;
2708 if (refVars.empty()) {
2709 diagLoc = stackE->getLocStart();
2710 diagRange = stackE->getSourceRange();
2711 } else {
2712 // We followed through a reference variable. 'stackE' contains the
2713 // problematic expression but we will warn at the return statement pointing
2714 // at the reference variable. We will later display the "trail" of
2715 // reference variables using notes.
2716 diagLoc = refVars[0]->getLocStart();
2717 diagRange = refVars[0]->getSourceRange();
2718 }
2719
2720 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
2721 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
2722 : diag::warn_ret_stack_addr)
2723 << DR->getDecl()->getDeclName() << diagRange;
2724 } else if (isa<BlockExpr>(stackE)) { // local block.
2725 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
2726 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
2727 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
2728 } else { // local temporary.
2729 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
2730 : diag::warn_ret_local_temp_addr)
2731 << diagRange;
2732 }
2733
2734 // Display the "trail" of reference variables that we followed until we
2735 // found the problematic expression using notes.
2736 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
2737 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
2738 // If this var binds to another reference var, show the range of the next
2739 // var, otherwise the var binds to the problematic expression, in which case
2740 // show the range of the expression.
2741 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
2742 : stackE->getSourceRange();
2743 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
2744 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002745 }
2746}
2747
2748/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
2749/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002750/// to a location on the stack, a local block, an address of a label, or a
2751/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002752/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002753/// encounter a subexpression that (1) clearly does not lead to one of the
2754/// above problematic expressions (2) is something we cannot determine leads to
2755/// a problematic expression based on such local checking.
2756///
2757/// Both EvalAddr and EvalVal follow through reference variables to evaluate
2758/// the expression that they point to. Such variables are added to the
2759/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002760///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00002761/// EvalAddr processes expressions that are pointers that are used as
2762/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002763/// At the base case of the recursion is a check for the above problematic
2764/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002765///
2766/// This implementation handles:
2767///
2768/// * pointer-to-pointer casts
2769/// * implicit conversions from array references to pointers
2770/// * taking the address of fields
2771/// * arbitrary interplay between "&" and "*" operators
2772/// * pointer arithmetic from an address of a stack variable
2773/// * taking the address of an array element where the array is on the stack
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002774static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002775 if (E->isTypeDependent())
2776 return NULL;
2777
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002778 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00002779 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002780 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002781 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00002782 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00002783
Peter Collingbourne91147592011-04-15 00:35:48 +00002784 E = E->IgnoreParens();
2785
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002786 // Our "symbolic interpreter" is just a dispatch off the currently
2787 // viewed AST node. We then recursively traverse the AST by calling
2788 // EvalAddr and EvalVal appropriately.
2789 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002790 case Stmt::DeclRefExprClass: {
2791 DeclRefExpr *DR = cast<DeclRefExpr>(E);
2792
2793 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
2794 // If this is a reference variable, follow through to the expression that
2795 // it points to.
2796 if (V->hasLocalStorage() &&
2797 V->getType()->isReferenceType() && V->hasInit()) {
2798 // Add the reference variable to the "trail".
2799 refVars.push_back(DR);
2800 return EvalAddr(V->getInit(), refVars);
2801 }
2802
2803 return NULL;
2804 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002805
Chris Lattner934edb22007-12-28 05:31:15 +00002806 case Stmt::UnaryOperatorClass: {
2807 // The only unary operator that make sense to handle here
2808 // is AddrOf. All others don't make sense as pointers.
2809 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002810
John McCalle3027922010-08-25 11:45:40 +00002811 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002812 return EvalVal(U->getSubExpr(), refVars);
Chris Lattner934edb22007-12-28 05:31:15 +00002813 else
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002814 return NULL;
2815 }
Mike Stump11289f42009-09-09 15:08:12 +00002816
Chris Lattner934edb22007-12-28 05:31:15 +00002817 case Stmt::BinaryOperatorClass: {
2818 // Handle pointer arithmetic. All other binary operators are not valid
2819 // in this context.
2820 BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00002821 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00002822
John McCalle3027922010-08-25 11:45:40 +00002823 if (op != BO_Add && op != BO_Sub)
Chris Lattner934edb22007-12-28 05:31:15 +00002824 return NULL;
Mike Stump11289f42009-09-09 15:08:12 +00002825
Chris Lattner934edb22007-12-28 05:31:15 +00002826 Expr *Base = B->getLHS();
2827
2828 // Determine which argument is the real pointer base. It could be
2829 // the RHS argument instead of the LHS.
2830 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00002831
Chris Lattner934edb22007-12-28 05:31:15 +00002832 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002833 return EvalAddr(Base, refVars);
Chris Lattner934edb22007-12-28 05:31:15 +00002834 }
Steve Naroff2752a172008-09-10 19:17:48 +00002835
Chris Lattner934edb22007-12-28 05:31:15 +00002836 // For conditional operators we need to see if either the LHS or RHS are
2837 // valid DeclRefExpr*s. If one of them is valid, we return it.
2838 case Stmt::ConditionalOperatorClass: {
2839 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002840
Chris Lattner934edb22007-12-28 05:31:15 +00002841 // Handle the GNU extension for missing LHS.
Douglas Gregor270b2ef2010-10-21 16:21:08 +00002842 if (Expr *lhsExpr = C->getLHS()) {
2843 // In C++, we can have a throw-expression, which has 'void' type.
2844 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002845 if (Expr* LHS = EvalAddr(lhsExpr, refVars))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00002846 return LHS;
2847 }
Chris Lattner934edb22007-12-28 05:31:15 +00002848
Douglas Gregor270b2ef2010-10-21 16:21:08 +00002849 // In C++, we can have a throw-expression, which has 'void' type.
2850 if (C->getRHS()->getType()->isVoidType())
2851 return NULL;
2852
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002853 return EvalAddr(C->getRHS(), refVars);
Chris Lattner934edb22007-12-28 05:31:15 +00002854 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002855
2856 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00002857 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002858 return E; // local block.
2859 return NULL;
2860
2861 case Stmt::AddrLabelExprClass:
2862 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00002863
John McCall28fc7092011-11-10 05:35:25 +00002864 case Stmt::ExprWithCleanupsClass:
2865 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars);
2866
Ted Kremenekc3b4c522008-08-07 00:49:01 +00002867 // For casts, we need to handle conversions from arrays to
2868 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00002869 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00002870 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00002871 case Stmt::CXXFunctionalCastExprClass:
2872 case Stmt::ObjCBridgedCastExprClass: {
Argyrios Kyrtzidis3bab3d22008-08-18 23:01:59 +00002873 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenekc3b4c522008-08-07 00:49:01 +00002874 QualType T = SubExpr->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002875
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002876 if (SubExpr->getType()->isPointerType() ||
2877 SubExpr->getType()->isBlockPointerType() ||
2878 SubExpr->getType()->isObjCQualifiedIdType())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002879 return EvalAddr(SubExpr, refVars);
Ted Kremenekc3b4c522008-08-07 00:49:01 +00002880 else if (T->isArrayType())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002881 return EvalVal(SubExpr, refVars);
Chris Lattner934edb22007-12-28 05:31:15 +00002882 else
Ted Kremenekc3b4c522008-08-07 00:49:01 +00002883 return 0;
Chris Lattner934edb22007-12-28 05:31:15 +00002884 }
Mike Stump11289f42009-09-09 15:08:12 +00002885
Chris Lattner934edb22007-12-28 05:31:15 +00002886 // C++ casts. For dynamic casts, static casts, and const casts, we
2887 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregore200adc2008-10-27 19:41:14 +00002888 // through the cast. In the case the dynamic cast doesn't fail (and
2889 // return NULL), we take the conservative route and report cases
Chris Lattner934edb22007-12-28 05:31:15 +00002890 // where we return the address of a stack variable. For Reinterpre
Douglas Gregore200adc2008-10-27 19:41:14 +00002891 // FIXME: The comment about is wrong; we're not always converting
2892 // from pointer to pointer. I'm guessing that this code should also
Mike Stump11289f42009-09-09 15:08:12 +00002893 // handle references to objects.
2894 case Stmt::CXXStaticCastExprClass:
2895 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00002896 case Stmt::CXXConstCastExprClass:
2897 case Stmt::CXXReinterpretCastExprClass: {
2898 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002899 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002900 return EvalAddr(S, refVars);
Chris Lattner934edb22007-12-28 05:31:15 +00002901 else
2902 return NULL;
Chris Lattner934edb22007-12-28 05:31:15 +00002903 }
Mike Stump11289f42009-09-09 15:08:12 +00002904
Douglas Gregorfe314812011-06-21 17:03:29 +00002905 case Stmt::MaterializeTemporaryExprClass:
2906 if (Expr *Result = EvalAddr(
2907 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
2908 refVars))
2909 return Result;
2910
2911 return E;
2912
Chris Lattner934edb22007-12-28 05:31:15 +00002913 // Everything else: we simply don't reason about them.
2914 default:
2915 return NULL;
2916 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002917}
Mike Stump11289f42009-09-09 15:08:12 +00002918
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002919
2920/// EvalVal - This function is complements EvalAddr in the mutual recursion.
2921/// See the comments for EvalAddr for more details.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002922static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
Ted Kremenekb7861562010-08-04 20:01:07 +00002923do {
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00002924 // We should only be called for evaluating non-pointer expressions, or
2925 // expressions with a pointer type that are not used as references but instead
2926 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00002927
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002928 // Our "symbolic interpreter" is just a dispatch off the currently
2929 // viewed AST node. We then recursively traverse the AST by calling
2930 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00002931
2932 E = E->IgnoreParens();
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002933 switch (E->getStmtClass()) {
Ted Kremenekb7861562010-08-04 20:01:07 +00002934 case Stmt::ImplicitCastExprClass: {
2935 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall2536c6d2010-08-25 10:28:54 +00002936 if (IE->getValueKind() == VK_LValue) {
Ted Kremenekb7861562010-08-04 20:01:07 +00002937 E = IE->getSubExpr();
2938 continue;
2939 }
2940 return NULL;
2941 }
2942
John McCall28fc7092011-11-10 05:35:25 +00002943 case Stmt::ExprWithCleanupsClass:
2944 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars);
2945
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002946 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002947 // When we hit a DeclRefExpr we are looking at code that refers to a
2948 // variable's name. If it's not a reference variable we check if it has
2949 // local storage within the function, and if so, return the expression.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002950 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002951
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002952 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002953 if (V->hasLocalStorage()) {
2954 if (!V->getType()->isReferenceType())
2955 return DR;
2956
2957 // Reference variable, follow through to the expression that
2958 // it points to.
2959 if (V->hasInit()) {
2960 // Add the reference variable to the "trail".
2961 refVars.push_back(DR);
2962 return EvalVal(V->getInit(), refVars);
2963 }
2964 }
Mike Stump11289f42009-09-09 15:08:12 +00002965
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002966 return NULL;
2967 }
Mike Stump11289f42009-09-09 15:08:12 +00002968
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002969 case Stmt::UnaryOperatorClass: {
2970 // The only unary operator that make sense to handle here
2971 // is Deref. All others don't resolve to a "name." This includes
2972 // handling all sorts of rvalues passed to a unary operator.
2973 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002974
John McCalle3027922010-08-25 11:45:40 +00002975 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002976 return EvalAddr(U->getSubExpr(), refVars);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002977
2978 return NULL;
2979 }
Mike Stump11289f42009-09-09 15:08:12 +00002980
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002981 case Stmt::ArraySubscriptExprClass: {
2982 // Array subscripts are potential references to data on the stack. We
2983 // retrieve the DeclRefExpr* for the array variable if it indeed
2984 // has local storage.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002985 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002986 }
Mike Stump11289f42009-09-09 15:08:12 +00002987
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002988 case Stmt::ConditionalOperatorClass: {
2989 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002990 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002991 ConditionalOperator *C = cast<ConditionalOperator>(E);
2992
Anders Carlsson801c5c72007-11-30 19:04:31 +00002993 // Handle the GNU extension for missing LHS.
2994 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002995 if (Expr *LHS = EvalVal(lhsExpr, refVars))
Anders Carlsson801c5c72007-11-30 19:04:31 +00002996 return LHS;
2997
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002998 return EvalVal(C->getRHS(), refVars);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002999 }
Mike Stump11289f42009-09-09 15:08:12 +00003000
Ted Kremenekcff94fa2007-08-17 16:46:58 +00003001 // Accesses to members are potential references to data on the stack.
Douglas Gregorf405d7e2009-08-31 23:41:50 +00003002 case Stmt::MemberExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00003003 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00003004
Ted Kremenekcff94fa2007-08-17 16:46:58 +00003005 // Check for indirect access. We only want direct field accesses.
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00003006 if (M->isArrow())
Ted Kremenekcff94fa2007-08-17 16:46:58 +00003007 return NULL;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00003008
3009 // Check whether the member type is itself a reference, in which case
3010 // we're not going to refer to the member, but to what the member refers to.
3011 if (M->getMemberDecl()->getType()->isReferenceType())
3012 return NULL;
3013
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00003014 return EvalVal(M->getBase(), refVars);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00003015 }
Mike Stump11289f42009-09-09 15:08:12 +00003016
Douglas Gregorfe314812011-06-21 17:03:29 +00003017 case Stmt::MaterializeTemporaryExprClass:
3018 if (Expr *Result = EvalVal(
3019 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
3020 refVars))
3021 return Result;
3022
3023 return E;
3024
Ted Kremenekcff94fa2007-08-17 16:46:58 +00003025 default:
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00003026 // Check that we don't return or take the address of a reference to a
3027 // temporary. This is only useful in C++.
3028 if (!E->isTypeDependent() && E->isRValue())
3029 return E;
3030
3031 // Everything else: we simply don't reason about them.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00003032 return NULL;
3033 }
Ted Kremenekb7861562010-08-04 20:01:07 +00003034} while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00003035}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00003036
3037//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
3038
3039/// Check for comparisons of floating point operands using != and ==.
3040/// Issue a warning if these are no self-comparisons, as they are not likely
3041/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00003042void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Ted Kremenek43fb8b02007-11-25 00:58:00 +00003043 bool EmitWarning = true;
Mike Stump11289f42009-09-09 15:08:12 +00003044
Richard Trieu82402a02011-09-15 21:56:47 +00003045 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
3046 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00003047
3048 // Special case: check for x == x (which is OK).
3049 // Do not emit warnings for such cases.
3050 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
3051 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
3052 if (DRL->getDecl() == DRR->getDecl())
3053 EmitWarning = false;
Mike Stump11289f42009-09-09 15:08:12 +00003054
3055
Ted Kremenekeda40e22007-11-29 00:59:04 +00003056 // Special case: check for comparisons against literals that can be exactly
3057 // represented by APFloat. In such cases, do not emit a warning. This
3058 // is a heuristic: often comparison against such literals are used to
3059 // detect if a value in a variable has not changed. This clearly can
3060 // lead to false negatives.
3061 if (EmitWarning) {
3062 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
3063 if (FLL->isExact())
3064 EmitWarning = false;
Mike Stump12b8ce12009-08-04 21:02:39 +00003065 } else
Ted Kremenekeda40e22007-11-29 00:59:04 +00003066 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
3067 if (FLR->isExact())
3068 EmitWarning = false;
3069 }
3070 }
Mike Stump11289f42009-09-09 15:08:12 +00003071
Ted Kremenek43fb8b02007-11-25 00:58:00 +00003072 // Check for comparisons with builtin types.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003073 if (EmitWarning)
Ted Kremenek43fb8b02007-11-25 00:58:00 +00003074 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Richard Smithd62306a2011-11-10 06:34:14 +00003075 if (CL->isBuiltinCall())
Ted Kremenek43fb8b02007-11-25 00:58:00 +00003076 EmitWarning = false;
Mike Stump11289f42009-09-09 15:08:12 +00003077
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003078 if (EmitWarning)
Ted Kremenek43fb8b02007-11-25 00:58:00 +00003079 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Richard Smithd62306a2011-11-10 06:34:14 +00003080 if (CR->isBuiltinCall())
Ted Kremenek43fb8b02007-11-25 00:58:00 +00003081 EmitWarning = false;
Mike Stump11289f42009-09-09 15:08:12 +00003082
Ted Kremenek43fb8b02007-11-25 00:58:00 +00003083 // Emit the diagnostic.
3084 if (EmitWarning)
Richard Trieu82402a02011-09-15 21:56:47 +00003085 Diag(Loc, diag::warn_floatingpoint_eq)
3086 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00003087}
John McCallca01b222010-01-04 23:21:16 +00003088
John McCall70aa5392010-01-06 05:24:50 +00003089//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
3090//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00003091
John McCall70aa5392010-01-06 05:24:50 +00003092namespace {
John McCallca01b222010-01-04 23:21:16 +00003093
John McCall70aa5392010-01-06 05:24:50 +00003094/// Structure recording the 'active' range of an integer-valued
3095/// expression.
3096struct IntRange {
3097 /// The number of bits active in the int.
3098 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00003099
John McCall70aa5392010-01-06 05:24:50 +00003100 /// True if the int is known not to have negative values.
3101 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00003102
John McCall70aa5392010-01-06 05:24:50 +00003103 IntRange(unsigned Width, bool NonNegative)
3104 : Width(Width), NonNegative(NonNegative)
3105 {}
John McCallca01b222010-01-04 23:21:16 +00003106
John McCall817d4af2010-11-10 23:38:19 +00003107 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00003108 static IntRange forBoolType() {
3109 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00003110 }
3111
John McCall817d4af2010-11-10 23:38:19 +00003112 /// Returns the range of an opaque value of the given integral type.
3113 static IntRange forValueOfType(ASTContext &C, QualType T) {
3114 return forValueOfCanonicalType(C,
3115 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00003116 }
3117
John McCall817d4af2010-11-10 23:38:19 +00003118 /// Returns the range of an opaque value of a canonical integral type.
3119 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00003120 assert(T->isCanonicalUnqualified());
3121
3122 if (const VectorType *VT = dyn_cast<VectorType>(T))
3123 T = VT->getElementType().getTypePtr();
3124 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
3125 T = CT->getElementType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00003126
John McCall18a2c2c2010-11-09 22:22:12 +00003127 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00003128 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
3129 EnumDecl *Enum = ET->getDecl();
John McCallf937c022011-10-07 06:10:15 +00003130 if (!Enum->isCompleteDefinition())
John McCall18a2c2c2010-11-09 22:22:12 +00003131 return IntRange(C.getIntWidth(QualType(T, 0)), false);
3132
John McCallcc7e5bf2010-05-06 08:58:33 +00003133 unsigned NumPositive = Enum->getNumPositiveBits();
3134 unsigned NumNegative = Enum->getNumNegativeBits();
3135
3136 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
3137 }
John McCall70aa5392010-01-06 05:24:50 +00003138
3139 const BuiltinType *BT = cast<BuiltinType>(T);
3140 assert(BT->isInteger());
3141
3142 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
3143 }
3144
John McCall817d4af2010-11-10 23:38:19 +00003145 /// Returns the "target" range of a canonical integral type, i.e.
3146 /// the range of values expressible in the type.
3147 ///
3148 /// This matches forValueOfCanonicalType except that enums have the
3149 /// full range of their type, not the range of their enumerators.
3150 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
3151 assert(T->isCanonicalUnqualified());
3152
3153 if (const VectorType *VT = dyn_cast<VectorType>(T))
3154 T = VT->getElementType().getTypePtr();
3155 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
3156 T = CT->getElementType().getTypePtr();
3157 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00003158 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00003159
3160 const BuiltinType *BT = cast<BuiltinType>(T);
3161 assert(BT->isInteger());
3162
3163 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
3164 }
3165
3166 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00003167 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00003168 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00003169 L.NonNegative && R.NonNegative);
3170 }
3171
John McCall817d4af2010-11-10 23:38:19 +00003172 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00003173 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00003174 return IntRange(std::min(L.Width, R.Width),
3175 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00003176 }
3177};
3178
3179IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
3180 if (value.isSigned() && value.isNegative())
3181 return IntRange(value.getMinSignedBits(), false);
3182
3183 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00003184 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00003185
3186 // isNonNegative() just checks the sign bit without considering
3187 // signedness.
3188 return IntRange(value.getActiveBits(), true);
3189}
3190
John McCall74430522010-01-06 22:57:21 +00003191IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
John McCall70aa5392010-01-06 05:24:50 +00003192 unsigned MaxWidth) {
3193 if (result.isInt())
3194 return GetValueRange(C, result.getInt(), MaxWidth);
3195
3196 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00003197 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
3198 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
3199 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
3200 R = IntRange::join(R, El);
3201 }
John McCall70aa5392010-01-06 05:24:50 +00003202 return R;
3203 }
3204
3205 if (result.isComplexInt()) {
3206 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
3207 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
3208 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00003209 }
3210
3211 // This can happen with lossless casts to intptr_t of "based" lvalues.
3212 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00003213 // FIXME: The only reason we need to pass the type in here is to get
3214 // the sign right on this one case. It would be nice if APValue
3215 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00003216 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00003217 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00003218}
John McCall70aa5392010-01-06 05:24:50 +00003219
3220/// Pseudo-evaluate the given integer expression, estimating the
3221/// range of values it might take.
3222///
3223/// \param MaxWidth - the width to which the value will be truncated
3224IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
3225 E = E->IgnoreParens();
3226
3227 // Try a full evaluation first.
3228 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00003229 if (E->EvaluateAsRValue(result, C))
John McCall74430522010-01-06 22:57:21 +00003230 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00003231
3232 // I think we only want to look through implicit casts here; if the
3233 // user has an explicit widening cast, we should treat the value as
3234 // being of the new, wider type.
3235 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00003236 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00003237 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
3238
John McCall817d4af2010-11-10 23:38:19 +00003239 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
John McCall70aa5392010-01-06 05:24:50 +00003240
John McCalle3027922010-08-25 11:45:40 +00003241 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall2ce81ad2010-01-06 22:07:33 +00003242
John McCall70aa5392010-01-06 05:24:50 +00003243 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00003244 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00003245 return OutputTypeRange;
3246
3247 IntRange SubRange
3248 = GetExprRange(C, CE->getSubExpr(),
3249 std::min(MaxWidth, OutputTypeRange.Width));
3250
3251 // Bail out if the subexpr's range is as wide as the cast type.
3252 if (SubRange.Width >= OutputTypeRange.Width)
3253 return OutputTypeRange;
3254
3255 // Otherwise, we take the smaller width, and we're non-negative if
3256 // either the output type or the subexpr is.
3257 return IntRange(SubRange.Width,
3258 SubRange.NonNegative || OutputTypeRange.NonNegative);
3259 }
3260
3261 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3262 // If we can fold the condition, just take that operand.
3263 bool CondResult;
3264 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
3265 return GetExprRange(C, CondResult ? CO->getTrueExpr()
3266 : CO->getFalseExpr(),
3267 MaxWidth);
3268
3269 // Otherwise, conservatively merge.
3270 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
3271 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
3272 return IntRange::join(L, R);
3273 }
3274
3275 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3276 switch (BO->getOpcode()) {
3277
3278 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00003279 case BO_LAnd:
3280 case BO_LOr:
3281 case BO_LT:
3282 case BO_GT:
3283 case BO_LE:
3284 case BO_GE:
3285 case BO_EQ:
3286 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00003287 return IntRange::forBoolType();
3288
John McCallc3688382011-07-13 06:35:24 +00003289 // The type of the assignments is the type of the LHS, so the RHS
3290 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00003291 case BO_MulAssign:
3292 case BO_DivAssign:
3293 case BO_RemAssign:
3294 case BO_AddAssign:
3295 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00003296 case BO_XorAssign:
3297 case BO_OrAssign:
3298 // TODO: bitfields?
John McCall817d4af2010-11-10 23:38:19 +00003299 return IntRange::forValueOfType(C, E->getType());
John McCallff96ccd2010-02-23 19:22:29 +00003300
John McCallc3688382011-07-13 06:35:24 +00003301 // Simple assignments just pass through the RHS, which will have
3302 // been coerced to the LHS type.
3303 case BO_Assign:
3304 // TODO: bitfields?
3305 return GetExprRange(C, BO->getRHS(), MaxWidth);
3306
John McCall70aa5392010-01-06 05:24:50 +00003307 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00003308 case BO_PtrMemD:
3309 case BO_PtrMemI:
John McCall817d4af2010-11-10 23:38:19 +00003310 return IntRange::forValueOfType(C, E->getType());
John McCall70aa5392010-01-06 05:24:50 +00003311
John McCall2ce81ad2010-01-06 22:07:33 +00003312 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00003313 case BO_And:
3314 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00003315 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
3316 GetExprRange(C, BO->getRHS(), MaxWidth));
3317
John McCall70aa5392010-01-06 05:24:50 +00003318 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00003319 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00003320 // ...except that we want to treat '1 << (blah)' as logically
3321 // positive. It's an important idiom.
3322 if (IntegerLiteral *I
3323 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
3324 if (I->getValue() == 1) {
John McCall817d4af2010-11-10 23:38:19 +00003325 IntRange R = IntRange::forValueOfType(C, E->getType());
John McCall1bff9932010-04-07 01:14:35 +00003326 return IntRange(R.Width, /*NonNegative*/ true);
3327 }
3328 }
3329 // fallthrough
3330
John McCalle3027922010-08-25 11:45:40 +00003331 case BO_ShlAssign:
John McCall817d4af2010-11-10 23:38:19 +00003332 return IntRange::forValueOfType(C, E->getType());
John McCall70aa5392010-01-06 05:24:50 +00003333
John McCall2ce81ad2010-01-06 22:07:33 +00003334 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00003335 case BO_Shr:
3336 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00003337 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3338
3339 // If the shift amount is a positive constant, drop the width by
3340 // that much.
3341 llvm::APSInt shift;
3342 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
3343 shift.isNonNegative()) {
3344 unsigned zext = shift.getZExtValue();
3345 if (zext >= L.Width)
3346 L.Width = (L.NonNegative ? 0 : 1);
3347 else
3348 L.Width -= zext;
3349 }
3350
3351 return L;
3352 }
3353
3354 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00003355 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00003356 return GetExprRange(C, BO->getRHS(), MaxWidth);
3357
John McCall2ce81ad2010-01-06 22:07:33 +00003358 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00003359 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00003360 if (BO->getLHS()->getType()->isPointerType())
John McCall817d4af2010-11-10 23:38:19 +00003361 return IntRange::forValueOfType(C, E->getType());
John McCall51431812011-07-14 22:39:48 +00003362 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003363
John McCall51431812011-07-14 22:39:48 +00003364 // The width of a division result is mostly determined by the size
3365 // of the LHS.
3366 case BO_Div: {
3367 // Don't 'pre-truncate' the operands.
3368 unsigned opWidth = C.getIntWidth(E->getType());
3369 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3370
3371 // If the divisor is constant, use that.
3372 llvm::APSInt divisor;
3373 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
3374 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
3375 if (log2 >= L.Width)
3376 L.Width = (L.NonNegative ? 0 : 1);
3377 else
3378 L.Width = std::min(L.Width - log2, MaxWidth);
3379 return L;
3380 }
3381
3382 // Otherwise, just use the LHS's width.
3383 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3384 return IntRange(L.Width, L.NonNegative && R.NonNegative);
3385 }
3386
3387 // The result of a remainder can't be larger than the result of
3388 // either side.
3389 case BO_Rem: {
3390 // Don't 'pre-truncate' the operands.
3391 unsigned opWidth = C.getIntWidth(E->getType());
3392 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3393 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3394
3395 IntRange meet = IntRange::meet(L, R);
3396 meet.Width = std::min(meet.Width, MaxWidth);
3397 return meet;
3398 }
3399
3400 // The default behavior is okay for these.
3401 case BO_Mul:
3402 case BO_Add:
3403 case BO_Xor:
3404 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00003405 break;
3406 }
3407
John McCall51431812011-07-14 22:39:48 +00003408 // The default case is to treat the operation as if it were closed
3409 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00003410 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3411 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
3412 return IntRange::join(L, R);
3413 }
3414
3415 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
3416 switch (UO->getOpcode()) {
3417 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00003418 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00003419 return IntRange::forBoolType();
3420
3421 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00003422 case UO_Deref:
3423 case UO_AddrOf: // should be impossible
John McCall817d4af2010-11-10 23:38:19 +00003424 return IntRange::forValueOfType(C, E->getType());
John McCall70aa5392010-01-06 05:24:50 +00003425
3426 default:
3427 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
3428 }
3429 }
Douglas Gregor882211c2010-04-28 22:16:22 +00003430
3431 if (dyn_cast<OffsetOfExpr>(E)) {
John McCall817d4af2010-11-10 23:38:19 +00003432 IntRange::forValueOfType(C, E->getType());
Douglas Gregor882211c2010-04-28 22:16:22 +00003433 }
John McCall70aa5392010-01-06 05:24:50 +00003434
Richard Smithcaf33902011-10-10 18:28:20 +00003435 if (FieldDecl *BitField = E->getBitField())
3436 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00003437 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00003438
John McCall817d4af2010-11-10 23:38:19 +00003439 return IntRange::forValueOfType(C, E->getType());
John McCall70aa5392010-01-06 05:24:50 +00003440}
John McCall263a48b2010-01-04 23:31:57 +00003441
John McCallcc7e5bf2010-05-06 08:58:33 +00003442IntRange GetExprRange(ASTContext &C, Expr *E) {
3443 return GetExprRange(C, E, C.getIntWidth(E->getType()));
3444}
3445
John McCall263a48b2010-01-04 23:31:57 +00003446/// Checks whether the given value, which currently has the given
3447/// source semantics, has the same value when coerced through the
3448/// target semantics.
John McCall70aa5392010-01-06 05:24:50 +00003449bool IsSameFloatAfterCast(const llvm::APFloat &value,
3450 const llvm::fltSemantics &Src,
3451 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00003452 llvm::APFloat truncated = value;
3453
3454 bool ignored;
3455 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
3456 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
3457
3458 return truncated.bitwiseIsEqual(value);
3459}
3460
3461/// Checks whether the given value, which currently has the given
3462/// source semantics, has the same value when coerced through the
3463/// target semantics.
3464///
3465/// The value might be a vector of floats (or a complex number).
John McCall70aa5392010-01-06 05:24:50 +00003466bool IsSameFloatAfterCast(const APValue &value,
3467 const llvm::fltSemantics &Src,
3468 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00003469 if (value.isFloat())
3470 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
3471
3472 if (value.isVector()) {
3473 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
3474 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
3475 return false;
3476 return true;
3477 }
3478
3479 assert(value.isComplexFloat());
3480 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
3481 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
3482}
3483
John McCallacf0ee52010-10-08 02:01:28 +00003484void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00003485
Ted Kremenek6274be42010-09-23 21:43:44 +00003486static bool IsZero(Sema &S, Expr *E) {
3487 // Suppress cases where we are comparing against an enum constant.
3488 if (const DeclRefExpr *DR =
3489 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
3490 if (isa<EnumConstantDecl>(DR->getDecl()))
3491 return false;
3492
3493 // Suppress cases where the '0' value is expanded from a macro.
3494 if (E->getLocStart().isMacroID())
3495 return false;
3496
John McCallcc7e5bf2010-05-06 08:58:33 +00003497 llvm::APSInt Value;
3498 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
3499}
3500
John McCall2551c1b2010-10-06 00:25:24 +00003501static bool HasEnumType(Expr *E) {
3502 // Strip off implicit integral promotions.
3503 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00003504 if (ICE->getCastKind() != CK_IntegralCast &&
3505 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00003506 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00003507 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00003508 }
3509
3510 return E->getType()->isEnumeralType();
3511}
3512
John McCallcc7e5bf2010-05-06 08:58:33 +00003513void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00003514 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00003515 if (E->isValueDependent())
3516 return;
3517
John McCalle3027922010-08-25 11:45:40 +00003518 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00003519 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00003520 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00003521 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00003522 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00003523 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00003524 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00003525 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00003526 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00003527 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00003528 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00003529 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00003530 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00003531 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00003532 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00003533 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
3534 }
3535}
3536
3537/// Analyze the operands of the given comparison. Implements the
3538/// fallback case from AnalyzeComparison.
3539void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00003540 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
3541 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00003542}
John McCall263a48b2010-01-04 23:31:57 +00003543
John McCallca01b222010-01-04 23:21:16 +00003544/// \brief Implements -Wsign-compare.
3545///
Richard Trieu82402a02011-09-15 21:56:47 +00003546/// \param E the binary operator to check for warnings
John McCallcc7e5bf2010-05-06 08:58:33 +00003547void AnalyzeComparison(Sema &S, BinaryOperator *E) {
3548 // The type the comparison is being performed in.
3549 QualType T = E->getLHS()->getType();
3550 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
3551 && "comparison with mismatched types");
John McCallca01b222010-01-04 23:21:16 +00003552
John McCallcc7e5bf2010-05-06 08:58:33 +00003553 // We don't do anything special if this isn't an unsigned integral
3554 // comparison: we're only interested in integral comparisons, and
3555 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00003556 //
3557 // We also don't care about value-dependent expressions or expressions
3558 // whose result is a constant.
3559 if (!T->hasUnsignedIntegerRepresentation()
3560 || E->isValueDependent() || E->isIntegerConstantExpr(S.Context))
John McCallcc7e5bf2010-05-06 08:58:33 +00003561 return AnalyzeImpConvsInComparison(S, E);
John McCall70aa5392010-01-06 05:24:50 +00003562
Richard Trieu82402a02011-09-15 21:56:47 +00003563 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
3564 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
John McCallca01b222010-01-04 23:21:16 +00003565
John McCallcc7e5bf2010-05-06 08:58:33 +00003566 // Check to see if one of the (unmodified) operands is of different
3567 // signedness.
3568 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00003569 if (LHS->getType()->hasSignedIntegerRepresentation()) {
3570 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00003571 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00003572 signedOperand = LHS;
3573 unsignedOperand = RHS;
3574 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
3575 signedOperand = RHS;
3576 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00003577 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00003578 CheckTrivialUnsignedComparison(S, E);
3579 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00003580 }
3581
John McCallcc7e5bf2010-05-06 08:58:33 +00003582 // Otherwise, calculate the effective range of the signed operand.
3583 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00003584
John McCallcc7e5bf2010-05-06 08:58:33 +00003585 // Go ahead and analyze implicit conversions in the operands. Note
3586 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00003587 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
3588 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00003589
John McCallcc7e5bf2010-05-06 08:58:33 +00003590 // If the signed range is non-negative, -Wsign-compare won't fire,
3591 // but we should still check for comparisons which are always true
3592 // or false.
3593 if (signedRange.NonNegative)
3594 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00003595
3596 // For (in)equality comparisons, if the unsigned operand is a
3597 // constant which cannot collide with a overflowed signed operand,
3598 // then reinterpreting the signed operand as unsigned will not
3599 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00003600 if (E->isEqualityOp()) {
3601 unsigned comparisonWidth = S.Context.getIntWidth(T);
3602 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00003603
John McCallcc7e5bf2010-05-06 08:58:33 +00003604 // We should never be unable to prove that the unsigned operand is
3605 // non-negative.
3606 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
3607
3608 if (unsignedRange.Width < comparisonWidth)
3609 return;
3610 }
3611
3612 S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison)
Richard Trieu82402a02011-09-15 21:56:47 +00003613 << LHS->getType() << RHS->getType()
3614 << LHS->getSourceRange() << RHS->getSourceRange();
John McCallca01b222010-01-04 23:21:16 +00003615}
3616
John McCall1f425642010-11-11 03:21:53 +00003617/// Analyzes an attempt to assign the given value to a bitfield.
3618///
3619/// Returns true if there was something fishy about the attempt.
3620bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
3621 SourceLocation InitLoc) {
3622 assert(Bitfield->isBitField());
3623 if (Bitfield->isInvalidDecl())
3624 return false;
3625
John McCalldeebbcf2010-11-11 05:33:51 +00003626 // White-list bool bitfields.
3627 if (Bitfield->getType()->isBooleanType())
3628 return false;
3629
Douglas Gregor789adec2011-02-04 13:09:01 +00003630 // Ignore value- or type-dependent expressions.
3631 if (Bitfield->getBitWidth()->isValueDependent() ||
3632 Bitfield->getBitWidth()->isTypeDependent() ||
3633 Init->isValueDependent() ||
3634 Init->isTypeDependent())
3635 return false;
3636
John McCall1f425642010-11-11 03:21:53 +00003637 Expr *OriginalInit = Init->IgnoreParenImpCasts();
3638
Richard Smith5fab0c92011-12-28 19:48:30 +00003639 llvm::APSInt Value;
3640 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00003641 return false;
3642
John McCall1f425642010-11-11 03:21:53 +00003643 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00003644 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00003645
3646 if (OriginalWidth <= FieldWidth)
3647 return false;
3648
Eli Friedmanc267a322012-01-26 23:11:39 +00003649 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00003650 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00003651 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00003652
Eli Friedmanc267a322012-01-26 23:11:39 +00003653 // Check whether the stored value is equal to the original value.
3654 TruncatedValue = TruncatedValue.extend(OriginalWidth);
John McCall1f425642010-11-11 03:21:53 +00003655 if (Value == TruncatedValue)
3656 return false;
3657
Eli Friedmanc267a322012-01-26 23:11:39 +00003658 // Special-case bitfields of width 1: booleans are naturally 0/1, and
3659 // therefore don't strictly fit into a bitfield of width 1.
3660 if (FieldWidth == 1 && Value.getBoolValue() == TruncatedValue.getBoolValue())
3661 return false;
3662
John McCall1f425642010-11-11 03:21:53 +00003663 std::string PrettyValue = Value.toString(10);
3664 std::string PrettyTrunc = TruncatedValue.toString(10);
3665
3666 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
3667 << PrettyValue << PrettyTrunc << OriginalInit->getType()
3668 << Init->getSourceRange();
3669
3670 return true;
3671}
3672
John McCalld2a53122010-11-09 23:24:47 +00003673/// Analyze the given simple or compound assignment for warning-worthy
3674/// operations.
3675void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
3676 // Just recurse on the LHS.
3677 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
3678
3679 // We want to recurse on the RHS as normal unless we're assigning to
3680 // a bitfield.
3681 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
John McCall1f425642010-11-11 03:21:53 +00003682 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
3683 E->getOperatorLoc())) {
3684 // Recurse, ignoring any implicit conversions on the RHS.
3685 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
3686 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00003687 }
3688 }
3689
3690 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
3691}
3692
John McCall263a48b2010-01-04 23:31:57 +00003693/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Douglas Gregor364f7db2011-03-12 00:14:31 +00003694void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
3695 SourceLocation CContext, unsigned diag) {
3696 S.Diag(E->getExprLoc(), diag)
3697 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
3698}
3699
Chandler Carruth7f3654f2011-04-05 06:47:57 +00003700/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
3701void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
3702 unsigned diag) {
3703 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag);
3704}
3705
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00003706/// Diagnose an implicit cast from a literal expression. Does not warn when the
3707/// cast wouldn't lose information.
Chandler Carruth016ef402011-04-10 08:36:24 +00003708void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
3709 SourceLocation CContext) {
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00003710 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruth016ef402011-04-10 08:36:24 +00003711 bool isExact = false;
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00003712 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00003713 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
3714 T->hasUnsignedIntegerRepresentation());
3715 if (Value.convertToInteger(IntegerValue,
Chandler Carruth016ef402011-04-10 08:36:24 +00003716 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00003717 == llvm::APFloat::opOK && isExact)
Chandler Carruth016ef402011-04-10 08:36:24 +00003718 return;
3719
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00003720 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
3721 << FL->getType() << T << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruth016ef402011-04-10 08:36:24 +00003722}
3723
John McCall18a2c2c2010-11-09 22:22:12 +00003724std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
3725 if (!Range.Width) return "0";
3726
3727 llvm::APSInt ValueInRange = Value;
3728 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00003729 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00003730 return ValueInRange.toString(10);
3731}
3732
John McCallcc7e5bf2010-05-06 08:58:33 +00003733void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00003734 SourceLocation CC, bool *ICContext = 0) {
John McCallcc7e5bf2010-05-06 08:58:33 +00003735 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00003736
John McCallcc7e5bf2010-05-06 08:58:33 +00003737 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
3738 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
3739 if (Source == Target) return;
3740 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00003741
Chandler Carruthc22845a2011-07-26 05:40:03 +00003742 // If the conversion context location is invalid don't complain. We also
3743 // don't want to emit a warning if the issue occurs from the expansion of
3744 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
3745 // delay this check as long as possible. Once we detect we are in that
3746 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00003747 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00003748 return;
3749
Richard Trieu021baa32011-09-23 20:10:00 +00003750 // Diagnose implicit casts to bool.
3751 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
3752 if (isa<StringLiteral>(E))
3753 // Warn on string literal to bool. Checks for string literals in logical
3754 // expressions, for instances, assert(0 && "error here"), is prevented
3755 // by a check in AnalyzeImplicitConversions().
3756 return DiagnoseImpCast(S, E, T, CC,
3757 diag::warn_impcast_string_literal_to_bool);
Lang Hamesdf5c1212011-12-05 20:49:50 +00003758 if (Source->isFunctionType()) {
3759 // Warn on function to bool. Checks free functions and static member
3760 // functions. Weakly imported functions are excluded from the check,
3761 // since it's common to test their value to check whether the linker
3762 // found a definition for them.
3763 ValueDecl *D = 0;
3764 if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
3765 D = R->getDecl();
3766 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
3767 D = M->getMemberDecl();
3768 }
3769
3770 if (D && !D->isWeak()) {
Richard Trieu5f623222011-12-06 04:48:01 +00003771 if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
3772 S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
3773 << F << E->getSourceRange() << SourceRange(CC);
David Blaikie10eb4b62011-12-09 21:42:37 +00003774 S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
3775 << FixItHint::CreateInsertion(E->getExprLoc(), "&");
3776 QualType ReturnType;
3777 UnresolvedSet<4> NonTemplateOverloads;
3778 S.isExprCallable(*E, ReturnType, NonTemplateOverloads);
3779 if (!ReturnType.isNull()
3780 && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
3781 S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
3782 << FixItHint::CreateInsertion(
3783 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu5f623222011-12-06 04:48:01 +00003784 return;
3785 }
Lang Hamesdf5c1212011-12-05 20:49:50 +00003786 }
3787 }
David Blaikie7833b7d2011-09-29 04:06:47 +00003788 return; // Other casts to bool are not checked.
Richard Trieu021baa32011-09-23 20:10:00 +00003789 }
John McCall263a48b2010-01-04 23:31:57 +00003790
3791 // Strip vector types.
3792 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00003793 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00003794 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00003795 return;
John McCallacf0ee52010-10-08 02:01:28 +00003796 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00003797 }
Chris Lattneree7286f2011-06-14 04:51:15 +00003798
3799 // If the vector cast is cast between two vectors of the same size, it is
3800 // a bitcast, not a conversion.
3801 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
3802 return;
John McCall263a48b2010-01-04 23:31:57 +00003803
3804 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
3805 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
3806 }
3807
3808 // Strip complex types.
3809 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00003810 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00003811 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00003812 return;
3813
John McCallacf0ee52010-10-08 02:01:28 +00003814 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00003815 }
John McCall263a48b2010-01-04 23:31:57 +00003816
3817 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
3818 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
3819 }
3820
3821 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
3822 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
3823
3824 // If the source is floating point...
3825 if (SourceBT && SourceBT->isFloatingPoint()) {
3826 // ...and the target is floating point...
3827 if (TargetBT && TargetBT->isFloatingPoint()) {
3828 // ...then warn if we're dropping FP rank.
3829
3830 // Builtin FP kinds are ordered by increasing FP rank.
3831 if (SourceBT->getKind() > TargetBT->getKind()) {
3832 // Don't warn about float constants that are precisely
3833 // representable in the target type.
3834 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00003835 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00003836 // Value might be a float, a float vector, or a float complex.
3837 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00003838 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
3839 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00003840 return;
3841 }
3842
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00003843 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00003844 return;
3845
John McCallacf0ee52010-10-08 02:01:28 +00003846 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall263a48b2010-01-04 23:31:57 +00003847 }
3848 return;
3849 }
3850
Ted Kremenek4c0826c2011-03-10 20:03:42 +00003851 // If the target is integral, always warn.
Chandler Carruth22c7a792011-02-17 11:05:49 +00003852 if ((TargetBT && TargetBT->isInteger())) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00003853 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00003854 return;
3855
Chandler Carruth22c7a792011-02-17 11:05:49 +00003856 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00003857 // We also want to warn on, e.g., "int i = -1.234"
3858 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
3859 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
3860 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
3861
Chandler Carruth016ef402011-04-10 08:36:24 +00003862 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
3863 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00003864 } else {
3865 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
3866 }
3867 }
John McCall263a48b2010-01-04 23:31:57 +00003868
3869 return;
3870 }
3871
John McCall70aa5392010-01-06 05:24:50 +00003872 if (!Source->isIntegerType() || !Target->isIntegerType())
John McCall263a48b2010-01-04 23:31:57 +00003873 return;
3874
Richard Trieubeaf3452011-05-29 19:59:02 +00003875 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
3876 == Expr::NPCK_GNUNull) && Target->isIntegerType()) {
3877 S.Diag(E->getExprLoc(), diag::warn_impcast_null_pointer_to_integer)
3878 << E->getSourceRange() << clang::SourceRange(CC);
3879 return;
3880 }
3881
John McCallcc7e5bf2010-05-06 08:58:33 +00003882 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00003883 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00003884
3885 if (SourceRange.Width > TargetRange.Width) {
John McCall18a2c2c2010-11-09 22:22:12 +00003886 // If the source is a constant, use a default-on diagnostic.
3887 // TODO: this should happen for bitfield stores, too.
3888 llvm::APSInt Value(32);
3889 if (E->isIntegerConstantExpr(Value, S.Context)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00003890 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00003891 return;
3892
John McCall18a2c2c2010-11-09 22:22:12 +00003893 std::string PrettySourceValue = Value.toString(10);
3894 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
3895
Ted Kremenek33ba9952011-10-22 02:37:33 +00003896 S.DiagRuntimeBehavior(E->getExprLoc(), E,
3897 S.PDiag(diag::warn_impcast_integer_precision_constant)
3898 << PrettySourceValue << PrettyTargetValue
3899 << E->getType() << T << E->getSourceRange()
3900 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00003901 return;
3902 }
3903
Chris Lattneree7286f2011-06-14 04:51:15 +00003904 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00003905 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00003906 return;
3907
John McCall70aa5392010-01-06 05:24:50 +00003908 if (SourceRange.Width == 64 && TargetRange.Width == 32)
John McCallacf0ee52010-10-08 02:01:28 +00003909 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32);
3910 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00003911 }
3912
3913 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
3914 (!TargetRange.NonNegative && SourceRange.NonNegative &&
3915 SourceRange.Width == TargetRange.Width)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00003916
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00003917 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00003918 return;
3919
John McCallcc7e5bf2010-05-06 08:58:33 +00003920 unsigned DiagID = diag::warn_impcast_integer_sign;
3921
3922 // Traditionally, gcc has warned about this under -Wsign-compare.
3923 // We also want to warn about it in -Wconversion.
3924 // So if -Wconversion is off, use a completely identical diagnostic
3925 // in the sign-compare group.
3926 // The conditional-checking code will
3927 if (ICContext) {
3928 DiagID = diag::warn_impcast_integer_sign_conditional;
3929 *ICContext = true;
3930 }
3931
John McCallacf0ee52010-10-08 02:01:28 +00003932 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00003933 }
3934
Douglas Gregora78f1932011-02-22 02:45:07 +00003935 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00003936 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
3937 // type, to give us better diagnostics.
3938 QualType SourceType = E->getType();
3939 if (!S.getLangOptions().CPlusPlus) {
3940 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3941 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3942 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
3943 SourceType = S.Context.getTypeDeclType(Enum);
3944 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
3945 }
3946 }
3947
Douglas Gregora78f1932011-02-22 02:45:07 +00003948 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
3949 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
3950 if ((SourceEnum->getDecl()->getIdentifier() ||
Richard Smithdda56e42011-04-15 14:24:37 +00003951 SourceEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Douglas Gregora78f1932011-02-22 02:45:07 +00003952 (TargetEnum->getDecl()->getIdentifier() ||
Richard Smithdda56e42011-04-15 14:24:37 +00003953 TargetEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00003954 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00003955 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00003956 return;
3957
Douglas Gregor364f7db2011-03-12 00:14:31 +00003958 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00003959 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00003960 }
Douglas Gregora78f1932011-02-22 02:45:07 +00003961
John McCall263a48b2010-01-04 23:31:57 +00003962 return;
3963}
3964
John McCallcc7e5bf2010-05-06 08:58:33 +00003965void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T);
3966
3967void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00003968 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00003969 E = E->IgnoreParenImpCasts();
3970
3971 if (isa<ConditionalOperator>(E))
3972 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T);
3973
John McCallacf0ee52010-10-08 02:01:28 +00003974 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00003975 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00003976 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00003977 return;
3978}
3979
3980void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) {
John McCallacf0ee52010-10-08 02:01:28 +00003981 SourceLocation CC = E->getQuestionLoc();
3982
3983 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00003984
3985 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00003986 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
3987 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00003988
3989 // If -Wconversion would have warned about either of the candidates
3990 // for a signedness conversion to the context type...
3991 if (!Suspicious) return;
3992
3993 // ...but it's currently ignored...
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003994 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
3995 CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00003996 return;
3997
John McCallcc7e5bf2010-05-06 08:58:33 +00003998 // ...then check whether it would have warned about either of the
3999 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00004000 if (E->getType() == T) return;
4001
4002 Suspicious = false;
4003 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
4004 E->getType(), CC, &Suspicious);
4005 if (!Suspicious)
4006 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00004007 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00004008}
4009
4010/// AnalyzeImplicitConversions - Find and report any interesting
4011/// implicit conversions in the given expression. There are a couple
4012/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00004013void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00004014 QualType T = OrigE->getType();
4015 Expr *E = OrigE->IgnoreParenImpCasts();
4016
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00004017 if (E->isTypeDependent() || E->isValueDependent())
4018 return;
4019
John McCallcc7e5bf2010-05-06 08:58:33 +00004020 // For conditional operators, we analyze the arguments as if they
4021 // were being fed directly into the output.
4022 if (isa<ConditionalOperator>(E)) {
4023 ConditionalOperator *CO = cast<ConditionalOperator>(E);
4024 CheckConditionalOperator(S, CO, T);
4025 return;
4026 }
4027
4028 // Go ahead and check any implicit conversions we might have skipped.
4029 // The non-canonical typecheck is just an optimization;
4030 // CheckImplicitConversion will filter out dead implicit conversions.
4031 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00004032 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00004033
4034 // Now continue drilling into this expression.
4035
4036 // Skip past explicit casts.
4037 if (isa<ExplicitCastExpr>(E)) {
4038 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00004039 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00004040 }
4041
John McCalld2a53122010-11-09 23:24:47 +00004042 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4043 // Do a somewhat different check with comparison operators.
4044 if (BO->isComparisonOp())
4045 return AnalyzeComparison(S, BO);
4046
Eli Friedman66b63952012-01-26 23:34:06 +00004047 // And with simple assignments.
4048 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00004049 return AnalyzeAssignment(S, BO);
4050 }
John McCallcc7e5bf2010-05-06 08:58:33 +00004051
4052 // These break the otherwise-useful invariant below. Fortunately,
4053 // we don't really need to recurse into them, because any internal
4054 // expressions should have been analyzed already when they were
4055 // built into statements.
4056 if (isa<StmtExpr>(E)) return;
4057
4058 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00004059 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00004060
4061 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00004062 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00004063 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
4064 bool IsLogicalOperator = BO && BO->isLogicalOp();
4065 for (Stmt::child_range I = E->children(); I; ++I) {
4066 Expr *ChildExpr = cast<Expr>(*I);
4067 if (IsLogicalOperator &&
4068 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
4069 // Ignore checking string literals that are in logical operators.
4070 continue;
4071 AnalyzeImplicitConversions(S, ChildExpr, CC);
4072 }
John McCallcc7e5bf2010-05-06 08:58:33 +00004073}
4074
4075} // end anonymous namespace
4076
4077/// Diagnoses "dangerous" implicit conversions within the given
4078/// expression (which is a full expression). Implements -Wconversion
4079/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00004080///
4081/// \param CC the "context" location of the implicit conversion, i.e.
4082/// the most location of the syntactic entity requiring the implicit
4083/// conversion
4084void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00004085 // Don't diagnose in unevaluated contexts.
4086 if (ExprEvalContexts.back().Context == Sema::Unevaluated)
4087 return;
4088
4089 // Don't diagnose for value- or type-dependent expressions.
4090 if (E->isTypeDependent() || E->isValueDependent())
4091 return;
4092
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00004093 // Check for array bounds violations in cases where the check isn't triggered
4094 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
4095 // ArraySubscriptExpr is on the RHS of a variable initialization.
4096 CheckArrayAccess(E);
4097
John McCallacf0ee52010-10-08 02:01:28 +00004098 // This is not the right CC for (e.g.) a variable initialization.
4099 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00004100}
4101
John McCall1f425642010-11-11 03:21:53 +00004102void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
4103 FieldDecl *BitField,
4104 Expr *Init) {
4105 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
4106}
4107
Mike Stump0c2ec772010-01-21 03:59:47 +00004108/// CheckParmsForFunctionDef - Check that the parameters of the given
4109/// function are appropriate for the definition of a function. This
4110/// takes care of any checks that cannot be performed on the
4111/// declaration itself, e.g., that the types of each of the function
4112/// parameters are complete.
Douglas Gregorb524d902010-11-01 18:37:59 +00004113bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
4114 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00004115 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00004116 for (; P != PEnd; ++P) {
4117 ParmVarDecl *Param = *P;
4118
Mike Stump0c2ec772010-01-21 03:59:47 +00004119 // C99 6.7.5.3p4: the parameters in a parameter type list in a
4120 // function declarator that is part of a function definition of
4121 // that function shall not have incomplete type.
4122 //
4123 // This is also C++ [dcl.fct]p6.
4124 if (!Param->isInvalidDecl() &&
4125 RequireCompleteType(Param->getLocation(), Param->getType(),
4126 diag::err_typecheck_decl_incomplete_type)) {
4127 Param->setInvalidDecl();
4128 HasInvalidParm = true;
4129 }
4130
4131 // C99 6.9.1p5: If the declarator includes a parameter type list, the
4132 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00004133 if (CheckParameterNames &&
4134 Param->getIdentifier() == 0 &&
Mike Stump0c2ec772010-01-21 03:59:47 +00004135 !Param->isImplicit() &&
4136 !getLangOptions().CPlusPlus)
4137 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00004138
4139 // C99 6.7.5.3p12:
4140 // If the function declarator is not part of a definition of that
4141 // function, parameters may have incomplete type and may use the [*]
4142 // notation in their sequences of declarator specifiers to specify
4143 // variable length array types.
4144 QualType PType = Param->getOriginalType();
4145 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
4146 if (AT->getSizeModifier() == ArrayType::Star) {
4147 // FIXME: This diagnosic should point the the '[*]' if source-location
4148 // information is added for it.
4149 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
4150 }
4151 }
Mike Stump0c2ec772010-01-21 03:59:47 +00004152 }
4153
4154 return HasInvalidParm;
4155}
John McCall2b5c1b22010-08-12 21:44:57 +00004156
4157/// CheckCastAlign - Implements -Wcast-align, which warns when a
4158/// pointer cast increases the alignment requirements.
4159void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
4160 // This is actually a lot of work to potentially be doing on every
4161 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00004162 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
4163 TRange.getBegin())
David Blaikie9c902b52011-09-25 23:23:43 +00004164 == DiagnosticsEngine::Ignored)
John McCall2b5c1b22010-08-12 21:44:57 +00004165 return;
4166
4167 // Ignore dependent types.
4168 if (T->isDependentType() || Op->getType()->isDependentType())
4169 return;
4170
4171 // Require that the destination be a pointer type.
4172 const PointerType *DestPtr = T->getAs<PointerType>();
4173 if (!DestPtr) return;
4174
4175 // If the destination has alignment 1, we're done.
4176 QualType DestPointee = DestPtr->getPointeeType();
4177 if (DestPointee->isIncompleteType()) return;
4178 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
4179 if (DestAlign.isOne()) return;
4180
4181 // Require that the source be a pointer type.
4182 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
4183 if (!SrcPtr) return;
4184 QualType SrcPointee = SrcPtr->getPointeeType();
4185
4186 // Whitelist casts from cv void*. We already implicitly
4187 // whitelisted casts to cv void*, since they have alignment 1.
4188 // Also whitelist casts involving incomplete types, which implicitly
4189 // includes 'void'.
4190 if (SrcPointee->isIncompleteType()) return;
4191
4192 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
4193 if (SrcAlign >= DestAlign) return;
4194
4195 Diag(TRange.getBegin(), diag::warn_cast_align)
4196 << Op->getType() << T
4197 << static_cast<unsigned>(SrcAlign.getQuantity())
4198 << static_cast<unsigned>(DestAlign.getQuantity())
4199 << TRange << Op->getSourceRange();
4200}
4201
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00004202static const Type* getElementType(const Expr *BaseExpr) {
4203 const Type* EltType = BaseExpr->getType().getTypePtr();
4204 if (EltType->isAnyPointerType())
4205 return EltType->getPointeeType().getTypePtr();
4206 else if (EltType->isArrayType())
4207 return EltType->getBaseElementTypeUnsafe();
4208 return EltType;
4209}
4210
Chandler Carruth28389f02011-08-05 09:10:50 +00004211/// \brief Check whether this array fits the idiom of a size-one tail padded
4212/// array member of a struct.
4213///
4214/// We avoid emitting out-of-bounds access warnings for such arrays as they are
4215/// commonly used to emulate flexible arrays in C89 code.
4216static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
4217 const NamedDecl *ND) {
4218 if (Size != 1 || !ND) return false;
4219
4220 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
4221 if (!FD) return false;
4222
4223 // Don't consider sizes resulting from macro expansions or template argument
4224 // substitution to form C89 tail-padded arrays.
4225 ConstantArrayTypeLoc TL =
4226 cast<ConstantArrayTypeLoc>(FD->getTypeSourceInfo()->getTypeLoc());
4227 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(TL.getSizeExpr());
4228 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
4229 return false;
4230
4231 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00004232 if (!RD) return false;
4233 if (RD->isUnion()) return false;
4234 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
4235 if (!CRD->isStandardLayout()) return false;
4236 }
Chandler Carruth28389f02011-08-05 09:10:50 +00004237
Benjamin Kramer8c543672011-08-06 03:04:42 +00004238 // See if this is the last field decl in the record.
4239 const Decl *D = FD;
4240 while ((D = D->getNextDeclInContext()))
4241 if (isa<FieldDecl>(D))
4242 return false;
4243 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00004244}
4245
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00004246void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00004247 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00004248 bool AllowOnePastEnd, bool IndexNegated) {
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00004249 IndexExpr = IndexExpr->IgnoreParenCasts();
4250 if (IndexExpr->isValueDependent())
4251 return;
4252
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00004253 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00004254 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00004255 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00004256 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00004257 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00004258 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00004259
Chandler Carruth2a666fc2011-02-17 20:55:08 +00004260 llvm::APSInt index;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00004261 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremenek64699be2011-02-16 01:57:07 +00004262 return;
Richard Smith13f67182011-12-16 19:31:14 +00004263 if (IndexNegated)
4264 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00004265
Chandler Carruth126b1552011-08-05 08:07:29 +00004266 const NamedDecl *ND = NULL;
Chandler Carruth126b1552011-08-05 08:07:29 +00004267 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
4268 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00004269 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00004270 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00004271
Ted Kremeneke4b316c2011-02-23 23:06:04 +00004272 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00004273 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00004274 if (!size.isStrictlyPositive())
4275 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00004276
4277 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00004278 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00004279 // Make sure we're comparing apples to apples when comparing index to size
4280 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
4281 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00004282 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00004283 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00004284 if (ptrarith_typesize != array_typesize) {
4285 // There's a cast to a different size type involved
4286 uint64_t ratio = array_typesize / ptrarith_typesize;
4287 // TODO: Be smarter about handling cases where array_typesize is not a
4288 // multiple of ptrarith_typesize
4289 if (ptrarith_typesize * ratio == array_typesize)
4290 size *= llvm::APInt(size.getBitWidth(), ratio);
4291 }
4292 }
4293
Chandler Carruth2a666fc2011-02-17 20:55:08 +00004294 if (size.getBitWidth() > index.getBitWidth())
4295 index = index.sext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00004296 else if (size.getBitWidth() < index.getBitWidth())
4297 size = size.sext(index.getBitWidth());
4298
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00004299 // For array subscripting the index must be less than size, but for pointer
4300 // arithmetic also allow the index (offset) to be equal to size since
4301 // computing the next address after the end of the array is legal and
4302 // commonly done e.g. in C++ iterators and range-based for loops.
4303 if (AllowOnePastEnd ? index.sle(size) : index.slt(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00004304 return;
4305
4306 // Also don't warn for arrays of size 1 which are members of some
4307 // structure. These are often used to approximate flexible arrays in C89
4308 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00004309 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00004310 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00004311
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00004312 // Suppress the warning if the subscript expression (as identified by the
4313 // ']' location) and the index expression are both from macro expansions
4314 // within a system header.
4315 if (ASE) {
4316 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
4317 ASE->getRBracketLoc());
4318 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
4319 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
4320 IndexExpr->getLocStart());
4321 if (SourceMgr.isFromSameFile(RBracketLoc, IndexLoc))
4322 return;
4323 }
4324 }
4325
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00004326 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00004327 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00004328 DiagID = diag::warn_array_index_exceeds_bounds;
4329
4330 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
4331 PDiag(DiagID) << index.toString(10, true)
4332 << size.toString(10, true)
4333 << (unsigned)size.getLimitedValue(~0U)
4334 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00004335 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00004336 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00004337 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00004338 DiagID = diag::warn_ptr_arith_precedes_bounds;
4339 if (index.isNegative()) index = -index;
4340 }
4341
4342 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
4343 PDiag(DiagID) << index.toString(10, true)
4344 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00004345 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00004346
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00004347 if (!ND) {
4348 // Try harder to find a NamedDecl to point at in the note.
4349 while (const ArraySubscriptExpr *ASE =
4350 dyn_cast<ArraySubscriptExpr>(BaseExpr))
4351 BaseExpr = ASE->getBase()->IgnoreParenCasts();
4352 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
4353 ND = dyn_cast<NamedDecl>(DRE->getDecl());
4354 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
4355 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
4356 }
4357
Chandler Carruth1af88f12011-02-17 21:10:52 +00004358 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00004359 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
4360 PDiag(diag::note_array_index_out_of_bounds)
4361 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00004362}
4363
Ted Kremenekdf26df72011-03-01 18:41:00 +00004364void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00004365 int AllowOnePastEnd = 0;
4366 while (expr) {
4367 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00004368 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00004369 case Stmt::ArraySubscriptExprClass: {
4370 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00004371 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00004372 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00004373 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00004374 }
4375 case Stmt::UnaryOperatorClass: {
4376 // Only unwrap the * and & unary operators
4377 const UnaryOperator *UO = cast<UnaryOperator>(expr);
4378 expr = UO->getSubExpr();
4379 switch (UO->getOpcode()) {
4380 case UO_AddrOf:
4381 AllowOnePastEnd++;
4382 break;
4383 case UO_Deref:
4384 AllowOnePastEnd--;
4385 break;
4386 default:
4387 return;
4388 }
4389 break;
4390 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00004391 case Stmt::ConditionalOperatorClass: {
4392 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
4393 if (const Expr *lhs = cond->getLHS())
4394 CheckArrayAccess(lhs);
4395 if (const Expr *rhs = cond->getRHS())
4396 CheckArrayAccess(rhs);
4397 return;
4398 }
4399 default:
4400 return;
4401 }
Peter Collingbourne91147592011-04-15 00:35:48 +00004402 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00004403}
John McCall31168b02011-06-15 23:02:42 +00004404
4405//===--- CHECK: Objective-C retain cycles ----------------------------------//
4406
4407namespace {
4408 struct RetainCycleOwner {
4409 RetainCycleOwner() : Variable(0), Indirect(false) {}
4410 VarDecl *Variable;
4411 SourceRange Range;
4412 SourceLocation Loc;
4413 bool Indirect;
4414
4415 void setLocsFrom(Expr *e) {
4416 Loc = e->getExprLoc();
4417 Range = e->getSourceRange();
4418 }
4419 };
4420}
4421
4422/// Consider whether capturing the given variable can possibly lead to
4423/// a retain cycle.
4424static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
4425 // In ARC, it's captured strongly iff the variable has __strong
4426 // lifetime. In MRR, it's captured strongly if the variable is
4427 // __block and has an appropriate type.
4428 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
4429 return false;
4430
4431 owner.Variable = var;
4432 owner.setLocsFrom(ref);
4433 return true;
4434}
4435
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00004436static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00004437 while (true) {
4438 e = e->IgnoreParens();
4439 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
4440 switch (cast->getCastKind()) {
4441 case CK_BitCast:
4442 case CK_LValueBitCast:
4443 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00004444 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00004445 e = cast->getSubExpr();
4446 continue;
4447
John McCall31168b02011-06-15 23:02:42 +00004448 default:
4449 return false;
4450 }
4451 }
4452
4453 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
4454 ObjCIvarDecl *ivar = ref->getDecl();
4455 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
4456 return false;
4457
4458 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00004459 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00004460 return false;
4461
4462 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
4463 owner.Indirect = true;
4464 return true;
4465 }
4466
4467 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
4468 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
4469 if (!var) return false;
4470 return considerVariable(var, ref, owner);
4471 }
4472
4473 if (BlockDeclRefExpr *ref = dyn_cast<BlockDeclRefExpr>(e)) {
4474 owner.Variable = ref->getDecl();
4475 owner.setLocsFrom(ref);
4476 return true;
4477 }
4478
4479 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
4480 if (member->isArrow()) return false;
4481
4482 // Don't count this as an indirect ownership.
4483 e = member->getBase();
4484 continue;
4485 }
4486
John McCallfe96e0b2011-11-06 09:01:30 +00004487 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
4488 // Only pay attention to pseudo-objects on property references.
4489 ObjCPropertyRefExpr *pre
4490 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
4491 ->IgnoreParens());
4492 if (!pre) return false;
4493 if (pre->isImplicitProperty()) return false;
4494 ObjCPropertyDecl *property = pre->getExplicitProperty();
4495 if (!property->isRetaining() &&
4496 !(property->getPropertyIvarDecl() &&
4497 property->getPropertyIvarDecl()->getType()
4498 .getObjCLifetime() == Qualifiers::OCL_Strong))
4499 return false;
4500
4501 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00004502 if (pre->isSuperReceiver()) {
4503 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
4504 if (!owner.Variable)
4505 return false;
4506 owner.Loc = pre->getLocation();
4507 owner.Range = pre->getSourceRange();
4508 return true;
4509 }
John McCallfe96e0b2011-11-06 09:01:30 +00004510 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
4511 ->getSourceExpr());
4512 continue;
4513 }
4514
John McCall31168b02011-06-15 23:02:42 +00004515 // Array ivars?
4516
4517 return false;
4518 }
4519}
4520
4521namespace {
4522 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
4523 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
4524 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
4525 Variable(variable), Capturer(0) {}
4526
4527 VarDecl *Variable;
4528 Expr *Capturer;
4529
4530 void VisitDeclRefExpr(DeclRefExpr *ref) {
4531 if (ref->getDecl() == Variable && !Capturer)
4532 Capturer = ref;
4533 }
4534
4535 void VisitBlockDeclRefExpr(BlockDeclRefExpr *ref) {
4536 if (ref->getDecl() == Variable && !Capturer)
4537 Capturer = ref;
4538 }
4539
4540 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
4541 if (Capturer) return;
4542 Visit(ref->getBase());
4543 if (Capturer && ref->isFreeIvar())
4544 Capturer = ref;
4545 }
4546
4547 void VisitBlockExpr(BlockExpr *block) {
4548 // Look inside nested blocks
4549 if (block->getBlockDecl()->capturesVariable(Variable))
4550 Visit(block->getBlockDecl()->getBody());
4551 }
4552 };
4553}
4554
4555/// Check whether the given argument is a block which captures a
4556/// variable.
4557static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
4558 assert(owner.Variable && owner.Loc.isValid());
4559
4560 e = e->IgnoreParenCasts();
4561 BlockExpr *block = dyn_cast<BlockExpr>(e);
4562 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
4563 return 0;
4564
4565 FindCaptureVisitor visitor(S.Context, owner.Variable);
4566 visitor.Visit(block->getBlockDecl()->getBody());
4567 return visitor.Capturer;
4568}
4569
4570static void diagnoseRetainCycle(Sema &S, Expr *capturer,
4571 RetainCycleOwner &owner) {
4572 assert(capturer);
4573 assert(owner.Variable && owner.Loc.isValid());
4574
4575 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
4576 << owner.Variable << capturer->getSourceRange();
4577 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
4578 << owner.Indirect << owner.Range;
4579}
4580
4581/// Check for a keyword selector that starts with the word 'add' or
4582/// 'set'.
4583static bool isSetterLikeSelector(Selector sel) {
4584 if (sel.isUnarySelector()) return false;
4585
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004586 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00004587 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00004588 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00004589 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00004590 else if (str.startswith("add")) {
4591 // Specially whitelist 'addOperationWithBlock:'.
4592 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
4593 return false;
4594 str = str.substr(3);
4595 }
John McCall31168b02011-06-15 23:02:42 +00004596 else
4597 return false;
4598
4599 if (str.empty()) return true;
4600 return !islower(str.front());
4601}
4602
4603/// Check a message send to see if it's likely to cause a retain cycle.
4604void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
4605 // Only check instance methods whose selector looks like a setter.
4606 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
4607 return;
4608
4609 // Try to find a variable that the receiver is strongly owned by.
4610 RetainCycleOwner owner;
4611 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00004612 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00004613 return;
4614 } else {
4615 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
4616 owner.Variable = getCurMethodDecl()->getSelfDecl();
4617 owner.Loc = msg->getSuperLoc();
4618 owner.Range = msg->getSuperLoc();
4619 }
4620
4621 // Check whether the receiver is captured by any of the arguments.
4622 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
4623 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
4624 return diagnoseRetainCycle(*this, capturer, owner);
4625}
4626
4627/// Check a property assign to see if it's likely to cause a retain cycle.
4628void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
4629 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00004630 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00004631 return;
4632
4633 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
4634 diagnoseRetainCycle(*this, capturer, owner);
4635}
4636
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00004637bool Sema::checkUnsafeAssigns(SourceLocation Loc,
John McCall31168b02011-06-15 23:02:42 +00004638 QualType LHS, Expr *RHS) {
4639 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
4640 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00004641 return false;
4642 // strip off any implicit cast added to get to the one arc-specific
4643 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00004644 if (cast->getCastKind() == CK_ARCConsumeObject) {
John McCall31168b02011-06-15 23:02:42 +00004645 Diag(Loc, diag::warn_arc_retained_assign)
4646 << (LT == Qualifiers::OCL_ExplicitNone)
4647 << RHS->getSourceRange();
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00004648 return true;
4649 }
4650 RHS = cast->getSubExpr();
4651 }
4652 return false;
John McCall31168b02011-06-15 23:02:42 +00004653}
4654
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00004655void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
4656 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00004657 QualType LHSType;
4658 // PropertyRef on LHS type need be directly obtained from
4659 // its declaration as it has a PsuedoType.
4660 ObjCPropertyRefExpr *PRE
4661 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
4662 if (PRE && !PRE->isImplicitProperty()) {
4663 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
4664 if (PD)
4665 LHSType = PD->getType();
4666 }
4667
4668 if (LHSType.isNull())
4669 LHSType = LHS->getType();
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00004670 if (checkUnsafeAssigns(Loc, LHSType, RHS))
4671 return;
4672 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
4673 // FIXME. Check for other life times.
4674 if (LT != Qualifiers::OCL_None)
4675 return;
4676
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00004677 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00004678 if (PRE->isImplicitProperty())
4679 return;
4680 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
4681 if (!PD)
4682 return;
4683
4684 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00004685 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
4686 // when 'assign' attribute was not explicitly specified
4687 // by user, ignore it and rely on property type itself
4688 // for lifetime info.
4689 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
4690 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
4691 LHSType->isObjCRetainableType())
4692 return;
4693
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00004694 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00004695 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00004696 Diag(Loc, diag::warn_arc_retained_property_assign)
4697 << RHS->getSourceRange();
4698 return;
4699 }
4700 RHS = cast->getSubExpr();
4701 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00004702 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00004703 }
4704}