blob: dd1f9e109baf575d75bf8a6ae2eab7a83415c5bc [file] [log] [blame]
Chris Lattner59907c42007-08-10 20:18:51 +00001//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner59907c42007-08-10 20:18:51 +00007//
8//===----------------------------------------------------------------------===//
9//
Mike Stump1eb44332009-09-09 15:08:12 +000010// This file implements extra semantic analysis beyond what is enforced
Chris Lattner59907c42007-08-10 20:18:51 +000011// by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
John McCall5f8d6042011-08-27 01:09:30 +000015#include "clang/Sema/Initialization.h"
Douglas Gregore737f502010-08-12 20:07:10 +000016#include "clang/Sema/Sema.h"
John McCall2d887082010-08-25 22:03:47 +000017#include "clang/Sema/SemaInternal.h"
Eli Friedman276b0612011-10-11 02:20:01 +000018#include "clang/Sema/Initialization.h"
Richard Smith831421f2012-06-25 20:30:08 +000019#include "clang/Sema/Lookup.h"
John McCall781472f2010-08-25 08:40:02 +000020#include "clang/Sema/ScopeInfo.h"
Ted Kremenek826a3452010-07-16 02:11:22 +000021#include "clang/Analysis/Analyses/FormatString.h"
Chris Lattner59907c42007-08-10 20:18:51 +000022#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000023#include "clang/AST/CharUnits.h"
John McCall384aff82010-08-25 07:42:41 +000024#include "clang/AST/DeclCXX.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000025#include "clang/AST/DeclObjC.h"
David Blaikiebe0ee872012-05-15 16:56:36 +000026#include "clang/AST/Expr.h"
Ted Kremenek23245122007-08-20 16:18:38 +000027#include "clang/AST/ExprCXX.h"
Ted Kremenek7ff22b22008-06-16 18:00:42 +000028#include "clang/AST/ExprObjC.h"
John McCallf85e1932011-06-15 23:02:42 +000029#include "clang/AST/EvaluatedExprVisitor.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000030#include "clang/AST/DeclObjC.h"
31#include "clang/AST/StmtCXX.h"
32#include "clang/AST/StmtObjC.h"
Chris Lattner59907c42007-08-10 20:18:51 +000033#include "clang/Lex/Preprocessor.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000034#include "llvm/ADT/BitVector.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000035#include "llvm/ADT/SmallString.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000036#include "llvm/ADT/STLExtras.h"
Tom Care3bfc5f42010-06-09 04:11:11 +000037#include "llvm/Support/raw_ostream.h"
Eric Christopher691ebc32010-04-17 02:26:23 +000038#include "clang/Basic/TargetBuiltins.h"
Nate Begeman26a31422010-06-08 02:47:44 +000039#include "clang/Basic/TargetInfo.h"
Fariborz Jahanian7da71022010-09-07 19:38:13 +000040#include "clang/Basic/ConvertUTF.h"
Zhongxing Xua1f3dba2009-05-20 01:55:10 +000041#include <limits>
Chris Lattner59907c42007-08-10 20:18:51 +000042using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000043using namespace sema;
Chris Lattner59907c42007-08-10 20:18:51 +000044
Chris Lattner60800082009-02-18 17:49:48 +000045SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
46 unsigned ByteNo) const {
Chris Lattner08f92e32010-11-17 07:37:15 +000047 return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +000048 PP.getLangOpts(), PP.getTargetInfo());
Chris Lattner60800082009-02-18 17:49:48 +000049}
50
John McCall8e10f3b2011-02-26 05:39:39 +000051/// Checks that a call expression's argument count is the desired number.
52/// This is useful when doing custom type-checking. Returns true on error.
53static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
54 unsigned argCount = call->getNumArgs();
55 if (argCount == desiredArgCount) return false;
56
57 if (argCount < desiredArgCount)
58 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
59 << 0 /*function call*/ << desiredArgCount << argCount
60 << call->getSourceRange();
61
62 // Highlight all the excess arguments.
63 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
64 call->getArg(argCount - 1)->getLocEnd());
65
66 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
67 << 0 /*function call*/ << desiredArgCount << argCount
68 << call->getArg(1)->getSourceRange();
69}
70
Julien Lerougee5939212012-04-28 17:39:16 +000071/// Check that the first argument to __builtin_annotation is an integer
72/// and the second argument is a non-wide string literal.
73static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
74 if (checkArgCount(S, TheCall, 2))
75 return true;
76
77 // First argument should be an integer.
78 Expr *ValArg = TheCall->getArg(0);
79 QualType Ty = ValArg->getType();
80 if (!Ty->isIntegerType()) {
81 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
82 << ValArg->getSourceRange();
Julien Lerouge77f68bb2011-09-09 22:41:49 +000083 return true;
84 }
Julien Lerougee5939212012-04-28 17:39:16 +000085
86 // Second argument should be a constant string.
87 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
88 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
89 if (!Literal || !Literal->isAscii()) {
90 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
91 << StrArg->getSourceRange();
92 return true;
93 }
94
95 TheCall->setType(Ty);
Julien Lerouge77f68bb2011-09-09 22:41:49 +000096 return false;
97}
98
John McCall60d7b3a2010-08-24 06:29:42 +000099ExprResult
Anders Carlssond406bf02009-08-16 01:56:34 +0000100Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
John McCall60d7b3a2010-08-24 06:29:42 +0000101 ExprResult TheCallResult(Owned(TheCall));
Douglas Gregor2def4832008-11-17 20:34:05 +0000102
Chris Lattner946928f2010-10-01 23:23:24 +0000103 // Find out if any arguments are required to be integer constant expressions.
104 unsigned ICEArguments = 0;
105 ASTContext::GetBuiltinTypeError Error;
106 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
107 if (Error != ASTContext::GE_None)
108 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
109
110 // If any arguments are required to be ICE's, check and diagnose.
111 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
112 // Skip arguments not required to be ICE's.
113 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
114
115 llvm::APSInt Result;
116 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
117 return true;
118 ICEArguments &= ~(1 << ArgNo);
119 }
120
Anders Carlssond406bf02009-08-16 01:56:34 +0000121 switch (BuiltinID) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000122 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +0000123 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +0000124 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner69039812009-02-18 06:01:06 +0000125 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000126 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000127 break;
Ted Kremenek49ff7a12008-07-09 17:58:53 +0000128 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +0000129 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000130 if (SemaBuiltinVAStart(TheCall))
131 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000132 break;
Chris Lattner1b9a0792007-12-20 00:26:33 +0000133 case Builtin::BI__builtin_isgreater:
134 case Builtin::BI__builtin_isgreaterequal:
135 case Builtin::BI__builtin_isless:
136 case Builtin::BI__builtin_islessequal:
137 case Builtin::BI__builtin_islessgreater:
138 case Builtin::BI__builtin_isunordered:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000139 if (SemaBuiltinUnorderedCompare(TheCall))
140 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000141 break;
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000142 case Builtin::BI__builtin_fpclassify:
143 if (SemaBuiltinFPClassification(TheCall, 6))
144 return ExprError();
145 break;
Eli Friedman9ac6f622009-08-31 20:06:00 +0000146 case Builtin::BI__builtin_isfinite:
147 case Builtin::BI__builtin_isinf:
148 case Builtin::BI__builtin_isinf_sign:
149 case Builtin::BI__builtin_isnan:
150 case Builtin::BI__builtin_isnormal:
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000151 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman9ac6f622009-08-31 20:06:00 +0000152 return ExprError();
153 break;
Eli Friedmand38617c2008-05-14 19:38:39 +0000154 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000155 return SemaBuiltinShuffleVector(TheCall);
156 // TheCall will be freed by the smart pointer here, but that's fine, since
157 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000158 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000159 if (SemaBuiltinPrefetch(TheCall))
160 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000161 break;
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000162 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000163 if (SemaBuiltinObjectSize(TheCall))
164 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000165 break;
Eli Friedmand875fed2009-05-03 04:46:36 +0000166 case Builtin::BI__builtin_longjmp:
167 if (SemaBuiltinLongjmp(TheCall))
168 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000169 break;
John McCall8e10f3b2011-02-26 05:39:39 +0000170
171 case Builtin::BI__builtin_classify_type:
172 if (checkArgCount(*this, TheCall, 1)) return true;
173 TheCall->setType(Context.IntTy);
174 break;
Chris Lattner75c29a02010-10-12 17:47:42 +0000175 case Builtin::BI__builtin_constant_p:
John McCall8e10f3b2011-02-26 05:39:39 +0000176 if (checkArgCount(*this, TheCall, 1)) return true;
177 TheCall->setType(Context.IntTy);
Chris Lattner75c29a02010-10-12 17:47:42 +0000178 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000179 case Builtin::BI__sync_fetch_and_add:
Douglas Gregora9766412011-11-28 16:30:08 +0000180 case Builtin::BI__sync_fetch_and_add_1:
181 case Builtin::BI__sync_fetch_and_add_2:
182 case Builtin::BI__sync_fetch_and_add_4:
183 case Builtin::BI__sync_fetch_and_add_8:
184 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000185 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregora9766412011-11-28 16:30:08 +0000186 case Builtin::BI__sync_fetch_and_sub_1:
187 case Builtin::BI__sync_fetch_and_sub_2:
188 case Builtin::BI__sync_fetch_and_sub_4:
189 case Builtin::BI__sync_fetch_and_sub_8:
190 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000191 case Builtin::BI__sync_fetch_and_or:
Douglas Gregora9766412011-11-28 16:30:08 +0000192 case Builtin::BI__sync_fetch_and_or_1:
193 case Builtin::BI__sync_fetch_and_or_2:
194 case Builtin::BI__sync_fetch_and_or_4:
195 case Builtin::BI__sync_fetch_and_or_8:
196 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000197 case Builtin::BI__sync_fetch_and_and:
Douglas Gregora9766412011-11-28 16:30:08 +0000198 case Builtin::BI__sync_fetch_and_and_1:
199 case Builtin::BI__sync_fetch_and_and_2:
200 case Builtin::BI__sync_fetch_and_and_4:
201 case Builtin::BI__sync_fetch_and_and_8:
202 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000203 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregora9766412011-11-28 16:30:08 +0000204 case Builtin::BI__sync_fetch_and_xor_1:
205 case Builtin::BI__sync_fetch_and_xor_2:
206 case Builtin::BI__sync_fetch_and_xor_4:
207 case Builtin::BI__sync_fetch_and_xor_8:
208 case Builtin::BI__sync_fetch_and_xor_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000209 case Builtin::BI__sync_add_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000210 case Builtin::BI__sync_add_and_fetch_1:
211 case Builtin::BI__sync_add_and_fetch_2:
212 case Builtin::BI__sync_add_and_fetch_4:
213 case Builtin::BI__sync_add_and_fetch_8:
214 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000215 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000216 case Builtin::BI__sync_sub_and_fetch_1:
217 case Builtin::BI__sync_sub_and_fetch_2:
218 case Builtin::BI__sync_sub_and_fetch_4:
219 case Builtin::BI__sync_sub_and_fetch_8:
220 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000221 case Builtin::BI__sync_and_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000222 case Builtin::BI__sync_and_and_fetch_1:
223 case Builtin::BI__sync_and_and_fetch_2:
224 case Builtin::BI__sync_and_and_fetch_4:
225 case Builtin::BI__sync_and_and_fetch_8:
226 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000227 case Builtin::BI__sync_or_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000228 case Builtin::BI__sync_or_and_fetch_1:
229 case Builtin::BI__sync_or_and_fetch_2:
230 case Builtin::BI__sync_or_and_fetch_4:
231 case Builtin::BI__sync_or_and_fetch_8:
232 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000233 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000234 case Builtin::BI__sync_xor_and_fetch_1:
235 case Builtin::BI__sync_xor_and_fetch_2:
236 case Builtin::BI__sync_xor_and_fetch_4:
237 case Builtin::BI__sync_xor_and_fetch_8:
238 case Builtin::BI__sync_xor_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000239 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000240 case Builtin::BI__sync_val_compare_and_swap_1:
241 case Builtin::BI__sync_val_compare_and_swap_2:
242 case Builtin::BI__sync_val_compare_and_swap_4:
243 case Builtin::BI__sync_val_compare_and_swap_8:
244 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000245 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000246 case Builtin::BI__sync_bool_compare_and_swap_1:
247 case Builtin::BI__sync_bool_compare_and_swap_2:
248 case Builtin::BI__sync_bool_compare_and_swap_4:
249 case Builtin::BI__sync_bool_compare_and_swap_8:
250 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000251 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregora9766412011-11-28 16:30:08 +0000252 case Builtin::BI__sync_lock_test_and_set_1:
253 case Builtin::BI__sync_lock_test_and_set_2:
254 case Builtin::BI__sync_lock_test_and_set_4:
255 case Builtin::BI__sync_lock_test_and_set_8:
256 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000257 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +0000258 case Builtin::BI__sync_lock_release_1:
259 case Builtin::BI__sync_lock_release_2:
260 case Builtin::BI__sync_lock_release_4:
261 case Builtin::BI__sync_lock_release_8:
262 case Builtin::BI__sync_lock_release_16:
Chris Lattner23aa9c82011-04-09 03:57:26 +0000263 case Builtin::BI__sync_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000264 case Builtin::BI__sync_swap_1:
265 case Builtin::BI__sync_swap_2:
266 case Builtin::BI__sync_swap_4:
267 case Builtin::BI__sync_swap_8:
268 case Builtin::BI__sync_swap_16:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000269 return SemaBuiltinAtomicOverloaded(TheCallResult);
Richard Smithff34d402012-04-12 05:08:17 +0000270#define BUILTIN(ID, TYPE, ATTRS)
271#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
272 case Builtin::BI##ID: \
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000273 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithff34d402012-04-12 05:08:17 +0000274#include "clang/Basic/Builtins.def"
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000275 case Builtin::BI__builtin_annotation:
Julien Lerougee5939212012-04-28 17:39:16 +0000276 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000277 return ExprError();
278 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000279 }
280
281 // Since the target specific builtins for each arch overlap, only check those
282 // of the arch we are compiling for.
283 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000284 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman26a31422010-06-08 02:47:44 +0000285 case llvm::Triple::arm:
286 case llvm::Triple::thumb:
287 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
288 return ExprError();
289 break;
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000290 case llvm::Triple::mips:
291 case llvm::Triple::mipsel:
292 case llvm::Triple::mips64:
293 case llvm::Triple::mips64el:
294 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
295 return ExprError();
296 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000297 default:
298 break;
299 }
300 }
301
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000302 return TheCallResult;
Nate Begeman26a31422010-06-08 02:47:44 +0000303}
304
Nate Begeman61eecf52010-06-14 05:21:25 +0000305// Get the valid immediate range for the specified NEON type code.
306static unsigned RFT(unsigned t, bool shift = false) {
Bob Wilsonda95f732011-11-08 01:16:11 +0000307 NeonTypeFlags Type(t);
308 int IsQuad = Type.isQuad();
309 switch (Type.getEltType()) {
310 case NeonTypeFlags::Int8:
311 case NeonTypeFlags::Poly8:
312 return shift ? 7 : (8 << IsQuad) - 1;
313 case NeonTypeFlags::Int16:
314 case NeonTypeFlags::Poly16:
315 return shift ? 15 : (4 << IsQuad) - 1;
316 case NeonTypeFlags::Int32:
317 return shift ? 31 : (2 << IsQuad) - 1;
318 case NeonTypeFlags::Int64:
319 return shift ? 63 : (1 << IsQuad) - 1;
320 case NeonTypeFlags::Float16:
321 assert(!shift && "cannot shift float types!");
322 return (4 << IsQuad) - 1;
323 case NeonTypeFlags::Float32:
324 assert(!shift && "cannot shift float types!");
325 return (2 << IsQuad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000326 }
David Blaikie7530c032012-01-17 06:56:22 +0000327 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman61eecf52010-06-14 05:21:25 +0000328}
329
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000330/// getNeonEltType - Return the QualType corresponding to the elements of
331/// the vector type specified by the NeonTypeFlags. This is used to check
332/// the pointer arguments for Neon load/store intrinsics.
333static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context) {
334 switch (Flags.getEltType()) {
335 case NeonTypeFlags::Int8:
336 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
337 case NeonTypeFlags::Int16:
338 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
339 case NeonTypeFlags::Int32:
340 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
341 case NeonTypeFlags::Int64:
342 return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy;
343 case NeonTypeFlags::Poly8:
344 return Context.SignedCharTy;
345 case NeonTypeFlags::Poly16:
346 return Context.ShortTy;
347 case NeonTypeFlags::Float16:
348 return Context.UnsignedShortTy;
349 case NeonTypeFlags::Float32:
350 return Context.FloatTy;
351 }
David Blaikie7530c032012-01-17 06:56:22 +0000352 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000353}
354
Nate Begeman26a31422010-06-08 02:47:44 +0000355bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000356 llvm::APSInt Result;
357
Richard Smithf8ee6bc2012-08-14 01:28:02 +0000358 uint64_t mask = 0;
Nate Begeman61eecf52010-06-14 05:21:25 +0000359 unsigned TV = 0;
Bob Wilson46482552011-11-16 21:32:23 +0000360 int PtrArgNum = -1;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000361 bool HasConstPtr = false;
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000362 switch (BuiltinID) {
Nate Begemana23326b2010-06-17 04:17:01 +0000363#define GET_NEON_OVERLOAD_CHECK
364#include "clang/Basic/arm_neon.inc"
365#undef GET_NEON_OVERLOAD_CHECK
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000366 }
367
Nate Begeman0d15c532010-06-13 04:47:52 +0000368 // For NEON intrinsics which are overloaded on vector element type, validate
369 // the immediate which specifies which variant to emit.
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000370 unsigned ImmArg = TheCall->getNumArgs()-1;
Nate Begeman0d15c532010-06-13 04:47:52 +0000371 if (mask) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000372 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
Nate Begeman0d15c532010-06-13 04:47:52 +0000373 return true;
374
Bob Wilsonda95f732011-11-08 01:16:11 +0000375 TV = Result.getLimitedValue(64);
Richard Smithf8ee6bc2012-08-14 01:28:02 +0000376 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
Nate Begeman0d15c532010-06-13 04:47:52 +0000377 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000378 << TheCall->getArg(ImmArg)->getSourceRange();
379 }
380
Bob Wilson46482552011-11-16 21:32:23 +0000381 if (PtrArgNum >= 0) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000382 // Check that pointer arguments have the specified type.
Bob Wilson46482552011-11-16 21:32:23 +0000383 Expr *Arg = TheCall->getArg(PtrArgNum);
384 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
385 Arg = ICE->getSubExpr();
386 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
387 QualType RHSTy = RHS.get()->getType();
388 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context);
389 if (HasConstPtr)
390 EltTy = EltTy.withConst();
391 QualType LHSTy = Context.getPointerType(EltTy);
392 AssignConvertType ConvTy;
393 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
394 if (RHS.isInvalid())
395 return true;
396 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
397 RHS.get(), AA_Assigning))
398 return true;
Nate Begeman0d15c532010-06-13 04:47:52 +0000399 }
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000400
Nate Begeman0d15c532010-06-13 04:47:52 +0000401 // For NEON intrinsics which take an immediate value as part of the
402 // instruction, range check them here.
Nate Begeman61eecf52010-06-14 05:21:25 +0000403 unsigned i = 0, l = 0, u = 0;
Nate Begeman0d15c532010-06-13 04:47:52 +0000404 switch (BuiltinID) {
405 default: return false;
Nate Begemanbb37f502010-07-29 22:48:34 +0000406 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
407 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begeman99c40bb2010-08-03 21:32:34 +0000408 case ARM::BI__builtin_arm_vcvtr_f:
409 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Nate Begemana23326b2010-06-17 04:17:01 +0000410#define GET_NEON_IMMEDIATE_CHECK
411#include "clang/Basic/arm_neon.inc"
412#undef GET_NEON_IMMEDIATE_CHECK
Nate Begeman0d15c532010-06-13 04:47:52 +0000413 };
414
Douglas Gregor592a4232012-06-29 01:05:22 +0000415 // We can't check the value of a dependent argument.
416 if (TheCall->getArg(i)->isTypeDependent() ||
417 TheCall->getArg(i)->isValueDependent())
418 return false;
419
Nate Begeman61eecf52010-06-14 05:21:25 +0000420 // Check that the immediate argument is actually a constant.
Nate Begeman0d15c532010-06-13 04:47:52 +0000421 if (SemaBuiltinConstantArg(TheCall, i, Result))
422 return true;
423
Nate Begeman61eecf52010-06-14 05:21:25 +0000424 // Range check against the upper/lower values for this isntruction.
Nate Begeman0d15c532010-06-13 04:47:52 +0000425 unsigned Val = Result.getZExtValue();
Nate Begeman61eecf52010-06-14 05:21:25 +0000426 if (Val < l || Val > (u + l))
Nate Begeman0d15c532010-06-13 04:47:52 +0000427 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramer476d8b82010-08-11 14:47:12 +0000428 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begeman0d15c532010-06-13 04:47:52 +0000429
Nate Begeman99c40bb2010-08-03 21:32:34 +0000430 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman26a31422010-06-08 02:47:44 +0000431 return false;
Anders Carlssond406bf02009-08-16 01:56:34 +0000432}
Daniel Dunbarde454282008-10-02 18:44:07 +0000433
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000434bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
435 unsigned i = 0, l = 0, u = 0;
436 switch (BuiltinID) {
437 default: return false;
438 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
439 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyanbe22cb82012-08-27 12:29:20 +0000440 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
441 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
442 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
443 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
444 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000445 };
446
447 // We can't check the value of a dependent argument.
448 if (TheCall->getArg(i)->isTypeDependent() ||
449 TheCall->getArg(i)->isValueDependent())
450 return false;
451
452 // Check that the immediate argument is actually a constant.
453 llvm::APSInt Result;
454 if (SemaBuiltinConstantArg(TheCall, i, Result))
455 return true;
456
457 // Range check against the upper/lower values for this instruction.
458 unsigned Val = Result.getZExtValue();
459 if (Val < l || Val > u)
460 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
461 << l << u << TheCall->getArg(i)->getSourceRange();
462
463 return false;
464}
465
Richard Smith831421f2012-06-25 20:30:08 +0000466/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
467/// parameter with the FormatAttr's correct format_idx and firstDataArg.
468/// Returns true when the format fits the function and the FormatStringInfo has
469/// been populated.
470bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
471 FormatStringInfo *FSI) {
472 FSI->HasVAListArg = Format->getFirstArg() == 0;
473 FSI->FormatIdx = Format->getFormatIdx() - 1;
474 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssond406bf02009-08-16 01:56:34 +0000475
Richard Smith831421f2012-06-25 20:30:08 +0000476 // The way the format attribute works in GCC, the implicit this argument
477 // of member functions is counted. However, it doesn't appear in our own
478 // lists, so decrement format_idx in that case.
479 if (IsCXXMember) {
480 if(FSI->FormatIdx == 0)
481 return false;
482 --FSI->FormatIdx;
483 if (FSI->FirstDataArg != 0)
484 --FSI->FirstDataArg;
485 }
486 return true;
487}
Mike Stump1eb44332009-09-09 15:08:12 +0000488
Richard Smith831421f2012-06-25 20:30:08 +0000489/// Handles the checks for format strings, non-POD arguments to vararg
490/// functions, and NULL arguments passed to non-NULL parameters.
491void Sema::checkCall(NamedDecl *FDecl, Expr **Args,
492 unsigned NumArgs,
493 unsigned NumProtoArgs,
494 bool IsMemberFunction,
495 SourceLocation Loc,
496 SourceRange Range,
497 VariadicCallType CallType) {
Daniel Dunbarde454282008-10-02 18:44:07 +0000498 // FIXME: This mechanism should be abstracted to be less fragile and
499 // more efficient. For example, just map function ids to custom
500 // handlers.
501
Ted Kremenekc82faca2010-09-09 04:33:05 +0000502 // Printf and scanf checking.
Richard Smith831421f2012-06-25 20:30:08 +0000503 bool HandledFormatString = false;
Ted Kremenekc82faca2010-09-09 04:33:05 +0000504 for (specific_attr_iterator<FormatAttr>
Richard Smith831421f2012-06-25 20:30:08 +0000505 I = FDecl->specific_attr_begin<FormatAttr>(),
506 E = FDecl->specific_attr_end<FormatAttr>(); I != E ; ++I)
Jordan Roseddcfbc92012-07-19 18:10:23 +0000507 if (CheckFormatArguments(*I, Args, NumArgs, IsMemberFunction, CallType,
508 Loc, Range))
Richard Smith831421f2012-06-25 20:30:08 +0000509 HandledFormatString = true;
510
511 // Refuse POD arguments that weren't caught by the format string
512 // checks above.
513 if (!HandledFormatString && CallType != VariadicDoesNotApply)
514 for (unsigned ArgIdx = NumProtoArgs; ArgIdx < NumArgs; ++ArgIdx)
515 variadicArgumentPODCheck(Args[ArgIdx], CallType);
Mike Stump1eb44332009-09-09 15:08:12 +0000516
Ted Kremenekc82faca2010-09-09 04:33:05 +0000517 for (specific_attr_iterator<NonNullAttr>
Richard Smith831421f2012-06-25 20:30:08 +0000518 I = FDecl->specific_attr_begin<NonNullAttr>(),
519 E = FDecl->specific_attr_end<NonNullAttr>(); I != E; ++I)
520 CheckNonNullArguments(*I, Args, Loc);
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +0000521
522 // Type safety checking.
523 for (specific_attr_iterator<ArgumentWithTypeTagAttr>
524 i = FDecl->specific_attr_begin<ArgumentWithTypeTagAttr>(),
525 e = FDecl->specific_attr_end<ArgumentWithTypeTagAttr>(); i != e; ++i) {
526 CheckArgumentWithTypeTag(*i, Args);
527 }
Richard Smith831421f2012-06-25 20:30:08 +0000528}
529
530/// CheckConstructorCall - Check a constructor call for correctness and safety
531/// properties not enforced by the C type system.
532void Sema::CheckConstructorCall(FunctionDecl *FDecl, Expr **Args,
533 unsigned NumArgs,
534 const FunctionProtoType *Proto,
535 SourceLocation Loc) {
536 VariadicCallType CallType =
537 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
538 checkCall(FDecl, Args, NumArgs, Proto->getNumArgs(),
539 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
540}
541
542/// CheckFunctionCall - Check a direct function call for various correctness
543/// and safety properties not strictly enforced by the C type system.
544bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
545 const FunctionProtoType *Proto) {
546 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall);
547 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
548 TheCall->getCallee());
549 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
550 checkCall(FDecl, TheCall->getArgs(), TheCall->getNumArgs(), NumProtoArgs,
551 IsMemberFunction, TheCall->getRParenLoc(),
552 TheCall->getCallee()->getSourceRange(), CallType);
553
554 IdentifierInfo *FnInfo = FDecl->getIdentifier();
555 // None of the checks below are needed for functions that don't have
556 // simple names (e.g., C++ conversion functions).
557 if (!FnInfo)
558 return false;
Sebastian Redl0eb23302009-01-19 00:08:26 +0000559
Anna Zaks0a151a12012-01-17 00:37:07 +0000560 unsigned CMId = FDecl->getMemoryFunctionKind();
561 if (CMId == 0)
Anna Zaksd9b859a2012-01-13 21:52:01 +0000562 return false;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000563
Anna Zaksd9b859a2012-01-13 21:52:01 +0000564 // Handle memory setting and copying functions.
Anna Zaks0a151a12012-01-17 00:37:07 +0000565 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000566 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaksc36bedc2012-02-01 19:08:57 +0000567 else if (CMId == Builtin::BIstrncat)
568 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaksd9b859a2012-01-13 21:52:01 +0000569 else
Anna Zaks0a151a12012-01-17 00:37:07 +0000570 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth7ccc95b2011-04-27 07:05:31 +0000571
Anders Carlssond406bf02009-08-16 01:56:34 +0000572 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000573}
574
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000575bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
576 Expr **Args, unsigned NumArgs) {
Richard Smith831421f2012-06-25 20:30:08 +0000577 VariadicCallType CallType =
578 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000579
Richard Smith831421f2012-06-25 20:30:08 +0000580 checkCall(Method, Args, NumArgs, Method->param_size(),
581 /*IsMemberFunction=*/false,
582 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000583
584 return false;
585}
586
Richard Smith831421f2012-06-25 20:30:08 +0000587bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall,
588 const FunctionProtoType *Proto) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000589 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
590 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000591 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000592
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000593 QualType Ty = V->getType();
594 if (!Ty->isBlockPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000595 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000596
Richard Smith831421f2012-06-25 20:30:08 +0000597 VariadicCallType CallType =
598 Proto && Proto->isVariadic() ? VariadicBlock : VariadicDoesNotApply ;
599 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
Anders Carlssond406bf02009-08-16 01:56:34 +0000600
Richard Smith831421f2012-06-25 20:30:08 +0000601 checkCall(NDecl, TheCall->getArgs(), TheCall->getNumArgs(),
602 NumProtoArgs, /*IsMemberFunction=*/false,
603 TheCall->getRParenLoc(),
604 TheCall->getCallee()->getSourceRange(), CallType);
605
Anders Carlssond406bf02009-08-16 01:56:34 +0000606 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000607}
608
Richard Smithff34d402012-04-12 05:08:17 +0000609ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
610 AtomicExpr::AtomicOp Op) {
Eli Friedman276b0612011-10-11 02:20:01 +0000611 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
612 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedman276b0612011-10-11 02:20:01 +0000613
Richard Smithff34d402012-04-12 05:08:17 +0000614 // All these operations take one of the following forms:
615 enum {
616 // C __c11_atomic_init(A *, C)
617 Init,
618 // C __c11_atomic_load(A *, int)
619 Load,
620 // void __atomic_load(A *, CP, int)
621 Copy,
622 // C __c11_atomic_add(A *, M, int)
623 Arithmetic,
624 // C __atomic_exchange_n(A *, CP, int)
625 Xchg,
626 // void __atomic_exchange(A *, C *, CP, int)
627 GNUXchg,
628 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
629 C11CmpXchg,
630 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
631 GNUCmpXchg
632 } Form = Init;
633 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
634 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
635 // where:
636 // C is an appropriate type,
637 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
638 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
639 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
640 // the int parameters are for orderings.
Eli Friedman276b0612011-10-11 02:20:01 +0000641
Richard Smithff34d402012-04-12 05:08:17 +0000642 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
643 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
644 && "need to update code for modified C11 atomics");
645 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
646 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
647 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
648 Op == AtomicExpr::AO__atomic_store_n ||
649 Op == AtomicExpr::AO__atomic_exchange_n ||
650 Op == AtomicExpr::AO__atomic_compare_exchange_n;
651 bool IsAddSub = false;
652
653 switch (Op) {
654 case AtomicExpr::AO__c11_atomic_init:
655 Form = Init;
656 break;
657
658 case AtomicExpr::AO__c11_atomic_load:
659 case AtomicExpr::AO__atomic_load_n:
660 Form = Load;
661 break;
662
663 case AtomicExpr::AO__c11_atomic_store:
664 case AtomicExpr::AO__atomic_load:
665 case AtomicExpr::AO__atomic_store:
666 case AtomicExpr::AO__atomic_store_n:
667 Form = Copy;
668 break;
669
670 case AtomicExpr::AO__c11_atomic_fetch_add:
671 case AtomicExpr::AO__c11_atomic_fetch_sub:
672 case AtomicExpr::AO__atomic_fetch_add:
673 case AtomicExpr::AO__atomic_fetch_sub:
674 case AtomicExpr::AO__atomic_add_fetch:
675 case AtomicExpr::AO__atomic_sub_fetch:
676 IsAddSub = true;
677 // Fall through.
678 case AtomicExpr::AO__c11_atomic_fetch_and:
679 case AtomicExpr::AO__c11_atomic_fetch_or:
680 case AtomicExpr::AO__c11_atomic_fetch_xor:
681 case AtomicExpr::AO__atomic_fetch_and:
682 case AtomicExpr::AO__atomic_fetch_or:
683 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smith51b92402012-04-13 06:31:38 +0000684 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithff34d402012-04-12 05:08:17 +0000685 case AtomicExpr::AO__atomic_and_fetch:
686 case AtomicExpr::AO__atomic_or_fetch:
687 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smith51b92402012-04-13 06:31:38 +0000688 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithff34d402012-04-12 05:08:17 +0000689 Form = Arithmetic;
690 break;
691
692 case AtomicExpr::AO__c11_atomic_exchange:
693 case AtomicExpr::AO__atomic_exchange_n:
694 Form = Xchg;
695 break;
696
697 case AtomicExpr::AO__atomic_exchange:
698 Form = GNUXchg;
699 break;
700
701 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
702 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
703 Form = C11CmpXchg;
704 break;
705
706 case AtomicExpr::AO__atomic_compare_exchange:
707 case AtomicExpr::AO__atomic_compare_exchange_n:
708 Form = GNUCmpXchg;
709 break;
710 }
711
712 // Check we have the right number of arguments.
713 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedman276b0612011-10-11 02:20:01 +0000714 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithff34d402012-04-12 05:08:17 +0000715 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +0000716 << TheCall->getCallee()->getSourceRange();
717 return ExprError();
Richard Smithff34d402012-04-12 05:08:17 +0000718 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
719 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedman276b0612011-10-11 02:20:01 +0000720 diag::err_typecheck_call_too_many_args)
Richard Smithff34d402012-04-12 05:08:17 +0000721 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +0000722 << TheCall->getCallee()->getSourceRange();
723 return ExprError();
724 }
725
Richard Smithff34d402012-04-12 05:08:17 +0000726 // Inspect the first argument of the atomic operation.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000727 Expr *Ptr = TheCall->getArg(0);
Eli Friedman276b0612011-10-11 02:20:01 +0000728 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
729 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
730 if (!pointerType) {
Richard Smithff34d402012-04-12 05:08:17 +0000731 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedman276b0612011-10-11 02:20:01 +0000732 << Ptr->getType() << Ptr->getSourceRange();
733 return ExprError();
734 }
735
Richard Smithff34d402012-04-12 05:08:17 +0000736 // For a __c11 builtin, this should be a pointer to an _Atomic type.
737 QualType AtomTy = pointerType->getPointeeType(); // 'A'
738 QualType ValType = AtomTy; // 'C'
739 if (IsC11) {
740 if (!AtomTy->isAtomicType()) {
741 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
742 << Ptr->getType() << Ptr->getSourceRange();
743 return ExprError();
744 }
745 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedman276b0612011-10-11 02:20:01 +0000746 }
Eli Friedman276b0612011-10-11 02:20:01 +0000747
Richard Smithff34d402012-04-12 05:08:17 +0000748 // For an arithmetic operation, the implied arithmetic must be well-formed.
749 if (Form == Arithmetic) {
750 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
751 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
752 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
753 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
754 return ExprError();
755 }
756 if (!IsAddSub && !ValType->isIntegerType()) {
757 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
758 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
759 return ExprError();
760 }
761 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
762 // For __atomic_*_n operations, the value type must be a scalar integral or
763 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedman276b0612011-10-11 02:20:01 +0000764 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithff34d402012-04-12 05:08:17 +0000765 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
766 return ExprError();
767 }
768
769 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context)) {
770 // For GNU atomics, require a trivially-copyable type. This is not part of
771 // the GNU atomics specification, but we enforce it for sanity.
772 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedman276b0612011-10-11 02:20:01 +0000773 << Ptr->getType() << Ptr->getSourceRange();
774 return ExprError();
775 }
776
Richard Smithff34d402012-04-12 05:08:17 +0000777 // FIXME: For any builtin other than a load, the ValType must not be
778 // const-qualified.
Eli Friedman276b0612011-10-11 02:20:01 +0000779
780 switch (ValType.getObjCLifetime()) {
781 case Qualifiers::OCL_None:
782 case Qualifiers::OCL_ExplicitNone:
783 // okay
784 break;
785
786 case Qualifiers::OCL_Weak:
787 case Qualifiers::OCL_Strong:
788 case Qualifiers::OCL_Autoreleasing:
Richard Smithff34d402012-04-12 05:08:17 +0000789 // FIXME: Can this happen? By this point, ValType should be known
790 // to be trivially copyable.
Eli Friedman276b0612011-10-11 02:20:01 +0000791 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
792 << ValType << Ptr->getSourceRange();
793 return ExprError();
794 }
795
796 QualType ResultType = ValType;
Richard Smithff34d402012-04-12 05:08:17 +0000797 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedman276b0612011-10-11 02:20:01 +0000798 ResultType = Context.VoidTy;
Richard Smithff34d402012-04-12 05:08:17 +0000799 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedman276b0612011-10-11 02:20:01 +0000800 ResultType = Context.BoolTy;
801
Richard Smithff34d402012-04-12 05:08:17 +0000802 // The type of a parameter passed 'by value'. In the GNU atomics, such
803 // arguments are actually passed as pointers.
804 QualType ByValType = ValType; // 'CP'
805 if (!IsC11 && !IsN)
806 ByValType = Ptr->getType();
807
Eli Friedman276b0612011-10-11 02:20:01 +0000808 // The first argument --- the pointer --- has a fixed type; we
809 // deduce the types of the rest of the arguments accordingly. Walk
810 // the remaining arguments, converting them to the deduced value type.
Richard Smithff34d402012-04-12 05:08:17 +0000811 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedman276b0612011-10-11 02:20:01 +0000812 QualType Ty;
Richard Smithff34d402012-04-12 05:08:17 +0000813 if (i < NumVals[Form] + 1) {
814 switch (i) {
815 case 1:
816 // The second argument is the non-atomic operand. For arithmetic, this
817 // is always passed by value, and for a compare_exchange it is always
818 // passed by address. For the rest, GNU uses by-address and C11 uses
819 // by-value.
820 assert(Form != Load);
821 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
822 Ty = ValType;
823 else if (Form == Copy || Form == Xchg)
824 Ty = ByValType;
825 else if (Form == Arithmetic)
826 Ty = Context.getPointerDiffType();
827 else
828 Ty = Context.getPointerType(ValType.getUnqualifiedType());
829 break;
830 case 2:
831 // The third argument to compare_exchange / GNU exchange is a
832 // (pointer to a) desired value.
833 Ty = ByValType;
834 break;
835 case 3:
836 // The fourth argument to GNU compare_exchange is a 'weak' flag.
837 Ty = Context.BoolTy;
838 break;
839 }
Eli Friedman276b0612011-10-11 02:20:01 +0000840 } else {
841 // The order(s) are always converted to int.
842 Ty = Context.IntTy;
843 }
Richard Smithff34d402012-04-12 05:08:17 +0000844
Eli Friedman276b0612011-10-11 02:20:01 +0000845 InitializedEntity Entity =
846 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithff34d402012-04-12 05:08:17 +0000847 ExprResult Arg = TheCall->getArg(i);
Eli Friedman276b0612011-10-11 02:20:01 +0000848 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
849 if (Arg.isInvalid())
850 return true;
851 TheCall->setArg(i, Arg.get());
852 }
853
Richard Smithff34d402012-04-12 05:08:17 +0000854 // Permute the arguments into a 'consistent' order.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000855 SmallVector<Expr*, 5> SubExprs;
856 SubExprs.push_back(Ptr);
Richard Smithff34d402012-04-12 05:08:17 +0000857 switch (Form) {
858 case Init:
859 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnall7a7ee302012-01-16 17:27:18 +0000860 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +0000861 break;
862 case Load:
863 SubExprs.push_back(TheCall->getArg(1)); // Order
864 break;
865 case Copy:
866 case Arithmetic:
867 case Xchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000868 SubExprs.push_back(TheCall->getArg(2)); // Order
869 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +0000870 break;
871 case GNUXchg:
872 // Note, AtomicExpr::getVal2() has a special case for this atomic.
873 SubExprs.push_back(TheCall->getArg(3)); // Order
874 SubExprs.push_back(TheCall->getArg(1)); // Val1
875 SubExprs.push_back(TheCall->getArg(2)); // Val2
876 break;
877 case C11CmpXchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000878 SubExprs.push_back(TheCall->getArg(3)); // Order
879 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000880 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall2ebb98a2012-03-29 17:58:59 +0000881 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithff34d402012-04-12 05:08:17 +0000882 break;
883 case GNUCmpXchg:
884 SubExprs.push_back(TheCall->getArg(4)); // Order
885 SubExprs.push_back(TheCall->getArg(1)); // Val1
886 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
887 SubExprs.push_back(TheCall->getArg(2)); // Val2
888 SubExprs.push_back(TheCall->getArg(3)); // Weak
889 break;
Eli Friedman276b0612011-10-11 02:20:01 +0000890 }
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000891
892 return Owned(new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +0000893 SubExprs, ResultType, Op,
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000894 TheCall->getRParenLoc()));
Eli Friedman276b0612011-10-11 02:20:01 +0000895}
896
897
John McCall5f8d6042011-08-27 01:09:30 +0000898/// checkBuiltinArgument - Given a call to a builtin function, perform
899/// normal type-checking on the given argument, updating the call in
900/// place. This is useful when a builtin function requires custom
901/// type-checking for some of its arguments but not necessarily all of
902/// them.
903///
904/// Returns true on error.
905static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
906 FunctionDecl *Fn = E->getDirectCallee();
907 assert(Fn && "builtin call without direct callee!");
908
909 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
910 InitializedEntity Entity =
911 InitializedEntity::InitializeParameter(S.Context, Param);
912
913 ExprResult Arg = E->getArg(0);
914 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
915 if (Arg.isInvalid())
916 return true;
917
918 E->setArg(ArgIndex, Arg.take());
919 return false;
920}
921
Chris Lattner5caa3702009-05-08 06:58:22 +0000922/// SemaBuiltinAtomicOverloaded - We have a call to a function like
923/// __sync_fetch_and_add, which is an overloaded function based on the pointer
924/// type of its first argument. The main ActOnCallExpr routines have already
925/// promoted the types of arguments because all of these calls are prototyped as
926/// void(...).
927///
928/// This function goes through and does final semantic checking for these
929/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +0000930ExprResult
931Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000932 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +0000933 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
934 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
935
936 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +0000937 if (TheCall->getNumArgs() < 1) {
938 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
939 << 0 << 1 << TheCall->getNumArgs()
940 << TheCall->getCallee()->getSourceRange();
941 return ExprError();
942 }
Mike Stump1eb44332009-09-09 15:08:12 +0000943
Chris Lattner5caa3702009-05-08 06:58:22 +0000944 // Inspect the first argument of the atomic builtin. This should always be
945 // a pointer type, whose element is an integral scalar or pointer type.
946 // Because it is a pointer type, we don't have to worry about any implicit
947 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +0000948 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +0000949 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman8c382062012-01-23 02:35:22 +0000950 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
951 if (FirstArgResult.isInvalid())
952 return ExprError();
953 FirstArg = FirstArgResult.take();
954 TheCall->setArg(0, FirstArg);
955
John McCallf85e1932011-06-15 23:02:42 +0000956 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
957 if (!pointerType) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000958 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
959 << FirstArg->getType() << FirstArg->getSourceRange();
960 return ExprError();
961 }
Mike Stump1eb44332009-09-09 15:08:12 +0000962
John McCallf85e1932011-06-15 23:02:42 +0000963 QualType ValType = pointerType->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +0000964 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +0000965 !ValType->isBlockPointerType()) {
966 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
967 << FirstArg->getType() << FirstArg->getSourceRange();
968 return ExprError();
969 }
Chris Lattner5caa3702009-05-08 06:58:22 +0000970
John McCallf85e1932011-06-15 23:02:42 +0000971 switch (ValType.getObjCLifetime()) {
972 case Qualifiers::OCL_None:
973 case Qualifiers::OCL_ExplicitNone:
974 // okay
975 break;
976
977 case Qualifiers::OCL_Weak:
978 case Qualifiers::OCL_Strong:
979 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +0000980 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCallf85e1932011-06-15 23:02:42 +0000981 << ValType << FirstArg->getSourceRange();
982 return ExprError();
983 }
984
John McCallb45ae252011-10-05 07:41:44 +0000985 // Strip any qualifiers off ValType.
986 ValType = ValType.getUnqualifiedType();
987
Chandler Carruth8d13d222010-07-18 20:54:12 +0000988 // The majority of builtins return a value, but a few have special return
989 // types, so allow them to override appropriately below.
990 QualType ResultType = ValType;
991
Chris Lattner5caa3702009-05-08 06:58:22 +0000992 // We need to figure out which concrete builtin this maps onto. For example,
993 // __sync_fetch_and_add with a 2 byte object turns into
994 // __sync_fetch_and_add_2.
995#define BUILTIN_ROW(x) \
996 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
997 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +0000998
Chris Lattner5caa3702009-05-08 06:58:22 +0000999 static const unsigned BuiltinIndices[][5] = {
1000 BUILTIN_ROW(__sync_fetch_and_add),
1001 BUILTIN_ROW(__sync_fetch_and_sub),
1002 BUILTIN_ROW(__sync_fetch_and_or),
1003 BUILTIN_ROW(__sync_fetch_and_and),
1004 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +00001005
Chris Lattner5caa3702009-05-08 06:58:22 +00001006 BUILTIN_ROW(__sync_add_and_fetch),
1007 BUILTIN_ROW(__sync_sub_and_fetch),
1008 BUILTIN_ROW(__sync_and_and_fetch),
1009 BUILTIN_ROW(__sync_or_and_fetch),
1010 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +00001011
Chris Lattner5caa3702009-05-08 06:58:22 +00001012 BUILTIN_ROW(__sync_val_compare_and_swap),
1013 BUILTIN_ROW(__sync_bool_compare_and_swap),
1014 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner23aa9c82011-04-09 03:57:26 +00001015 BUILTIN_ROW(__sync_lock_release),
1016 BUILTIN_ROW(__sync_swap)
Chris Lattner5caa3702009-05-08 06:58:22 +00001017 };
Mike Stump1eb44332009-09-09 15:08:12 +00001018#undef BUILTIN_ROW
1019
Chris Lattner5caa3702009-05-08 06:58:22 +00001020 // Determine the index of the size.
1021 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +00001022 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +00001023 case 1: SizeIndex = 0; break;
1024 case 2: SizeIndex = 1; break;
1025 case 4: SizeIndex = 2; break;
1026 case 8: SizeIndex = 3; break;
1027 case 16: SizeIndex = 4; break;
1028 default:
Chandler Carruthd2014572010-07-09 18:59:35 +00001029 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1030 << FirstArg->getType() << FirstArg->getSourceRange();
1031 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +00001032 }
Mike Stump1eb44332009-09-09 15:08:12 +00001033
Chris Lattner5caa3702009-05-08 06:58:22 +00001034 // Each of these builtins has one pointer argument, followed by some number of
1035 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1036 // that we ignore. Find out which row of BuiltinIndices to read from as well
1037 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +00001038 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +00001039 unsigned BuiltinIndex, NumFixed = 1;
1040 switch (BuiltinID) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001041 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregora9766412011-11-28 16:30:08 +00001042 case Builtin::BI__sync_fetch_and_add:
1043 case Builtin::BI__sync_fetch_and_add_1:
1044 case Builtin::BI__sync_fetch_and_add_2:
1045 case Builtin::BI__sync_fetch_and_add_4:
1046 case Builtin::BI__sync_fetch_and_add_8:
1047 case Builtin::BI__sync_fetch_and_add_16:
1048 BuiltinIndex = 0;
1049 break;
1050
1051 case Builtin::BI__sync_fetch_and_sub:
1052 case Builtin::BI__sync_fetch_and_sub_1:
1053 case Builtin::BI__sync_fetch_and_sub_2:
1054 case Builtin::BI__sync_fetch_and_sub_4:
1055 case Builtin::BI__sync_fetch_and_sub_8:
1056 case Builtin::BI__sync_fetch_and_sub_16:
1057 BuiltinIndex = 1;
1058 break;
1059
1060 case Builtin::BI__sync_fetch_and_or:
1061 case Builtin::BI__sync_fetch_and_or_1:
1062 case Builtin::BI__sync_fetch_and_or_2:
1063 case Builtin::BI__sync_fetch_and_or_4:
1064 case Builtin::BI__sync_fetch_and_or_8:
1065 case Builtin::BI__sync_fetch_and_or_16:
1066 BuiltinIndex = 2;
1067 break;
1068
1069 case Builtin::BI__sync_fetch_and_and:
1070 case Builtin::BI__sync_fetch_and_and_1:
1071 case Builtin::BI__sync_fetch_and_and_2:
1072 case Builtin::BI__sync_fetch_and_and_4:
1073 case Builtin::BI__sync_fetch_and_and_8:
1074 case Builtin::BI__sync_fetch_and_and_16:
1075 BuiltinIndex = 3;
1076 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001077
Douglas Gregora9766412011-11-28 16:30:08 +00001078 case Builtin::BI__sync_fetch_and_xor:
1079 case Builtin::BI__sync_fetch_and_xor_1:
1080 case Builtin::BI__sync_fetch_and_xor_2:
1081 case Builtin::BI__sync_fetch_and_xor_4:
1082 case Builtin::BI__sync_fetch_and_xor_8:
1083 case Builtin::BI__sync_fetch_and_xor_16:
1084 BuiltinIndex = 4;
1085 break;
1086
1087 case Builtin::BI__sync_add_and_fetch:
1088 case Builtin::BI__sync_add_and_fetch_1:
1089 case Builtin::BI__sync_add_and_fetch_2:
1090 case Builtin::BI__sync_add_and_fetch_4:
1091 case Builtin::BI__sync_add_and_fetch_8:
1092 case Builtin::BI__sync_add_and_fetch_16:
1093 BuiltinIndex = 5;
1094 break;
1095
1096 case Builtin::BI__sync_sub_and_fetch:
1097 case Builtin::BI__sync_sub_and_fetch_1:
1098 case Builtin::BI__sync_sub_and_fetch_2:
1099 case Builtin::BI__sync_sub_and_fetch_4:
1100 case Builtin::BI__sync_sub_and_fetch_8:
1101 case Builtin::BI__sync_sub_and_fetch_16:
1102 BuiltinIndex = 6;
1103 break;
1104
1105 case Builtin::BI__sync_and_and_fetch:
1106 case Builtin::BI__sync_and_and_fetch_1:
1107 case Builtin::BI__sync_and_and_fetch_2:
1108 case Builtin::BI__sync_and_and_fetch_4:
1109 case Builtin::BI__sync_and_and_fetch_8:
1110 case Builtin::BI__sync_and_and_fetch_16:
1111 BuiltinIndex = 7;
1112 break;
1113
1114 case Builtin::BI__sync_or_and_fetch:
1115 case Builtin::BI__sync_or_and_fetch_1:
1116 case Builtin::BI__sync_or_and_fetch_2:
1117 case Builtin::BI__sync_or_and_fetch_4:
1118 case Builtin::BI__sync_or_and_fetch_8:
1119 case Builtin::BI__sync_or_and_fetch_16:
1120 BuiltinIndex = 8;
1121 break;
1122
1123 case Builtin::BI__sync_xor_and_fetch:
1124 case Builtin::BI__sync_xor_and_fetch_1:
1125 case Builtin::BI__sync_xor_and_fetch_2:
1126 case Builtin::BI__sync_xor_and_fetch_4:
1127 case Builtin::BI__sync_xor_and_fetch_8:
1128 case Builtin::BI__sync_xor_and_fetch_16:
1129 BuiltinIndex = 9;
1130 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001131
Chris Lattner5caa3702009-05-08 06:58:22 +00001132 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001133 case Builtin::BI__sync_val_compare_and_swap_1:
1134 case Builtin::BI__sync_val_compare_and_swap_2:
1135 case Builtin::BI__sync_val_compare_and_swap_4:
1136 case Builtin::BI__sync_val_compare_and_swap_8:
1137 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001138 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +00001139 NumFixed = 2;
1140 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001141
Chris Lattner5caa3702009-05-08 06:58:22 +00001142 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001143 case Builtin::BI__sync_bool_compare_and_swap_1:
1144 case Builtin::BI__sync_bool_compare_and_swap_2:
1145 case Builtin::BI__sync_bool_compare_and_swap_4:
1146 case Builtin::BI__sync_bool_compare_and_swap_8:
1147 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001148 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +00001149 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001150 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001151 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001152
1153 case Builtin::BI__sync_lock_test_and_set:
1154 case Builtin::BI__sync_lock_test_and_set_1:
1155 case Builtin::BI__sync_lock_test_and_set_2:
1156 case Builtin::BI__sync_lock_test_and_set_4:
1157 case Builtin::BI__sync_lock_test_and_set_8:
1158 case Builtin::BI__sync_lock_test_and_set_16:
1159 BuiltinIndex = 12;
1160 break;
1161
Chris Lattner5caa3702009-05-08 06:58:22 +00001162 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +00001163 case Builtin::BI__sync_lock_release_1:
1164 case Builtin::BI__sync_lock_release_2:
1165 case Builtin::BI__sync_lock_release_4:
1166 case Builtin::BI__sync_lock_release_8:
1167 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001168 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +00001169 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001170 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001171 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001172
1173 case Builtin::BI__sync_swap:
1174 case Builtin::BI__sync_swap_1:
1175 case Builtin::BI__sync_swap_2:
1176 case Builtin::BI__sync_swap_4:
1177 case Builtin::BI__sync_swap_8:
1178 case Builtin::BI__sync_swap_16:
1179 BuiltinIndex = 14;
1180 break;
Chris Lattner5caa3702009-05-08 06:58:22 +00001181 }
Mike Stump1eb44332009-09-09 15:08:12 +00001182
Chris Lattner5caa3702009-05-08 06:58:22 +00001183 // Now that we know how many fixed arguments we expect, first check that we
1184 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +00001185 if (TheCall->getNumArgs() < 1+NumFixed) {
1186 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1187 << 0 << 1+NumFixed << TheCall->getNumArgs()
1188 << TheCall->getCallee()->getSourceRange();
1189 return ExprError();
1190 }
Mike Stump1eb44332009-09-09 15:08:12 +00001191
Chris Lattnere7ac0a92009-05-08 15:36:58 +00001192 // Get the decl for the concrete builtin from this, we can tell what the
1193 // concrete integer type we should convert to is.
1194 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1195 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
1196 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
Mike Stump1eb44332009-09-09 15:08:12 +00001197 FunctionDecl *NewBuiltinDecl =
Chris Lattnere7ac0a92009-05-08 15:36:58 +00001198 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
1199 TUScope, false, DRE->getLocStart()));
Chandler Carruthd2014572010-07-09 18:59:35 +00001200
John McCallf871d0c2010-08-07 06:22:56 +00001201 // The first argument --- the pointer --- has a fixed type; we
1202 // deduce the types of the rest of the arguments accordingly. Walk
1203 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +00001204 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley429bb272011-04-08 18:41:53 +00001205 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +00001206
Chris Lattner5caa3702009-05-08 06:58:22 +00001207 // GCC does an implicit conversion to the pointer or integer ValType. This
1208 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb45ae252011-10-05 07:41:44 +00001209 // Initialize the argument.
1210 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1211 ValType, /*consume*/ false);
1212 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley429bb272011-04-08 18:41:53 +00001213 if (Arg.isInvalid())
Chandler Carruthd2014572010-07-09 18:59:35 +00001214 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001215
Chris Lattner5caa3702009-05-08 06:58:22 +00001216 // Okay, we have something that *can* be converted to the right type. Check
1217 // to see if there is a potentially weird extension going on here. This can
1218 // happen when you do an atomic operation on something like an char* and
1219 // pass in 42. The 42 gets converted to char. This is even more strange
1220 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +00001221 // FIXME: Do this check.
John McCallb45ae252011-10-05 07:41:44 +00001222 TheCall->setArg(i+1, Arg.take());
Chris Lattner5caa3702009-05-08 06:58:22 +00001223 }
Mike Stump1eb44332009-09-09 15:08:12 +00001224
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001225 ASTContext& Context = this->getASTContext();
1226
1227 // Create a new DeclRefExpr to refer to the new decl.
1228 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1229 Context,
1230 DRE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001231 SourceLocation(),
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001232 NewBuiltinDecl,
John McCallf4b88a42012-03-10 09:33:50 +00001233 /*enclosing*/ false,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001234 DRE->getLocation(),
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001235 Context.BuiltinFnTy,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001236 DRE->getValueKind());
Mike Stump1eb44332009-09-09 15:08:12 +00001237
Chris Lattner5caa3702009-05-08 06:58:22 +00001238 // Set the callee in the CallExpr.
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001239 // FIXME: This loses syntactic information.
1240 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1241 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1242 CK_BuiltinFnToFnPtr);
John Wiegley429bb272011-04-08 18:41:53 +00001243 TheCall->setCallee(PromotedCall.take());
Mike Stump1eb44332009-09-09 15:08:12 +00001244
Chandler Carruthdb4325b2010-07-18 07:23:17 +00001245 // Change the result type of the call to match the original value type. This
1246 // is arbitrary, but the codegen for these builtins ins design to handle it
1247 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +00001248 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +00001249
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001250 return TheCallResult;
Chris Lattner5caa3702009-05-08 06:58:22 +00001251}
1252
Chris Lattner69039812009-02-18 06:01:06 +00001253/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +00001254/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +00001255/// Note: It might also make sense to do the UTF-16 conversion here (would
1256/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +00001257bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +00001258 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +00001259 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1260
Douglas Gregor5cee1192011-07-27 05:40:30 +00001261 if (!Literal || !Literal->isAscii()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001262 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1263 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001264 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +00001265 }
Mike Stump1eb44332009-09-09 15:08:12 +00001266
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001267 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001268 StringRef String = Literal->getString();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001269 unsigned NumBytes = String.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001270 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divacky31ba6132012-09-06 15:59:27 +00001271 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001272 UTF16 *ToPtr = &ToBuf[0];
1273
1274 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1275 &ToPtr, ToPtr + NumBytes,
1276 strictConversion);
1277 // Check for conversion failure.
1278 if (Result != conversionOK)
1279 Diag(Arg->getLocStart(),
1280 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1281 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001282 return false;
Chris Lattner59907c42007-08-10 20:18:51 +00001283}
1284
Chris Lattnerc27c6652007-12-20 00:05:45 +00001285/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1286/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +00001287bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1288 Expr *Fn = TheCall->getCallee();
1289 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +00001290 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001291 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001292 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1293 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +00001294 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001295 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +00001296 return true;
1297 }
Eli Friedman56f20ae2008-12-15 22:05:35 +00001298
1299 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +00001300 return Diag(TheCall->getLocEnd(),
1301 diag::err_typecheck_call_too_few_args_at_least)
1302 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +00001303 }
1304
John McCall5f8d6042011-08-27 01:09:30 +00001305 // Type-check the first argument normally.
1306 if (checkBuiltinArgument(*this, TheCall, 0))
1307 return true;
1308
Chris Lattnerc27c6652007-12-20 00:05:45 +00001309 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001310 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +00001311 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001312 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +00001313 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +00001314 else if (FunctionDecl *FD = getCurFunctionDecl())
1315 isVariadic = FD->isVariadic();
1316 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001317 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +00001318
Chris Lattnerc27c6652007-12-20 00:05:45 +00001319 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001320 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1321 return true;
1322 }
Mike Stump1eb44332009-09-09 15:08:12 +00001323
Chris Lattner30ce3442007-12-19 23:59:04 +00001324 // Verify that the second argument to the builtin is the last argument of the
1325 // current function or method.
1326 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +00001327 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001328
Anders Carlsson88cf2262008-02-11 04:20:54 +00001329 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1330 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001331 // FIXME: This isn't correct for methods (results in bogus warning).
1332 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +00001333 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001334 if (CurBlock)
1335 LastArg = *(CurBlock->TheDecl->param_end()-1);
1336 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +00001337 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001338 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001339 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001340 SecondArgIsLastNamedArgument = PV == LastArg;
1341 }
1342 }
Mike Stump1eb44332009-09-09 15:08:12 +00001343
Chris Lattner30ce3442007-12-19 23:59:04 +00001344 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001345 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +00001346 diag::warn_second_parameter_of_va_start_not_last_named_argument);
1347 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +00001348}
Chris Lattner30ce3442007-12-19 23:59:04 +00001349
Chris Lattner1b9a0792007-12-20 00:26:33 +00001350/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1351/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +00001352bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1353 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +00001354 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001355 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +00001356 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +00001357 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001358 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001359 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001360 << SourceRange(TheCall->getArg(2)->getLocStart(),
1361 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001362
John Wiegley429bb272011-04-08 18:41:53 +00001363 ExprResult OrigArg0 = TheCall->getArg(0);
1364 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +00001365
Chris Lattner1b9a0792007-12-20 00:26:33 +00001366 // Do standard promotions between the two arguments, returning their common
1367 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +00001368 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley429bb272011-04-08 18:41:53 +00001369 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1370 return true;
Daniel Dunbar403bc2b2009-02-19 19:28:43 +00001371
1372 // Make sure any conversions are pushed back into the call; this is
1373 // type safe since unordered compare builtins are declared as "_Bool
1374 // foo(...)".
John Wiegley429bb272011-04-08 18:41:53 +00001375 TheCall->setArg(0, OrigArg0.get());
1376 TheCall->setArg(1, OrigArg1.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001377
John Wiegley429bb272011-04-08 18:41:53 +00001378 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorcde01732009-05-19 22:10:17 +00001379 return false;
1380
Chris Lattner1b9a0792007-12-20 00:26:33 +00001381 // If the common type isn't a real floating type, then the arguments were
1382 // invalid for this operation.
Eli Friedman860a3192012-06-16 02:19:17 +00001383 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +00001384 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001385 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley429bb272011-04-08 18:41:53 +00001386 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1387 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001388
Chris Lattner1b9a0792007-12-20 00:26:33 +00001389 return false;
1390}
1391
Benjamin Kramere771a7a2010-02-15 22:42:31 +00001392/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1393/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001394/// to check everything. We expect the last argument to be a floating point
1395/// value.
1396bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1397 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +00001398 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001399 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001400 if (TheCall->getNumArgs() > NumArgs)
1401 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001402 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001403 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001404 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001405 (*(TheCall->arg_end()-1))->getLocEnd());
1406
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001407 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001408
Eli Friedman9ac6f622009-08-31 20:06:00 +00001409 if (OrigArg->isTypeDependent())
1410 return false;
1411
Chris Lattner81368fb2010-05-06 05:50:07 +00001412 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +00001413 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +00001414 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001415 diag::err_typecheck_call_invalid_unary_fp)
1416 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001417
Chris Lattner81368fb2010-05-06 05:50:07 +00001418 // If this is an implicit conversion from float -> double, remove it.
1419 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1420 Expr *CastArg = Cast->getSubExpr();
1421 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1422 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1423 "promotion from float to double is the only expected cast here");
1424 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +00001425 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner81368fb2010-05-06 05:50:07 +00001426 }
1427 }
1428
Eli Friedman9ac6f622009-08-31 20:06:00 +00001429 return false;
1430}
1431
Eli Friedmand38617c2008-05-14 19:38:39 +00001432/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1433// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +00001434ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001435 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001436 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +00001437 diag::err_typecheck_call_too_few_args_at_least)
Nate Begeman37b6a572010-06-08 00:16:34 +00001438 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherd77b9a22010-04-16 04:48:22 +00001439 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001440
Nate Begeman37b6a572010-06-08 00:16:34 +00001441 // Determine which of the following types of shufflevector we're checking:
1442 // 1) unary, vector mask: (lhs, mask)
1443 // 2) binary, vector mask: (lhs, rhs, mask)
1444 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1445 QualType resType = TheCall->getArg(0)->getType();
1446 unsigned numElements = 0;
1447
Douglas Gregorcde01732009-05-19 22:10:17 +00001448 if (!TheCall->getArg(0)->isTypeDependent() &&
1449 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001450 QualType LHSType = TheCall->getArg(0)->getType();
1451 QualType RHSType = TheCall->getArg(1)->getType();
1452
1453 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001454 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001455 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001456 TheCall->getArg(1)->getLocEnd());
1457 return ExprError();
1458 }
Nate Begeman37b6a572010-06-08 00:16:34 +00001459
1460 numElements = LHSType->getAs<VectorType>()->getNumElements();
1461 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +00001462
Nate Begeman37b6a572010-06-08 00:16:34 +00001463 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1464 // with mask. If so, verify that RHS is an integer vector type with the
1465 // same number of elts as lhs.
1466 if (TheCall->getNumArgs() == 2) {
Douglas Gregorf6094622010-07-23 15:58:24 +00001467 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +00001468 RHSType->getAs<VectorType>()->getNumElements() != numElements)
1469 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
1470 << SourceRange(TheCall->getArg(1)->getLocStart(),
1471 TheCall->getArg(1)->getLocEnd());
1472 numResElements = numElements;
1473 }
1474 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001475 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001476 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001477 TheCall->getArg(1)->getLocEnd());
1478 return ExprError();
Nate Begeman37b6a572010-06-08 00:16:34 +00001479 } else if (numElements != numResElements) {
1480 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +00001481 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001482 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +00001483 }
Eli Friedmand38617c2008-05-14 19:38:39 +00001484 }
1485
1486 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001487 if (TheCall->getArg(i)->isTypeDependent() ||
1488 TheCall->getArg(i)->isValueDependent())
1489 continue;
1490
Nate Begeman37b6a572010-06-08 00:16:34 +00001491 llvm::APSInt Result(32);
1492 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1493 return ExprError(Diag(TheCall->getLocStart(),
1494 diag::err_shufflevector_nonconstant_argument)
1495 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001496
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001497 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001498 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001499 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001500 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001501 }
1502
Chris Lattner5f9e2722011-07-23 10:55:15 +00001503 SmallVector<Expr*, 32> exprs;
Eli Friedmand38617c2008-05-14 19:38:39 +00001504
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001505 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +00001506 exprs.push_back(TheCall->getArg(i));
1507 TheCall->setArg(i, 0);
1508 }
1509
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001510 return Owned(new (Context) ShuffleVectorExpr(Context, exprs, resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001511 TheCall->getCallee()->getLocStart(),
1512 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +00001513}
Chris Lattner30ce3442007-12-19 23:59:04 +00001514
Daniel Dunbar4493f792008-07-21 22:59:13 +00001515/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1516// This is declared to take (const void*, ...) and can take two
1517// optional constant int args.
1518bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001519 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001520
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001521 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +00001522 return Diag(TheCall->getLocEnd(),
1523 diag::err_typecheck_call_too_many_args_at_most)
1524 << 0 /*function call*/ << 3 << NumArgs
1525 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001526
1527 // Argument 0 is checked for us and the remaining arguments must be
1528 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001529 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +00001530 Expr *Arg = TheCall->getArg(i);
Douglas Gregor592a4232012-06-29 01:05:22 +00001531
1532 // We can't check the value of a dependent argument.
1533 if (Arg->isTypeDependent() || Arg->isValueDependent())
1534 continue;
1535
Eli Friedman9aef7262009-12-04 00:30:06 +00001536 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +00001537 if (SemaBuiltinConstantArg(TheCall, i, Result))
1538 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001539
Daniel Dunbar4493f792008-07-21 22:59:13 +00001540 // FIXME: gcc issues a warning and rewrites these to 0. These
1541 // seems especially odd for the third argument since the default
1542 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001543 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +00001544 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001545 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001546 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001547 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +00001548 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001549 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001550 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001551 }
1552 }
1553
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001554 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +00001555}
1556
Eric Christopher691ebc32010-04-17 02:26:23 +00001557/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1558/// TheCall is a constant expression.
1559bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1560 llvm::APSInt &Result) {
1561 Expr *Arg = TheCall->getArg(ArgNum);
1562 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1563 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1564
1565 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1566
1567 if (!Arg->isIntegerConstantExpr(Result, Context))
1568 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +00001569 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +00001570
Chris Lattner21fb98e2009-09-23 06:06:36 +00001571 return false;
1572}
1573
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001574/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1575/// int type). This simply type checks that type is one of the defined
1576/// constants (0-3).
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001577// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001578bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +00001579 llvm::APSInt Result;
Douglas Gregor592a4232012-06-29 01:05:22 +00001580
1581 // We can't check the value of a dependent argument.
1582 if (TheCall->getArg(1)->isTypeDependent() ||
1583 TheCall->getArg(1)->isValueDependent())
1584 return false;
1585
Eric Christopher691ebc32010-04-17 02:26:23 +00001586 // Check constant-ness first.
1587 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1588 return true;
1589
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001590 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001591 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001592 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1593 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001594 }
1595
1596 return false;
1597}
1598
Eli Friedman586d6a82009-05-03 06:04:26 +00001599/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +00001600/// This checks that val is a constant 1.
1601bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1602 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +00001603 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +00001604
Eric Christopher691ebc32010-04-17 02:26:23 +00001605 // TODO: This is less than ideal. Overload this to take a value.
1606 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1607 return true;
1608
1609 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +00001610 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1611 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1612
1613 return false;
1614}
1615
Richard Smith831421f2012-06-25 20:30:08 +00001616// Determine if an expression is a string literal or constant string.
1617// If this function returns false on the arguments to a function expecting a
1618// format string, we will usually need to emit a warning.
1619// True string literals are then checked by CheckFormatString.
1620Sema::StringLiteralCheckType
1621Sema::checkFormatStringExpr(const Expr *E, Expr **Args,
1622 unsigned NumArgs, bool HasVAListArg,
1623 unsigned format_idx, unsigned firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001624 FormatStringType Type, VariadicCallType CallType,
1625 bool inFunctionCall) {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001626 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +00001627 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith831421f2012-06-25 20:30:08 +00001628 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001629
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001630 E = E->IgnoreParenCasts();
Peter Collingbournef111d932011-04-15 00:35:48 +00001631
David Blaikiea73cdcb2012-02-10 21:07:25 +00001632 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
1633 // Technically -Wformat-nonliteral does not warn about this case.
1634 // The behavior of printf and friends in this case is implementation
1635 // dependent. Ideally if the format string cannot be null then
1636 // it should have a 'nonnull' attribute in the function prototype.
Richard Smith831421f2012-06-25 20:30:08 +00001637 return SLCT_CheckedLiteral;
David Blaikiea73cdcb2012-02-10 21:07:25 +00001638
Ted Kremenekd30ef872009-01-12 23:09:09 +00001639 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +00001640 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +00001641 case Stmt::ConditionalOperatorClass: {
Richard Smith831421f2012-06-25 20:30:08 +00001642 // The expression is a literal if both sub-expressions were, and it was
1643 // completely checked only if both sub-expressions were checked.
1644 const AbstractConditionalOperator *C =
1645 cast<AbstractConditionalOperator>(E);
1646 StringLiteralCheckType Left =
1647 checkFormatStringExpr(C->getTrueExpr(), Args, NumArgs,
1648 HasVAListArg, format_idx, firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001649 Type, CallType, inFunctionCall);
Richard Smith831421f2012-06-25 20:30:08 +00001650 if (Left == SLCT_NotALiteral)
1651 return SLCT_NotALiteral;
1652 StringLiteralCheckType Right =
1653 checkFormatStringExpr(C->getFalseExpr(), Args, NumArgs,
1654 HasVAListArg, format_idx, firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001655 Type, CallType, inFunctionCall);
Richard Smith831421f2012-06-25 20:30:08 +00001656 return Left < Right ? Left : Right;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001657 }
1658
1659 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001660 E = cast<ImplicitCastExpr>(E)->getSubExpr();
1661 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001662 }
1663
John McCall56ca35d2011-02-17 10:25:35 +00001664 case Stmt::OpaqueValueExprClass:
1665 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
1666 E = src;
1667 goto tryAgain;
1668 }
Richard Smith831421f2012-06-25 20:30:08 +00001669 return SLCT_NotALiteral;
John McCall56ca35d2011-02-17 10:25:35 +00001670
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001671 case Stmt::PredefinedExprClass:
1672 // While __func__, etc., are technically not string literals, they
1673 // cannot contain format specifiers and thus are not a security
1674 // liability.
Richard Smith831421f2012-06-25 20:30:08 +00001675 return SLCT_UncheckedLiteral;
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001676
Ted Kremenek082d9362009-03-20 21:35:28 +00001677 case Stmt::DeclRefExprClass: {
1678 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001679
Ted Kremenek082d9362009-03-20 21:35:28 +00001680 // As an exception, do not flag errors for variables binding to
1681 // const string literals.
1682 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1683 bool isConstant = false;
1684 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001685
Ted Kremenek082d9362009-03-20 21:35:28 +00001686 if (const ArrayType *AT = Context.getAsArrayType(T)) {
1687 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001688 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001689 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +00001690 PT->getPointeeType().isConstant(Context);
Jean-Daniel Dupase98e5b52012-01-25 10:35:33 +00001691 } else if (T->isObjCObjectPointerType()) {
1692 // In ObjC, there is usually no "const ObjectPointer" type,
1693 // so don't check if the pointee type is constant.
1694 isConstant = T.isConstant(Context);
Ted Kremenek082d9362009-03-20 21:35:28 +00001695 }
Mike Stump1eb44332009-09-09 15:08:12 +00001696
Ted Kremenek082d9362009-03-20 21:35:28 +00001697 if (isConstant) {
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00001698 if (const Expr *Init = VD->getAnyInitializer()) {
1699 // Look through initializers like const char c[] = { "foo" }
1700 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
1701 if (InitList->isStringLiteralInit())
1702 Init = InitList->getInit(0)->IgnoreParenImpCasts();
1703 }
Richard Smith831421f2012-06-25 20:30:08 +00001704 return checkFormatStringExpr(Init, Args, NumArgs,
1705 HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001706 firstDataArg, Type, CallType,
Richard Smith831421f2012-06-25 20:30:08 +00001707 /*inFunctionCall*/false);
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00001708 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001709 }
Mike Stump1eb44332009-09-09 15:08:12 +00001710
Anders Carlssond966a552009-06-28 19:55:58 +00001711 // For vprintf* functions (i.e., HasVAListArg==true), we add a
1712 // special check to see if the format string is a function parameter
1713 // of the function calling the printf function. If the function
1714 // has an attribute indicating it is a printf-like function, then we
1715 // should suppress warnings concerning non-literals being used in a call
1716 // to a vprintf function. For example:
1717 //
1718 // void
1719 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
1720 // va_list ap;
1721 // va_start(ap, fmt);
1722 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
1723 // ...
1724 //
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00001725 if (HasVAListArg) {
1726 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
1727 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
1728 int PVIndex = PV->getFunctionScopeIndex() + 1;
1729 for (specific_attr_iterator<FormatAttr>
1730 i = ND->specific_attr_begin<FormatAttr>(),
1731 e = ND->specific_attr_end<FormatAttr>(); i != e ; ++i) {
1732 FormatAttr *PVFormat = *i;
1733 // adjust for implicit parameter
1734 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
1735 if (MD->isInstance())
1736 ++PVIndex;
1737 // We also check if the formats are compatible.
1738 // We can't pass a 'scanf' string to a 'printf' function.
1739 if (PVIndex == PVFormat->getFormatIdx() &&
1740 Type == GetFormatStringType(PVFormat))
Richard Smith831421f2012-06-25 20:30:08 +00001741 return SLCT_UncheckedLiteral;
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00001742 }
1743 }
1744 }
1745 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001746 }
Mike Stump1eb44332009-09-09 15:08:12 +00001747
Richard Smith831421f2012-06-25 20:30:08 +00001748 return SLCT_NotALiteral;
Ted Kremenek082d9362009-03-20 21:35:28 +00001749 }
Ted Kremenekd30ef872009-01-12 23:09:09 +00001750
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001751 case Stmt::CallExprClass:
1752 case Stmt::CXXMemberCallExprClass: {
Anders Carlsson8f031b32009-06-27 04:05:33 +00001753 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001754 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
1755 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
1756 unsigned ArgIndex = FA->getFormatIdx();
1757 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
1758 if (MD->isInstance())
1759 --ArgIndex;
1760 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001761
Richard Smith831421f2012-06-25 20:30:08 +00001762 return checkFormatStringExpr(Arg, Args, NumArgs,
1763 HasVAListArg, format_idx, firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001764 Type, CallType, inFunctionCall);
Jordan Rose50687312012-06-04 23:52:23 +00001765 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
1766 unsigned BuiltinID = FD->getBuiltinID();
1767 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
1768 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
1769 const Expr *Arg = CE->getArg(0);
Richard Smith831421f2012-06-25 20:30:08 +00001770 return checkFormatStringExpr(Arg, Args, NumArgs,
1771 HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001772 firstDataArg, Type, CallType,
1773 inFunctionCall);
Jordan Rose50687312012-06-04 23:52:23 +00001774 }
Anders Carlsson8f031b32009-06-27 04:05:33 +00001775 }
1776 }
Mike Stump1eb44332009-09-09 15:08:12 +00001777
Richard Smith831421f2012-06-25 20:30:08 +00001778 return SLCT_NotALiteral;
Anders Carlsson8f031b32009-06-27 04:05:33 +00001779 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001780 case Stmt::ObjCStringLiteralClass:
1781 case Stmt::StringLiteralClass: {
1782 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001783
Ted Kremenek082d9362009-03-20 21:35:28 +00001784 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00001785 StrE = ObjCFExpr->getString();
1786 else
Ted Kremenek082d9362009-03-20 21:35:28 +00001787 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001788
Ted Kremenekd30ef872009-01-12 23:09:09 +00001789 if (StrE) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001790 CheckFormatString(StrE, E, Args, NumArgs, HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001791 firstDataArg, Type, inFunctionCall, CallType);
Richard Smith831421f2012-06-25 20:30:08 +00001792 return SLCT_CheckedLiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001793 }
Mike Stump1eb44332009-09-09 15:08:12 +00001794
Richard Smith831421f2012-06-25 20:30:08 +00001795 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001796 }
Mike Stump1eb44332009-09-09 15:08:12 +00001797
Ted Kremenek082d9362009-03-20 21:35:28 +00001798 default:
Richard Smith831421f2012-06-25 20:30:08 +00001799 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001800 }
1801}
1802
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001803void
Mike Stump1eb44332009-09-09 15:08:12 +00001804Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewycky909a70d2011-03-25 01:44:32 +00001805 const Expr * const *ExprArgs,
1806 SourceLocation CallSiteLoc) {
Sean Huntcf807c42010-08-18 23:23:40 +00001807 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1808 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001809 i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +00001810 const Expr *ArgExpr = ExprArgs[*i];
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001811 if (ArgExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00001812 Expr::NPC_ValueDependentIsNotNull))
Nick Lewycky909a70d2011-03-25 01:44:32 +00001813 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001814 }
1815}
Ted Kremenekd30ef872009-01-12 23:09:09 +00001816
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001817Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
1818 return llvm::StringSwitch<FormatStringType>(Format->getType())
1819 .Case("scanf", FST_Scanf)
1820 .Cases("printf", "printf0", FST_Printf)
1821 .Cases("NSString", "CFString", FST_NSString)
1822 .Case("strftime", FST_Strftime)
1823 .Case("strfmon", FST_Strfmon)
1824 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
1825 .Default(FST_Unknown);
1826}
1827
Jordan Roseddcfbc92012-07-19 18:10:23 +00001828/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek826a3452010-07-16 02:11:22 +00001829/// functions) for correct use of format strings.
Richard Smith831421f2012-06-25 20:30:08 +00001830/// Returns true if a format string has been fully checked.
Richard Smith831421f2012-06-25 20:30:08 +00001831bool Sema::CheckFormatArguments(const FormatAttr *Format, Expr **Args,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001832 unsigned NumArgs, bool IsCXXMember,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001833 VariadicCallType CallType,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001834 SourceLocation Loc, SourceRange Range) {
Richard Smith831421f2012-06-25 20:30:08 +00001835 FormatStringInfo FSI;
1836 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
1837 return CheckFormatArguments(Args, NumArgs, FSI.HasVAListArg, FSI.FormatIdx,
1838 FSI.FirstDataArg, GetFormatStringType(Format),
Jordan Roseddcfbc92012-07-19 18:10:23 +00001839 CallType, Loc, Range);
Richard Smith831421f2012-06-25 20:30:08 +00001840 return false;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001841}
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001842
Richard Smith831421f2012-06-25 20:30:08 +00001843bool Sema::CheckFormatArguments(Expr **Args, unsigned NumArgs,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001844 bool HasVAListArg, unsigned format_idx,
1845 unsigned firstDataArg, FormatStringType Type,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001846 VariadicCallType CallType,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001847 SourceLocation Loc, SourceRange Range) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001848 // CHECK: printf/scanf-like function is called with no format string.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001849 if (format_idx >= NumArgs) {
1850 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith831421f2012-06-25 20:30:08 +00001851 return false;
Ted Kremenek71895b92007-08-14 17:39:48 +00001852 }
Mike Stump1eb44332009-09-09 15:08:12 +00001853
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001854 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001855
Chris Lattner59907c42007-08-10 20:18:51 +00001856 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001857 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001858 // Dynamically generated format strings are difficult to
1859 // automatically vet at compile time. Requiring that format strings
1860 // are string literals: (1) permits the checking of format strings by
1861 // the compiler and thereby (2) can practically remove the source of
1862 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001863
Mike Stump1eb44332009-09-09 15:08:12 +00001864 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001865 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001866 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001867 // the same format string checking logic for both ObjC and C strings.
Richard Smith831421f2012-06-25 20:30:08 +00001868 StringLiteralCheckType CT =
1869 checkFormatStringExpr(OrigFormatExpr, Args, NumArgs, HasVAListArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001870 format_idx, firstDataArg, Type, CallType);
Richard Smith831421f2012-06-25 20:30:08 +00001871 if (CT != SLCT_NotALiteral)
1872 // Literal format string found, check done!
1873 return CT == SLCT_CheckedLiteral;
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001874
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00001875 // Strftime is particular as it always uses a single 'time' argument,
1876 // so it is safe to pass a non-literal string.
1877 if (Type == FST_Strftime)
Richard Smith831421f2012-06-25 20:30:08 +00001878 return false;
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00001879
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00001880 // Do not emit diag when the string param is a macro expansion and the
1881 // format is either NSString or CFString. This is a hack to prevent
1882 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
1883 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupasdc170202012-05-04 21:08:08 +00001884 if (Type == FST_NSString &&
1885 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith831421f2012-06-25 20:30:08 +00001886 return false;
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00001887
Chris Lattner655f1412009-04-29 04:59:47 +00001888 // If there are no arguments specified, warn with -Wformat-security, otherwise
1889 // warn only with -Wformat-nonliteral.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001890 if (NumArgs == format_idx+1)
1891 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001892 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00001893 << OrigFormatExpr->getSourceRange();
1894 else
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001895 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001896 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00001897 << OrigFormatExpr->getSourceRange();
Richard Smith831421f2012-06-25 20:30:08 +00001898 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001899}
Ted Kremenek71895b92007-08-14 17:39:48 +00001900
Ted Kremeneke0e53132010-01-28 23:39:18 +00001901namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00001902class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1903protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00001904 Sema &S;
1905 const StringLiteral *FExpr;
1906 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00001907 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001908 const unsigned NumDataArgs;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001909 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00001910 const bool HasVAListArg;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001911 const Expr * const *Args;
1912 const unsigned NumArgs;
Ted Kremenek0d277352010-01-29 01:06:55 +00001913 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001914 llvm::BitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00001915 bool usesPositionalArgs;
1916 bool atFirstArg;
Richard Trieu55733de2011-10-28 00:41:25 +00001917 bool inFunctionCall;
Jordan Roseddcfbc92012-07-19 18:10:23 +00001918 Sema::VariadicCallType CallType;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001919public:
Ted Kremenek826a3452010-07-16 02:11:22 +00001920 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00001921 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00001922 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001923 Expr **args, unsigned numArgs,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001924 unsigned formatIdx, bool inFunctionCall,
1925 Sema::VariadicCallType callType)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001926 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose50687312012-06-04 23:52:23 +00001927 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
1928 Beg(beg), HasVAListArg(hasVAListArg),
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001929 Args(args), NumArgs(numArgs), FormatIdx(formatIdx),
Richard Trieu55733de2011-10-28 00:41:25 +00001930 usesPositionalArgs(false), atFirstArg(true),
Jordan Roseddcfbc92012-07-19 18:10:23 +00001931 inFunctionCall(inFunctionCall), CallType(callType) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001932 CoveredArgs.resize(numDataArgs);
1933 CoveredArgs.reset();
1934 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001935
Ted Kremenek07d161f2010-01-29 01:50:07 +00001936 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001937
Ted Kremenek826a3452010-07-16 02:11:22 +00001938 void HandleIncompleteSpecifier(const char *startSpecifier,
1939 unsigned specifierLen);
Hans Wennborg76517422012-02-22 10:17:01 +00001940
Jordan Rosebbb6bb42012-09-08 04:00:03 +00001941 void HandleInvalidLengthModifier(
1942 const analyze_format_string::FormatSpecifier &FS,
1943 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose8be066e2012-09-08 04:00:12 +00001944 const char *startSpecifier, unsigned specifierLen, unsigned DiagID);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00001945
Hans Wennborg76517422012-02-22 10:17:01 +00001946 void HandleNonStandardLengthModifier(
Jordan Rose8be066e2012-09-08 04:00:12 +00001947 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborg76517422012-02-22 10:17:01 +00001948 const char *startSpecifier, unsigned specifierLen);
1949
1950 void HandleNonStandardConversionSpecifier(
1951 const analyze_format_string::ConversionSpecifier &CS,
1952 const char *startSpecifier, unsigned specifierLen);
1953
Hans Wennborgf8562642012-03-09 10:10:54 +00001954 virtual void HandlePosition(const char *startPos, unsigned posLen);
1955
Ted Kremenekefaff192010-02-27 01:41:03 +00001956 virtual void HandleInvalidPosition(const char *startSpecifier,
1957 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00001958 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00001959
1960 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1961
Ted Kremeneke0e53132010-01-28 23:39:18 +00001962 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001963
Richard Trieu55733de2011-10-28 00:41:25 +00001964 template <typename Range>
1965 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
1966 const Expr *ArgumentExpr,
1967 PartialDiagnostic PDiag,
1968 SourceLocation StringLoc,
1969 bool IsStringLocation, Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00001970 ArrayRef<FixItHint> Fixit = ArrayRef<FixItHint>());
Richard Trieu55733de2011-10-28 00:41:25 +00001971
Ted Kremenek826a3452010-07-16 02:11:22 +00001972protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001973 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
1974 const char *startSpec,
1975 unsigned specifierLen,
1976 const char *csStart, unsigned csLen);
Richard Trieu55733de2011-10-28 00:41:25 +00001977
1978 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
1979 const char *startSpec,
1980 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001981
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001982 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00001983 CharSourceRange getSpecifierRange(const char *startSpecifier,
1984 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001985 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001986
Ted Kremenek0d277352010-01-29 01:06:55 +00001987 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00001988
1989 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
1990 const analyze_format_string::ConversionSpecifier &CS,
1991 const char *startSpecifier, unsigned specifierLen,
1992 unsigned argIndex);
Richard Trieu55733de2011-10-28 00:41:25 +00001993
1994 template <typename Range>
1995 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
1996 bool IsStringLocation, Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00001997 ArrayRef<FixItHint> Fixit = ArrayRef<FixItHint>());
Richard Trieu55733de2011-10-28 00:41:25 +00001998
1999 void CheckPositionalAndNonpositionalArgs(
2000 const analyze_format_string::FormatSpecifier *FS);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002001};
2002}
2003
Ted Kremenek826a3452010-07-16 02:11:22 +00002004SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00002005 return OrigFormatExpr->getSourceRange();
2006}
2007
Ted Kremenek826a3452010-07-16 02:11:22 +00002008CharSourceRange CheckFormatHandler::
2009getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002010 SourceLocation Start = getLocationOfByte(startSpecifier);
2011 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2012
2013 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002014 End = End.getLocWithOffset(1);
Tom Care45f9b7e2010-06-21 21:21:01 +00002015
2016 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002017}
2018
Ted Kremenek826a3452010-07-16 02:11:22 +00002019SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002020 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002021}
2022
Ted Kremenek826a3452010-07-16 02:11:22 +00002023void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2024 unsigned specifierLen){
Richard Trieu55733de2011-10-28 00:41:25 +00002025 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2026 getLocationOfByte(startSpecifier),
2027 /*IsStringLocation*/true,
2028 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek808015a2010-01-29 03:16:21 +00002029}
2030
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002031void CheckFormatHandler::HandleInvalidLengthModifier(
2032 const analyze_format_string::FormatSpecifier &FS,
2033 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose8be066e2012-09-08 04:00:12 +00002034 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002035 using namespace analyze_format_string;
2036
2037 const LengthModifier &LM = FS.getLengthModifier();
2038 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2039
2040 // See if we know how to fix this length modifier.
2041 llvm::Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
2042 if (FixedLM) {
Jordan Rose8be066e2012-09-08 04:00:12 +00002043 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002044 getLocationOfByte(LM.getStart()),
2045 /*IsStringLocation*/true,
2046 getSpecifierRange(startSpecifier, specifierLen));
2047
2048 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2049 << FixedLM->toString()
2050 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2051
2052 } else {
Jordan Rose8be066e2012-09-08 04:00:12 +00002053 FixItHint Hint;
2054 if (DiagID == diag::warn_format_nonsensical_length)
2055 Hint = FixItHint::CreateRemoval(LMRange);
2056
2057 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002058 getLocationOfByte(LM.getStart()),
2059 /*IsStringLocation*/true,
2060 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose8be066e2012-09-08 04:00:12 +00002061 Hint);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002062 }
2063}
2064
Hans Wennborg76517422012-02-22 10:17:01 +00002065void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose8be066e2012-09-08 04:00:12 +00002066 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborg76517422012-02-22 10:17:01 +00002067 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose8be066e2012-09-08 04:00:12 +00002068 using namespace analyze_format_string;
2069
2070 const LengthModifier &LM = FS.getLengthModifier();
2071 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2072
2073 // See if we know how to fix this length modifier.
2074 llvm::Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
2075 if (FixedLM) {
2076 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2077 << LM.toString() << 0,
2078 getLocationOfByte(LM.getStart()),
2079 /*IsStringLocation*/true,
2080 getSpecifierRange(startSpecifier, specifierLen));
2081
2082 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2083 << FixedLM->toString()
2084 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2085
2086 } else {
2087 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2088 << LM.toString() << 0,
2089 getLocationOfByte(LM.getStart()),
2090 /*IsStringLocation*/true,
2091 getSpecifierRange(startSpecifier, specifierLen));
2092 }
Hans Wennborg76517422012-02-22 10:17:01 +00002093}
2094
2095void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2096 const analyze_format_string::ConversionSpecifier &CS,
2097 const char *startSpecifier, unsigned specifierLen) {
2098 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) << CS.toString()
Hans Wennborgf8562642012-03-09 10:10:54 +00002099 << 1,
Hans Wennborg76517422012-02-22 10:17:01 +00002100 getLocationOfByte(CS.getStart()),
2101 /*IsStringLocation*/true,
2102 getSpecifierRange(startSpecifier, specifierLen));
2103}
2104
Hans Wennborgf8562642012-03-09 10:10:54 +00002105void CheckFormatHandler::HandlePosition(const char *startPos,
2106 unsigned posLen) {
2107 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2108 getLocationOfByte(startPos),
2109 /*IsStringLocation*/true,
2110 getSpecifierRange(startPos, posLen));
2111}
2112
Ted Kremenekefaff192010-02-27 01:41:03 +00002113void
Ted Kremenek826a3452010-07-16 02:11:22 +00002114CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2115 analyze_format_string::PositionContext p) {
Richard Trieu55733de2011-10-28 00:41:25 +00002116 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2117 << (unsigned) p,
2118 getLocationOfByte(startPos), /*IsStringLocation*/true,
2119 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00002120}
2121
Ted Kremenek826a3452010-07-16 02:11:22 +00002122void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00002123 unsigned posLen) {
Richard Trieu55733de2011-10-28 00:41:25 +00002124 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2125 getLocationOfByte(startPos),
2126 /*IsStringLocation*/true,
2127 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00002128}
2129
Ted Kremenek826a3452010-07-16 02:11:22 +00002130void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose50687312012-06-04 23:52:23 +00002131 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0c069442011-03-15 21:18:48 +00002132 // The presence of a null character is likely an error.
Richard Trieu55733de2011-10-28 00:41:25 +00002133 EmitFormatDiagnostic(
2134 S.PDiag(diag::warn_printf_format_string_contains_null_char),
2135 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2136 getFormatStringRange());
Ted Kremenek0c069442011-03-15 21:18:48 +00002137 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002138}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002139
Jordan Rose48716662012-07-19 18:10:08 +00002140// Note that this may return NULL if there was an error parsing or building
2141// one of the argument expressions.
Ted Kremenek826a3452010-07-16 02:11:22 +00002142const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002143 return Args[FirstDataArg + i];
Ted Kremenek826a3452010-07-16 02:11:22 +00002144}
2145
2146void CheckFormatHandler::DoneProcessing() {
2147 // Does the number of data arguments exceed the number of
2148 // format conversions in the format string?
2149 if (!HasVAListArg) {
2150 // Find any arguments that weren't covered.
2151 CoveredArgs.flip();
2152 signed notCoveredArg = CoveredArgs.find_first();
2153 if (notCoveredArg >= 0) {
2154 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose48716662012-07-19 18:10:08 +00002155 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2156 SourceLocation Loc = E->getLocStart();
2157 if (!S.getSourceManager().isInSystemMacro(Loc)) {
2158 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2159 Loc, /*IsStringLocation*/false,
2160 getFormatStringRange());
2161 }
Bob Wilsonc03f2df2012-05-03 19:47:19 +00002162 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002163 }
2164 }
2165}
2166
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002167bool
2168CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2169 SourceLocation Loc,
2170 const char *startSpec,
2171 unsigned specifierLen,
2172 const char *csStart,
2173 unsigned csLen) {
2174
2175 bool keepGoing = true;
2176 if (argIndex < NumDataArgs) {
2177 // Consider the argument coverered, even though the specifier doesn't
2178 // make sense.
2179 CoveredArgs.set(argIndex);
2180 }
2181 else {
2182 // If argIndex exceeds the number of data arguments we
2183 // don't issue a warning because that is just a cascade of warnings (and
2184 // they may have intended '%%' anyway). We don't want to continue processing
2185 // the format string after this point, however, as we will like just get
2186 // gibberish when trying to match arguments.
2187 keepGoing = false;
2188 }
2189
Richard Trieu55733de2011-10-28 00:41:25 +00002190 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2191 << StringRef(csStart, csLen),
2192 Loc, /*IsStringLocation*/true,
2193 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002194
2195 return keepGoing;
2196}
2197
Richard Trieu55733de2011-10-28 00:41:25 +00002198void
2199CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2200 const char *startSpec,
2201 unsigned specifierLen) {
2202 EmitFormatDiagnostic(
2203 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2204 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2205}
2206
Ted Kremenek666a1972010-07-26 19:45:42 +00002207bool
2208CheckFormatHandler::CheckNumArgs(
2209 const analyze_format_string::FormatSpecifier &FS,
2210 const analyze_format_string::ConversionSpecifier &CS,
2211 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2212
2213 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002214 PartialDiagnostic PDiag = FS.usesPositionalArg()
2215 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2216 << (argIndex+1) << NumDataArgs)
2217 : S.PDiag(diag::warn_printf_insufficient_data_args);
2218 EmitFormatDiagnostic(
2219 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2220 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek666a1972010-07-26 19:45:42 +00002221 return false;
2222 }
2223 return true;
2224}
2225
Richard Trieu55733de2011-10-28 00:41:25 +00002226template<typename Range>
2227void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2228 SourceLocation Loc,
2229 bool IsStringLocation,
2230 Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00002231 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002232 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu55733de2011-10-28 00:41:25 +00002233 Loc, IsStringLocation, StringRange, FixIt);
2234}
2235
2236/// \brief If the format string is not within the funcion call, emit a note
2237/// so that the function call and string are in diagnostic messages.
2238///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00002239/// \param InFunctionCall if true, the format string is within the function
Richard Trieu55733de2011-10-28 00:41:25 +00002240/// call and only one diagnostic message will be produced. Otherwise, an
2241/// extra note will be emitted pointing to location of the format string.
2242///
2243/// \param ArgumentExpr the expression that is passed as the format string
2244/// argument in the function call. Used for getting locations when two
2245/// diagnostics are emitted.
2246///
2247/// \param PDiag the callee should already have provided any strings for the
2248/// diagnostic message. This function only adds locations and fixits
2249/// to diagnostics.
2250///
2251/// \param Loc primary location for diagnostic. If two diagnostics are
2252/// required, one will be at Loc and a new SourceLocation will be created for
2253/// the other one.
2254///
2255/// \param IsStringLocation if true, Loc points to the format string should be
2256/// used for the note. Otherwise, Loc points to the argument list and will
2257/// be used with PDiag.
2258///
2259/// \param StringRange some or all of the string to highlight. This is
2260/// templated so it can accept either a CharSourceRange or a SourceRange.
2261///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00002262/// \param FixIt optional fix it hint for the format string.
Richard Trieu55733de2011-10-28 00:41:25 +00002263template<typename Range>
2264void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2265 const Expr *ArgumentExpr,
2266 PartialDiagnostic PDiag,
2267 SourceLocation Loc,
2268 bool IsStringLocation,
2269 Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00002270 ArrayRef<FixItHint> FixIt) {
2271 if (InFunctionCall) {
2272 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
2273 D << StringRange;
2274 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2275 I != E; ++I) {
2276 D << *I;
2277 }
2278 } else {
Richard Trieu55733de2011-10-28 00:41:25 +00002279 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2280 << ArgumentExpr->getSourceRange();
Jordan Roseec087352012-09-05 22:56:26 +00002281
2282 const Sema::SemaDiagnosticBuilder &Note =
2283 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2284 diag::note_format_string_defined);
2285
2286 Note << StringRange;
2287 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2288 I != E; ++I) {
2289 Note << *I;
2290 }
Richard Trieu55733de2011-10-28 00:41:25 +00002291 }
2292}
2293
Ted Kremenek826a3452010-07-16 02:11:22 +00002294//===--- CHECK: Printf format string checking ------------------------------===//
2295
2296namespace {
2297class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose50687312012-06-04 23:52:23 +00002298 bool ObjCContext;
Ted Kremenek826a3452010-07-16 02:11:22 +00002299public:
2300 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2301 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002302 unsigned numDataArgs, bool isObjC,
Ted Kremenek826a3452010-07-16 02:11:22 +00002303 const char *beg, bool hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002304 Expr **Args, unsigned NumArgs,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002305 unsigned formatIdx, bool inFunctionCall,
2306 Sema::VariadicCallType CallType)
Ted Kremenek826a3452010-07-16 02:11:22 +00002307 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002308 numDataArgs, beg, hasVAListArg, Args, NumArgs,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002309 formatIdx, inFunctionCall, CallType), ObjCContext(isObjC)
2310 {}
2311
Ted Kremenek826a3452010-07-16 02:11:22 +00002312
2313 bool HandleInvalidPrintfConversionSpecifier(
2314 const analyze_printf::PrintfSpecifier &FS,
2315 const char *startSpecifier,
2316 unsigned specifierLen);
2317
2318 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2319 const char *startSpecifier,
2320 unsigned specifierLen);
Richard Smith831421f2012-06-25 20:30:08 +00002321 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2322 const char *StartSpecifier,
2323 unsigned SpecifierLen,
2324 const Expr *E);
2325
Ted Kremenek826a3452010-07-16 02:11:22 +00002326 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2327 const char *startSpecifier, unsigned specifierLen);
2328 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2329 const analyze_printf::OptionalAmount &Amt,
2330 unsigned type,
2331 const char *startSpecifier, unsigned specifierLen);
2332 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2333 const analyze_printf::OptionalFlag &flag,
2334 const char *startSpecifier, unsigned specifierLen);
2335 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2336 const analyze_printf::OptionalFlag &ignoredFlag,
2337 const analyze_printf::OptionalFlag &flag,
2338 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgf3749f42012-08-07 08:11:26 +00002339 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith831421f2012-06-25 20:30:08 +00002340 const Expr *E, const CharSourceRange &CSR);
2341
Ted Kremenek826a3452010-07-16 02:11:22 +00002342};
2343}
2344
2345bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2346 const analyze_printf::PrintfSpecifier &FS,
2347 const char *startSpecifier,
2348 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002349 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002350 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002351
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002352 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2353 getLocationOfByte(CS.getStart()),
2354 startSpecifier, specifierLen,
2355 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00002356}
2357
Ted Kremenek826a3452010-07-16 02:11:22 +00002358bool CheckPrintfHandler::HandleAmount(
2359 const analyze_format_string::OptionalAmount &Amt,
2360 unsigned k, const char *startSpecifier,
2361 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002362
2363 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002364 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002365 unsigned argIndex = Amt.getArgIndex();
2366 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002367 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2368 << k,
2369 getLocationOfByte(Amt.getStart()),
2370 /*IsStringLocation*/true,
2371 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002372 // Don't do any more checking. We will just emit
2373 // spurious errors.
2374 return false;
2375 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002376
Ted Kremenek0d277352010-01-29 01:06:55 +00002377 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00002378 // Although not in conformance with C99, we also allow the argument to be
2379 // an 'unsigned int' as that is a reasonably safe case. GCC also
2380 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002381 CoveredArgs.set(argIndex);
2382 const Expr *Arg = getDataArg(argIndex);
Jordan Rose48716662012-07-19 18:10:08 +00002383 if (!Arg)
2384 return false;
2385
Ted Kremenek0d277352010-01-29 01:06:55 +00002386 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002387
Hans Wennborgf3749f42012-08-07 08:11:26 +00002388 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
2389 assert(AT.isValid());
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002390
Hans Wennborgf3749f42012-08-07 08:11:26 +00002391 if (!AT.matchesType(S.Context, T)) {
Richard Trieu55733de2011-10-28 00:41:25 +00002392 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgf3749f42012-08-07 08:11:26 +00002393 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu55733de2011-10-28 00:41:25 +00002394 << T << Arg->getSourceRange(),
2395 getLocationOfByte(Amt.getStart()),
2396 /*IsStringLocation*/true,
2397 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002398 // Don't do any more checking. We will just emit
2399 // spurious errors.
2400 return false;
2401 }
2402 }
2403 }
2404 return true;
2405}
Ted Kremenek0d277352010-01-29 01:06:55 +00002406
Tom Caree4ee9662010-06-17 19:00:27 +00002407void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00002408 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002409 const analyze_printf::OptionalAmount &Amt,
2410 unsigned type,
2411 const char *startSpecifier,
2412 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002413 const analyze_printf::PrintfConversionSpecifier &CS =
2414 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00002415
Richard Trieu55733de2011-10-28 00:41:25 +00002416 FixItHint fixit =
2417 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2418 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2419 Amt.getConstantLength()))
2420 : FixItHint();
2421
2422 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2423 << type << CS.toString(),
2424 getLocationOfByte(Amt.getStart()),
2425 /*IsStringLocation*/true,
2426 getSpecifierRange(startSpecifier, specifierLen),
2427 fixit);
Tom Caree4ee9662010-06-17 19:00:27 +00002428}
2429
Ted Kremenek826a3452010-07-16 02:11:22 +00002430void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002431 const analyze_printf::OptionalFlag &flag,
2432 const char *startSpecifier,
2433 unsigned specifierLen) {
2434 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002435 const analyze_printf::PrintfConversionSpecifier &CS =
2436 FS.getConversionSpecifier();
Richard Trieu55733de2011-10-28 00:41:25 +00002437 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2438 << flag.toString() << CS.toString(),
2439 getLocationOfByte(flag.getPosition()),
2440 /*IsStringLocation*/true,
2441 getSpecifierRange(startSpecifier, specifierLen),
2442 FixItHint::CreateRemoval(
2443 getSpecifierRange(flag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002444}
2445
2446void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00002447 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002448 const analyze_printf::OptionalFlag &ignoredFlag,
2449 const analyze_printf::OptionalFlag &flag,
2450 const char *startSpecifier,
2451 unsigned specifierLen) {
2452 // Warn about ignored flag with a fixit removal.
Richard Trieu55733de2011-10-28 00:41:25 +00002453 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2454 << ignoredFlag.toString() << flag.toString(),
2455 getLocationOfByte(ignoredFlag.getPosition()),
2456 /*IsStringLocation*/true,
2457 getSpecifierRange(startSpecifier, specifierLen),
2458 FixItHint::CreateRemoval(
2459 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002460}
2461
Richard Smith831421f2012-06-25 20:30:08 +00002462// Determines if the specified is a C++ class or struct containing
2463// a member with the specified name and kind (e.g. a CXXMethodDecl named
2464// "c_str()").
2465template<typename MemberKind>
2466static llvm::SmallPtrSet<MemberKind*, 1>
2467CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
2468 const RecordType *RT = Ty->getAs<RecordType>();
2469 llvm::SmallPtrSet<MemberKind*, 1> Results;
2470
2471 if (!RT)
2472 return Results;
2473 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
2474 if (!RD)
2475 return Results;
2476
2477 LookupResult R(S, &S.PP.getIdentifierTable().get(Name), SourceLocation(),
2478 Sema::LookupMemberName);
2479
2480 // We just need to include all members of the right kind turned up by the
2481 // filter, at this point.
2482 if (S.LookupQualifiedName(R, RT->getDecl()))
2483 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2484 NamedDecl *decl = (*I)->getUnderlyingDecl();
2485 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
2486 Results.insert(FK);
2487 }
2488 return Results;
2489}
2490
2491// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgf3749f42012-08-07 08:11:26 +00002492// better diagnostic if so. AT is assumed to be valid.
Richard Smith831421f2012-06-25 20:30:08 +00002493// Returns true when a c_str() conversion method is found.
2494bool CheckPrintfHandler::checkForCStrMembers(
Hans Wennborgf3749f42012-08-07 08:11:26 +00002495 const analyze_printf::ArgType &AT, const Expr *E,
Richard Smith831421f2012-06-25 20:30:08 +00002496 const CharSourceRange &CSR) {
2497 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2498
2499 MethodSet Results =
2500 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
2501
2502 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2503 MI != ME; ++MI) {
2504 const CXXMethodDecl *Method = *MI;
2505 if (Method->getNumParams() == 0 &&
Hans Wennborgf3749f42012-08-07 08:11:26 +00002506 AT.matchesType(S.Context, Method->getResultType())) {
Richard Smith831421f2012-06-25 20:30:08 +00002507 // FIXME: Suggest parens if the expression needs them.
2508 SourceLocation EndLoc =
2509 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd());
2510 S.Diag(E->getLocStart(), diag::note_printf_c_str)
2511 << "c_str()"
2512 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
2513 return true;
2514 }
2515 }
2516
2517 return false;
2518}
2519
Ted Kremeneke0e53132010-01-28 23:39:18 +00002520bool
Ted Kremenek826a3452010-07-16 02:11:22 +00002521CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00002522 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00002523 const char *startSpecifier,
2524 unsigned specifierLen) {
2525
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002526 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00002527 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002528 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00002529
Ted Kremenekbaa40062010-07-19 22:01:06 +00002530 if (FS.consumesDataArgument()) {
2531 if (atFirstArg) {
2532 atFirstArg = false;
2533 usesPositionalArgs = FS.usesPositionalArg();
2534 }
2535 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002536 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2537 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002538 return false;
2539 }
Ted Kremenek0d277352010-01-29 01:06:55 +00002540 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002541
Ted Kremenekefaff192010-02-27 01:41:03 +00002542 // First check if the field width, precision, and conversion specifier
2543 // have matching data arguments.
2544 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2545 startSpecifier, specifierLen)) {
2546 return false;
2547 }
2548
2549 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2550 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002551 return false;
2552 }
2553
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002554 if (!CS.consumesDataArgument()) {
2555 // FIXME: Technically specifying a precision or field width here
2556 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002557 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002558 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002559
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002560 // Consume the argument.
2561 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00002562 if (argIndex < NumDataArgs) {
2563 // The check to see if the argIndex is valid will come later.
2564 // We set the bit here because we may exit early from this
2565 // function if we encounter some other error.
2566 CoveredArgs.set(argIndex);
2567 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002568
2569 // Check for using an Objective-C specific conversion specifier
2570 // in a non-ObjC literal.
Jordan Rose50687312012-06-04 23:52:23 +00002571 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002572 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
2573 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002574 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002575
Tom Caree4ee9662010-06-17 19:00:27 +00002576 // Check for invalid use of field width
2577 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002578 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00002579 startSpecifier, specifierLen);
2580 }
2581
2582 // Check for invalid use of precision
2583 if (!FS.hasValidPrecision()) {
2584 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
2585 startSpecifier, specifierLen);
2586 }
2587
2588 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00002589 if (!FS.hasValidThousandsGroupingPrefix())
2590 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002591 if (!FS.hasValidLeadingZeros())
2592 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
2593 if (!FS.hasValidPlusPrefix())
2594 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00002595 if (!FS.hasValidSpacePrefix())
2596 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002597 if (!FS.hasValidAlternativeForm())
2598 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
2599 if (!FS.hasValidLeftJustified())
2600 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
2601
2602 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00002603 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
2604 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
2605 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002606 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
2607 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
2608 startSpecifier, specifierLen);
2609
2610 // Check the length modifier is valid with the given conversion specifier.
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002611 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose8be066e2012-09-08 04:00:12 +00002612 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
2613 diag::warn_format_nonsensical_length);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002614 else if (!FS.hasStandardLengthModifier())
Jordan Rose8be066e2012-09-08 04:00:12 +00002615 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002616 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose8be066e2012-09-08 04:00:12 +00002617 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
2618 diag::warn_format_non_standard_conversion_spec);
Tom Caree4ee9662010-06-17 19:00:27 +00002619
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002620 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
2621 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
2622
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002623 // The remaining checks depend on the data arguments.
2624 if (HasVAListArg)
2625 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002626
Ted Kremenek666a1972010-07-26 19:45:42 +00002627 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002628 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002629
Jordan Rose48716662012-07-19 18:10:08 +00002630 const Expr *Arg = getDataArg(argIndex);
2631 if (!Arg)
2632 return true;
2633
2634 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith831421f2012-06-25 20:30:08 +00002635}
2636
Jordan Roseec087352012-09-05 22:56:26 +00002637static bool requiresParensToAddCast(const Expr *E) {
2638 // FIXME: We should have a general way to reason about operator
2639 // precedence and whether parens are actually needed here.
2640 // Take care of a few common cases where they aren't.
2641 const Expr *Inside = E->IgnoreImpCasts();
2642 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
2643 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
2644
2645 switch (Inside->getStmtClass()) {
2646 case Stmt::ArraySubscriptExprClass:
2647 case Stmt::CallExprClass:
2648 case Stmt::DeclRefExprClass:
2649 case Stmt::MemberExprClass:
2650 case Stmt::ObjCIvarRefExprClass:
2651 case Stmt::ObjCMessageExprClass:
2652 case Stmt::ObjCPropertyRefExprClass:
2653 case Stmt::ParenExprClass:
2654 case Stmt::UnaryOperatorClass:
2655 return false;
2656 default:
2657 return true;
2658 }
2659}
2660
Richard Smith831421f2012-06-25 20:30:08 +00002661bool
2662CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2663 const char *StartSpecifier,
2664 unsigned SpecifierLen,
2665 const Expr *E) {
2666 using namespace analyze_format_string;
2667 using namespace analyze_printf;
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002668 // Now type check the data expression that matches the
2669 // format specifier.
Hans Wennborgf3749f42012-08-07 08:11:26 +00002670 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
2671 ObjCContext);
Jordan Rose614a8652012-09-05 22:56:19 +00002672 if (!AT.isValid())
2673 return true;
Jordan Roseec087352012-09-05 22:56:26 +00002674
2675 QualType IntendedTy = E->getType();
2676 if (AT.matchesType(S.Context, IntendedTy))
Jordan Rose614a8652012-09-05 22:56:19 +00002677 return true;
Jordan Roseee0259d2012-06-04 22:48:57 +00002678
Jordan Rose614a8652012-09-05 22:56:19 +00002679 // Look through argument promotions for our error message's reported type.
2680 // This includes the integral and floating promotions, but excludes array
2681 // and function pointer decay; seeing that an argument intended to be a
2682 // string has type 'char [6]' is probably more confusing than 'char *'.
2683 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2684 if (ICE->getCastKind() == CK_IntegralCast ||
2685 ICE->getCastKind() == CK_FloatingCast) {
2686 E = ICE->getSubExpr();
Jordan Roseec087352012-09-05 22:56:26 +00002687 IntendedTy = E->getType();
Jordan Rose614a8652012-09-05 22:56:19 +00002688
2689 // Check if we didn't match because of an implicit cast from a 'char'
2690 // or 'short' to an 'int'. This is done because printf is a varargs
2691 // function.
2692 if (ICE->getType() == S.Context.IntTy ||
2693 ICE->getType() == S.Context.UnsignedIntTy) {
2694 // All further checking is done on the subexpression.
Jordan Roseec087352012-09-05 22:56:26 +00002695 if (AT.matchesType(S.Context, IntendedTy))
Jordan Rose614a8652012-09-05 22:56:19 +00002696 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00002697 }
Jordan Roseee0259d2012-06-04 22:48:57 +00002698 }
Jordan Rose614a8652012-09-05 22:56:19 +00002699 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002700
Jordan Roseec087352012-09-05 22:56:26 +00002701 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
2702 // Special-case some of Darwin's platform-independence types.
2703 if (const TypedefType *UserTy = IntendedTy->getAs<TypedefType>()) {
2704 StringRef Name = UserTy->getDecl()->getName();
2705 IntendedTy = llvm::StringSwitch<QualType>(Name)
2706 .Case("NSInteger", S.Context.LongTy)
2707 .Case("NSUInteger", S.Context.UnsignedLongTy)
2708 .Case("SInt32", S.Context.IntTy)
2709 .Case("UInt32", S.Context.UnsignedIntTy)
2710 .Default(IntendedTy);
2711 }
2712 }
2713
Jordan Rose614a8652012-09-05 22:56:19 +00002714 // We may be able to offer a FixItHint if it is a supported type.
2715 PrintfSpecifier fixedFS = FS;
Jordan Roseec087352012-09-05 22:56:26 +00002716 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose614a8652012-09-05 22:56:19 +00002717 S.Context, ObjCContext);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002718
Jordan Rose614a8652012-09-05 22:56:19 +00002719 if (success) {
2720 // Get the fix string from the fixed format specifier
2721 SmallString<16> buf;
2722 llvm::raw_svector_ostream os(buf);
2723 fixedFS.toString(os);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002724
Jordan Roseec087352012-09-05 22:56:26 +00002725 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
2726
2727 if (IntendedTy != E->getType()) {
2728 // The canonical type for formatting this value is different from the
2729 // actual type of the expression. (This occurs, for example, with Darwin's
2730 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
2731 // should be printed as 'long' for 64-bit compatibility.)
2732 // Rather than emitting a normal format/argument mismatch, we want to
2733 // add a cast to the recommended type (and correct the format string
2734 // if necessary).
2735 SmallString<16> CastBuf;
2736 llvm::raw_svector_ostream CastFix(CastBuf);
2737 CastFix << "(";
2738 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
2739 CastFix << ")";
2740
2741 SmallVector<FixItHint,4> Hints;
2742 if (!AT.matchesType(S.Context, IntendedTy))
2743 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
2744
2745 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
2746 // If there's already a cast present, just replace it.
2747 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
2748 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
2749
2750 } else if (!requiresParensToAddCast(E)) {
2751 // If the expression has high enough precedence,
2752 // just write the C-style cast.
2753 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
2754 CastFix.str()));
2755 } else {
2756 // Otherwise, add parens around the expression as well as the cast.
2757 CastFix << "(";
2758 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
2759 CastFix.str()));
2760
2761 SourceLocation After = S.PP.getLocForEndOfToken(E->getLocEnd());
2762 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
2763 }
2764
2765 // We extract the name from the typedef because we don't want to show
2766 // the underlying type in the diagnostic.
2767 const TypedefType *UserTy = cast<TypedefType>(E->getType());
2768 StringRef Name = UserTy->getDecl()->getName();
2769
2770 // Finally, emit the diagnostic.
2771 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
2772 << Name << IntendedTy
2773 << E->getSourceRange(),
2774 E->getLocStart(), /*IsStringLocation=*/false,
2775 SpecRange, Hints);
2776 } else {
2777 EmitFormatDiagnostic(
2778 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2779 << AT.getRepresentativeTypeName(S.Context) << IntendedTy
2780 << E->getSourceRange(),
2781 E->getLocStart(),
2782 /*IsStringLocation*/false,
2783 SpecRange,
2784 FixItHint::CreateReplacement(SpecRange, os.str()));
2785 }
Jordan Rose614a8652012-09-05 22:56:19 +00002786 } else {
2787 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
2788 SpecifierLen);
2789 // Since the warning for passing non-POD types to variadic functions
2790 // was deferred until now, we emit a warning for non-POD
2791 // arguments here.
2792 if (S.isValidVarArgType(E->getType()) == Sema::VAK_Invalid) {
2793 unsigned DiagKind;
2794 if (E->getType()->isObjCObjectType())
2795 DiagKind = diag::err_cannot_pass_objc_interface_to_vararg_format;
2796 else
2797 DiagKind = diag::warn_non_pod_vararg_with_format_string;
2798
2799 EmitFormatDiagnostic(
2800 S.PDiag(DiagKind)
2801 << S.getLangOpts().CPlusPlus0x
2802 << E->getType()
2803 << CallType
2804 << AT.getRepresentativeTypeName(S.Context)
2805 << CSR
2806 << E->getSourceRange(),
2807 E->getLocStart(), /*IsStringLocation*/false, CSR);
2808
2809 checkForCStrMembers(AT, E, CSR);
2810 } else
Richard Trieu55733de2011-10-28 00:41:25 +00002811 EmitFormatDiagnostic(
2812 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborgf3749f42012-08-07 08:11:26 +00002813 << AT.getRepresentativeTypeName(S.Context) << E->getType()
Jordan Rose614a8652012-09-05 22:56:19 +00002814 << CSR
Richard Smith831421f2012-06-25 20:30:08 +00002815 << E->getSourceRange(),
Jordan Rose614a8652012-09-05 22:56:19 +00002816 E->getLocStart(), /*IsStringLocation*/false, CSR);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002817 }
2818
Ted Kremeneke0e53132010-01-28 23:39:18 +00002819 return true;
2820}
2821
Ted Kremenek826a3452010-07-16 02:11:22 +00002822//===--- CHECK: Scanf format string checking ------------------------------===//
2823
2824namespace {
2825class CheckScanfHandler : public CheckFormatHandler {
2826public:
2827 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
2828 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002829 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002830 Expr **Args, unsigned NumArgs,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002831 unsigned formatIdx, bool inFunctionCall,
2832 Sema::VariadicCallType CallType)
Ted Kremenek826a3452010-07-16 02:11:22 +00002833 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002834 numDataArgs, beg, hasVAListArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002835 Args, NumArgs, formatIdx, inFunctionCall, CallType)
2836 {}
Ted Kremenek826a3452010-07-16 02:11:22 +00002837
2838 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
2839 const char *startSpecifier,
2840 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002841
2842 bool HandleInvalidScanfConversionSpecifier(
2843 const analyze_scanf::ScanfSpecifier &FS,
2844 const char *startSpecifier,
2845 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00002846
2847 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00002848};
Ted Kremenek07d161f2010-01-29 01:50:07 +00002849}
Ted Kremeneke0e53132010-01-28 23:39:18 +00002850
Ted Kremenekb7c21012010-07-16 18:28:03 +00002851void CheckScanfHandler::HandleIncompleteScanList(const char *start,
2852 const char *end) {
Richard Trieu55733de2011-10-28 00:41:25 +00002853 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
2854 getLocationOfByte(end), /*IsStringLocation*/true,
2855 getSpecifierRange(start, end - start));
Ted Kremenekb7c21012010-07-16 18:28:03 +00002856}
2857
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002858bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
2859 const analyze_scanf::ScanfSpecifier &FS,
2860 const char *startSpecifier,
2861 unsigned specifierLen) {
2862
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002863 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002864 FS.getConversionSpecifier();
2865
2866 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2867 getLocationOfByte(CS.getStart()),
2868 startSpecifier, specifierLen,
2869 CS.getStart(), CS.getLength());
2870}
2871
Ted Kremenek826a3452010-07-16 02:11:22 +00002872bool CheckScanfHandler::HandleScanfSpecifier(
2873 const analyze_scanf::ScanfSpecifier &FS,
2874 const char *startSpecifier,
2875 unsigned specifierLen) {
2876
2877 using namespace analyze_scanf;
2878 using namespace analyze_format_string;
2879
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002880 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002881
Ted Kremenekbaa40062010-07-19 22:01:06 +00002882 // Handle case where '%' and '*' don't consume an argument. These shouldn't
2883 // be used to decide if we are using positional arguments consistently.
2884 if (FS.consumesDataArgument()) {
2885 if (atFirstArg) {
2886 atFirstArg = false;
2887 usesPositionalArgs = FS.usesPositionalArg();
2888 }
2889 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002890 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2891 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002892 return false;
2893 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002894 }
2895
2896 // Check if the field with is non-zero.
2897 const OptionalAmount &Amt = FS.getFieldWidth();
2898 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
2899 if (Amt.getConstantAmount() == 0) {
2900 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
2901 Amt.getConstantLength());
Richard Trieu55733de2011-10-28 00:41:25 +00002902 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
2903 getLocationOfByte(Amt.getStart()),
2904 /*IsStringLocation*/true, R,
2905 FixItHint::CreateRemoval(R));
Ted Kremenek826a3452010-07-16 02:11:22 +00002906 }
2907 }
2908
2909 if (!FS.consumesDataArgument()) {
2910 // FIXME: Technically specifying a precision or field width here
2911 // makes no sense. Worth issuing a warning at some point.
2912 return true;
2913 }
2914
2915 // Consume the argument.
2916 unsigned argIndex = FS.getArgIndex();
2917 if (argIndex < NumDataArgs) {
2918 // The check to see if the argIndex is valid will come later.
2919 // We set the bit here because we may exit early from this
2920 // function if we encounter some other error.
2921 CoveredArgs.set(argIndex);
2922 }
2923
Ted Kremenek1e51c202010-07-20 20:04:47 +00002924 // Check the length modifier is valid with the given conversion specifier.
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002925 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose8be066e2012-09-08 04:00:12 +00002926 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
2927 diag::warn_format_nonsensical_length);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002928 else if (!FS.hasStandardLengthModifier())
Jordan Rose8be066e2012-09-08 04:00:12 +00002929 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002930 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose8be066e2012-09-08 04:00:12 +00002931 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
2932 diag::warn_format_non_standard_conversion_spec);
Hans Wennborg76517422012-02-22 10:17:01 +00002933
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002934 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
2935 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
2936
Ted Kremenek826a3452010-07-16 02:11:22 +00002937 // The remaining checks depend on the data arguments.
2938 if (HasVAListArg)
2939 return true;
2940
Ted Kremenek666a1972010-07-26 19:45:42 +00002941 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00002942 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00002943
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002944 // Check that the argument type matches the format specifier.
2945 const Expr *Ex = getDataArg(argIndex);
Jordan Rose48716662012-07-19 18:10:08 +00002946 if (!Ex)
2947 return true;
2948
Hans Wennborg58e1e542012-08-07 08:59:46 +00002949 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
2950 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002951 ScanfSpecifier fixedFS = FS;
David Blaikie4e4d0842012-03-11 07:00:24 +00002952 bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(),
Hans Wennborgbe6126a2012-02-15 09:59:46 +00002953 S.Context);
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002954
2955 if (success) {
2956 // Get the fix string from the fixed format specifier.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002957 SmallString<128> buf;
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002958 llvm::raw_svector_ostream os(buf);
2959 fixedFS.toString(os);
2960
2961 EmitFormatDiagnostic(
2962 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg58e1e542012-08-07 08:59:46 +00002963 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002964 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00002965 Ex->getLocStart(),
2966 /*IsStringLocation*/false,
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002967 getSpecifierRange(startSpecifier, specifierLen),
2968 FixItHint::CreateReplacement(
2969 getSpecifierRange(startSpecifier, specifierLen),
2970 os.str()));
2971 } else {
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00002972 EmitFormatDiagnostic(
2973 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg58e1e542012-08-07 08:59:46 +00002974 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00002975 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00002976 Ex->getLocStart(),
2977 /*IsStringLocation*/false,
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00002978 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002979 }
2980 }
2981
Ted Kremenek826a3452010-07-16 02:11:22 +00002982 return true;
2983}
2984
2985void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002986 const Expr *OrigFormatExpr,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002987 Expr **Args, unsigned NumArgs,
2988 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002989 unsigned firstDataArg, FormatStringType Type,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002990 bool inFunctionCall, VariadicCallType CallType) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002991
Ted Kremeneke0e53132010-01-28 23:39:18 +00002992 // CHECK: is the format string a wide literal?
Richard Smithdf9ef1b2012-06-13 05:37:23 +00002993 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002994 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002995 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00002996 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
2997 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00002998 return;
2999 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003000
Ted Kremeneke0e53132010-01-28 23:39:18 +00003001 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner5f9e2722011-07-23 10:55:15 +00003002 StringRef StrRef = FExpr->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00003003 const char *Str = StrRef.data();
3004 unsigned StrLen = StrRef.size();
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003005 const unsigned numDataArgs = NumArgs - firstDataArg;
Ted Kremenek826a3452010-07-16 02:11:22 +00003006
Ted Kremeneke0e53132010-01-28 23:39:18 +00003007 // CHECK: empty format string?
Ted Kremenek4cd57912011-09-29 05:52:16 +00003008 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu55733de2011-10-28 00:41:25 +00003009 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003010 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00003011 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3012 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00003013 return;
3014 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003015
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003016 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek826a3452010-07-16 02:11:22 +00003017 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00003018 numDataArgs, (Type == FST_NSString),
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003019 Str, HasVAListArg, Args, NumArgs, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003020 inFunctionCall, CallType);
Ted Kremenek826a3452010-07-16 02:11:22 +00003021
Hans Wennborgd02deeb2011-12-15 10:25:47 +00003022 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
David Blaikie4e4d0842012-03-11 07:00:24 +00003023 getLangOpts()))
Ted Kremenek826a3452010-07-16 02:11:22 +00003024 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003025 } else if (Type == FST_Scanf) {
Jordan Rose50687312012-06-04 23:52:23 +00003026 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003027 Str, HasVAListArg, Args, NumArgs, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003028 inFunctionCall, CallType);
Ted Kremenek826a3452010-07-16 02:11:22 +00003029
Hans Wennborgd02deeb2011-12-15 10:25:47 +00003030 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
David Blaikie4e4d0842012-03-11 07:00:24 +00003031 getLangOpts()))
Ted Kremenek826a3452010-07-16 02:11:22 +00003032 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003033 } // TODO: handle other formats
Ted Kremenekce7024e2010-01-28 01:18:22 +00003034}
3035
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003036//===--- CHECK: Standard memory functions ---------------------------------===//
3037
Douglas Gregor2a053a32011-05-03 20:05:22 +00003038/// \brief Determine whether the given type is a dynamic class type (e.g.,
3039/// whether it has a vtable).
3040static bool isDynamicClassType(QualType T) {
3041 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3042 if (CXXRecordDecl *Definition = Record->getDefinition())
3043 if (Definition->isDynamicClass())
3044 return true;
3045
3046 return false;
3047}
3048
Chandler Carrutha72a12f2011-06-21 23:04:20 +00003049/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth000d4282011-06-16 09:09:40 +00003050/// otherwise returns NULL.
3051static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Webere4a1c642011-06-14 16:14:58 +00003052 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth000d4282011-06-16 09:09:40 +00003053 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3054 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
3055 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00003056
Chandler Carruth000d4282011-06-16 09:09:40 +00003057 return 0;
3058}
3059
Chandler Carrutha72a12f2011-06-21 23:04:20 +00003060/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth000d4282011-06-16 09:09:40 +00003061static QualType getSizeOfArgType(const Expr* E) {
3062 if (const UnaryExprOrTypeTraitExpr *SizeOf =
3063 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3064 if (SizeOf->getKind() == clang::UETT_SizeOf)
3065 return SizeOf->getTypeOfArgument();
3066
3067 return QualType();
Nico Webere4a1c642011-06-14 16:14:58 +00003068}
3069
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003070/// \brief Check for dangerous or invalid arguments to memset().
3071///
Chandler Carruth929f0132011-06-03 06:23:57 +00003072/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003073/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
3074/// function calls.
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003075///
3076/// \param Call The call expression to diagnose.
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003077void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks0a151a12012-01-17 00:37:07 +00003078 unsigned BId,
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003079 IdentifierInfo *FnName) {
Anna Zaks0a151a12012-01-17 00:37:07 +00003080 assert(BId != 0);
3081
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00003082 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor707a23e2011-06-16 17:56:04 +00003083 // we have enough arguments, and if not, abort further checking.
Anna Zaks0a151a12012-01-17 00:37:07 +00003084 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Webercda57822011-10-13 22:30:23 +00003085 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00003086 return;
3087
Anna Zaks0a151a12012-01-17 00:37:07 +00003088 unsigned LastArg = (BId == Builtin::BImemset ||
3089 BId == Builtin::BIstrndup ? 1 : 2);
3090 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Webercda57822011-10-13 22:30:23 +00003091 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth000d4282011-06-16 09:09:40 +00003092
3093 // We have special checking when the length is a sizeof expression.
3094 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
3095 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
3096 llvm::FoldingSetNodeID SizeOfArgID;
3097
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003098 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
3099 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00003100 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003101
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003102 QualType DestTy = Dest->getType();
3103 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
3104 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00003105
Chandler Carruth000d4282011-06-16 09:09:40 +00003106 // Never warn about void type pointers. This can be used to suppress
3107 // false positives.
3108 if (PointeeTy->isVoidType())
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003109 continue;
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003110
Chandler Carruth000d4282011-06-16 09:09:40 +00003111 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
3112 // actually comparing the expressions for equality. Because computing the
3113 // expression IDs can be expensive, we only do this if the diagnostic is
3114 // enabled.
3115 if (SizeOfArg &&
3116 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
3117 SizeOfArg->getExprLoc())) {
3118 // We only compute IDs for expressions if the warning is enabled, and
3119 // cache the sizeof arg's ID.
3120 if (SizeOfArgID == llvm::FoldingSetNodeID())
3121 SizeOfArg->Profile(SizeOfArgID, Context, true);
3122 llvm::FoldingSetNodeID DestID;
3123 Dest->Profile(DestID, Context, true);
3124 if (DestID == SizeOfArgID) {
Nico Webercda57822011-10-13 22:30:23 +00003125 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
3126 // over sizeof(src) as well.
Chandler Carruth000d4282011-06-16 09:09:40 +00003127 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks6fcb3722012-05-30 00:34:21 +00003128 StringRef ReadableName = FnName->getName();
3129
Chandler Carruth000d4282011-06-16 09:09:40 +00003130 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaks90c78322012-05-30 23:14:52 +00003131 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth000d4282011-06-16 09:09:40 +00003132 ActionIdx = 1; // If its an address-of operator, just remove it.
3133 if (Context.getTypeSize(PointeeTy) == Context.getCharWidth())
3134 ActionIdx = 2; // If the pointee's size is sizeof(char),
3135 // suggest an explicit length.
Anna Zaks6fcb3722012-05-30 00:34:21 +00003136
3137 // If the function is defined as a builtin macro, do not show macro
3138 // expansion.
3139 SourceLocation SL = SizeOfArg->getExprLoc();
3140 SourceRange DSR = Dest->getSourceRange();
3141 SourceRange SSR = SizeOfArg->getSourceRange();
3142 SourceManager &SM = PP.getSourceManager();
3143
3144 if (SM.isMacroArgExpansion(SL)) {
3145 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
3146 SL = SM.getSpellingLoc(SL);
3147 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
3148 SM.getSpellingLoc(DSR.getEnd()));
3149 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
3150 SM.getSpellingLoc(SSR.getEnd()));
3151 }
3152
Anna Zaks90c78322012-05-30 23:14:52 +00003153 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth000d4282011-06-16 09:09:40 +00003154 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks6fcb3722012-05-30 00:34:21 +00003155 << ReadableName
Anna Zaks90c78322012-05-30 23:14:52 +00003156 << PointeeTy
3157 << DestTy
Anna Zaks6fcb3722012-05-30 00:34:21 +00003158 << DSR
Anna Zaks90c78322012-05-30 23:14:52 +00003159 << SSR);
3160 DiagRuntimeBehavior(SL, SizeOfArg,
3161 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
3162 << ActionIdx
3163 << SSR);
3164
Chandler Carruth000d4282011-06-16 09:09:40 +00003165 break;
3166 }
3167 }
3168
3169 // Also check for cases where the sizeof argument is the exact same
3170 // type as the memory argument, and where it points to a user-defined
3171 // record type.
3172 if (SizeOfArgTy != QualType()) {
3173 if (PointeeTy->isRecordType() &&
3174 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
3175 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
3176 PDiag(diag::warn_sizeof_pointer_type_memaccess)
3177 << FnName << SizeOfArgTy << ArgIdx
3178 << PointeeTy << Dest->getSourceRange()
3179 << LenExpr->getSourceRange());
3180 break;
3181 }
Nico Webere4a1c642011-06-14 16:14:58 +00003182 }
3183
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003184 // Always complain about dynamic classes.
Anna Zaks0a151a12012-01-17 00:37:07 +00003185 if (isDynamicClassType(PointeeTy)) {
3186
3187 unsigned OperationType = 0;
3188 // "overwritten" if we're warning about the destination for any call
3189 // but memcmp; otherwise a verb appropriate to the call.
3190 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
3191 if (BId == Builtin::BImemcpy)
3192 OperationType = 1;
3193 else if(BId == Builtin::BImemmove)
3194 OperationType = 2;
3195 else if (BId == Builtin::BImemcmp)
3196 OperationType = 3;
3197 }
3198
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003199 DiagRuntimeBehavior(
3200 Dest->getExprLoc(), Dest,
3201 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks0a151a12012-01-17 00:37:07 +00003202 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Anna Zaksd9b859a2012-01-13 21:52:01 +00003203 << FnName << PointeeTy
Anna Zaks0a151a12012-01-17 00:37:07 +00003204 << OperationType
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003205 << Call->getCallee()->getSourceRange());
Anna Zaks0a151a12012-01-17 00:37:07 +00003206 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
3207 BId != Builtin::BImemset)
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003208 DiagRuntimeBehavior(
3209 Dest->getExprLoc(), Dest,
3210 PDiag(diag::warn_arc_object_memaccess)
3211 << ArgIdx << FnName << PointeeTy
3212 << Call->getCallee()->getSourceRange());
John McCallf85e1932011-06-15 23:02:42 +00003213 else
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003214 continue;
John McCallf85e1932011-06-15 23:02:42 +00003215
3216 DiagRuntimeBehavior(
3217 Dest->getExprLoc(), Dest,
Chandler Carruth929f0132011-06-03 06:23:57 +00003218 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003219 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
3220 break;
3221 }
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003222 }
3223}
3224
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003225// A little helper routine: ignore addition and subtraction of integer literals.
3226// This intentionally does not ignore all integer constant expressions because
3227// we don't want to remove sizeof().
3228static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
3229 Ex = Ex->IgnoreParenCasts();
3230
3231 for (;;) {
3232 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
3233 if (!BO || !BO->isAdditiveOp())
3234 break;
3235
3236 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
3237 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
3238
3239 if (isa<IntegerLiteral>(RHS))
3240 Ex = LHS;
3241 else if (isa<IntegerLiteral>(LHS))
3242 Ex = RHS;
3243 else
3244 break;
3245 }
3246
3247 return Ex;
3248}
3249
Anna Zaks0f38ace2012-08-08 21:42:23 +00003250static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
3251 ASTContext &Context) {
3252 // Only handle constant-sized or VLAs, but not flexible members.
3253 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
3254 // Only issue the FIXIT for arrays of size > 1.
3255 if (CAT->getSize().getSExtValue() <= 1)
3256 return false;
3257 } else if (!Ty->isVariableArrayType()) {
3258 return false;
3259 }
3260 return true;
3261}
3262
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003263// Warn if the user has made the 'size' argument to strlcpy or strlcat
3264// be the size of the source, instead of the destination.
3265void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
3266 IdentifierInfo *FnName) {
3267
3268 // Don't crash if the user has the wrong number of arguments
3269 if (Call->getNumArgs() != 3)
3270 return;
3271
3272 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
3273 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
3274 const Expr *CompareWithSrc = NULL;
3275
3276 // Look for 'strlcpy(dst, x, sizeof(x))'
3277 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
3278 CompareWithSrc = Ex;
3279 else {
3280 // Look for 'strlcpy(dst, x, strlen(x))'
3281 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Richard Smith180f4792011-11-10 06:34:14 +00003282 if (SizeCall->isBuiltinCall() == Builtin::BIstrlen
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003283 && SizeCall->getNumArgs() == 1)
3284 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
3285 }
3286 }
3287
3288 if (!CompareWithSrc)
3289 return;
3290
3291 // Determine if the argument to sizeof/strlen is equal to the source
3292 // argument. In principle there's all kinds of things you could do
3293 // here, for instance creating an == expression and evaluating it with
3294 // EvaluateAsBooleanCondition, but this uses a more direct technique:
3295 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
3296 if (!SrcArgDRE)
3297 return;
3298
3299 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
3300 if (!CompareWithSrcDRE ||
3301 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
3302 return;
3303
3304 const Expr *OriginalSizeArg = Call->getArg(2);
3305 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
3306 << OriginalSizeArg->getSourceRange() << FnName;
3307
3308 // Output a FIXIT hint if the destination is an array (rather than a
3309 // pointer to an array). This could be enhanced to handle some
3310 // pointers if we know the actual size, like if DstArg is 'array+2'
3311 // we could say 'sizeof(array)-2'.
3312 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks0f38ace2012-08-08 21:42:23 +00003313 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek8f746222011-08-18 22:48:41 +00003314 return;
Ted Kremenek8f746222011-08-18 22:48:41 +00003315
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003316 SmallString<128> sizeString;
Ted Kremenek8f746222011-08-18 22:48:41 +00003317 llvm::raw_svector_ostream OS(sizeString);
3318 OS << "sizeof(";
Richard Smithd1420c62012-08-16 03:56:14 +00003319 DstArg->printPretty(OS, 0, getPrintingPolicy());
Ted Kremenek8f746222011-08-18 22:48:41 +00003320 OS << ")";
3321
3322 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
3323 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
3324 OS.str());
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003325}
3326
Anna Zaksc36bedc2012-02-01 19:08:57 +00003327/// Check if two expressions refer to the same declaration.
3328static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
3329 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
3330 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
3331 return D1->getDecl() == D2->getDecl();
3332 return false;
3333}
3334
3335static const Expr *getStrlenExprArg(const Expr *E) {
3336 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
3337 const FunctionDecl *FD = CE->getDirectCallee();
3338 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
3339 return 0;
3340 return CE->getArg(0)->IgnoreParenCasts();
3341 }
3342 return 0;
3343}
3344
3345// Warn on anti-patterns as the 'size' argument to strncat.
3346// The correct size argument should look like following:
3347// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
3348void Sema::CheckStrncatArguments(const CallExpr *CE,
3349 IdentifierInfo *FnName) {
3350 // Don't crash if the user has the wrong number of arguments.
3351 if (CE->getNumArgs() < 3)
3352 return;
3353 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
3354 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
3355 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
3356
3357 // Identify common expressions, which are wrongly used as the size argument
3358 // to strncat and may lead to buffer overflows.
3359 unsigned PatternType = 0;
3360 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
3361 // - sizeof(dst)
3362 if (referToTheSameDecl(SizeOfArg, DstArg))
3363 PatternType = 1;
3364 // - sizeof(src)
3365 else if (referToTheSameDecl(SizeOfArg, SrcArg))
3366 PatternType = 2;
3367 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
3368 if (BE->getOpcode() == BO_Sub) {
3369 const Expr *L = BE->getLHS()->IgnoreParenCasts();
3370 const Expr *R = BE->getRHS()->IgnoreParenCasts();
3371 // - sizeof(dst) - strlen(dst)
3372 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
3373 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
3374 PatternType = 1;
3375 // - sizeof(src) - (anything)
3376 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
3377 PatternType = 2;
3378 }
3379 }
3380
3381 if (PatternType == 0)
3382 return;
3383
Anna Zaksafdb0412012-02-03 01:27:37 +00003384 // Generate the diagnostic.
3385 SourceLocation SL = LenArg->getLocStart();
3386 SourceRange SR = LenArg->getSourceRange();
3387 SourceManager &SM = PP.getSourceManager();
3388
3389 // If the function is defined as a builtin macro, do not show macro expansion.
3390 if (SM.isMacroArgExpansion(SL)) {
3391 SL = SM.getSpellingLoc(SL);
3392 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
3393 SM.getSpellingLoc(SR.getEnd()));
3394 }
3395
Anna Zaks0f38ace2012-08-08 21:42:23 +00003396 // Check if the destination is an array (rather than a pointer to an array).
3397 QualType DstTy = DstArg->getType();
3398 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
3399 Context);
3400 if (!isKnownSizeArray) {
3401 if (PatternType == 1)
3402 Diag(SL, diag::warn_strncat_wrong_size) << SR;
3403 else
3404 Diag(SL, diag::warn_strncat_src_size) << SR;
3405 return;
3406 }
3407
Anna Zaksc36bedc2012-02-01 19:08:57 +00003408 if (PatternType == 1)
Anna Zaksafdb0412012-02-03 01:27:37 +00003409 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003410 else
Anna Zaksafdb0412012-02-03 01:27:37 +00003411 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003412
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003413 SmallString<128> sizeString;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003414 llvm::raw_svector_ostream OS(sizeString);
3415 OS << "sizeof(";
Richard Smithd1420c62012-08-16 03:56:14 +00003416 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003417 OS << ") - ";
3418 OS << "strlen(";
Richard Smithd1420c62012-08-16 03:56:14 +00003419 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003420 OS << ") - 1";
3421
Anna Zaksafdb0412012-02-03 01:27:37 +00003422 Diag(SL, diag::note_strncat_wrong_size)
3423 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003424}
3425
Ted Kremenek06de2762007-08-17 16:46:58 +00003426//===--- CHECK: Return Address of Stack Variable --------------------------===//
3427
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003428static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3429 Decl *ParentDecl);
3430static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
3431 Decl *ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003432
3433/// CheckReturnStackAddr - Check if a return statement returns the address
3434/// of a stack variable.
3435void
3436Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
3437 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00003438
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003439 Expr *stackE = 0;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003440 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003441
3442 // Perform checking for returned stack addresses, local blocks,
3443 // label addresses or references to temporaries.
John McCallf85e1932011-06-15 23:02:42 +00003444 if (lhsType->isPointerType() ||
David Blaikie4e4d0842012-03-11 07:00:24 +00003445 (!getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003446 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003447 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003448 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003449 }
3450
3451 if (stackE == 0)
3452 return; // Nothing suspicious was found.
3453
3454 SourceLocation diagLoc;
3455 SourceRange diagRange;
3456 if (refVars.empty()) {
3457 diagLoc = stackE->getLocStart();
3458 diagRange = stackE->getSourceRange();
3459 } else {
3460 // We followed through a reference variable. 'stackE' contains the
3461 // problematic expression but we will warn at the return statement pointing
3462 // at the reference variable. We will later display the "trail" of
3463 // reference variables using notes.
3464 diagLoc = refVars[0]->getLocStart();
3465 diagRange = refVars[0]->getSourceRange();
3466 }
3467
3468 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
3469 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
3470 : diag::warn_ret_stack_addr)
3471 << DR->getDecl()->getDeclName() << diagRange;
3472 } else if (isa<BlockExpr>(stackE)) { // local block.
3473 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
3474 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
3475 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
3476 } else { // local temporary.
3477 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
3478 : diag::warn_ret_local_temp_addr)
3479 << diagRange;
3480 }
3481
3482 // Display the "trail" of reference variables that we followed until we
3483 // found the problematic expression using notes.
3484 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
3485 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
3486 // If this var binds to another reference var, show the range of the next
3487 // var, otherwise the var binds to the problematic expression, in which case
3488 // show the range of the expression.
3489 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
3490 : stackE->getSourceRange();
3491 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
3492 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00003493 }
3494}
3495
3496/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
3497/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003498/// to a location on the stack, a local block, an address of a label, or a
3499/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00003500/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003501/// encounter a subexpression that (1) clearly does not lead to one of the
3502/// above problematic expressions (2) is something we cannot determine leads to
3503/// a problematic expression based on such local checking.
3504///
3505/// Both EvalAddr and EvalVal follow through reference variables to evaluate
3506/// the expression that they point to. Such variables are added to the
3507/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00003508///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00003509/// EvalAddr processes expressions that are pointers that are used as
3510/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003511/// At the base case of the recursion is a check for the above problematic
3512/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00003513///
3514/// This implementation handles:
3515///
3516/// * pointer-to-pointer casts
3517/// * implicit conversions from array references to pointers
3518/// * taking the address of fields
3519/// * arbitrary interplay between "&" and "*" operators
3520/// * pointer arithmetic from an address of a stack variable
3521/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003522static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3523 Decl *ParentDecl) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003524 if (E->isTypeDependent())
3525 return NULL;
3526
Ted Kremenek06de2762007-08-17 16:46:58 +00003527 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00003528 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00003529 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003530 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003531 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00003532
Peter Collingbournef111d932011-04-15 00:35:48 +00003533 E = E->IgnoreParens();
3534
Ted Kremenek06de2762007-08-17 16:46:58 +00003535 // Our "symbolic interpreter" is just a dispatch off the currently
3536 // viewed AST node. We then recursively traverse the AST by calling
3537 // EvalAddr and EvalVal appropriately.
3538 switch (E->getStmtClass()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003539 case Stmt::DeclRefExprClass: {
3540 DeclRefExpr *DR = cast<DeclRefExpr>(E);
3541
3542 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
3543 // If this is a reference variable, follow through to the expression that
3544 // it points to.
3545 if (V->hasLocalStorage() &&
3546 V->getType()->isReferenceType() && V->hasInit()) {
3547 // Add the reference variable to the "trail".
3548 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003549 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003550 }
3551
3552 return NULL;
3553 }
Ted Kremenek06de2762007-08-17 16:46:58 +00003554
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003555 case Stmt::UnaryOperatorClass: {
3556 // The only unary operator that make sense to handle here
3557 // is AddrOf. All others don't make sense as pointers.
3558 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003559
John McCall2de56d12010-08-25 11:45:40 +00003560 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003561 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003562 else
Ted Kremenek06de2762007-08-17 16:46:58 +00003563 return NULL;
3564 }
Mike Stump1eb44332009-09-09 15:08:12 +00003565
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003566 case Stmt::BinaryOperatorClass: {
3567 // Handle pointer arithmetic. All other binary operators are not valid
3568 // in this context.
3569 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00003570 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00003571
John McCall2de56d12010-08-25 11:45:40 +00003572 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003573 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00003574
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003575 Expr *Base = B->getLHS();
3576
3577 // Determine which argument is the real pointer base. It could be
3578 // the RHS argument instead of the LHS.
3579 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00003580
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003581 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003582 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003583 }
Steve Naroff61f40a22008-09-10 19:17:48 +00003584
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003585 // For conditional operators we need to see if either the LHS or RHS are
3586 // valid DeclRefExpr*s. If one of them is valid, we return it.
3587 case Stmt::ConditionalOperatorClass: {
3588 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003589
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003590 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003591 if (Expr *lhsExpr = C->getLHS()) {
3592 // In C++, we can have a throw-expression, which has 'void' type.
3593 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003594 if (Expr* LHS = EvalAddr(lhsExpr, refVars, ParentDecl))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003595 return LHS;
3596 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003597
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003598 // In C++, we can have a throw-expression, which has 'void' type.
3599 if (C->getRHS()->getType()->isVoidType())
3600 return NULL;
3601
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003602 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003603 }
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003604
3605 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00003606 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003607 return E; // local block.
3608 return NULL;
3609
3610 case Stmt::AddrLabelExprClass:
3611 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00003612
John McCall80ee6e82011-11-10 05:35:25 +00003613 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003614 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
3615 ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00003616
Ted Kremenek54b52742008-08-07 00:49:01 +00003617 // For casts, we need to handle conversions from arrays to
3618 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00003619 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00003620 case Stmt::CStyleCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00003621 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8b9414e2012-02-23 23:04:32 +00003622 case Stmt::ObjCBridgedCastExprClass:
Mike Stump1eb44332009-09-09 15:08:12 +00003623 case Stmt::CXXStaticCastExprClass:
3624 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00003625 case Stmt::CXXConstCastExprClass:
3626 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8b9414e2012-02-23 23:04:32 +00003627 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
3628 switch (cast<CastExpr>(E)->getCastKind()) {
3629 case CK_BitCast:
3630 case CK_LValueToRValue:
3631 case CK_NoOp:
3632 case CK_BaseToDerived:
3633 case CK_DerivedToBase:
3634 case CK_UncheckedDerivedToBase:
3635 case CK_Dynamic:
3636 case CK_CPointerToObjCPointerCast:
3637 case CK_BlockPointerToObjCPointerCast:
3638 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003639 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00003640
3641 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003642 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00003643
3644 default:
3645 return 0;
3646 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003647 }
Mike Stump1eb44332009-09-09 15:08:12 +00003648
Douglas Gregor03e80032011-06-21 17:03:29 +00003649 case Stmt::MaterializeTemporaryExprClass:
3650 if (Expr *Result = EvalAddr(
3651 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003652 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00003653 return Result;
3654
3655 return E;
3656
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003657 // Everything else: we simply don't reason about them.
3658 default:
3659 return NULL;
3660 }
Ted Kremenek06de2762007-08-17 16:46:58 +00003661}
Mike Stump1eb44332009-09-09 15:08:12 +00003662
Ted Kremenek06de2762007-08-17 16:46:58 +00003663
3664/// EvalVal - This function is complements EvalAddr in the mutual recursion.
3665/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003666static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3667 Decl *ParentDecl) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003668do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00003669 // We should only be called for evaluating non-pointer expressions, or
3670 // expressions with a pointer type that are not used as references but instead
3671 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00003672
Ted Kremenek06de2762007-08-17 16:46:58 +00003673 // Our "symbolic interpreter" is just a dispatch off the currently
3674 // viewed AST node. We then recursively traverse the AST by calling
3675 // EvalAddr and EvalVal appropriately.
Peter Collingbournef111d932011-04-15 00:35:48 +00003676
3677 E = E->IgnoreParens();
Ted Kremenek06de2762007-08-17 16:46:58 +00003678 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003679 case Stmt::ImplicitCastExprClass: {
3680 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00003681 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003682 E = IE->getSubExpr();
3683 continue;
3684 }
3685 return NULL;
3686 }
3687
John McCall80ee6e82011-11-10 05:35:25 +00003688 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003689 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00003690
Douglas Gregora2813ce2009-10-23 18:54:35 +00003691 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003692 // When we hit a DeclRefExpr we are looking at code that refers to a
3693 // variable's name. If it's not a reference variable we check if it has
3694 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00003695 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003696
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003697 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
3698 // Check if it refers to itself, e.g. "int& i = i;".
3699 if (V == ParentDecl)
3700 return DR;
3701
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003702 if (V->hasLocalStorage()) {
3703 if (!V->getType()->isReferenceType())
3704 return DR;
3705
3706 // Reference variable, follow through to the expression that
3707 // it points to.
3708 if (V->hasInit()) {
3709 // Add the reference variable to the "trail".
3710 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003711 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003712 }
3713 }
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003714 }
Mike Stump1eb44332009-09-09 15:08:12 +00003715
Ted Kremenek06de2762007-08-17 16:46:58 +00003716 return NULL;
3717 }
Mike Stump1eb44332009-09-09 15:08:12 +00003718
Ted Kremenek06de2762007-08-17 16:46:58 +00003719 case Stmt::UnaryOperatorClass: {
3720 // The only unary operator that make sense to handle here
3721 // is Deref. All others don't resolve to a "name." This includes
3722 // handling all sorts of rvalues passed to a unary operator.
3723 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003724
John McCall2de56d12010-08-25 11:45:40 +00003725 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003726 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003727
3728 return NULL;
3729 }
Mike Stump1eb44332009-09-09 15:08:12 +00003730
Ted Kremenek06de2762007-08-17 16:46:58 +00003731 case Stmt::ArraySubscriptExprClass: {
3732 // Array subscripts are potential references to data on the stack. We
3733 // retrieve the DeclRefExpr* for the array variable if it indeed
3734 // has local storage.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003735 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003736 }
Mike Stump1eb44332009-09-09 15:08:12 +00003737
Ted Kremenek06de2762007-08-17 16:46:58 +00003738 case Stmt::ConditionalOperatorClass: {
3739 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003740 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00003741 ConditionalOperator *C = cast<ConditionalOperator>(E);
3742
Anders Carlsson39073232007-11-30 19:04:31 +00003743 // Handle the GNU extension for missing LHS.
3744 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003745 if (Expr *LHS = EvalVal(lhsExpr, refVars, ParentDecl))
Anders Carlsson39073232007-11-30 19:04:31 +00003746 return LHS;
3747
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003748 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003749 }
Mike Stump1eb44332009-09-09 15:08:12 +00003750
Ted Kremenek06de2762007-08-17 16:46:58 +00003751 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00003752 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00003753 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003754
Ted Kremenek06de2762007-08-17 16:46:58 +00003755 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00003756 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00003757 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00003758
3759 // Check whether the member type is itself a reference, in which case
3760 // we're not going to refer to the member, but to what the member refers to.
3761 if (M->getMemberDecl()->getType()->isReferenceType())
3762 return NULL;
3763
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003764 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003765 }
Mike Stump1eb44332009-09-09 15:08:12 +00003766
Douglas Gregor03e80032011-06-21 17:03:29 +00003767 case Stmt::MaterializeTemporaryExprClass:
3768 if (Expr *Result = EvalVal(
3769 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003770 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00003771 return Result;
3772
3773 return E;
3774
Ted Kremenek06de2762007-08-17 16:46:58 +00003775 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003776 // Check that we don't return or take the address of a reference to a
3777 // temporary. This is only useful in C++.
3778 if (!E->isTypeDependent() && E->isRValue())
3779 return E;
3780
3781 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00003782 return NULL;
3783 }
Ted Kremenek68957a92010-08-04 20:01:07 +00003784} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00003785}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003786
3787//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
3788
3789/// Check for comparisons of floating point operands using != and ==.
3790/// Issue a warning if these are no self-comparisons, as they are not likely
3791/// to do what the programmer intended.
Richard Trieudd225092011-09-15 21:56:47 +00003792void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieudd225092011-09-15 21:56:47 +00003793 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
3794 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003795
3796 // Special case: check for x == x (which is OK).
3797 // Do not emit warnings for such cases.
3798 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
3799 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
3800 if (DRL->getDecl() == DRR->getDecl())
David Blaikie980343b2012-07-16 20:47:22 +00003801 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003802
3803
Ted Kremenek1b500bb2007-11-29 00:59:04 +00003804 // Special case: check for comparisons against literals that can be exactly
3805 // represented by APFloat. In such cases, do not emit a warning. This
3806 // is a heuristic: often comparison against such literals are used to
3807 // detect if a value in a variable has not changed. This clearly can
3808 // lead to false negatives.
David Blaikie980343b2012-07-16 20:47:22 +00003809 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
3810 if (FLL->isExact())
3811 return;
3812 } else
3813 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
3814 if (FLR->isExact())
3815 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003816
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003817 // Check for comparisons with builtin types.
David Blaikie980343b2012-07-16 20:47:22 +00003818 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
3819 if (CL->isBuiltinCall())
3820 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003821
David Blaikie980343b2012-07-16 20:47:22 +00003822 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
3823 if (CR->isBuiltinCall())
3824 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003825
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003826 // Emit the diagnostic.
David Blaikie980343b2012-07-16 20:47:22 +00003827 Diag(Loc, diag::warn_floatingpoint_eq)
3828 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003829}
John McCallba26e582010-01-04 23:21:16 +00003830
John McCallf2370c92010-01-06 05:24:50 +00003831//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
3832//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00003833
John McCallf2370c92010-01-06 05:24:50 +00003834namespace {
John McCallba26e582010-01-04 23:21:16 +00003835
John McCallf2370c92010-01-06 05:24:50 +00003836/// Structure recording the 'active' range of an integer-valued
3837/// expression.
3838struct IntRange {
3839 /// The number of bits active in the int.
3840 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00003841
John McCallf2370c92010-01-06 05:24:50 +00003842 /// True if the int is known not to have negative values.
3843 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00003844
John McCallf2370c92010-01-06 05:24:50 +00003845 IntRange(unsigned Width, bool NonNegative)
3846 : Width(Width), NonNegative(NonNegative)
3847 {}
John McCallba26e582010-01-04 23:21:16 +00003848
John McCall1844a6e2010-11-10 23:38:19 +00003849 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00003850 static IntRange forBoolType() {
3851 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00003852 }
3853
John McCall1844a6e2010-11-10 23:38:19 +00003854 /// Returns the range of an opaque value of the given integral type.
3855 static IntRange forValueOfType(ASTContext &C, QualType T) {
3856 return forValueOfCanonicalType(C,
3857 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00003858 }
3859
John McCall1844a6e2010-11-10 23:38:19 +00003860 /// Returns the range of an opaque value of a canonical integral type.
3861 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00003862 assert(T->isCanonicalUnqualified());
3863
3864 if (const VectorType *VT = dyn_cast<VectorType>(T))
3865 T = VT->getElementType().getTypePtr();
3866 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
3867 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00003868
John McCall091f23f2010-11-09 22:22:12 +00003869 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00003870 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
3871 EnumDecl *Enum = ET->getDecl();
John McCall5e1cdac2011-10-07 06:10:15 +00003872 if (!Enum->isCompleteDefinition())
John McCall091f23f2010-11-09 22:22:12 +00003873 return IntRange(C.getIntWidth(QualType(T, 0)), false);
3874
John McCall323ed742010-05-06 08:58:33 +00003875 unsigned NumPositive = Enum->getNumPositiveBits();
3876 unsigned NumNegative = Enum->getNumNegativeBits();
3877
3878 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
3879 }
John McCallf2370c92010-01-06 05:24:50 +00003880
3881 const BuiltinType *BT = cast<BuiltinType>(T);
3882 assert(BT->isInteger());
3883
3884 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
3885 }
3886
John McCall1844a6e2010-11-10 23:38:19 +00003887 /// Returns the "target" range of a canonical integral type, i.e.
3888 /// the range of values expressible in the type.
3889 ///
3890 /// This matches forValueOfCanonicalType except that enums have the
3891 /// full range of their type, not the range of their enumerators.
3892 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
3893 assert(T->isCanonicalUnqualified());
3894
3895 if (const VectorType *VT = dyn_cast<VectorType>(T))
3896 T = VT->getElementType().getTypePtr();
3897 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
3898 T = CT->getElementType().getTypePtr();
3899 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor69ff26b2011-09-08 23:29:05 +00003900 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall1844a6e2010-11-10 23:38:19 +00003901
3902 const BuiltinType *BT = cast<BuiltinType>(T);
3903 assert(BT->isInteger());
3904
3905 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
3906 }
3907
3908 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00003909 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00003910 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00003911 L.NonNegative && R.NonNegative);
3912 }
3913
John McCall1844a6e2010-11-10 23:38:19 +00003914 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00003915 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00003916 return IntRange(std::min(L.Width, R.Width),
3917 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00003918 }
3919};
3920
Ted Kremenek0692a192012-01-31 05:37:37 +00003921static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
3922 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00003923 if (value.isSigned() && value.isNegative())
3924 return IntRange(value.getMinSignedBits(), false);
3925
3926 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00003927 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00003928
3929 // isNonNegative() just checks the sign bit without considering
3930 // signedness.
3931 return IntRange(value.getActiveBits(), true);
3932}
3933
Ted Kremenek0692a192012-01-31 05:37:37 +00003934static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
3935 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00003936 if (result.isInt())
3937 return GetValueRange(C, result.getInt(), MaxWidth);
3938
3939 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00003940 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
3941 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
3942 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
3943 R = IntRange::join(R, El);
3944 }
John McCallf2370c92010-01-06 05:24:50 +00003945 return R;
3946 }
3947
3948 if (result.isComplexInt()) {
3949 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
3950 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
3951 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00003952 }
3953
3954 // This can happen with lossless casts to intptr_t of "based" lvalues.
3955 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00003956 // FIXME: The only reason we need to pass the type in here is to get
3957 // the sign right on this one case. It would be nice if APValue
3958 // preserved this.
Eli Friedman65639282012-01-04 23:13:47 +00003959 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00003960 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall51313c32010-01-04 23:31:57 +00003961}
John McCallf2370c92010-01-06 05:24:50 +00003962
3963/// Pseudo-evaluate the given integer expression, estimating the
3964/// range of values it might take.
3965///
3966/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek0692a192012-01-31 05:37:37 +00003967static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00003968 E = E->IgnoreParens();
3969
3970 // Try a full evaluation first.
3971 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00003972 if (E->EvaluateAsRValue(result, C))
John McCall0acc3112010-01-06 22:57:21 +00003973 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00003974
3975 // I think we only want to look through implicit casts here; if the
3976 // user has an explicit widening cast, we should treat the value as
3977 // being of the new, wider type.
3978 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedmanb17ee5b2011-12-15 02:41:52 +00003979 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCallf2370c92010-01-06 05:24:50 +00003980 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
3981
John McCall1844a6e2010-11-10 23:38:19 +00003982 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
John McCallf2370c92010-01-06 05:24:50 +00003983
John McCall2de56d12010-08-25 11:45:40 +00003984 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00003985
John McCallf2370c92010-01-06 05:24:50 +00003986 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00003987 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00003988 return OutputTypeRange;
3989
3990 IntRange SubRange
3991 = GetExprRange(C, CE->getSubExpr(),
3992 std::min(MaxWidth, OutputTypeRange.Width));
3993
3994 // Bail out if the subexpr's range is as wide as the cast type.
3995 if (SubRange.Width >= OutputTypeRange.Width)
3996 return OutputTypeRange;
3997
3998 // Otherwise, we take the smaller width, and we're non-negative if
3999 // either the output type or the subexpr is.
4000 return IntRange(SubRange.Width,
4001 SubRange.NonNegative || OutputTypeRange.NonNegative);
4002 }
4003
4004 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4005 // If we can fold the condition, just take that operand.
4006 bool CondResult;
4007 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
4008 return GetExprRange(C, CondResult ? CO->getTrueExpr()
4009 : CO->getFalseExpr(),
4010 MaxWidth);
4011
4012 // Otherwise, conservatively merge.
4013 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
4014 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
4015 return IntRange::join(L, R);
4016 }
4017
4018 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4019 switch (BO->getOpcode()) {
4020
4021 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00004022 case BO_LAnd:
4023 case BO_LOr:
4024 case BO_LT:
4025 case BO_GT:
4026 case BO_LE:
4027 case BO_GE:
4028 case BO_EQ:
4029 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00004030 return IntRange::forBoolType();
4031
John McCall862ff872011-07-13 06:35:24 +00004032 // The type of the assignments is the type of the LHS, so the RHS
4033 // is not necessarily the same type.
John McCall2de56d12010-08-25 11:45:40 +00004034 case BO_MulAssign:
4035 case BO_DivAssign:
4036 case BO_RemAssign:
4037 case BO_AddAssign:
4038 case BO_SubAssign:
John McCall862ff872011-07-13 06:35:24 +00004039 case BO_XorAssign:
4040 case BO_OrAssign:
4041 // TODO: bitfields?
John McCall1844a6e2010-11-10 23:38:19 +00004042 return IntRange::forValueOfType(C, E->getType());
John McCallc0cd21d2010-02-23 19:22:29 +00004043
John McCall862ff872011-07-13 06:35:24 +00004044 // Simple assignments just pass through the RHS, which will have
4045 // been coerced to the LHS type.
4046 case BO_Assign:
4047 // TODO: bitfields?
4048 return GetExprRange(C, BO->getRHS(), MaxWidth);
4049
John McCallf2370c92010-01-06 05:24:50 +00004050 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00004051 case BO_PtrMemD:
4052 case BO_PtrMemI:
John McCall1844a6e2010-11-10 23:38:19 +00004053 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00004054
John McCall60fad452010-01-06 22:07:33 +00004055 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00004056 case BO_And:
4057 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00004058 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
4059 GetExprRange(C, BO->getRHS(), MaxWidth));
4060
John McCallf2370c92010-01-06 05:24:50 +00004061 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00004062 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00004063 // ...except that we want to treat '1 << (blah)' as logically
4064 // positive. It's an important idiom.
4065 if (IntegerLiteral *I
4066 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
4067 if (I->getValue() == 1) {
John McCall1844a6e2010-11-10 23:38:19 +00004068 IntRange R = IntRange::forValueOfType(C, E->getType());
John McCall3aae6092010-04-07 01:14:35 +00004069 return IntRange(R.Width, /*NonNegative*/ true);
4070 }
4071 }
4072 // fallthrough
4073
John McCall2de56d12010-08-25 11:45:40 +00004074 case BO_ShlAssign:
John McCall1844a6e2010-11-10 23:38:19 +00004075 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00004076
John McCall60fad452010-01-06 22:07:33 +00004077 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00004078 case BO_Shr:
4079 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00004080 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4081
4082 // If the shift amount is a positive constant, drop the width by
4083 // that much.
4084 llvm::APSInt shift;
4085 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
4086 shift.isNonNegative()) {
4087 unsigned zext = shift.getZExtValue();
4088 if (zext >= L.Width)
4089 L.Width = (L.NonNegative ? 0 : 1);
4090 else
4091 L.Width -= zext;
4092 }
4093
4094 return L;
4095 }
4096
4097 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00004098 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00004099 return GetExprRange(C, BO->getRHS(), MaxWidth);
4100
John McCall60fad452010-01-06 22:07:33 +00004101 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00004102 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00004103 if (BO->getLHS()->getType()->isPointerType())
John McCall1844a6e2010-11-10 23:38:19 +00004104 return IntRange::forValueOfType(C, E->getType());
John McCall00fe7612011-07-14 22:39:48 +00004105 break;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00004106
John McCall00fe7612011-07-14 22:39:48 +00004107 // The width of a division result is mostly determined by the size
4108 // of the LHS.
4109 case BO_Div: {
4110 // Don't 'pre-truncate' the operands.
4111 unsigned opWidth = C.getIntWidth(E->getType());
4112 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4113
4114 // If the divisor is constant, use that.
4115 llvm::APSInt divisor;
4116 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
4117 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
4118 if (log2 >= L.Width)
4119 L.Width = (L.NonNegative ? 0 : 1);
4120 else
4121 L.Width = std::min(L.Width - log2, MaxWidth);
4122 return L;
4123 }
4124
4125 // Otherwise, just use the LHS's width.
4126 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4127 return IntRange(L.Width, L.NonNegative && R.NonNegative);
4128 }
4129
4130 // The result of a remainder can't be larger than the result of
4131 // either side.
4132 case BO_Rem: {
4133 // Don't 'pre-truncate' the operands.
4134 unsigned opWidth = C.getIntWidth(E->getType());
4135 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4136 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4137
4138 IntRange meet = IntRange::meet(L, R);
4139 meet.Width = std::min(meet.Width, MaxWidth);
4140 return meet;
4141 }
4142
4143 // The default behavior is okay for these.
4144 case BO_Mul:
4145 case BO_Add:
4146 case BO_Xor:
4147 case BO_Or:
John McCallf2370c92010-01-06 05:24:50 +00004148 break;
4149 }
4150
John McCall00fe7612011-07-14 22:39:48 +00004151 // The default case is to treat the operation as if it were closed
4152 // on the narrowest type that encompasses both operands.
John McCallf2370c92010-01-06 05:24:50 +00004153 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4154 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
4155 return IntRange::join(L, R);
4156 }
4157
4158 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
4159 switch (UO->getOpcode()) {
4160 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00004161 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00004162 return IntRange::forBoolType();
4163
4164 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00004165 case UO_Deref:
4166 case UO_AddrOf: // should be impossible
John McCall1844a6e2010-11-10 23:38:19 +00004167 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00004168
4169 default:
4170 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
4171 }
4172 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004173
4174 if (dyn_cast<OffsetOfExpr>(E)) {
John McCall1844a6e2010-11-10 23:38:19 +00004175 IntRange::forValueOfType(C, E->getType());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004176 }
John McCallf2370c92010-01-06 05:24:50 +00004177
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004178 if (FieldDecl *BitField = E->getBitField())
4179 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00004180 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCallf2370c92010-01-06 05:24:50 +00004181
John McCall1844a6e2010-11-10 23:38:19 +00004182 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00004183}
John McCall51313c32010-01-04 23:31:57 +00004184
Ted Kremenek0692a192012-01-31 05:37:37 +00004185static IntRange GetExprRange(ASTContext &C, Expr *E) {
John McCall323ed742010-05-06 08:58:33 +00004186 return GetExprRange(C, E, C.getIntWidth(E->getType()));
4187}
4188
John McCall51313c32010-01-04 23:31:57 +00004189/// Checks whether the given value, which currently has the given
4190/// source semantics, has the same value when coerced through the
4191/// target semantics.
Ted Kremenek0692a192012-01-31 05:37:37 +00004192static bool IsSameFloatAfterCast(const llvm::APFloat &value,
4193 const llvm::fltSemantics &Src,
4194 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00004195 llvm::APFloat truncated = value;
4196
4197 bool ignored;
4198 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
4199 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
4200
4201 return truncated.bitwiseIsEqual(value);
4202}
4203
4204/// Checks whether the given value, which currently has the given
4205/// source semantics, has the same value when coerced through the
4206/// target semantics.
4207///
4208/// The value might be a vector of floats (or a complex number).
Ted Kremenek0692a192012-01-31 05:37:37 +00004209static bool IsSameFloatAfterCast(const APValue &value,
4210 const llvm::fltSemantics &Src,
4211 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00004212 if (value.isFloat())
4213 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
4214
4215 if (value.isVector()) {
4216 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
4217 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
4218 return false;
4219 return true;
4220 }
4221
4222 assert(value.isComplexFloat());
4223 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
4224 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
4225}
4226
Ted Kremenek0692a192012-01-31 05:37:37 +00004227static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00004228
Ted Kremeneke3b159c2010-09-23 21:43:44 +00004229static bool IsZero(Sema &S, Expr *E) {
4230 // Suppress cases where we are comparing against an enum constant.
4231 if (const DeclRefExpr *DR =
4232 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
4233 if (isa<EnumConstantDecl>(DR->getDecl()))
4234 return false;
4235
4236 // Suppress cases where the '0' value is expanded from a macro.
4237 if (E->getLocStart().isMacroID())
4238 return false;
4239
John McCall323ed742010-05-06 08:58:33 +00004240 llvm::APSInt Value;
4241 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
4242}
4243
John McCall372e1032010-10-06 00:25:24 +00004244static bool HasEnumType(Expr *E) {
4245 // Strip off implicit integral promotions.
4246 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00004247 if (ICE->getCastKind() != CK_IntegralCast &&
4248 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00004249 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00004250 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00004251 }
4252
4253 return E->getType()->isEnumeralType();
4254}
4255
Ted Kremenek0692a192012-01-31 05:37:37 +00004256static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00004257 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00004258 if (E->isValueDependent())
4259 return;
4260
John McCall2de56d12010-08-25 11:45:40 +00004261 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00004262 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004263 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00004264 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004265 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00004266 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004267 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00004268 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004269 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00004270 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004271 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00004272 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004273 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00004274 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004275 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00004276 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4277 }
4278}
4279
4280/// Analyze the operands of the given comparison. Implements the
4281/// fallback case from AnalyzeComparison.
Ted Kremenek0692a192012-01-31 05:37:37 +00004282static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00004283 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
4284 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00004285}
John McCall51313c32010-01-04 23:31:57 +00004286
John McCallba26e582010-01-04 23:21:16 +00004287/// \brief Implements -Wsign-compare.
4288///
Richard Trieudd225092011-09-15 21:56:47 +00004289/// \param E the binary operator to check for warnings
Ted Kremenek0692a192012-01-31 05:37:37 +00004290static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCall323ed742010-05-06 08:58:33 +00004291 // The type the comparison is being performed in.
4292 QualType T = E->getLHS()->getType();
4293 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
4294 && "comparison with mismatched types");
John McCallba26e582010-01-04 23:21:16 +00004295
John McCall323ed742010-05-06 08:58:33 +00004296 // We don't do anything special if this isn't an unsigned integral
4297 // comparison: we're only interested in integral comparisons, and
4298 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00004299 //
4300 // We also don't care about value-dependent expressions or expressions
4301 // whose result is a constant.
4302 if (!T->hasUnsignedIntegerRepresentation()
4303 || E->isValueDependent() || E->isIntegerConstantExpr(S.Context))
John McCall323ed742010-05-06 08:58:33 +00004304 return AnalyzeImpConvsInComparison(S, E);
John McCallf2370c92010-01-06 05:24:50 +00004305
Richard Trieudd225092011-09-15 21:56:47 +00004306 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
4307 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
John McCallba26e582010-01-04 23:21:16 +00004308
John McCall323ed742010-05-06 08:58:33 +00004309 // Check to see if one of the (unmodified) operands is of different
4310 // signedness.
4311 Expr *signedOperand, *unsignedOperand;
Richard Trieudd225092011-09-15 21:56:47 +00004312 if (LHS->getType()->hasSignedIntegerRepresentation()) {
4313 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00004314 "unsigned comparison between two signed integer expressions?");
Richard Trieudd225092011-09-15 21:56:47 +00004315 signedOperand = LHS;
4316 unsignedOperand = RHS;
4317 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
4318 signedOperand = RHS;
4319 unsignedOperand = LHS;
John McCallba26e582010-01-04 23:21:16 +00004320 } else {
John McCall323ed742010-05-06 08:58:33 +00004321 CheckTrivialUnsignedComparison(S, E);
4322 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004323 }
4324
John McCall323ed742010-05-06 08:58:33 +00004325 // Otherwise, calculate the effective range of the signed operand.
4326 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00004327
John McCall323ed742010-05-06 08:58:33 +00004328 // Go ahead and analyze implicit conversions in the operands. Note
4329 // that we skip the implicit conversions on both sides.
Richard Trieudd225092011-09-15 21:56:47 +00004330 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
4331 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00004332
John McCall323ed742010-05-06 08:58:33 +00004333 // If the signed range is non-negative, -Wsign-compare won't fire,
4334 // but we should still check for comparisons which are always true
4335 // or false.
4336 if (signedRange.NonNegative)
4337 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004338
4339 // For (in)equality comparisons, if the unsigned operand is a
4340 // constant which cannot collide with a overflowed signed operand,
4341 // then reinterpreting the signed operand as unsigned will not
4342 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00004343 if (E->isEqualityOp()) {
4344 unsigned comparisonWidth = S.Context.getIntWidth(T);
4345 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00004346
John McCall323ed742010-05-06 08:58:33 +00004347 // We should never be unable to prove that the unsigned operand is
4348 // non-negative.
4349 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
4350
4351 if (unsignedRange.Width < comparisonWidth)
4352 return;
4353 }
4354
Douglas Gregor6d3b93d2012-05-01 01:53:49 +00004355 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
4356 S.PDiag(diag::warn_mixed_sign_comparison)
4357 << LHS->getType() << RHS->getType()
4358 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallba26e582010-01-04 23:21:16 +00004359}
4360
John McCall15d7d122010-11-11 03:21:53 +00004361/// Analyzes an attempt to assign the given value to a bitfield.
4362///
4363/// Returns true if there was something fishy about the attempt.
Ted Kremenek0692a192012-01-31 05:37:37 +00004364static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
4365 SourceLocation InitLoc) {
John McCall15d7d122010-11-11 03:21:53 +00004366 assert(Bitfield->isBitField());
4367 if (Bitfield->isInvalidDecl())
4368 return false;
4369
John McCall91b60142010-11-11 05:33:51 +00004370 // White-list bool bitfields.
4371 if (Bitfield->getType()->isBooleanType())
4372 return false;
4373
Douglas Gregor46ff3032011-02-04 13:09:01 +00004374 // Ignore value- or type-dependent expressions.
4375 if (Bitfield->getBitWidth()->isValueDependent() ||
4376 Bitfield->getBitWidth()->isTypeDependent() ||
4377 Init->isValueDependent() ||
4378 Init->isTypeDependent())
4379 return false;
4380
John McCall15d7d122010-11-11 03:21:53 +00004381 Expr *OriginalInit = Init->IgnoreParenImpCasts();
4382
Richard Smith80d4b552011-12-28 19:48:30 +00004383 llvm::APSInt Value;
4384 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall15d7d122010-11-11 03:21:53 +00004385 return false;
4386
John McCall15d7d122010-11-11 03:21:53 +00004387 unsigned OriginalWidth = Value.getBitWidth();
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004388 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall15d7d122010-11-11 03:21:53 +00004389
4390 if (OriginalWidth <= FieldWidth)
4391 return false;
4392
Eli Friedman3a643af2012-01-26 23:11:39 +00004393 // Compute the value which the bitfield will contain.
Jay Foad9f71a8f2010-12-07 08:25:34 +00004394 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedman3a643af2012-01-26 23:11:39 +00004395 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall15d7d122010-11-11 03:21:53 +00004396
Eli Friedman3a643af2012-01-26 23:11:39 +00004397 // Check whether the stored value is equal to the original value.
4398 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieue1ecdc12012-07-23 20:21:35 +00004399 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall15d7d122010-11-11 03:21:53 +00004400 return false;
4401
Eli Friedman3a643af2012-01-26 23:11:39 +00004402 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedman34ff0622012-02-02 00:40:20 +00004403 // therefore don't strictly fit into a signed bitfield of width 1.
4404 if (FieldWidth == 1 && Value == 1)
Eli Friedman3a643af2012-01-26 23:11:39 +00004405 return false;
4406
John McCall15d7d122010-11-11 03:21:53 +00004407 std::string PrettyValue = Value.toString(10);
4408 std::string PrettyTrunc = TruncatedValue.toString(10);
4409
4410 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
4411 << PrettyValue << PrettyTrunc << OriginalInit->getType()
4412 << Init->getSourceRange();
4413
4414 return true;
4415}
4416
John McCallbeb22aa2010-11-09 23:24:47 +00004417/// Analyze the given simple or compound assignment for warning-worthy
4418/// operations.
Ted Kremenek0692a192012-01-31 05:37:37 +00004419static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCallbeb22aa2010-11-09 23:24:47 +00004420 // Just recurse on the LHS.
4421 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
4422
4423 // We want to recurse on the RHS as normal unless we're assigning to
4424 // a bitfield.
4425 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
John McCall15d7d122010-11-11 03:21:53 +00004426 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
4427 E->getOperatorLoc())) {
4428 // Recurse, ignoring any implicit conversions on the RHS.
4429 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
4430 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00004431 }
4432 }
4433
4434 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
4435}
4436
John McCall51313c32010-01-04 23:31:57 +00004437/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00004438static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00004439 SourceLocation CContext, unsigned diag,
4440 bool pruneControlFlow = false) {
4441 if (pruneControlFlow) {
4442 S.DiagRuntimeBehavior(E->getExprLoc(), E,
4443 S.PDiag(diag)
4444 << SourceType << T << E->getSourceRange()
4445 << SourceRange(CContext));
4446 return;
4447 }
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004448 S.Diag(E->getExprLoc(), diag)
4449 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
4450}
4451
Chandler Carruthe1b02e02011-04-05 06:47:57 +00004452/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00004453static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00004454 SourceLocation CContext, unsigned diag,
4455 bool pruneControlFlow = false) {
4456 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruthe1b02e02011-04-05 06:47:57 +00004457}
4458
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004459/// Diagnose an implicit cast from a literal expression. Does not warn when the
4460/// cast wouldn't lose information.
Chandler Carruthf65076e2011-04-10 08:36:24 +00004461void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
4462 SourceLocation CContext) {
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004463 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruthf65076e2011-04-10 08:36:24 +00004464 bool isExact = false;
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004465 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00004466 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
4467 T->hasUnsignedIntegerRepresentation());
4468 if (Value.convertToInteger(IntegerValue,
Chandler Carruthf65076e2011-04-10 08:36:24 +00004469 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004470 == llvm::APFloat::opOK && isExact)
Chandler Carruthf65076e2011-04-10 08:36:24 +00004471 return;
4472
David Blaikiebe0ee872012-05-15 16:56:36 +00004473 SmallString<16> PrettySourceValue;
4474 Value.toString(PrettySourceValue);
David Blaikiede7e7b82012-05-15 17:18:27 +00004475 SmallString<16> PrettyTargetValue;
David Blaikiebe0ee872012-05-15 16:56:36 +00004476 if (T->isSpecificBuiltinType(BuiltinType::Bool))
4477 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
4478 else
David Blaikiede7e7b82012-05-15 17:18:27 +00004479 IntegerValue.toString(PrettyTargetValue);
David Blaikiebe0ee872012-05-15 16:56:36 +00004480
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004481 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikiebe0ee872012-05-15 16:56:36 +00004482 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
4483 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruthf65076e2011-04-10 08:36:24 +00004484}
4485
John McCall091f23f2010-11-09 22:22:12 +00004486std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
4487 if (!Range.Width) return "0";
4488
4489 llvm::APSInt ValueInRange = Value;
4490 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00004491 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00004492 return ValueInRange.toString(10);
4493}
4494
Hans Wennborg88617a22012-08-28 15:44:30 +00004495static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
4496 if (!isa<ImplicitCastExpr>(Ex))
4497 return false;
4498
4499 Expr *InnerE = Ex->IgnoreParenImpCasts();
4500 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
4501 const Type *Source =
4502 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
4503 if (Target->isDependentType())
4504 return false;
4505
4506 const BuiltinType *FloatCandidateBT =
4507 dyn_cast<BuiltinType>(ToBool ? Source : Target);
4508 const Type *BoolCandidateType = ToBool ? Target : Source;
4509
4510 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
4511 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
4512}
4513
4514void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
4515 SourceLocation CC) {
4516 unsigned NumArgs = TheCall->getNumArgs();
4517 for (unsigned i = 0; i < NumArgs; ++i) {
4518 Expr *CurrA = TheCall->getArg(i);
4519 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
4520 continue;
4521
4522 bool IsSwapped = ((i > 0) &&
4523 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
4524 IsSwapped |= ((i < (NumArgs - 1)) &&
4525 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
4526 if (IsSwapped) {
4527 // Warn on this floating-point to bool conversion.
4528 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
4529 CurrA->getType(), CC,
4530 diag::warn_impcast_floating_point_to_bool);
4531 }
4532 }
4533}
4534
John McCall323ed742010-05-06 08:58:33 +00004535void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00004536 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00004537 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00004538
John McCall323ed742010-05-06 08:58:33 +00004539 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
4540 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
4541 if (Source == Target) return;
4542 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00004543
Chandler Carruth108f7562011-07-26 05:40:03 +00004544 // If the conversion context location is invalid don't complain. We also
4545 // don't want to emit a warning if the issue occurs from the expansion of
4546 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
4547 // delay this check as long as possible. Once we detect we are in that
4548 // scenario, we just return.
Ted Kremenekef9ff882011-03-10 20:03:42 +00004549 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00004550 return;
4551
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004552 // Diagnose implicit casts to bool.
4553 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
4554 if (isa<StringLiteral>(E))
4555 // Warn on string literal to bool. Checks for string literals in logical
4556 // expressions, for instances, assert(0 && "error here"), is prevented
4557 // by a check in AnalyzeImplicitConversions().
4558 return DiagnoseImpCast(S, E, T, CC,
4559 diag::warn_impcast_string_literal_to_bool);
Lang Hamese14ca9f2011-12-05 20:49:50 +00004560 if (Source->isFunctionType()) {
4561 // Warn on function to bool. Checks free functions and static member
4562 // functions. Weakly imported functions are excluded from the check,
4563 // since it's common to test their value to check whether the linker
4564 // found a definition for them.
4565 ValueDecl *D = 0;
4566 if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
4567 D = R->getDecl();
4568 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
4569 D = M->getMemberDecl();
4570 }
4571
4572 if (D && !D->isWeak()) {
Richard Trieu26b45d82011-12-06 04:48:01 +00004573 if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
4574 S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
4575 << F << E->getSourceRange() << SourceRange(CC);
David Blaikie2def7732011-12-09 21:42:37 +00004576 S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
4577 << FixItHint::CreateInsertion(E->getExprLoc(), "&");
4578 QualType ReturnType;
4579 UnresolvedSet<4> NonTemplateOverloads;
4580 S.isExprCallable(*E, ReturnType, NonTemplateOverloads);
4581 if (!ReturnType.isNull()
4582 && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
4583 S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
4584 << FixItHint::CreateInsertion(
4585 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu26b45d82011-12-06 04:48:01 +00004586 return;
4587 }
Lang Hamese14ca9f2011-12-05 20:49:50 +00004588 }
4589 }
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004590 }
John McCall51313c32010-01-04 23:31:57 +00004591
4592 // Strip vector types.
4593 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004594 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004595 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004596 return;
John McCallb4eb64d2010-10-08 02:01:28 +00004597 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004598 }
Chris Lattnerb792b302011-06-14 04:51:15 +00004599
4600 // If the vector cast is cast between two vectors of the same size, it is
4601 // a bitcast, not a conversion.
4602 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
4603 return;
John McCall51313c32010-01-04 23:31:57 +00004604
4605 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
4606 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
4607 }
4608
4609 // Strip complex types.
4610 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004611 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004612 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004613 return;
4614
John McCallb4eb64d2010-10-08 02:01:28 +00004615 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004616 }
John McCall51313c32010-01-04 23:31:57 +00004617
4618 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
4619 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
4620 }
4621
4622 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
4623 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
4624
4625 // If the source is floating point...
4626 if (SourceBT && SourceBT->isFloatingPoint()) {
4627 // ...and the target is floating point...
4628 if (TargetBT && TargetBT->isFloatingPoint()) {
4629 // ...then warn if we're dropping FP rank.
4630
4631 // Builtin FP kinds are ordered by increasing FP rank.
4632 if (SourceBT->getKind() > TargetBT->getKind()) {
4633 // Don't warn about float constants that are precisely
4634 // representable in the target type.
4635 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00004636 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00004637 // Value might be a float, a float vector, or a float complex.
4638 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00004639 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
4640 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00004641 return;
4642 }
4643
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004644 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004645 return;
4646
John McCallb4eb64d2010-10-08 02:01:28 +00004647 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00004648 }
4649 return;
4650 }
4651
Ted Kremenekef9ff882011-03-10 20:03:42 +00004652 // If the target is integral, always warn.
David Blaikiebe0ee872012-05-15 16:56:36 +00004653 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004654 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004655 return;
4656
Chandler Carrutha5b93322011-02-17 11:05:49 +00004657 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay634c8af2011-09-08 22:30:47 +00004658 // We also want to warn on, e.g., "int i = -1.234"
4659 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
4660 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
4661 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
4662
Chandler Carruthf65076e2011-04-10 08:36:24 +00004663 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
4664 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00004665 } else {
4666 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
4667 }
4668 }
John McCall51313c32010-01-04 23:31:57 +00004669
Hans Wennborg88617a22012-08-28 15:44:30 +00004670 // If the target is bool, warn if expr is a function or method call.
4671 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
4672 isa<CallExpr>(E)) {
4673 // Check last argument of function call to see if it is an
4674 // implicit cast from a type matching the type the result
4675 // is being cast to.
4676 CallExpr *CEx = cast<CallExpr>(E);
4677 unsigned NumArgs = CEx->getNumArgs();
4678 if (NumArgs > 0) {
4679 Expr *LastA = CEx->getArg(NumArgs - 1);
4680 Expr *InnerE = LastA->IgnoreParenImpCasts();
4681 const Type *InnerType =
4682 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
4683 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
4684 // Warn on this floating-point to bool conversion
4685 DiagnoseImpCast(S, E, T, CC,
4686 diag::warn_impcast_floating_point_to_bool);
4687 }
4688 }
4689 }
John McCall51313c32010-01-04 23:31:57 +00004690 return;
4691 }
4692
Richard Trieu1838ca52011-05-29 19:59:02 +00004693 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
David Blaikieb26331b2012-06-19 21:19:06 +00004694 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
David Blaikie28a5f0c2012-06-21 18:51:10 +00004695 && !Target->isBlockPointerType() && !Target->isMemberPointerType()) {
David Blaikieb1360492012-03-16 20:30:12 +00004696 SourceLocation Loc = E->getSourceRange().getBegin();
4697 if (Loc.isMacroID())
4698 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
David Blaikie9fb1ac52012-05-15 21:57:38 +00004699 if (!Loc.isMacroID() || CC.isMacroID())
4700 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
4701 << T << clang::SourceRange(CC)
4702 << FixItHint::CreateReplacement(Loc, S.getFixItZeroLiteralForType(T));
Richard Trieu1838ca52011-05-29 19:59:02 +00004703 }
4704
David Blaikieb26331b2012-06-19 21:19:06 +00004705 if (!Source->isIntegerType() || !Target->isIntegerType())
4706 return;
4707
David Blaikiebe0ee872012-05-15 16:56:36 +00004708 // TODO: remove this early return once the false positives for constant->bool
4709 // in templates, macros, etc, are reduced or removed.
4710 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
4711 return;
4712
John McCall323ed742010-05-06 08:58:33 +00004713 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00004714 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00004715
4716 if (SourceRange.Width > TargetRange.Width) {
John McCall091f23f2010-11-09 22:22:12 +00004717 // If the source is a constant, use a default-on diagnostic.
4718 // TODO: this should happen for bitfield stores, too.
4719 llvm::APSInt Value(32);
4720 if (E->isIntegerConstantExpr(Value, S.Context)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004721 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004722 return;
4723
John McCall091f23f2010-11-09 22:22:12 +00004724 std::string PrettySourceValue = Value.toString(10);
4725 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
4726
Ted Kremenek5e745da2011-10-22 02:37:33 +00004727 S.DiagRuntimeBehavior(E->getExprLoc(), E,
4728 S.PDiag(diag::warn_impcast_integer_precision_constant)
4729 << PrettySourceValue << PrettyTargetValue
4730 << E->getType() << T << E->getSourceRange()
4731 << clang::SourceRange(CC));
John McCall091f23f2010-11-09 22:22:12 +00004732 return;
4733 }
4734
Chris Lattnerb792b302011-06-14 04:51:15 +00004735 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004736 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004737 return;
4738
David Blaikie37050842012-04-12 22:40:54 +00004739 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaksc36bedc2012-02-01 19:08:57 +00004740 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
4741 /* pruneControlFlow */ true);
John McCallb4eb64d2010-10-08 02:01:28 +00004742 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00004743 }
4744
4745 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
4746 (!TargetRange.NonNegative && SourceRange.NonNegative &&
4747 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004748
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004749 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004750 return;
4751
John McCall323ed742010-05-06 08:58:33 +00004752 unsigned DiagID = diag::warn_impcast_integer_sign;
4753
4754 // Traditionally, gcc has warned about this under -Wsign-compare.
4755 // We also want to warn about it in -Wconversion.
4756 // So if -Wconversion is off, use a completely identical diagnostic
4757 // in the sign-compare group.
4758 // The conditional-checking code will
4759 if (ICContext) {
4760 DiagID = diag::warn_impcast_integer_sign_conditional;
4761 *ICContext = true;
4762 }
4763
John McCallb4eb64d2010-10-08 02:01:28 +00004764 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00004765 }
4766
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004767 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004768 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
4769 // type, to give us better diagnostics.
4770 QualType SourceType = E->getType();
David Blaikie4e4d0842012-03-11 07:00:24 +00004771 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004772 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
4773 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
4774 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
4775 SourceType = S.Context.getTypeDeclType(Enum);
4776 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
4777 }
4778 }
4779
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004780 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
4781 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
4782 if ((SourceEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00004783 SourceEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004784 (TargetEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00004785 TargetEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00004786 SourceEnum != TargetEnum) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004787 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004788 return;
4789
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004790 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004791 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004792 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004793
John McCall51313c32010-01-04 23:31:57 +00004794 return;
4795}
4796
David Blaikie9fb1ac52012-05-15 21:57:38 +00004797void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
4798 SourceLocation CC, QualType T);
John McCall323ed742010-05-06 08:58:33 +00004799
4800void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00004801 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00004802 E = E->IgnoreParenImpCasts();
4803
4804 if (isa<ConditionalOperator>(E))
David Blaikie9fb1ac52012-05-15 21:57:38 +00004805 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCall323ed742010-05-06 08:58:33 +00004806
John McCallb4eb64d2010-10-08 02:01:28 +00004807 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00004808 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00004809 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00004810 return;
4811}
4812
David Blaikie9fb1ac52012-05-15 21:57:38 +00004813void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
4814 SourceLocation CC, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00004815 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00004816
4817 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00004818 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
4819 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00004820
4821 // If -Wconversion would have warned about either of the candidates
4822 // for a signedness conversion to the context type...
4823 if (!Suspicious) return;
4824
4825 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00004826 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
4827 CC))
John McCall323ed742010-05-06 08:58:33 +00004828 return;
4829
John McCall323ed742010-05-06 08:58:33 +00004830 // ...then check whether it would have warned about either of the
4831 // candidates for a signedness conversion to the condition type.
Richard Trieu52541612011-07-21 02:46:28 +00004832 if (E->getType() == T) return;
4833
4834 Suspicious = false;
4835 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
4836 E->getType(), CC, &Suspicious);
4837 if (!Suspicious)
4838 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00004839 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00004840}
4841
4842/// AnalyzeImplicitConversions - Find and report any interesting
4843/// implicit conversions in the given expression. There are a couple
4844/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00004845void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00004846 QualType T = OrigE->getType();
4847 Expr *E = OrigE->IgnoreParenImpCasts();
4848
Douglas Gregorf8b6e152011-10-10 17:38:18 +00004849 if (E->isTypeDependent() || E->isValueDependent())
4850 return;
4851
John McCall323ed742010-05-06 08:58:33 +00004852 // For conditional operators, we analyze the arguments as if they
4853 // were being fed directly into the output.
4854 if (isa<ConditionalOperator>(E)) {
4855 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie9fb1ac52012-05-15 21:57:38 +00004856 CheckConditionalOperator(S, CO, CC, T);
John McCall323ed742010-05-06 08:58:33 +00004857 return;
4858 }
4859
Hans Wennborg88617a22012-08-28 15:44:30 +00004860 // Check implicit argument conversions for function calls.
4861 if (CallExpr *Call = dyn_cast<CallExpr>(E))
4862 CheckImplicitArgumentConversions(S, Call, CC);
4863
John McCall323ed742010-05-06 08:58:33 +00004864 // Go ahead and check any implicit conversions we might have skipped.
4865 // The non-canonical typecheck is just an optimization;
4866 // CheckImplicitConversion will filter out dead implicit conversions.
4867 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00004868 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00004869
4870 // Now continue drilling into this expression.
4871
4872 // Skip past explicit casts.
4873 if (isa<ExplicitCastExpr>(E)) {
4874 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00004875 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00004876 }
4877
John McCallbeb22aa2010-11-09 23:24:47 +00004878 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4879 // Do a somewhat different check with comparison operators.
4880 if (BO->isComparisonOp())
4881 return AnalyzeComparison(S, BO);
4882
Eli Friedman0fa06382012-01-26 23:34:06 +00004883 // And with simple assignments.
4884 if (BO->getOpcode() == BO_Assign)
John McCallbeb22aa2010-11-09 23:24:47 +00004885 return AnalyzeAssignment(S, BO);
4886 }
John McCall323ed742010-05-06 08:58:33 +00004887
4888 // These break the otherwise-useful invariant below. Fortunately,
4889 // we don't really need to recurse into them, because any internal
4890 // expressions should have been analyzed already when they were
4891 // built into statements.
4892 if (isa<StmtExpr>(E)) return;
4893
4894 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004895 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00004896
4897 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00004898 CC = E->getExprLoc();
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004899 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
4900 bool IsLogicalOperator = BO && BO->isLogicalOp();
4901 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor54042f12012-02-09 10:18:50 +00004902 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor503384f2012-02-09 00:47:04 +00004903 if (!ChildExpr)
4904 continue;
4905
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004906 if (IsLogicalOperator &&
4907 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
4908 // Ignore checking string literals that are in logical operators.
4909 continue;
4910 AnalyzeImplicitConversions(S, ChildExpr, CC);
4911 }
John McCall323ed742010-05-06 08:58:33 +00004912}
4913
4914} // end anonymous namespace
4915
4916/// Diagnoses "dangerous" implicit conversions within the given
4917/// expression (which is a full expression). Implements -Wconversion
4918/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00004919///
4920/// \param CC the "context" location of the implicit conversion, i.e.
4921/// the most location of the syntactic entity requiring the implicit
4922/// conversion
4923void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00004924 // Don't diagnose in unevaluated contexts.
David Blaikie71f55f72012-08-06 22:47:24 +00004925 if (isUnevaluatedContext())
John McCall323ed742010-05-06 08:58:33 +00004926 return;
4927
4928 // Don't diagnose for value- or type-dependent expressions.
4929 if (E->isTypeDependent() || E->isValueDependent())
4930 return;
4931
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004932 // Check for array bounds violations in cases where the check isn't triggered
4933 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
4934 // ArraySubscriptExpr is on the RHS of a variable initialization.
4935 CheckArrayAccess(E);
4936
John McCallb4eb64d2010-10-08 02:01:28 +00004937 // This is not the right CC for (e.g.) a variable initialization.
4938 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00004939}
4940
John McCall15d7d122010-11-11 03:21:53 +00004941void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
4942 FieldDecl *BitField,
4943 Expr *Init) {
4944 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
4945}
4946
Mike Stumpf8c49212010-01-21 03:59:47 +00004947/// CheckParmsForFunctionDef - Check that the parameters of the given
4948/// function are appropriate for the definition of a function. This
4949/// takes care of any checks that cannot be performed on the
4950/// declaration itself, e.g., that the types of each of the function
4951/// parameters are complete.
Douglas Gregor82aa7132010-11-01 18:37:59 +00004952bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
4953 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00004954 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00004955 for (; P != PEnd; ++P) {
4956 ParmVarDecl *Param = *P;
4957
Mike Stumpf8c49212010-01-21 03:59:47 +00004958 // C99 6.7.5.3p4: the parameters in a parameter type list in a
4959 // function declarator that is part of a function definition of
4960 // that function shall not have incomplete type.
4961 //
4962 // This is also C++ [dcl.fct]p6.
4963 if (!Param->isInvalidDecl() &&
4964 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00004965 diag::err_typecheck_decl_incomplete_type)) {
Mike Stumpf8c49212010-01-21 03:59:47 +00004966 Param->setInvalidDecl();
4967 HasInvalidParm = true;
4968 }
4969
4970 // C99 6.9.1p5: If the declarator includes a parameter type list, the
4971 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00004972 if (CheckParameterNames &&
4973 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00004974 !Param->isImplicit() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00004975 !getLangOpts().CPlusPlus)
Mike Stumpf8c49212010-01-21 03:59:47 +00004976 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00004977
4978 // C99 6.7.5.3p12:
4979 // If the function declarator is not part of a definition of that
4980 // function, parameters may have incomplete type and may use the [*]
4981 // notation in their sequences of declarator specifiers to specify
4982 // variable length array types.
4983 QualType PType = Param->getOriginalType();
4984 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
4985 if (AT->getSizeModifier() == ArrayType::Star) {
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00004986 // FIXME: This diagnosic should point the '[*]' if source-location
Sam Weinigd17e3402010-02-01 05:02:49 +00004987 // information is added for it.
4988 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
4989 }
4990 }
Mike Stumpf8c49212010-01-21 03:59:47 +00004991 }
4992
4993 return HasInvalidParm;
4994}
John McCallb7f4ffe2010-08-12 21:44:57 +00004995
4996/// CheckCastAlign - Implements -Wcast-align, which warns when a
4997/// pointer cast increases the alignment requirements.
4998void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
4999 // This is actually a lot of work to potentially be doing on every
5000 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00005001 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
5002 TRange.getBegin())
David Blaikied6471f72011-09-25 23:23:43 +00005003 == DiagnosticsEngine::Ignored)
John McCallb7f4ffe2010-08-12 21:44:57 +00005004 return;
5005
5006 // Ignore dependent types.
5007 if (T->isDependentType() || Op->getType()->isDependentType())
5008 return;
5009
5010 // Require that the destination be a pointer type.
5011 const PointerType *DestPtr = T->getAs<PointerType>();
5012 if (!DestPtr) return;
5013
5014 // If the destination has alignment 1, we're done.
5015 QualType DestPointee = DestPtr->getPointeeType();
5016 if (DestPointee->isIncompleteType()) return;
5017 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
5018 if (DestAlign.isOne()) return;
5019
5020 // Require that the source be a pointer type.
5021 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
5022 if (!SrcPtr) return;
5023 QualType SrcPointee = SrcPtr->getPointeeType();
5024
5025 // Whitelist casts from cv void*. We already implicitly
5026 // whitelisted casts to cv void*, since they have alignment 1.
5027 // Also whitelist casts involving incomplete types, which implicitly
5028 // includes 'void'.
5029 if (SrcPointee->isIncompleteType()) return;
5030
5031 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
5032 if (SrcAlign >= DestAlign) return;
5033
5034 Diag(TRange.getBegin(), diag::warn_cast_align)
5035 << Op->getType() << T
5036 << static_cast<unsigned>(SrcAlign.getQuantity())
5037 << static_cast<unsigned>(DestAlign.getQuantity())
5038 << TRange << Op->getSourceRange();
5039}
5040
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005041static const Type* getElementType(const Expr *BaseExpr) {
5042 const Type* EltType = BaseExpr->getType().getTypePtr();
5043 if (EltType->isAnyPointerType())
5044 return EltType->getPointeeType().getTypePtr();
5045 else if (EltType->isArrayType())
5046 return EltType->getBaseElementTypeUnsafe();
5047 return EltType;
5048}
5049
Chandler Carruthc2684342011-08-05 09:10:50 +00005050/// \brief Check whether this array fits the idiom of a size-one tail padded
5051/// array member of a struct.
5052///
5053/// We avoid emitting out-of-bounds access warnings for such arrays as they are
5054/// commonly used to emulate flexible arrays in C89 code.
5055static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
5056 const NamedDecl *ND) {
5057 if (Size != 1 || !ND) return false;
5058
5059 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
5060 if (!FD) return false;
5061
5062 // Don't consider sizes resulting from macro expansions or template argument
5063 // substitution to form C89 tail-padded arrays.
Sean Callanand2cf3482012-05-04 18:22:53 +00005064
5065 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00005066 while (TInfo) {
5067 TypeLoc TL = TInfo->getTypeLoc();
5068 // Look through typedefs.
5069 const TypedefTypeLoc *TTL = dyn_cast<TypedefTypeLoc>(&TL);
5070 if (TTL) {
5071 const TypedefNameDecl *TDL = TTL->getTypedefNameDecl();
5072 TInfo = TDL->getTypeSourceInfo();
5073 continue;
5074 }
5075 ConstantArrayTypeLoc CTL = cast<ConstantArrayTypeLoc>(TL);
5076 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Sean Callanand2cf3482012-05-04 18:22:53 +00005077 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
5078 return false;
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00005079 break;
Sean Callanand2cf3482012-05-04 18:22:53 +00005080 }
Chandler Carruthc2684342011-08-05 09:10:50 +00005081
5082 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gay381711c2011-11-29 22:43:53 +00005083 if (!RD) return false;
5084 if (RD->isUnion()) return false;
5085 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
5086 if (!CRD->isStandardLayout()) return false;
5087 }
Chandler Carruthc2684342011-08-05 09:10:50 +00005088
Benjamin Kramer22d4fed2011-08-06 03:04:42 +00005089 // See if this is the last field decl in the record.
5090 const Decl *D = FD;
5091 while ((D = D->getNextDeclInContext()))
5092 if (isa<FieldDecl>(D))
5093 return false;
5094 return true;
Chandler Carruthc2684342011-08-05 09:10:50 +00005095}
5096
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005097void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005098 const ArraySubscriptExpr *ASE,
Richard Smith25b009a2011-12-16 19:31:14 +00005099 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman92b670e2012-02-27 21:21:40 +00005100 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005101 if (IndexExpr->isValueDependent())
5102 return;
5103
Matt Beaumont-Gay8ef8f432011-12-12 22:35:02 +00005104 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005105 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth34064582011-02-17 20:55:08 +00005106 const ConstantArrayType *ArrayTy =
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005107 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00005108 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00005109 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00005110
Chandler Carruth34064582011-02-17 20:55:08 +00005111 llvm::APSInt index;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005112 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00005113 return;
Richard Smith25b009a2011-12-16 19:31:14 +00005114 if (IndexNegated)
5115 index = -index;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00005116
Chandler Carruthba447122011-08-05 08:07:29 +00005117 const NamedDecl *ND = NULL;
Chandler Carruthba447122011-08-05 08:07:29 +00005118 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
5119 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruthc2684342011-08-05 09:10:50 +00005120 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruthba447122011-08-05 08:07:29 +00005121 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruthba447122011-08-05 08:07:29 +00005122
Ted Kremenek9e060ca2011-02-23 23:06:04 +00005123 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00005124 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00005125 if (!size.isStrictlyPositive())
5126 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005127
5128 const Type* BaseType = getElementType(BaseExpr);
Nico Weberde5998f2011-09-17 22:59:41 +00005129 if (BaseType != EffectiveType) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005130 // Make sure we're comparing apples to apples when comparing index to size
5131 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
5132 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhraind10f4bc2011-08-10 19:47:25 +00005133 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhrain18f16972011-08-10 18:49:28 +00005134 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005135 if (ptrarith_typesize != array_typesize) {
5136 // There's a cast to a different size type involved
5137 uint64_t ratio = array_typesize / ptrarith_typesize;
5138 // TODO: Be smarter about handling cases where array_typesize is not a
5139 // multiple of ptrarith_typesize
5140 if (ptrarith_typesize * ratio == array_typesize)
5141 size *= llvm::APInt(size.getBitWidth(), ratio);
5142 }
5143 }
5144
Chandler Carruth34064582011-02-17 20:55:08 +00005145 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00005146 index = index.zext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00005147 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00005148 size = size.zext(index.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00005149
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005150 // For array subscripting the index must be less than size, but for pointer
5151 // arithmetic also allow the index (offset) to be equal to size since
5152 // computing the next address after the end of the array is legal and
5153 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman92b670e2012-02-27 21:21:40 +00005154 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruthba447122011-08-05 08:07:29 +00005155 return;
5156
5157 // Also don't warn for arrays of size 1 which are members of some
5158 // structure. These are often used to approximate flexible arrays in C89
5159 // code.
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005160 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00005161 return;
Chandler Carruth34064582011-02-17 20:55:08 +00005162
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005163 // Suppress the warning if the subscript expression (as identified by the
5164 // ']' location) and the index expression are both from macro expansions
5165 // within a system header.
5166 if (ASE) {
5167 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
5168 ASE->getRBracketLoc());
5169 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
5170 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
5171 IndexExpr->getLocStart());
5172 if (SourceMgr.isFromSameFile(RBracketLoc, IndexLoc))
5173 return;
5174 }
5175 }
5176
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005177 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005178 if (ASE)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005179 DiagID = diag::warn_array_index_exceeds_bounds;
5180
5181 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
5182 PDiag(DiagID) << index.toString(10, true)
5183 << size.toString(10, true)
5184 << (unsigned)size.getLimitedValue(~0U)
5185 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00005186 } else {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005187 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005188 if (!ASE) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005189 DiagID = diag::warn_ptr_arith_precedes_bounds;
5190 if (index.isNegative()) index = -index;
5191 }
5192
5193 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
5194 PDiag(DiagID) << index.toString(10, true)
5195 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00005196 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00005197
Matt Beaumont-Gaycfbc5b52011-11-29 19:27:11 +00005198 if (!ND) {
5199 // Try harder to find a NamedDecl to point at in the note.
5200 while (const ArraySubscriptExpr *ASE =
5201 dyn_cast<ArraySubscriptExpr>(BaseExpr))
5202 BaseExpr = ASE->getBase()->IgnoreParenCasts();
5203 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
5204 ND = dyn_cast<NamedDecl>(DRE->getDecl());
5205 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
5206 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
5207 }
5208
Chandler Carruth35001ca2011-02-17 21:10:52 +00005209 if (ND)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005210 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
5211 PDiag(diag::note_array_index_out_of_bounds)
5212 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00005213}
5214
Ted Kremenek3aea4da2011-03-01 18:41:00 +00005215void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005216 int AllowOnePastEnd = 0;
5217 while (expr) {
5218 expr = expr->IgnoreParenImpCasts();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00005219 switch (expr->getStmtClass()) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005220 case Stmt::ArraySubscriptExprClass: {
5221 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005222 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005223 AllowOnePastEnd > 0);
Ted Kremenek3aea4da2011-03-01 18:41:00 +00005224 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005225 }
5226 case Stmt::UnaryOperatorClass: {
5227 // Only unwrap the * and & unary operators
5228 const UnaryOperator *UO = cast<UnaryOperator>(expr);
5229 expr = UO->getSubExpr();
5230 switch (UO->getOpcode()) {
5231 case UO_AddrOf:
5232 AllowOnePastEnd++;
5233 break;
5234 case UO_Deref:
5235 AllowOnePastEnd--;
5236 break;
5237 default:
5238 return;
5239 }
5240 break;
5241 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00005242 case Stmt::ConditionalOperatorClass: {
5243 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
5244 if (const Expr *lhs = cond->getLHS())
5245 CheckArrayAccess(lhs);
5246 if (const Expr *rhs = cond->getRHS())
5247 CheckArrayAccess(rhs);
5248 return;
5249 }
5250 default:
5251 return;
5252 }
Peter Collingbournef111d932011-04-15 00:35:48 +00005253 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00005254}
John McCallf85e1932011-06-15 23:02:42 +00005255
5256//===--- CHECK: Objective-C retain cycles ----------------------------------//
5257
5258namespace {
5259 struct RetainCycleOwner {
5260 RetainCycleOwner() : Variable(0), Indirect(false) {}
5261 VarDecl *Variable;
5262 SourceRange Range;
5263 SourceLocation Loc;
5264 bool Indirect;
5265
5266 void setLocsFrom(Expr *e) {
5267 Loc = e->getExprLoc();
5268 Range = e->getSourceRange();
5269 }
5270 };
5271}
5272
5273/// Consider whether capturing the given variable can possibly lead to
5274/// a retain cycle.
5275static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
5276 // In ARC, it's captured strongly iff the variable has __strong
5277 // lifetime. In MRR, it's captured strongly if the variable is
5278 // __block and has an appropriate type.
5279 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
5280 return false;
5281
5282 owner.Variable = var;
5283 owner.setLocsFrom(ref);
5284 return true;
5285}
5286
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00005287static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCallf85e1932011-06-15 23:02:42 +00005288 while (true) {
5289 e = e->IgnoreParens();
5290 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
5291 switch (cast->getCastKind()) {
5292 case CK_BitCast:
5293 case CK_LValueBitCast:
5294 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00005295 case CK_ARCReclaimReturnedObject:
John McCallf85e1932011-06-15 23:02:42 +00005296 e = cast->getSubExpr();
5297 continue;
5298
John McCallf85e1932011-06-15 23:02:42 +00005299 default:
5300 return false;
5301 }
5302 }
5303
5304 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
5305 ObjCIvarDecl *ivar = ref->getDecl();
5306 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
5307 return false;
5308
5309 // Try to find a retain cycle in the base.
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00005310 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCallf85e1932011-06-15 23:02:42 +00005311 return false;
5312
5313 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
5314 owner.Indirect = true;
5315 return true;
5316 }
5317
5318 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
5319 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
5320 if (!var) return false;
5321 return considerVariable(var, ref, owner);
5322 }
5323
John McCallf85e1932011-06-15 23:02:42 +00005324 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
5325 if (member->isArrow()) return false;
5326
5327 // Don't count this as an indirect ownership.
5328 e = member->getBase();
5329 continue;
5330 }
5331
John McCall4b9c2d22011-11-06 09:01:30 +00005332 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
5333 // Only pay attention to pseudo-objects on property references.
5334 ObjCPropertyRefExpr *pre
5335 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
5336 ->IgnoreParens());
5337 if (!pre) return false;
5338 if (pre->isImplicitProperty()) return false;
5339 ObjCPropertyDecl *property = pre->getExplicitProperty();
5340 if (!property->isRetaining() &&
5341 !(property->getPropertyIvarDecl() &&
5342 property->getPropertyIvarDecl()->getType()
5343 .getObjCLifetime() == Qualifiers::OCL_Strong))
5344 return false;
5345
5346 owner.Indirect = true;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00005347 if (pre->isSuperReceiver()) {
5348 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
5349 if (!owner.Variable)
5350 return false;
5351 owner.Loc = pre->getLocation();
5352 owner.Range = pre->getSourceRange();
5353 return true;
5354 }
John McCall4b9c2d22011-11-06 09:01:30 +00005355 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
5356 ->getSourceExpr());
5357 continue;
5358 }
5359
John McCallf85e1932011-06-15 23:02:42 +00005360 // Array ivars?
5361
5362 return false;
5363 }
5364}
5365
5366namespace {
5367 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
5368 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
5369 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
5370 Variable(variable), Capturer(0) {}
5371
5372 VarDecl *Variable;
5373 Expr *Capturer;
5374
5375 void VisitDeclRefExpr(DeclRefExpr *ref) {
5376 if (ref->getDecl() == Variable && !Capturer)
5377 Capturer = ref;
5378 }
5379
John McCallf85e1932011-06-15 23:02:42 +00005380 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
5381 if (Capturer) return;
5382 Visit(ref->getBase());
5383 if (Capturer && ref->isFreeIvar())
5384 Capturer = ref;
5385 }
5386
5387 void VisitBlockExpr(BlockExpr *block) {
5388 // Look inside nested blocks
5389 if (block->getBlockDecl()->capturesVariable(Variable))
5390 Visit(block->getBlockDecl()->getBody());
5391 }
Fariborz Jahanian7e2e4c32012-08-31 20:04:47 +00005392
5393 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
5394 if (Capturer) return;
5395 if (OVE->getSourceExpr())
5396 Visit(OVE->getSourceExpr());
5397 }
John McCallf85e1932011-06-15 23:02:42 +00005398 };
5399}
5400
5401/// Check whether the given argument is a block which captures a
5402/// variable.
5403static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
5404 assert(owner.Variable && owner.Loc.isValid());
5405
5406 e = e->IgnoreParenCasts();
5407 BlockExpr *block = dyn_cast<BlockExpr>(e);
5408 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
5409 return 0;
5410
5411 FindCaptureVisitor visitor(S.Context, owner.Variable);
5412 visitor.Visit(block->getBlockDecl()->getBody());
5413 return visitor.Capturer;
5414}
5415
5416static void diagnoseRetainCycle(Sema &S, Expr *capturer,
5417 RetainCycleOwner &owner) {
5418 assert(capturer);
5419 assert(owner.Variable && owner.Loc.isValid());
5420
5421 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
5422 << owner.Variable << capturer->getSourceRange();
5423 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
5424 << owner.Indirect << owner.Range;
5425}
5426
5427/// Check for a keyword selector that starts with the word 'add' or
5428/// 'set'.
5429static bool isSetterLikeSelector(Selector sel) {
5430 if (sel.isUnarySelector()) return false;
5431
Chris Lattner5f9e2722011-07-23 10:55:15 +00005432 StringRef str = sel.getNameForSlot(0);
John McCallf85e1932011-06-15 23:02:42 +00005433 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00005434 if (str.startswith("set"))
John McCallf85e1932011-06-15 23:02:42 +00005435 str = str.substr(3);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00005436 else if (str.startswith("add")) {
5437 // Specially whitelist 'addOperationWithBlock:'.
5438 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
5439 return false;
5440 str = str.substr(3);
5441 }
John McCallf85e1932011-06-15 23:02:42 +00005442 else
5443 return false;
5444
5445 if (str.empty()) return true;
5446 return !islower(str.front());
5447}
5448
5449/// Check a message send to see if it's likely to cause a retain cycle.
5450void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
5451 // Only check instance methods whose selector looks like a setter.
5452 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
5453 return;
5454
5455 // Try to find a variable that the receiver is strongly owned by.
5456 RetainCycleOwner owner;
5457 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00005458 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCallf85e1932011-06-15 23:02:42 +00005459 return;
5460 } else {
5461 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
5462 owner.Variable = getCurMethodDecl()->getSelfDecl();
5463 owner.Loc = msg->getSuperLoc();
5464 owner.Range = msg->getSuperLoc();
5465 }
5466
5467 // Check whether the receiver is captured by any of the arguments.
5468 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
5469 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
5470 return diagnoseRetainCycle(*this, capturer, owner);
5471}
5472
5473/// Check a property assign to see if it's likely to cause a retain cycle.
5474void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
5475 RetainCycleOwner owner;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00005476 if (!findRetainCycleOwner(*this, receiver, owner))
John McCallf85e1932011-06-15 23:02:42 +00005477 return;
5478
5479 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
5480 diagnoseRetainCycle(*this, capturer, owner);
5481}
5482
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005483bool Sema::checkUnsafeAssigns(SourceLocation Loc,
John McCallf85e1932011-06-15 23:02:42 +00005484 QualType LHS, Expr *RHS) {
5485 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
5486 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005487 return false;
5488 // strip off any implicit cast added to get to the one arc-specific
5489 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00005490 if (cast->getCastKind() == CK_ARCConsumeObject) {
John McCallf85e1932011-06-15 23:02:42 +00005491 Diag(Loc, diag::warn_arc_retained_assign)
Fariborz Jahanianbd2e27e2012-07-06 21:09:27 +00005492 << (LT == Qualifiers::OCL_ExplicitNone) << 1
John McCallf85e1932011-06-15 23:02:42 +00005493 << RHS->getSourceRange();
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005494 return true;
5495 }
5496 RHS = cast->getSubExpr();
5497 }
5498 return false;
John McCallf85e1932011-06-15 23:02:42 +00005499}
5500
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005501void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
5502 Expr *LHS, Expr *RHS) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00005503 QualType LHSType;
5504 // PropertyRef on LHS type need be directly obtained from
5505 // its declaration as it has a PsuedoType.
5506 ObjCPropertyRefExpr *PRE
5507 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
5508 if (PRE && !PRE->isImplicitProperty()) {
5509 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
5510 if (PD)
5511 LHSType = PD->getType();
5512 }
5513
5514 if (LHSType.isNull())
5515 LHSType = LHS->getType();
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005516 if (checkUnsafeAssigns(Loc, LHSType, RHS))
5517 return;
5518 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
5519 // FIXME. Check for other life times.
5520 if (LT != Qualifiers::OCL_None)
5521 return;
5522
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00005523 if (PRE) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005524 if (PRE->isImplicitProperty())
5525 return;
5526 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
5527 if (!PD)
5528 return;
5529
5530 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00005531 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
5532 // when 'assign' attribute was not explicitly specified
5533 // by user, ignore it and rely on property type itself
5534 // for lifetime info.
5535 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
5536 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
5537 LHSType->isObjCRetainableType())
5538 return;
5539
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005540 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00005541 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005542 Diag(Loc, diag::warn_arc_retained_property_assign)
5543 << RHS->getSourceRange();
5544 return;
5545 }
5546 RHS = cast->getSubExpr();
5547 }
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00005548 }
Fariborz Jahanianbd2e27e2012-07-06 21:09:27 +00005549 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
5550 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
5551 if (cast->getCastKind() == CK_ARCConsumeObject) {
5552 Diag(Loc, diag::warn_arc_retained_assign)
5553 << 0 << 0<< RHS->getSourceRange();
5554 return;
5555 }
5556 RHS = cast->getSubExpr();
5557 }
5558 }
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005559 }
5560}
Dmitri Gribenko625bb562012-02-14 22:14:32 +00005561
5562//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
5563
5564namespace {
5565bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
5566 SourceLocation StmtLoc,
5567 const NullStmt *Body) {
5568 // Do not warn if the body is a macro that expands to nothing, e.g:
5569 //
5570 // #define CALL(x)
5571 // if (condition)
5572 // CALL(0);
5573 //
5574 if (Body->hasLeadingEmptyMacro())
5575 return false;
5576
5577 // Get line numbers of statement and body.
5578 bool StmtLineInvalid;
5579 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
5580 &StmtLineInvalid);
5581 if (StmtLineInvalid)
5582 return false;
5583
5584 bool BodyLineInvalid;
5585 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
5586 &BodyLineInvalid);
5587 if (BodyLineInvalid)
5588 return false;
5589
5590 // Warn if null statement and body are on the same line.
5591 if (StmtLine != BodyLine)
5592 return false;
5593
5594 return true;
5595}
5596} // Unnamed namespace
5597
5598void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
5599 const Stmt *Body,
5600 unsigned DiagID) {
5601 // Since this is a syntactic check, don't emit diagnostic for template
5602 // instantiations, this just adds noise.
5603 if (CurrentInstantiationScope)
5604 return;
5605
5606 // The body should be a null statement.
5607 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
5608 if (!NBody)
5609 return;
5610
5611 // Do the usual checks.
5612 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
5613 return;
5614
5615 Diag(NBody->getSemiLoc(), DiagID);
5616 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
5617}
5618
5619void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
5620 const Stmt *PossibleBody) {
5621 assert(!CurrentInstantiationScope); // Ensured by caller
5622
5623 SourceLocation StmtLoc;
5624 const Stmt *Body;
5625 unsigned DiagID;
5626 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
5627 StmtLoc = FS->getRParenLoc();
5628 Body = FS->getBody();
5629 DiagID = diag::warn_empty_for_body;
5630 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
5631 StmtLoc = WS->getCond()->getSourceRange().getEnd();
5632 Body = WS->getBody();
5633 DiagID = diag::warn_empty_while_body;
5634 } else
5635 return; // Neither `for' nor `while'.
5636
5637 // The body should be a null statement.
5638 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
5639 if (!NBody)
5640 return;
5641
5642 // Skip expensive checks if diagnostic is disabled.
5643 if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
5644 DiagnosticsEngine::Ignored)
5645 return;
5646
5647 // Do the usual checks.
5648 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
5649 return;
5650
5651 // `for(...);' and `while(...);' are popular idioms, so in order to keep
5652 // noise level low, emit diagnostics only if for/while is followed by a
5653 // CompoundStmt, e.g.:
5654 // for (int i = 0; i < n; i++);
5655 // {
5656 // a(i);
5657 // }
5658 // or if for/while is followed by a statement with more indentation
5659 // than for/while itself:
5660 // for (int i = 0; i < n; i++);
5661 // a(i);
5662 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
5663 if (!ProbableTypo) {
5664 bool BodyColInvalid;
5665 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
5666 PossibleBody->getLocStart(),
5667 &BodyColInvalid);
5668 if (BodyColInvalid)
5669 return;
5670
5671 bool StmtColInvalid;
5672 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
5673 S->getLocStart(),
5674 &StmtColInvalid);
5675 if (StmtColInvalid)
5676 return;
5677
5678 if (BodyCol > StmtCol)
5679 ProbableTypo = true;
5680 }
5681
5682 if (ProbableTypo) {
5683 Diag(NBody->getSemiLoc(), DiagID);
5684 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
5685 }
5686}
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00005687
5688//===--- Layout compatibility ----------------------------------------------//
5689
5690namespace {
5691
5692bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
5693
5694/// \brief Check if two enumeration types are layout-compatible.
5695bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
5696 // C++11 [dcl.enum] p8:
5697 // Two enumeration types are layout-compatible if they have the same
5698 // underlying type.
5699 return ED1->isComplete() && ED2->isComplete() &&
5700 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
5701}
5702
5703/// \brief Check if two fields are layout-compatible.
5704bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
5705 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
5706 return false;
5707
5708 if (Field1->isBitField() != Field2->isBitField())
5709 return false;
5710
5711 if (Field1->isBitField()) {
5712 // Make sure that the bit-fields are the same length.
5713 unsigned Bits1 = Field1->getBitWidthValue(C);
5714 unsigned Bits2 = Field2->getBitWidthValue(C);
5715
5716 if (Bits1 != Bits2)
5717 return false;
5718 }
5719
5720 return true;
5721}
5722
5723/// \brief Check if two standard-layout structs are layout-compatible.
5724/// (C++11 [class.mem] p17)
5725bool isLayoutCompatibleStruct(ASTContext &C,
5726 RecordDecl *RD1,
5727 RecordDecl *RD2) {
5728 // If both records are C++ classes, check that base classes match.
5729 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
5730 // If one of records is a CXXRecordDecl we are in C++ mode,
5731 // thus the other one is a CXXRecordDecl, too.
5732 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
5733 // Check number of base classes.
5734 if (D1CXX->getNumBases() != D2CXX->getNumBases())
5735 return false;
5736
5737 // Check the base classes.
5738 for (CXXRecordDecl::base_class_const_iterator
5739 Base1 = D1CXX->bases_begin(),
5740 BaseEnd1 = D1CXX->bases_end(),
5741 Base2 = D2CXX->bases_begin();
5742 Base1 != BaseEnd1;
5743 ++Base1, ++Base2) {
5744 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
5745 return false;
5746 }
5747 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
5748 // If only RD2 is a C++ class, it should have zero base classes.
5749 if (D2CXX->getNumBases() > 0)
5750 return false;
5751 }
5752
5753 // Check the fields.
5754 RecordDecl::field_iterator Field2 = RD2->field_begin(),
5755 Field2End = RD2->field_end(),
5756 Field1 = RD1->field_begin(),
5757 Field1End = RD1->field_end();
5758 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
5759 if (!isLayoutCompatible(C, *Field1, *Field2))
5760 return false;
5761 }
5762 if (Field1 != Field1End || Field2 != Field2End)
5763 return false;
5764
5765 return true;
5766}
5767
5768/// \brief Check if two standard-layout unions are layout-compatible.
5769/// (C++11 [class.mem] p18)
5770bool isLayoutCompatibleUnion(ASTContext &C,
5771 RecordDecl *RD1,
5772 RecordDecl *RD2) {
5773 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
5774 for (RecordDecl::field_iterator Field2 = RD2->field_begin(),
5775 Field2End = RD2->field_end();
5776 Field2 != Field2End; ++Field2) {
5777 UnmatchedFields.insert(*Field2);
5778 }
5779
5780 for (RecordDecl::field_iterator Field1 = RD1->field_begin(),
5781 Field1End = RD1->field_end();
5782 Field1 != Field1End; ++Field1) {
5783 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
5784 I = UnmatchedFields.begin(),
5785 E = UnmatchedFields.end();
5786
5787 for ( ; I != E; ++I) {
5788 if (isLayoutCompatible(C, *Field1, *I)) {
5789 bool Result = UnmatchedFields.erase(*I);
5790 (void) Result;
5791 assert(Result);
5792 break;
5793 }
5794 }
5795 if (I == E)
5796 return false;
5797 }
5798
5799 return UnmatchedFields.empty();
5800}
5801
5802bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
5803 if (RD1->isUnion() != RD2->isUnion())
5804 return false;
5805
5806 if (RD1->isUnion())
5807 return isLayoutCompatibleUnion(C, RD1, RD2);
5808 else
5809 return isLayoutCompatibleStruct(C, RD1, RD2);
5810}
5811
5812/// \brief Check if two types are layout-compatible in C++11 sense.
5813bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
5814 if (T1.isNull() || T2.isNull())
5815 return false;
5816
5817 // C++11 [basic.types] p11:
5818 // If two types T1 and T2 are the same type, then T1 and T2 are
5819 // layout-compatible types.
5820 if (C.hasSameType(T1, T2))
5821 return true;
5822
5823 T1 = T1.getCanonicalType().getUnqualifiedType();
5824 T2 = T2.getCanonicalType().getUnqualifiedType();
5825
5826 const Type::TypeClass TC1 = T1->getTypeClass();
5827 const Type::TypeClass TC2 = T2->getTypeClass();
5828
5829 if (TC1 != TC2)
5830 return false;
5831
5832 if (TC1 == Type::Enum) {
5833 return isLayoutCompatible(C,
5834 cast<EnumType>(T1)->getDecl(),
5835 cast<EnumType>(T2)->getDecl());
5836 } else if (TC1 == Type::Record) {
5837 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
5838 return false;
5839
5840 return isLayoutCompatible(C,
5841 cast<RecordType>(T1)->getDecl(),
5842 cast<RecordType>(T2)->getDecl());
5843 }
5844
5845 return false;
5846}
5847}
5848
5849//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
5850
5851namespace {
5852/// \brief Given a type tag expression find the type tag itself.
5853///
5854/// \param TypeExpr Type tag expression, as it appears in user's code.
5855///
5856/// \param VD Declaration of an identifier that appears in a type tag.
5857///
5858/// \param MagicValue Type tag magic value.
5859bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
5860 const ValueDecl **VD, uint64_t *MagicValue) {
5861 while(true) {
5862 if (!TypeExpr)
5863 return false;
5864
5865 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
5866
5867 switch (TypeExpr->getStmtClass()) {
5868 case Stmt::UnaryOperatorClass: {
5869 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
5870 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
5871 TypeExpr = UO->getSubExpr();
5872 continue;
5873 }
5874 return false;
5875 }
5876
5877 case Stmt::DeclRefExprClass: {
5878 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
5879 *VD = DRE->getDecl();
5880 return true;
5881 }
5882
5883 case Stmt::IntegerLiteralClass: {
5884 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
5885 llvm::APInt MagicValueAPInt = IL->getValue();
5886 if (MagicValueAPInt.getActiveBits() <= 64) {
5887 *MagicValue = MagicValueAPInt.getZExtValue();
5888 return true;
5889 } else
5890 return false;
5891 }
5892
5893 case Stmt::BinaryConditionalOperatorClass:
5894 case Stmt::ConditionalOperatorClass: {
5895 const AbstractConditionalOperator *ACO =
5896 cast<AbstractConditionalOperator>(TypeExpr);
5897 bool Result;
5898 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
5899 if (Result)
5900 TypeExpr = ACO->getTrueExpr();
5901 else
5902 TypeExpr = ACO->getFalseExpr();
5903 continue;
5904 }
5905 return false;
5906 }
5907
5908 case Stmt::BinaryOperatorClass: {
5909 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
5910 if (BO->getOpcode() == BO_Comma) {
5911 TypeExpr = BO->getRHS();
5912 continue;
5913 }
5914 return false;
5915 }
5916
5917 default:
5918 return false;
5919 }
5920 }
5921}
5922
5923/// \brief Retrieve the C type corresponding to type tag TypeExpr.
5924///
5925/// \param TypeExpr Expression that specifies a type tag.
5926///
5927/// \param MagicValues Registered magic values.
5928///
5929/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
5930/// kind.
5931///
5932/// \param TypeInfo Information about the corresponding C type.
5933///
5934/// \returns true if the corresponding C type was found.
5935bool GetMatchingCType(
5936 const IdentifierInfo *ArgumentKind,
5937 const Expr *TypeExpr, const ASTContext &Ctx,
5938 const llvm::DenseMap<Sema::TypeTagMagicValue,
5939 Sema::TypeTagData> *MagicValues,
5940 bool &FoundWrongKind,
5941 Sema::TypeTagData &TypeInfo) {
5942 FoundWrongKind = false;
5943
5944 // Variable declaration that has type_tag_for_datatype attribute.
5945 const ValueDecl *VD = NULL;
5946
5947 uint64_t MagicValue;
5948
5949 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
5950 return false;
5951
5952 if (VD) {
5953 for (specific_attr_iterator<TypeTagForDatatypeAttr>
5954 I = VD->specific_attr_begin<TypeTagForDatatypeAttr>(),
5955 E = VD->specific_attr_end<TypeTagForDatatypeAttr>();
5956 I != E; ++I) {
5957 if (I->getArgumentKind() != ArgumentKind) {
5958 FoundWrongKind = true;
5959 return false;
5960 }
5961 TypeInfo.Type = I->getMatchingCType();
5962 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
5963 TypeInfo.MustBeNull = I->getMustBeNull();
5964 return true;
5965 }
5966 return false;
5967 }
5968
5969 if (!MagicValues)
5970 return false;
5971
5972 llvm::DenseMap<Sema::TypeTagMagicValue,
5973 Sema::TypeTagData>::const_iterator I =
5974 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
5975 if (I == MagicValues->end())
5976 return false;
5977
5978 TypeInfo = I->second;
5979 return true;
5980}
5981} // unnamed namespace
5982
5983void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
5984 uint64_t MagicValue, QualType Type,
5985 bool LayoutCompatible,
5986 bool MustBeNull) {
5987 if (!TypeTagForDatatypeMagicValues)
5988 TypeTagForDatatypeMagicValues.reset(
5989 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
5990
5991 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
5992 (*TypeTagForDatatypeMagicValues)[Magic] =
5993 TypeTagData(Type, LayoutCompatible, MustBeNull);
5994}
5995
5996namespace {
5997bool IsSameCharType(QualType T1, QualType T2) {
5998 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
5999 if (!BT1)
6000 return false;
6001
6002 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
6003 if (!BT2)
6004 return false;
6005
6006 BuiltinType::Kind T1Kind = BT1->getKind();
6007 BuiltinType::Kind T2Kind = BT2->getKind();
6008
6009 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
6010 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
6011 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
6012 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
6013}
6014} // unnamed namespace
6015
6016void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
6017 const Expr * const *ExprArgs) {
6018 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
6019 bool IsPointerAttr = Attr->getIsPointer();
6020
6021 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
6022 bool FoundWrongKind;
6023 TypeTagData TypeInfo;
6024 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
6025 TypeTagForDatatypeMagicValues.get(),
6026 FoundWrongKind, TypeInfo)) {
6027 if (FoundWrongKind)
6028 Diag(TypeTagExpr->getExprLoc(),
6029 diag::warn_type_tag_for_datatype_wrong_kind)
6030 << TypeTagExpr->getSourceRange();
6031 return;
6032 }
6033
6034 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
6035 if (IsPointerAttr) {
6036 // Skip implicit cast of pointer to `void *' (as a function argument).
6037 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
6038 if (ICE->getType()->isVoidPointerType())
6039 ArgumentExpr = ICE->getSubExpr();
6040 }
6041 QualType ArgumentType = ArgumentExpr->getType();
6042
6043 // Passing a `void*' pointer shouldn't trigger a warning.
6044 if (IsPointerAttr && ArgumentType->isVoidPointerType())
6045 return;
6046
6047 if (TypeInfo.MustBeNull) {
6048 // Type tag with matching void type requires a null pointer.
6049 if (!ArgumentExpr->isNullPointerConstant(Context,
6050 Expr::NPC_ValueDependentIsNotNull)) {
6051 Diag(ArgumentExpr->getExprLoc(),
6052 diag::warn_type_safety_null_pointer_required)
6053 << ArgumentKind->getName()
6054 << ArgumentExpr->getSourceRange()
6055 << TypeTagExpr->getSourceRange();
6056 }
6057 return;
6058 }
6059
6060 QualType RequiredType = TypeInfo.Type;
6061 if (IsPointerAttr)
6062 RequiredType = Context.getPointerType(RequiredType);
6063
6064 bool mismatch = false;
6065 if (!TypeInfo.LayoutCompatible) {
6066 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
6067
6068 // C++11 [basic.fundamental] p1:
6069 // Plain char, signed char, and unsigned char are three distinct types.
6070 //
6071 // But we treat plain `char' as equivalent to `signed char' or `unsigned
6072 // char' depending on the current char signedness mode.
6073 if (mismatch)
6074 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
6075 RequiredType->getPointeeType())) ||
6076 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
6077 mismatch = false;
6078 } else
6079 if (IsPointerAttr)
6080 mismatch = !isLayoutCompatible(Context,
6081 ArgumentType->getPointeeType(),
6082 RequiredType->getPointeeType());
6083 else
6084 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
6085
6086 if (mismatch)
6087 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
6088 << ArgumentType << ArgumentKind->getName()
6089 << TypeInfo.LayoutCompatible << RequiredType
6090 << ArgumentExpr->getSourceRange()
6091 << TypeTagExpr->getSourceRange();
6092}
6093